diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.gitignore b/.gitignore index 524f096..d063c38 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,11 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* replay_pid* + +.idea + +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..feace10 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,58 @@ +plugins { + id("java") + `maven-publish` + id("net.minecrell.plugin-yml.paper") version "0.6.0" + id("com.github.johnrengelman.shadow") version "8.1.1" +} + +group = "dev.plex" +version = "1.0-SNAPSHOT" +description = "Medina" + +repositories { + mavenCentral() + maven { + name = "papermc-repo" + url = uri("https://repo.papermc.io/repository/maven-public/") + } + maven { + name = "sonatype" + url = uri("https://oss.sonatype.org/content/groups/public/") + } +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(17)) +} + +dependencies { + compileOnly(libs.paperApi) + implementation(libs.bundles.bstats) { isTransitive = false } +} + +tasks { + build { + dependsOn(shadowJar) + } + jar { + enabled = false + } + + shadowJar { + archiveBaseName.set("Medina") + archiveClassifier.set("") + relocate("org.bstats", "dev.plex.medina") + } +} + +paper { + name = "Medina" + version = project.version.toString() + main = "dev.plex.medina.Medina" + apiVersion = "1.20" + foliaSupported = true + authors = listOf("Telesphoreo") + description = "A sophisticated reporting plugin for Minecraft" + website = "https://plex.us.org" + generateLibrariesJson = true +} \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..f6e85d7 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,11 @@ +[versions] +paper = "1.20.4-R0.1-SNAPSHOT" +bstats = "3.0.2" + +[libraries] +paperApi = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" } +bstatsBase = { group = "org.bstats", name = "bstats-base", version.ref = "bstats" } +bstatsBukkit = { group = "org.bstats", name = "bstats-bukkit", version.ref = "bstats" } + +[bundles] +bstats = ["bstatsBase", "bstatsBukkit"] \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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/HEAD/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..604c1d5 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "Medina" diff --git a/src/main/java/dev/plex/medina/Medina.java b/src/main/java/dev/plex/medina/Medina.java new file mode 100644 index 0000000..2f110c6 --- /dev/null +++ b/src/main/java/dev/plex/medina/Medina.java @@ -0,0 +1,41 @@ +package dev.plex.medina; + +import dev.plex.medina.config.Config; +import dev.plex.medina.registration.CommandRegistration; +import org.bstats.bukkit.Metrics; +import org.bukkit.plugin.java.JavaPlugin; + + +public class Medina extends JavaPlugin +{ + private static Medina plugin; + + public Config config; + public Config messages; + + @Override + public void onLoad() + { + plugin = this; + config = new Config(this, "config.yml"); + messages = new Config(this, "messages.yml"); + } + + @Override + public void onEnable() + { + config.load(); + messages.load(); + + // Metrics @ https://bstats.org/plugin/bukkit/Medina/22026 + Metrics metrics = new Metrics(this, 22026); + + new CommandRegistration(); + } + + public static Medina getPlugin() + { + return plugin; + } + +} diff --git a/src/main/java/dev/plex/medina/MedinaBase.java b/src/main/java/dev/plex/medina/MedinaBase.java new file mode 100644 index 0000000..ff2696b --- /dev/null +++ b/src/main/java/dev/plex/medina/MedinaBase.java @@ -0,0 +1,6 @@ +package dev.plex.medina; + +public interface MedinaBase +{ + Medina plugin = Medina.getPlugin(); +} \ No newline at end of file diff --git a/src/main/java/dev/plex/medina/command/MedinaCommand.java b/src/main/java/dev/plex/medina/command/MedinaCommand.java new file mode 100644 index 0000000..a0f56c3 --- /dev/null +++ b/src/main/java/dev/plex/medina/command/MedinaCommand.java @@ -0,0 +1,311 @@ +package dev.plex.medina.command; + +import java.util.Arrays; +import java.util.List; + +import com.google.common.collect.Lists; +import dev.plex.medina.Medina; +import dev.plex.medina.command.annotation.CommandParameters; +import dev.plex.medina.command.source.RequiredCommandSource; +import dev.plex.medina.util.MedinaUtils; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@SuppressWarnings("all") +public abstract class MedinaCommand extends Command implements PluginIdentifiableCommand +{ + /** + * Returns the instance of the plugin + */ + protected static Medina plugin = Medina.getPlugin(); + + /** + * The parameters for the command + */ + private final CommandParameters params; + + /** + * Required command source fetched from the parameters + */ + private final RequiredCommandSource commandSource; + + public MedinaCommand(boolean register) + { + super(""); + this.params = getClass().getAnnotation(CommandParameters.class); + + setName(this.params.name()); + setLabel(this.params.name()); + setDescription(this.params.description()); + setDescription(this.params.permission()); + setUsage(params.usage().replace("", this.params.name())); + if (params.aliases().split(",").length > 0) + { + setAliases(Arrays.asList(params.aliases().split(","))); + } + this.commandSource = this.params.source(); + + if (register) + { + if (getMap().getKnownCommands().containsKey(this.getName().toLowerCase())) + { + getMap().getKnownCommands().remove(this.getName().toLowerCase()); + } + this.getAliases().forEach(s -> + { + if (getMap().getKnownCommands().containsKey(s.toLowerCase())) + { + getMap().getKnownCommands().remove(s.toLowerCase()); + } + }); + getMap().register("medina", this); + } + } + + public MedinaCommand() + { + this(true); + } + + /** + * The plugin + * + * @return The instance of the plugin + * @see Medina + */ + @Override + public @NotNull Medina getPlugin() + { + return plugin; + } + + /** + * Executes the command + * + * @param sender The sender of the command + * @param playerSender The player who executed the command (null if CommandSource is console or if CommandSource is any but console executed) + * @param args A Kyori Component to send to the sender (can be null) + */ + protected abstract Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args); + + /** + * @hidden + */ + @Override + public boolean execute(@NotNull CommandSender sender, @NotNull String label, String[] args) + { + if (!matches(label)) + { + return false; + } + + if (commandSource == RequiredCommandSource.CONSOLE && sender instanceof Player) + { + sender.sendMessage(messageComponent("noPermissionInGame")); + return true; + } + + if (commandSource == RequiredCommandSource.IN_GAME) + { + if (sender instanceof ConsoleCommandSender) + { + send(sender, messageComponent("noPermissionConsole")); + return true; + } + } + + if (sender instanceof Player player) + { + + if (!params.permission().isEmpty() && !player.hasPermission(params.permission())) + { + send(sender, messageComponent("noPermissionNode", params.permission())); + return true; + } + } + + if (sender instanceof ConsoleCommandSender && !sender.getName().equalsIgnoreCase("console")) //telnet + { + if (!params.permission().isEmpty() && !Bukkit.getPlayer(sender.getName()).hasPermission(params.permission())) + { + send(sender, messageComponent("noPermissionNode", params.permission())); + return true; + } + } + try + { + Component component = this.execute(sender, isConsole(sender) ? null : (Player) sender, args); + if (component != null) + { + send(sender, component); + } + } + catch (NumberFormatException ex) + { + send(sender, MedinaUtils.mmDeserialize(ex.getMessage())); + } + return true; + } + + /** + * Sends a message to an Audience + * + * @param audience The Audience to send the message to + * @param s The message to send + */ + protected void send(Audience audience, String s) + { + audience.sendMessage(componentFromString(s)); + } + + /** + * Sends a message to an Audience + * + * @param audience The Audience to send the message to + * @param component The Component to send + */ + protected void send(Audience audience, Component component) + { + audience.sendMessage(component); + } + + @NotNull + public abstract List smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException; + + @NotNull + @Override + public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException + { + List list = smartTabComplete(sender, alias, args); + return StringUtil.copyPartialMatches(args[args.length - 1], list, Lists.newArrayList()); + } + + /** + * Checks if the String given is a matching command + * + * @param label The String to check + * @return true if the string is a command name or alias + */ + private boolean matches(String label) + { + if (params.aliases().split(",").length > 0) + { + for (String alias : params.aliases().split(",")) + { + if (alias.equalsIgnoreCase(label) || getName().equalsIgnoreCase(label)) + { + return true; + } + } + } + else if (params.aliases().split(",").length < 1) + { + return getName().equalsIgnoreCase(label); + } + return false; + } + + /** + * Checks whether a sender is console + * + * @param sender A command sender + * @return true if the sender is console + */ + protected boolean isConsole(CommandSender sender) + { + return !(sender instanceof Player); + } + + /** + * Converts a message entry from the "messages.yml" to a Component + * + * @param s The message entry + * @param objects Any objects to replace in order + * @return A Kyori Component + */ + protected Component messageComponent(String s, Object... objects) + { + return MedinaUtils.messageComponent(s, objects); + } + + /** + * Converts a message entry from the "messages.yml" to a Component + * + * @param s The message entry + * @param objects Any objects to replace in order + * @return A Kyori Component + */ + protected Component messageComponent(String s, Component... objects) + { + return MedinaUtils.messageComponent(s, objects); + } + + /** + * Converts a message entry from the "messages.yml" to a String + * + * @param s The message entry + * @param objects Any objects to replace in order + * @return A String + */ + protected String messageString(String s, Object... objects) + { + return MedinaUtils.messageString(s, objects); + } + + /** + * Converts a String to a legacy Kyori Component + * + * @param s The String to convert + * @return A Kyori component + */ + protected Component componentFromString(String s) + { + return LegacyComponentSerializer.legacyAmpersand().deserialize(s).colorIfAbsent(NamedTextColor.GRAY); + } + + /** + * Converts usage to a Component + * + * @return A Kyori Component stating the usage + */ + protected Component usage() + { + return Component.text("Correct Usage: ").color(NamedTextColor.YELLOW).append(componentFromString(this.getUsage()).color(NamedTextColor.GRAY)); + } + + /** + * Converts usage to a Component + *

+ * s The usage to convert + * + * @return A Kyori Component stating the usage + */ + protected Component usage(String s) + { + return Component.text("Correct Usage: ").color(NamedTextColor.YELLOW).append(componentFromString(s).color(NamedTextColor.GRAY)); + } + + /** + * Converts a String to a MiniMessage Component + * + * @param s The String to convert + * @return A Kyori Component + */ + protected Component mmString(String s) + { + return MedinaUtils.mmDeserialize(s); + } + + public CommandMap getMap() + { + return Medina.getPlugin().getServer().getCommandMap(); + } +} \ No newline at end of file diff --git a/src/main/java/dev/plex/medina/command/annotation/CommandParameters.java b/src/main/java/dev/plex/medina/command/annotation/CommandParameters.java new file mode 100644 index 0000000..bb5e224 --- /dev/null +++ b/src/main/java/dev/plex/medina/command/annotation/CommandParameters.java @@ -0,0 +1,56 @@ +package dev.plex.medina.command.annotation; + +import dev.plex.medina.command.source.RequiredCommandSource; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Storage for a command's parameters + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface CommandParameters +{ + /** + * The name + * + * @return Name of the command + */ + String name(); + + /** + * The description + * + * @return Description of the command + */ + String description() default ""; + + /** + * The usage (optional) + * + * @return The usage of the command + */ + String usage() default "/"; + + /** + * The aliases (optional) + * + * @return The aliases of the command + */ + String aliases() default ""; + + /** + * Required command source + * + * @return The required command source of the command + * @see RequiredCommandSource + */ + RequiredCommandSource source() default RequiredCommandSource.ANY; + + /** + * The permission + * + * @return Permission of the command + */ + String permission() default ""; +} \ No newline at end of file diff --git a/src/main/java/dev/plex/medina/command/impl/AnyCommand.java b/src/main/java/dev/plex/medina/command/impl/AnyCommand.java new file mode 100644 index 0000000..cea9f92 --- /dev/null +++ b/src/main/java/dev/plex/medina/command/impl/AnyCommand.java @@ -0,0 +1,28 @@ +package dev.plex.medina.command.impl; + +import dev.plex.medina.command.MedinaCommand; +import dev.plex.medina.command.annotation.CommandParameters; +import dev.plex.medina.command.source.RequiredCommandSource; +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +@CommandParameters(name = "anycommand", usage = "/", description = "Tests the command system with a command", permission = "medina.anycommand", source = RequiredCommandSource.ANY) +public class AnyCommand extends MedinaCommand +{ + @Override + protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args) + { + return mmString("AnyCommand registered."); + } + + @Override + public @NotNull List smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException + { + return List.of(); + } +} diff --git a/src/main/java/dev/plex/medina/command/impl/ConsoleOnlyCommand.java b/src/main/java/dev/plex/medina/command/impl/ConsoleOnlyCommand.java new file mode 100644 index 0000000..141fc8e --- /dev/null +++ b/src/main/java/dev/plex/medina/command/impl/ConsoleOnlyCommand.java @@ -0,0 +1,28 @@ +package dev.plex.medina.command.impl; + +import dev.plex.medina.command.MedinaCommand; +import dev.plex.medina.command.annotation.CommandParameters; +import dev.plex.medina.command.source.RequiredCommandSource; +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +@CommandParameters(name = "consoleonly", usage = "/", description = "Tests the command system with a console only command", permission = "medina.consoleonly", source = RequiredCommandSource.CONSOLE) +public class ConsoleOnlyCommand extends MedinaCommand +{ + @Override + protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args) + { + return mmString("ConsoleOnlyCommand registered."); + } + + @Override + public @NotNull List smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException + { + return List.of(); + } +} diff --git a/src/main/java/dev/plex/medina/command/impl/ReportCommand.java b/src/main/java/dev/plex/medina/command/impl/ReportCommand.java new file mode 100644 index 0000000..fa473c9 --- /dev/null +++ b/src/main/java/dev/plex/medina/command/impl/ReportCommand.java @@ -0,0 +1,28 @@ +package dev.plex.medina.command.impl; + +import dev.plex.medina.command.MedinaCommand; +import dev.plex.medina.command.annotation.CommandParameters; +import dev.plex.medina.command.source.RequiredCommandSource; +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +@CommandParameters(name = "report", usage = "/ ", description = "Reports a player", permission = "medina.report", source = RequiredCommandSource.IN_GAME) +public class ReportCommand extends MedinaCommand +{ + @Override + protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args) + { + return mmString("Report command registered."); + } + + @Override + public @NotNull List smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException + { + return List.of(); + } +} diff --git a/src/main/java/dev/plex/medina/command/source/RequiredCommandSource.java b/src/main/java/dev/plex/medina/command/source/RequiredCommandSource.java new file mode 100644 index 0000000..104ede2 --- /dev/null +++ b/src/main/java/dev/plex/medina/command/source/RequiredCommandSource.java @@ -0,0 +1,8 @@ +package dev.plex.medina.command.source; + +public enum RequiredCommandSource +{ + IN_GAME, + CONSOLE, + ANY +} \ No newline at end of file diff --git a/src/main/java/dev/plex/medina/config/Config.java b/src/main/java/dev/plex/medina/config/Config.java new file mode 100644 index 0000000..bd672ff --- /dev/null +++ b/src/main/java/dev/plex/medina/config/Config.java @@ -0,0 +1,120 @@ +package dev.plex.medina.config; + +import dev.plex.medina.Medina; +import dev.plex.medina.util.MedinaLog; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +public class Config extends YamlConfiguration +{ + /** + * The plugin instance + */ + private Medina plugin; + + /** + * The File instance + */ + private File file; + + /** + * The file name + */ + private String name; + + /** + * Whether new entries were added to the file automatically + */ + private boolean added = false; + + /** + * Creates a config object + * + * @param plugin The plugin instance + * @param name The file name + */ + public Config(Medina plugin, String name) + { + this.plugin = plugin; + this.file = new File(plugin.getDataFolder(), name); + this.name = name; + + if (!file.exists()) + { + saveDefault(); + } + } + + public void load() + { + this.load(true); + } + + /** + * Loads the configuration file + */ + public void load(boolean loadFromFile) + { + try + { + if (loadFromFile) + { + YamlConfiguration externalYamlConfig = YamlConfiguration.loadConfiguration(file); + InputStreamReader internalConfigFileStream = new InputStreamReader(plugin.getResource(name), StandardCharsets.UTF_8); + YamlConfiguration internalYamlConfig = YamlConfiguration.loadConfiguration(internalConfigFileStream); + + // Gets all the keys inside the internal file and iterates through all of it's key pairs + for (String string : internalYamlConfig.getKeys(true)) + { + // Checks if the external file contains the key already. + if (!externalYamlConfig.contains(string)) + { + // If it doesn't contain the key, we set the key based off what was found inside the plugin jar + externalYamlConfig.setComments(string, internalYamlConfig.getComments(string)); + externalYamlConfig.setInlineComments(string, internalYamlConfig.getInlineComments(string)); + externalYamlConfig.set(string, internalYamlConfig.get(string)); + MedinaLog.log("Setting key: " + string + " in " + this.name + " to the default value(s) since it does not exist!"); + added = true; + } + } + if (added) + { + externalYamlConfig.save(file); + MedinaLog.log("Saving new file..."); + added = false; + } + } + super.load(file); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + /** + * Saves the configuration file + */ + public void save() + { + try + { + super.save(file); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + /** + * Moves the configuration file from the plugin's resources folder to the data folder (plugins/Medina/) + */ + private void saveDefault() + { + plugin.saveResource(name, false); + } +} diff --git a/src/main/java/dev/plex/medina/registration/CommandRegistration.java b/src/main/java/dev/plex/medina/registration/CommandRegistration.java new file mode 100644 index 0000000..16d13ae --- /dev/null +++ b/src/main/java/dev/plex/medina/registration/CommandRegistration.java @@ -0,0 +1,35 @@ +package dev.plex.medina.registration; + +import com.google.common.collect.Lists; +import dev.plex.medina.MedinaBase; +import dev.plex.medina.command.MedinaCommand; +import dev.plex.medina.util.MedinaLog; +import dev.plex.medina.util.ReflectionsUtil; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Set; + +public class CommandRegistration implements MedinaBase +{ + public CommandRegistration() + { + Set> commandSet = ReflectionsUtil.getClassesBySubType("dev.plex.medina.command.impl", MedinaCommand.class); + List commands = Lists.newArrayList(); + + commandSet.forEach(clazz -> + { + try + { + + commands.add(clazz.getConstructor().newInstance()); + } + catch (InvocationTargetException | InstantiationException | IllegalAccessException | + NoSuchMethodException ex) + { + MedinaLog.error("Failed to register " + clazz.getSimpleName() + " as a command!"); + } + }); + MedinaLog.log(String.format("Registered %s commands from %s classes!", commands.size(), commandSet.size())); + } +} diff --git a/src/main/java/dev/plex/medina/util/MedinaLog.java b/src/main/java/dev/plex/medina/util/MedinaLog.java new file mode 100644 index 0000000..619bb9e --- /dev/null +++ b/src/main/java/dev/plex/medina/util/MedinaLog.java @@ -0,0 +1,71 @@ +package dev.plex.medina.util; + +import dev.plex.medina.Medina; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.logger.slf4j.ComponentLogger; + +public class MedinaLog +{ + private static final ComponentLogger logger = ComponentLogger.logger(""); + + public static void log(String message, Object... strings) + { + for (int i = 0; i < strings.length; i++) + { + if (strings[i] == null) continue; + if (message.contains("{" + i + "}")) + { + message = message.replace("{" + i + "}", strings[i].toString()); + } + } + logger.info(MedinaUtils.mmDeserialize("[Medina] " + message)); + } + + public static void log(Component component) + { + logger.info(Component.text("[Medina] ").color(NamedTextColor.YELLOW).append(component).colorIfAbsent(NamedTextColor.GRAY)); + } + + public static void error(String message, Object... strings) + { + for (int i = 0; i < strings.length; i++) + { + if (strings[i] == null) continue; + if (message.contains("{" + i + "}")) + { + message = message.replace("{" + i + "}", strings[i].toString()); + } + } + logger.error(MedinaUtils.mmDeserialize("[Medina Error] " + message)); + } + + public static void warn(String message, Object... strings) + { + for (int i = 0; i < strings.length; i++) + { + if (strings[i] == null) continue; + if (message.contains("{" + i + "}")) + { + message = message.replace("{" + i + "}", strings[i].toString()); + } + } + logger.warn(MedinaUtils.mmDeserialize("<#eb7c0e>[Medina Warning] " + message)); + } + + public static void debug(String message, Object... strings) + { + if (Medina.getPlugin().config.getBoolean("debug")) + { + for (int i = 0; i < strings.length; i++) + { + if (strings[i] == null) continue; + if (message.contains("{" + i + "}")) + { + message = message.replace("{" + i + "}", strings[i].toString()); + } + } + logger.info(MedinaUtils.mmDeserialize("[Medina Debug] " + message)); + } + } +} \ No newline at end of file diff --git a/src/main/java/dev/plex/medina/util/MedinaUtils.java b/src/main/java/dev/plex/medina/util/MedinaUtils.java new file mode 100644 index 0000000..924b9bf --- /dev/null +++ b/src/main/java/dev/plex/medina/util/MedinaUtils.java @@ -0,0 +1,57 @@ +package dev.plex.medina.util; + +import dev.plex.medina.MedinaBase; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; + +public class MedinaUtils implements MedinaBase +{ + private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage(); + + public static Component mmDeserialize(String input) + { + return MINI_MESSAGE.deserialize(input); + } + + public static String mmSerialize(Component input) + { + return MINI_MESSAGE.serialize(input); + } + + public static Component mmCustomDeserialize(String input, TagResolver... resolvers) + { + return MiniMessage.builder().tags(TagResolver.builder().resolvers(resolvers).build()).build().deserialize(input); + } + + public static Component messageComponent(String entry, Object... objects) + { + return MINI_MESSAGE.deserialize(messageString(entry, objects)); + } + + public static Component messageComponent(String entry, Component... objects) + { + Component component = MINI_MESSAGE.deserialize(messageString(entry)); + for (int i = 0; i < objects.length; i++) + { + int finalI = i; + component = component.replaceText(builder -> builder.matchLiteral("{" + finalI + "}").replacement(objects[finalI]).build()); + } + return component; + } + + public static String messageString(String entry, Object... objects) + { + String f = plugin.messages.getString(entry); + if (f == null) + { + throw new NullPointerException(); + } + for (int i = 0; i < objects.length; i++) + { + f = f.replace("{" + i + "}", String.valueOf(objects[i])); + } + return f; + } +} diff --git a/src/main/java/dev/plex/medina/util/ReflectionsUtil.java b/src/main/java/dev/plex/medina/util/ReflectionsUtil.java new file mode 100644 index 0000000..47c11e1 --- /dev/null +++ b/src/main/java/dev/plex/medina/util/ReflectionsUtil.java @@ -0,0 +1,71 @@ +package dev.plex.medina.util; + +import com.google.common.collect.ImmutableSet; +import com.google.common.reflect.ClassPath; +import com.google.common.reflect.TypeToken; +import dev.plex.medina.Medina; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public class ReflectionsUtil +{ + public static Set> getClassesFrom(String packageName) + { + Set> classes = new HashSet<>(); + try + { + ClassPath path = ClassPath.from(Medina.class.getClassLoader()); + ImmutableSet infoSet = path.getTopLevelClasses(packageName); + infoSet.forEach(info -> + { + try + { + Class clazz = Class.forName(info.getName()); + classes.add(clazz); + } + catch (ClassNotFoundException ex) + { + MedinaLog.error("Unable to find class " + info.getName() + " in " + packageName); + } + }); + } + catch (IOException ex) + { + MedinaLog.error("Something went wrong while fetching classes from " + packageName); + throw new RuntimeException(ex); + } + return Collections.unmodifiableSet(classes); + } + + @SuppressWarnings("unchecked") + public static Set> getClassesBySubType(String packageName, Class subType) + { + Set> loadedClasses = getClassesFrom(packageName); + Set> classes = new HashSet<>(); + loadedClasses.forEach(clazz -> + { + if (clazz.getSuperclass() == subType || Arrays.asList(clazz.getInterfaces()).contains(subType)) + { + classes.add((Class) clazz); + } + }); + return Collections.unmodifiableSet(classes); + } + + public static Class getGenericField(Field field) + { + Type type = field.getGenericType(); + if (type instanceof ParameterizedType parameterizedType) + { + return TypeToken.of(parameterizedType.getActualTypeArguments()[0]).getRawType(); + } + return field.getType(); + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..eb0e276 --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1 @@ +# Medina Configuration File \ No newline at end of file diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml new file mode 100644 index 0000000..077ed08 --- /dev/null +++ b/src/main/resources/messages.yml @@ -0,0 +1,19 @@ +# Medina Messages File +# This file uses the MiniMessage system. +# Documentation available at https://docs.adventure.kyori.net/minimessage/format.html + +# Messages in here will be placed in for certain commands, actions, etc. +# Warning: not all commands have customizable messages + +# Variables {number} - these are code-defined replacements for things that should be inserted into messages. (e.g. names, statuses, numbers) +# If any of these variables are supposed to be used within a message, some documentation is provided to give more context to what the variables indicate. +# If you are wishing to change these messages it's recommended you use the same amount of variables as stated in the documentation, however it's not required. + +playerNotFound: "Player not found!" +specifyPlayer: "You must specify a player!" + +# 0 - The permission node required to use the command +noPermissionNode: "You must have the permission: {0} to use this command!" +noPermissionInGame: "You must be in console to use this command!" +noPermissionConsole: "You must be in-game to use this command!" +consoleOnly: "This command can only be executed by the console." \ No newline at end of file