add foundation work

This commit is contained in:
2024-05-26 12:03:30 -05:00
parent 8b0b1ea45b
commit 85cef1be11
23 changed files with 1315 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -0,0 +1,6 @@
package dev.plex.medina;
public interface MedinaBase
{
Medina plugin = Medina.getPlugin();
}

View File

@ -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("<command>", 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<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException;
@NotNull
@Override
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
List<String> 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
* <p>
* 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();
}
}

View File

@ -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 "/<command>";
/**
* 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 "";
}

View File

@ -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 = "/<command>", 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("<green>AnyCommand registered.");
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return List.of();
}
}

View File

@ -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 = "/<command>", 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("<green>ConsoleOnlyCommand registered.");
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return List.of();
}
}

View File

@ -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 = "/<command> <player> <message>", 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("<green>Report command registered.");
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return List.of();
}
}

View File

@ -0,0 +1,8 @@
package dev.plex.medina.command.source;
public enum RequiredCommandSource
{
IN_GAME,
CONSOLE,
ANY
}

View File

@ -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);
}
}

View File

@ -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<Class<? extends MedinaCommand>> commandSet = ReflectionsUtil.getClassesBySubType("dev.plex.medina.command.impl", MedinaCommand.class);
List<MedinaCommand> 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()));
}
}

View File

@ -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("<yellow>[Medina] <gray>" + 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("<red>[Medina Error] <gold>" + 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] <gold>" + 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("<dark_purple>[Medina Debug] <gold>" + message));
}
}
}

View File

@ -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;
}
}

View File

@ -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<Class<?>> getClassesFrom(String packageName)
{
Set<Class<?>> classes = new HashSet<>();
try
{
ClassPath path = ClassPath.from(Medina.class.getClassLoader());
ImmutableSet<ClassPath.ClassInfo> 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 <T> Set<Class<? extends T>> getClassesBySubType(String packageName, Class<T> subType)
{
Set<Class<?>> loadedClasses = getClassesFrom(packageName);
Set<Class<? extends T>> classes = new HashSet<>();
loadedClasses.forEach(clazz ->
{
if (clazz.getSuperclass() == subType || Arrays.asList(clazz.getInterfaces()).contains(subType))
{
classes.add((Class<? extends T>) 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();
}
}