Replaces all old functionality with a config command

This commit is contained in:
2022-05-29 19:26:34 +02:00
parent fe18034ac3
commit 5e7229ce35
12 changed files with 602 additions and 626 deletions

View File

@@ -0,0 +1,42 @@
package net.knarcraft.stargatecommand;
import net.TheDgtl.Stargate.api.StargateAPI;
import net.knarcraft.stargatecommand.command.CommandStarGateCommand;
import net.knarcraft.stargatecommand.command.StargateCommandTabCompleter;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.plugin.java.JavaPlugin;
/**
* The main class for the Stargate-Command add-on
*/
@SuppressWarnings("unused")
public class StargateCommand extends JavaPlugin {
@Override
public void onEnable() {
//Get the Stargate API
ServicesManager servicesManager = this.getServer().getServicesManager();
RegisteredServiceProvider<StargateAPI> stargateProvider = servicesManager.getRegistration(StargateAPI.class);
if (stargateProvider != null) {
StargateAPI stargateAPI = stargateProvider.getProvider();
//Register commands
PluginCommand stargateCommand = this.getCommand("stargatecommand");
if (stargateCommand != null) {
stargateCommand.setExecutor(new CommandStarGateCommand(stargateAPI));
stargateCommand.setTabCompleter(new StargateCommandTabCompleter());
}
} else {
throw new IllegalStateException("Unable to hook into Stargate. Make sure the Stargate plugin is installed " +
"and enabled.");
}
}
@Override
public void onDisable() {
//Currently, nothing needs to be disabled
}
}

View File

@@ -0,0 +1,241 @@
package net.knarcraft.stargatecommand.command;
import net.TheDgtl.Stargate.config.ConfigurationAPI;
import net.TheDgtl.Stargate.config.ConfigurationOption;
import net.TheDgtl.Stargate.config.OptionDataType;
import net.md_5.bungee.api.ChatColor;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
/**
* This command represents the config command for changing config values
*/
public class CommandConfig implements CommandExecutor {
private final ConfigurationAPI configurationAPI;
/**
* Instantiates a new instance of the config command
*
* @param configurationAPI <p>A reference to the Stargate API</p>
*/
public CommandConfig(ConfigurationAPI configurationAPI) {
super();
this.configurationAPI = configurationAPI;
}
@Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s,
@NotNull String[] args) {
if (commandSender instanceof Player player) {
if (!player.hasPermission("stargate.command.config")) {
player.sendMessage("Permission Denied");
return true;
}
}
if (args.length > 0) {
ConfigurationOption selectedOption;
try {
selectedOption = ConfigurationOption.valueOf(args[0].toUpperCase());
} catch (IllegalArgumentException exception) {
commandSender.sendMessage("Invalid configuration option specified");
return true;
}
if (args.length > 1) {
updateConfigValue(selectedOption, commandSender, args[1]);
} else {
//Display info and the current value of the given config value
printConfigOptionValue(commandSender, selectedOption);
}
return true;
} else {
//Display all config options
displayConfigValues(commandSender);
}
return true;
}
/**
* Updates a config value
*
* @param selectedOption <p>The option which should be updated</p>
* @param commandSender <p>The command sender that changed the value</p>
* @param value <p>The new value of the config option</p>
*/
private void updateConfigValue(ConfigurationOption selectedOption, CommandSender commandSender, String value) {
//Validate any sign colors
if (selectedOption.getDataType() == OptionDataType.COLOR) {
try {
ChatColor.of(value.toUpperCase());
} catch (IllegalArgumentException | NullPointerException ignored) {
commandSender.sendMessage(ChatColor.RED + "Invalid color given");
return;
}
}
OptionDataType optionDataType = selectedOption.getDataType();
//Validate the input based on the data type
switch (optionDataType) {
case INTEGER -> {
if (getInteger(commandSender, selectedOption, value) == null) {
return;
}
}
case DOUBLE -> {
if (getDouble(commandSender, selectedOption, value) == null) {
return;
}
}
}
/* Test any option data type with a defined set of values.
* Color is excluded as it has a near-infinite number of valid values. */
if (optionDataType != OptionDataType.COLOR && optionDataType.getValues() != null &&
optionDataType.getValues().length > 0) {
if (!checkIfValueMatchesDatatype(optionDataType, value, commandSender)) {
return;
}
}
configurationAPI.setConfigurationOptionValue(selectedOption, value);
saveAndReload(commandSender);
}
/**
* Checks if the given value is valid for the given option data type and warns if it isn't
*
* @param dataType <p>The expected type for the value</p>
* @param value <p>The value to check</p>
* @param commandSender <p>The command sender to warn about invalid values</p>
* @return <p>True if the given value is valid for the option data type</p>
*/
private boolean checkIfValueMatchesDatatype(OptionDataType dataType, String value, CommandSender commandSender) {
if (!matchesOptionDataType(dataType, value)) {
commandSender.sendMessage(String.format("Invalid %s given",
dataType.name().toLowerCase().replace('_', ' ')));
return false;
} else {
return true;
}
}
/**
* Checks if the given value is valid for the given option data type
*
* @param dataType <p>The expected type for the value</p>
* @param value <p>The value to check</p>
* @return <p>True if the given value is valid for the option data type</p>
*/
private boolean matchesOptionDataType(OptionDataType dataType, String value) {
return Arrays.asList(dataType.getValues()).contains(value);
}
/**
* Saves the configuration file and reloads
*
* @param commandSender <p>The command sender that executed the config command</p>
*/
private void saveAndReload(CommandSender commandSender) {
configurationAPI.saveConfiguration();
configurationAPI.reload();
commandSender.sendMessage("Config updated");
}
/**
* Gets an integer from a string
*
* @param commandSender <p>The command sender that sent the config command</p>
* @param selectedOption <p>The option the command sender is trying to change</p>
* @param value <p>The value given</p>
* @return <p>An integer, or null if it was invalid</p>
*/
private Integer getInteger(CommandSender commandSender, ConfigurationOption selectedOption, String value) {
try {
int intValue = Integer.parseInt(value);
if ((selectedOption == ConfigurationOption.USE_COST || selectedOption == ConfigurationOption.CREATION_COST) && intValue < 0) {
commandSender.sendMessage(ChatColor.RED + "This config option cannot be negative.");
return null;
}
return intValue;
} catch (NumberFormatException exception) {
commandSender.sendMessage(ChatColor.RED + "Invalid number given");
return null;
}
}
/**
* Gets a double from a string
*
* @param commandSender <p>The command sender that sent the config command</p>
* @param selectedOption <p>The option the command sender is trying to change</p>
* @param value <p>The value given</p>
* @return <p>A double, or null if it was invalid</p>
*/
private Double getDouble(CommandSender commandSender, ConfigurationOption selectedOption, String value) {
try {
double doubleValue = Double.parseDouble(value);
if (selectedOption == ConfigurationOption.GATE_EXIT_SPEED_MULTIPLIER && doubleValue < 0) {
commandSender.sendMessage(ChatColor.RED + "This config option cannot be negative.");
return null;
}
return doubleValue;
} catch (NumberFormatException exception) {
commandSender.sendMessage(ChatColor.RED + "Invalid number given");
return null;
}
}
/**
* Prints information about a config option and its current value
*
* @param sender <p>The command sender that sent the command</p>
* @param option <p>The config option to print information about</p>
*/
private void printConfigOptionValue(CommandSender sender, ConfigurationOption option) {
Object value = configurationAPI.getConfigurationOptionValue(option);
sender.sendMessage(getOptionDescription(option));
sender.sendMessage(ChatColor.GREEN + "Current value: " + ChatColor.GOLD + value);
}
/**
* Displays the name and a small description of every config value
*
* @param sender <p>The command sender to display the config list to</p>
*/
private void displayConfigValues(CommandSender sender) {
sender.sendMessage(ChatColor.GREEN + "Stargate" + ChatColor.GOLD + "Config values:");
for (ConfigurationOption option : ConfigurationOption.values()) {
sender.sendMessage(getOptionDescription(option));
}
}
/**
* Gets the description of a single config option
*
* @param option <p>The option to describe</p>
* @return <p>A string describing the config option</p>
*/
private String getOptionDescription(ConfigurationOption option) {
Object defaultValue = option.getDefaultValue();
String stringValue = String.valueOf(defaultValue);
if (option.getDataType() == OptionDataType.STRING_LIST) {
stringValue = "[" + StringUtils.join((String[]) defaultValue, ",") + "]";
}
return ChatColor.GOLD + option.name() + ChatColor.WHITE + " - " + ChatColor.GREEN + option.getDescription() +
ChatColor.DARK_GRAY + " (Default: " + ChatColor.GRAY + stringValue + ChatColor.DARK_GRAY + ")";
}
}

View File

@@ -0,0 +1,33 @@
package net.knarcraft.stargatecommand.command;
import net.TheDgtl.Stargate.api.StargateAPI;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
/**
* This command represents any command which starts with stargate-command (sgc)
*/
public class CommandStarGateCommand implements CommandExecutor {
private StargateAPI stargateAPI;
public CommandStarGateCommand(StargateAPI stargateAPI) {
this.stargateAPI = stargateAPI;
}
@Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s,
@NotNull String[] args) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("config")) {
String[] subArgs = (String[]) ArrayUtils.remove(args, 0);
return new CommandConfig(stargateAPI.getConfigurationAPI()).onCommand(commandSender, command, s, subArgs);
}
}
return false;
}
}

View File

@@ -0,0 +1,156 @@
package net.knarcraft.stargatecommand.command;
import net.TheDgtl.Stargate.config.ConfigurationOption;
import net.TheDgtl.Stargate.config.OptionDataType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* This is the completer for stargates config sub-command (/sg config)
*/
public class ConfigTabCompleter implements TabCompleter {
private List<String> booleans;
private List<String> integers;
private List<String> chatColors;
private List<String> doubles;
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s,
@NotNull String[] args) {
if (booleans == null || integers == null || chatColors == null) {
initializeAutoCompleteLists();
}
if (args.length > 1) {
ConfigurationOption selectedOption;
try {
selectedOption = ConfigurationOption.valueOf(args[0].toUpperCase());
} catch (IllegalArgumentException exception) {
return new ArrayList<>();
}
return getPossibleOptionValues(selectedOption, args[1]);
} else {
List<String> configOptionNames = new ArrayList<>();
for (ConfigurationOption option : ConfigurationOption.values()) {
configOptionNames.add(option.name());
}
return filterMatching(configOptionNames, args[0]);
}
}
/**
* Find completable strings which match the text typed by the command's sender
*
* @param values <p>The values to filter</p>
* @param typedText <p>The text the player has started typing</p>
* @return <p>The given string values which start with the player's typed text</p>
*/
private List<String> filterMatching(List<String> values, String typedText) {
List<String> configValues = new ArrayList<>();
for (String value : values) {
if (value.toLowerCase().startsWith(typedText.toLowerCase())) {
configValues.add(value);
}
}
return configValues;
}
/**
* Get possible values for the selected option
*
* @param selectedOption <p>The selected option</p>
* @param typedText <p>The beginning of the typed text, for filtering matching results</p>
* @return <p>Some or all of the valid values for the option</p>
*/
private List<String> getPossibleOptionValues(ConfigurationOption selectedOption, String typedText) {
switch (selectedOption) {
case LANGUAGE:
//Return available languages
return filterMatching(List.of(OptionDataType.LANGUAGE.getValues()), typedText);
case DEFAULT_NETWORK:
//Just return the default value as most values should be possible
if (typedText.trim().isEmpty()) {
return putStringInList((String) selectedOption.getDefaultValue());
} else {
return new ArrayList<>();
}
}
if (selectedOption.getDataType() == OptionDataType.COLOR) {
return filterMatching(chatColors, typedText);
}
//If the config value is a boolean, show the two boolean values
if (selectedOption.getDataType() == OptionDataType.BOOLEAN) {
return filterMatching(booleans, typedText);
}
//If the config value is an integer, display some valid numbers
if (selectedOption.getDataType() == OptionDataType.INTEGER) {
if (typedText.trim().isEmpty()) {
return integers;
} else {
return new ArrayList<>();
}
}
//If the config value is a double, display some valid numbers
if (selectedOption.getDataType() == OptionDataType.DOUBLE) {
if (typedText.trim().isEmpty()) {
return doubles;
} else {
return new ArrayList<>();
}
}
return null;
}
/**
* Puts a single string value into a string list
*
* @param value <p>The string to make into a list</p>
* @return <p>A list containing the string value</p>
*/
private List<String> putStringInList(String value) {
List<String> list = new ArrayList<>();
list.add(value);
return list;
}
/**
* Initializes all lists of auto-completable values
*/
private void initializeAutoCompleteLists() {
booleans = new ArrayList<>();
booleans.add("true");
booleans.add("false");
integers = new ArrayList<>();
integers.add("0");
integers.add("5");
getColors();
doubles = new ArrayList<>();
doubles.add("5");
doubles.add("1");
doubles.add("0.5");
doubles.add("0.1");
}
/**
* Initializes the list of chat colors
*/
private void getColors() {
chatColors = List.of(OptionDataType.COLOR.getValues());
}
}

View File

@@ -0,0 +1,50 @@
package net.knarcraft.stargatecommand.command;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class StargateCommandTabCompleter implements TabCompleter {
@Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command,
@NotNull String s, @NotNull String[] args) {
if (args.length == 1) {
List<String> commands = getAvailableCommands(commandSender);
List<String> matchingCommands = new ArrayList<>();
for (String availableCommand : commands) {
if (availableCommand.startsWith(args[0])) {
matchingCommands.add(availableCommand);
}
}
return matchingCommands;
} else if (args.length > 1 && args[0].equalsIgnoreCase("config")) {
String[] subArgs = (String[]) ArrayUtils.remove(args, 0);
return new ConfigTabCompleter().onTabComplete(commandSender, command, s, subArgs);
} else {
return new ArrayList<>();
}
}
/**
* Gets the available commands
*
* @param commandSender <p>The command sender to get available commands for</p>
* @return <p>The commands available to the command sender</p>
*/
private List<String> getAvailableCommands(CommandSender commandSender) {
List<String> commands = new ArrayList<>();
if (!(commandSender instanceof Player player) || player.hasPermission("stargate.command.config")) {
commands.add("config");
}
return commands;
}
}