Start command refactor

This commit is contained in:
William278 committed 2023-03-05 19:10:19 +00:00
1 parent 39e0b25d46
commit 3e27f7c5b1
57 files changed
+728 -384

No files matched your search

@@ -5,8 +5,7 @@ import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.Version;
import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.Spawn;
import net.william278.huskhomes.config.Locales;
@@ -24,6 +23,7 @@ import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Server;
@@ -76,7 +76,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
private UnsafeBlocks unsafeBlocks;
private EventDispatcher eventDispatcher;
private Set<PluginHook> pluginHooks;
private List<CommandBase> registeredCommands;
private List<Command> registeredCommands;
private Server server;
@Nullable
@@ -207,8 +207,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// Register commands
this.registeredCommands = new ArrayList<>();
Arrays.stream(BukkitCommandType.values()).forEach(commandType -> {
final PluginCommand pluginCommand = getCommand(commandType.commandBase.command);
Arrays.stream(BukkitCommand.Type.values()).forEach(commandType -> {
final PluginCommand pluginCommand = getCommand(commandType.getCommand().getName());
if (pluginCommand == null) {
return;
}
@@ -216,16 +216,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// If the command is disabled, use the disabled CommandBase
if (settings.getDisabledCommands().stream().anyMatch(disabledCommand -> {
final String command = (disabledCommand.startsWith("/") ? disabledCommand.substring(1) : disabledCommand);
return command.equalsIgnoreCase(commandType.commandBase.command) || Arrays.stream(commandType.commandBase.aliases).anyMatch(alias -> alias.equalsIgnoreCase(command));
return command.equalsIgnoreCase(commandType.getCommand().command) || Arrays.stream(commandType.getCommand().aliases).anyMatch(alias -> alias.equalsIgnoreCase(command));
})) {
new BukkitCommand(new DisabledCommand(this), this).register(pluginCommand);
return;
}
// Otherwise, register the command
final CommandBase commandBase = commandType.commandBase;
this.registeredCommands.add(commandBase);
new BukkitCommand(commandBase, this).register(pluginCommand);
final Command command = commandType.getCommand();
this.registeredCommands.add(command);
new BukkitCommand(command, this).register(pluginCommand);
});
getLoggingAdapter().log(Level.INFO, "Successfully registered permissions & commands.");
@@ -286,6 +286,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
return logger;
}
@Override
@NotNull
public ConsoleUser getConsole() {
return new ConsoleUser(audiences.console());
}
@NotNull
@Override
public List<OnlineUser> getOnlineUsers() {
@@ -422,7 +428,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
@Override
@NotNull
public List<CommandBase> getCommands() {
public List<Command> getCommands() {
return registeredCommands;
}
@@ -17,10 +17,10 @@ public class BrigadierUtil {
*
* @param plugin instance of the registering Bukkit plugin
* @param pluginCommand the Bukkit PluginCommand to register completions for
* @param command the {@link CommandBase} to register completions for
* @param command the {@link Command} to register completions for
*/
protected static void registerCommodore(@NotNull BukkitHuskHomes plugin, @NotNull PluginCommand pluginCommand,
@NotNull CommandBase command) {
@NotNull Command command) {
final InputStream commandCommodore = plugin.getResource("commodore/" + pluginCommand.getName() + ".commodore");
if (commandCommodore == null) {
return;
@@ -5,73 +5,106 @@ import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.user.BukkitUser;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.*;
/**
* Bukkit executor that implements and executes {@link CommandBase}s
*/
public class BukkitCommand implements CommandExecutor, TabExecutor {
public class BukkitCommand implements CommandExecutor, TabCompleter {
/**
* The {@link CommandBase} that will be executed
*/
private final CommandBase command;
/**
* The implementing plugin
*/
private final BukkitHuskHomes plugin;
private final Command command;
public BukkitCommand(@NotNull CommandBase command, @NotNull BukkitHuskHomes implementor) {
public BukkitCommand(@NotNull Command command, @NotNull BukkitHuskHomes plugin) {
this.command = command;
this.plugin = implementor;
}
/**
* Registers a {@link PluginCommand} to this implementation
*
* @param pluginCommand {@link PluginCommand} to register
*/
public void register(@NotNull PluginCommand pluginCommand) {
pluginCommand.setPermission(command.permission);
pluginCommand.setDescription(command.getDescription());
pluginCommand.setExecutor(this);
pluginCommand.setTabCompleter(this);
if (CommodoreProvider.isSupported()) {
BrigadierUtil.registerCommodore(plugin, pluginCommand, command);
}
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command,
@NotNull String label, @NotNull String[] args) {
if (sender instanceof Player player) {
this.command.onExecute(BukkitUser.adapt(player), args);
} else {
if (this.command instanceof ConsoleExecutable consoleExecutable) {
consoleExecutable.onConsoleExecute(args);
} else {
plugin.getLoggingAdapter().log(Level.WARNING, plugin.getLocales()
.getRawLocale("error_in_game_only")
.orElse("Error: That command can only be run in-game."));
}
}
this.command.execute(sender instanceof Player player ? BukkitUser.adapt(player) : plugin.getConsole(), args);
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command,
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command,
@NotNull String alias, @NotNull String[] args) {
if (this.command instanceof TabCompletable tabCompletable) {
return tabCompletable.onTabComplete(args, (sender instanceof Player ? BukkitUser.adapt((Player) sender) : null));
}
return Collections.emptyList();
return this.command.suggest(sender instanceof Player player ? BukkitUser.adapt(player) : plugin.getConsole(), args);
}
}
public void register() {
// Register with bukkit
final PluginCommand pluginCommand = Objects.requireNonNull(plugin.getCommand(command.getName()));
pluginCommand.setExecutor(this);
pluginCommand.setTabCompleter(this);
// Register commodore TAB completion
if (CommodoreProvider.isSupported() && plugin.getSettings().doBrigadierTabCompletion()) {
BrigadierUtil.registerCommodore(plugin, pluginCommand, command);
}
// Register permissions
final PluginManager manager = plugin.getServer().getPluginManager();
command.getChildren()
.stream().map(child -> new Permission(child.getPermission(), child.getUsage(),
child.isOperatorCommand() ? PermissionDefault.OP : PermissionDefault.TRUE))
.forEach(manager::addPermission);
manager.addPermission(new Permission(command.getPermission(), "/" + command.getName(),
command.isOperatorCommand() ? PermissionDefault.OP : PermissionDefault.TRUE));
// Register master permission
final Map<String, Boolean> childNodes = new HashMap<>();
command.getChildren().forEach(child -> childNodes.put(child.getPermission(), true));
manager.addPermission(new Permission(command.getPermission() + ".*", command.getUsage(),
PermissionDefault.FALSE, childNodes));
}
/**
* Commands available on the Bukkit HuskHomes implementation
*/
public enum Type {
HOME_COMMAND(new HomeCommand(BukkitHuskHomes.getInstance())),
SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())),
HOME_LIST_COMMAND(new HomeListCommand(BukkitHuskHomes.getInstance())),
DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())),
EDIT_HOME_COMMAND(new EditHomeCommand(BukkitHuskHomes.getInstance())),
PUBLIC_HOME_COMMAND(new PublicHomeCommand(BukkitHuskHomes.getInstance())),
PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(BukkitHuskHomes.getInstance())),
WARP_COMMAND(new WarpCommand(BukkitHuskHomes.getInstance())),
SET_WARP_COMMAND(new SetWarpCommand(BukkitHuskHomes.getInstance())),
WARP_LIST_COMMAND(new WarpListCommand(BukkitHuskHomes.getInstance())),
DEL_WARP_COMMAND(new DelWarpCommand(BukkitHuskHomes.getInstance())),
EDIT_WARP_COMMAND(new EditWarpCommand(BukkitHuskHomes.getInstance())),
TP_COMMAND(new TpCommand(BukkitHuskHomes.getInstance())),
TP_HERE_COMMAND(new TpHereCommand(BukkitHuskHomes.getInstance())),
TPA_COMMAND(new TpaCommand(BukkitHuskHomes.getInstance())),
TPA_HERE_COMMAND(new TpaHereCommand(BukkitHuskHomes.getInstance())),
TPACCEPT_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), true)),
TPDECLINE_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), false)),
RTP_COMMAND(new RtpCommand(BukkitHuskHomes.getInstance())),
TP_IGNORE_COMMAND(new TpIgnoreCommand(BukkitHuskHomes.getInstance())),
TP_OFFLINE_COMMAND(new TpOfflineCommand(BukkitHuskHomes.getInstance())),
TP_ALL_COMMAND(new TpAllCommand(BukkitHuskHomes.getInstance())),
TPA_ALL_COMMAND(new TpaAllCommand(BukkitHuskHomes.getInstance())),
SPAWN_COMMAND(new SpawnCommand(BukkitHuskHomes.getInstance())),
SET_SPAWN_COMMAND(new SetSpawnCommand(BukkitHuskHomes.getInstance())),
BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance())),
HUSKHOMES_COMMAND(new HuskHomesCommand(BukkitHuskHomes.getInstance()));
private final Command command;
Type(@NotNull Command command) {
this.command = command;
}
@NotNull
public Command getCommand() {
return command;
}
}
}
@@ -1,48 +0,0 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.BukkitHuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Commands available on the Bukkit HuskHomes implementation
*/
public enum BukkitCommandType {
HOME_COMMAND(new HomeCommand(BukkitHuskHomes.getInstance())),
SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())),
HOME_LIST_COMMAND(new HomeListCommand(BukkitHuskHomes.getInstance())),
DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())),
EDIT_HOME_COMMAND(new EditHomeCommand(BukkitHuskHomes.getInstance())),
PUBLIC_HOME_COMMAND(new PublicHomeCommand(BukkitHuskHomes.getInstance())),
PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(BukkitHuskHomes.getInstance())),
WARP_COMMAND(new WarpCommand(BukkitHuskHomes.getInstance())),
SET_WARP_COMMAND(new SetWarpCommand(BukkitHuskHomes.getInstance())),
WARP_LIST_COMMAND(new WarpListCommand(BukkitHuskHomes.getInstance())),
DEL_WARP_COMMAND(new DelWarpCommand(BukkitHuskHomes.getInstance())),
EDIT_WARP_COMMAND(new EditWarpCommand(BukkitHuskHomes.getInstance())),
TP_COMMAND(new TpCommand(BukkitHuskHomes.getInstance())),
TP_HERE_COMMAND(new TpHereCommand(BukkitHuskHomes.getInstance())),
TPA_COMMAND(new TpaCommand(BukkitHuskHomes.getInstance())),
TPA_HERE_COMMAND(new TpaHereCommand(BukkitHuskHomes.getInstance())),
TPACCEPT_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), true)),
TPDECLINE_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), false)),
RTP_COMMAND(new RtpCommand(BukkitHuskHomes.getInstance())),
TP_IGNORE_COMMAND(new TpIgnoreCommand(BukkitHuskHomes.getInstance())),
TP_OFFLINE_COMMAND(new TpOfflineCommand(BukkitHuskHomes.getInstance())),
TP_ALL_COMMAND(new TpAllCommand(BukkitHuskHomes.getInstance())),
TPA_ALL_COMMAND(new TpaAllCommand(BukkitHuskHomes.getInstance())),
SPAWN_COMMAND(new SpawnCommand(BukkitHuskHomes.getInstance())),
SET_SPAWN_COMMAND(new SetSpawnCommand(BukkitHuskHomes.getInstance())),
BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance())),
HUSKHOMES_COMMAND(new HuskHomesCommand(BukkitHuskHomes.getInstance()));
public final CommandBase commandBase;
BukkitCommandType(@NotNull CommandBase commandBase) {
this.commandBase = commandBase;
}
}
@@ -2,7 +2,7 @@ package net.william278.huskhomes.hook;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
@@ -74,8 +74,8 @@ public class DynMapHook extends MapHook {
.setDescription(MarkerInformationPopup.create(home.getMeta().getName())
.setThumbnailMarker(PUBLIC_HOME_MARKER_IMAGE_NAME)
.addField("Owner", home.getOwner().getUsername())
.addField("Description", plugin.getLocales().formatDescription(home.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommandType.PUBLIC_HOME_COMMAND.commandBase.command + " " + home.getMeta().getName())
.addField("Description", plugin.getLocales().wrapText(home.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommand.Type.PUBLIC_HOME_COMMAND.getCommand().command + " " + home.getMeta().getName())
.toHtml());
updatedFuture.complete(null);
}));
@@ -120,8 +120,8 @@ public class DynMapHook extends MapHook {
warp.getX(), warp.getY(), warp.getZ(), dynmapAPI.getMarkerAPI().getMarkerIcon(WARP_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(warp.getMeta().getName())
.setThumbnailMarker(WARP_MARKER_IMAGE_NAME)
.addField("Description", plugin.getLocales().formatDescription(warp.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommandType.WARP_COMMAND.commandBase.command + " " + warp.getMeta().getName())
.addField("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommand.Type.WARP_COMMAND.getCommand().command + " " + warp.getMeta().getName())
.toHtml());
updatedFuture.complete(null);
}));
@@ -102,7 +102,8 @@ public class BukkitUser extends OnlineUser {
}
@Override
protected @NotNull Audience getAudience() {
@NotNull
public Audience getAudience() {
return plugin.getAudiences().player(player);
}
@@ -4,7 +4,7 @@ import be.seeseemelk.mockbukkit.MockBukkit;
import be.seeseemelk.mockbukkit.ServerMock;
import be.seeseemelk.mockbukkit.entity.PlayerMock;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.user.BukkitUser;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
@@ -41,8 +41,8 @@ public class BukkitPluginTests {
@Test
public void testCommandRegistration() {
// Assert that all commands in BukkitCommandType are registered by the plugin
for (BukkitCommandType command : BukkitCommandType.values()) {
Assertions.assertNotNull(plugin.getCommand(command.commandBase.command));
for (BukkitCommand.Type command : BukkitCommand.Type.values()) {
Assertions.assertNotNull(plugin.getCommand(command.getCommand().command));
}
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.user.OnlineUser;
@@ -122,9 +122,9 @@ public class Cache {
final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.getUsername() : "";
final PaginatedList homeList = PaginatedList.of(homes.stream().map(home ->
locales.getRawLocale("home_list_item",
Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().getUsername() + "." + home.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
Locales.escapeText(home.getMeta().getName()),
Locales.escapeText(home.getOwner().getUsername() + "." + home.getMeta().getName()),
Locales.escapeText(locales.wrapText(home.getMeta().getDescription())))
.orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("home_list_page_title",
homeOwner.getUsername(), "%first_item_on_page_index%",
@@ -142,10 +142,10 @@ public class Cache {
}
final PaginatedList publicHomeList = PaginatedList.of(publicHomes.stream().map(home ->
locales.getRawLocale("public_home_list_item",
Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().getUsername() + "." + home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().getUsername()),
Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
Locales.escapeText(home.getMeta().getName()),
Locales.escapeText(home.getOwner().getUsername() + "." + home.getMeta().getName()),
Locales.escapeText(home.getOwner().getUsername()),
Locales.escapeText(locales.wrapText(home.getMeta().getDescription())))
.orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("public_home_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%",
@@ -163,8 +163,8 @@ public class Cache {
}
final PaginatedList warpList = PaginatedList.of(warps.stream()
.map(warp -> locales.getRawLocale("warp_list_item",
Locales.escapeMineDown(warp.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(warp.getMeta().getDescription())))
Locales.escapeText(warp.getMeta().getName()),
Locales.escapeText(locales.wrapText(warp.getMeta().getDescription())))
.orElse(warp.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("warp_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%",
@@ -176,16 +176,16 @@ public class Cache {
@NotNull
public MineDown getCommandList(@NotNull OnlineUser onlineUser, @NotNull Locales locales,
@NotNull List<CommandBase> commands, final int itemsPerPage, final int page) {
@NotNull List<Command> commands, final int itemsPerPage, final int page) {
return PaginatedList.of(commands.stream()
.filter(command -> onlineUser.hasPermission(command.permission))
.filter(command -> onlineUser.hasPermission(command.getPermission()))
.map(command -> locales.getRawLocale("command_list_item",
Locales.escapeMineDown(command.command),
Locales.escapeMineDown(command.getDescription().length() > 50
Locales.escapeText(command.getName()),
Locales.escapeText(command.getDescription().length() > 50
? command.getDescription().substring(0, 49).trim() + "…"
: command.getDescription()),
Locales.escapeMineDown(locales.formatDescription(command.getDescription())))
.orElse(command.command))
Locales.escapeText(locales.wrapText(command.getDescription())))
.orElse(command.getName()))
.collect(Collectors.toList()),
getBaseList(locales, Math.min(itemsPerPage, 6))
.setHeaderFormat(locales.getRawLocale("command_list_title").orElse(""))
@@ -6,7 +6,7 @@ import com.google.gson.GsonBuilder;
import net.kyori.adventure.key.Key;
import net.william278.desertwell.UpdateChecker;
import net.william278.desertwell.Version;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.Spawn;
@@ -17,6 +17,7 @@ import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RandomTeleportEngine;
@@ -50,6 +51,9 @@ public interface HuskHomes extends TaskRunner {
@NotNull
Logger getLoggingAdapter();
@NotNull
ConsoleUser getConsole();
/**
* The {@link Set} of online {@link OnlineUser}s on this server
*
@@ -331,10 +335,10 @@ public interface HuskHomes extends TaskRunner {
/**
* Returns a list of enabled commands
*
* @return A list of registered and enabled {@link CommandBase}s
* @return A list of registered and enabled {@link Command}s
*/
@NotNull
List<CommandBase> getCommands();
List<Command> getCommands();
/**
* Reloads the {@link Settings} and {@link Locales} from their respective config files
@@ -11,7 +11,7 @@ import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -41,24 +41,24 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Returns saved {@link UserData} for the given player's account {@link UUID}, if they exist.
* Returns saved {@link SavedUser} for the given player's account {@link UUID}, if they exist.
*
* @param uuid The {@link UUID} of the user to get data for.
* @return The {@link UserData} of the user.
* @return The {@link SavedUser} of the user.
* @since 3.0
*/
public final CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) {
public final CompletableFuture<Optional<SavedUser>> getUserData(@NotNull UUID uuid) {
return plugin.supplyAsync(() -> plugin.getDatabase().getUserData(uuid));
}
/**
* Returns saved {@link UserData} for the given player's username (case-insensitive), if they exist.
* Returns saved {@link SavedUser} for the given player's username (case-insensitive), if they exist.
*
* @param username The username of the user to get data for.
* @return The {@link UserData} of the user.
* @return The {@link SavedUser} of the user.
* @since 3.0
*/
public final CompletableFuture<Optional<UserData>> getUserData(@NotNull String username) {
public final CompletableFuture<Optional<SavedUser>> getUserData(@NotNull String username) {
return plugin.supplyAsync(() -> plugin.getDatabase().getUserDataByName(username));
}
@@ -114,13 +114,13 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Save {@link UserData} to the database, updating it if data for the user already exists, or adding new user data if it doesn't.
* Save {@link SavedUser} to the database, updating it if data for the user already exists, or adding new user data if it doesn't.
*
* @param userData The {@link UserData} to save
* @param savedUser The {@link SavedUser} to save
* @since 3.0
*/
public final void saveUserData(@NotNull UserData userData) {
plugin.runAsync(() -> plugin.getDatabase().updateUserData(userData));
public final void saveUserData(@NotNull SavedUser savedUser) {
plugin.runAsync(() -> plugin.getDatabase().updateUserData(savedUser));
}
/**
@@ -2,27 +2,39 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
public class BackCommand extends CommandBase {
import java.util.List;
import java.util.Optional;
protected BackCommand(@NotNull HuskHomes implementor) {
super("back", Permission.COMMAND_BACK, implementor);
public class BackCommand extends Command {
protected BackCommand(@NotNull HuskHomes plugin) {
super("back", List.of(), plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition ->
lastPosition.ifPresentOrElse(position -> Teleport.builder(plugin, onlineUser)
.setTarget(position)
.setEconomyActions(EconomyHook.Action.BACK_COMMAND)
.toTimedTeleport()
.thenApply(TimedTeleport::execute),
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage)));
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
final OnlineUser player = (OnlineUser) executor;
plugin.runAsync(() -> {
final Optional<Position> lastPosition = plugin.getDatabase().getLastPosition(player);
if (lastPosition.isEmpty()) {
plugin.getLocales().getLocale("error_no_last_position")
.ifPresent(player::sendMessage);
return;
}
Teleport.builder(plugin)
.teleporter(player)
.target(lastPosition.get())
.economyActions(EconomyHook.Action.BACK_COMMAND)
.toTimedTeleport()
.execute();
});
}
}
@@ -0,0 +1,39 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
public abstract class ChildCommand extends Node {
protected final Command parent;
private final String usage;
protected ChildCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull Command parent,
@NotNull String usage, @NotNull HuskHomes plugin) {
super(name, aliases, plugin);
this.parent = parent;
this.usage = usage;
}
@Override
@NotNull
public String getPermission() {
return new StringJoiner(".")
.add(parent.getPermission())
.add(getName()).toString();
}
@NotNull
public String getUsage() {
return "/" + parent.getName() + " " + getName() + ((" " + usage).isBlank() ? "" : " " + usage);
}
@NotNull
public final Optional<String> getDescription() {
return plugin.getLocales().getRawLocale("command_" + parent.getName() + "_" + getName() + "_description");
}
}
@@ -0,0 +1,168 @@
package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.paginedown.PaginatedList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public abstract class Command extends Node implements TabProvider {
public List<ChildCommand> children;
private Executable defaultExecutor;
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull HuskHomes plugin) {
super(name, aliases, plugin);
}
public void setDefaultExecutor(@NotNull Executable defaultExecutor) {
this.defaultExecutor = defaultExecutor;
}
@NotNull
protected Executable getDefaultExecutor() {
if (defaultExecutor == null) {
throw new IllegalStateException("Default executor not set");
}
return defaultExecutor;
}
public void setChildren(@NotNull List<ChildCommand> children) {
this.children = children;
}
@Override
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
if (!executor.hasPermission(getPermission())) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
}
if (args.length >= 1 && !children.isEmpty()) {
for (Node child : children) {
if (child.matchesInput(args[0])) {
if (!executor.hasPermission(child.getPermission())) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
}
if (executor instanceof ConsoleUser && !isConsoleExecutable()) {
plugin.getLocales().getLocale("error_command_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
child.execute(executor, removeFirstArg(args));
return;
}
}
plugin.getLocales().getLocale("error_unknown_command",
"/" + getName() + " " + getHelpCommand().getName())
.ifPresent(executor::sendMessage);
return;
}
if (executor instanceof ConsoleUser && !isConsoleExecutable()) {
plugin.getLocales().getLocale("error_command_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
this.defaultExecutor.execute(executor, args);
}
@Override
@NotNull
public final List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
if (args.length <= 1) {
return TabProvider.getMatchingNames(args[0], user, children);
} else {
for (final Node child : children) {
if (child.matchesInput(args[0]) && child instanceof TabProvider provider) {
return provider.getSuggestions(user, removeFirstArg(args));
}
}
}
return List.of();
}
@NotNull
private String[] removeFirstArg(String[] args) {
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
return newArgs;
}
@NotNull
public final String getUsage() {
final String arguments = children.stream().map(Node::getName).collect(Collectors.joining("|"));
return "/" + getName() + " [" + plugin.getLocales().truncateText(arguments, 40) + "]";
}
@NotNull
public String getDescription() {
return plugin.getLocales().getRawLocale(getName() + "_command_description")
.map(description -> plugin.getLocales().truncateText(description, 40))
.orElse(getUsage());
}
@NotNull
public List<ChildCommand> getChildren() {
return children;
}
@NotNull
protected MineDown getChildCommandList(@NotNull CommandUser user, final int page) {
final Locales locales = plugin.getLocales();
return PaginatedList.of(getChildren().stream()
.filter(child -> child.canPerform(user))
.map(command -> locales.getRawLocale("command_list_item",
Locales.escapeText(command.getUsage()),
"/" + command.parent.getName() + " " + command.getName(),
command.getDescription().map(description ->
Locales.escapeText(description.length() > 50
? description.substring(0, 49).trim() + "…"
: description)).orElse(""),
command.getDescription().map(description ->
Locales.escapeText(locales.wrapText(description, 40))).orElse(""))
.orElse(command.getUsage()))
.toList(),
locales.getBaseList(plugin.getSettings().getListItemsPerPage())
.setHeaderFormat(locales.getRawLocale("child_command_list_title",
"/" + getName()).orElse(""))
.setItemSeparator("\n").setCommand("/huskhomes:" + getName() + " help")
.build())
.getNearestValidPage(page);
}
@NotNull
public Command.HelpCommand getHelpCommand() {
return new HelpCommand(this, plugin);
}
public static class HelpCommand extends ChildCommand implements TabProvider {
protected HelpCommand(@NotNull Command parent, @NotNull HuskHomes plugin) {
super("help", List.of(), parent, "[page]", plugin);
}
@Override
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
int page = parseIntArg(args, 0).orElse(1);
executor.sendMessage(parent.getChildCommandList(executor, page));
}
@Override
@Nullable
public List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
return Stream.iterate(1, i -> i + 1)
.limit(9)
.map(String::valueOf)
.collect(Collectors.toList());
}
}
}
@@ -1,67 +0,0 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.intellij.lang.annotations.Pattern;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
/**
* Represents an abstract cross-platform representation for a plugin command
*/
public abstract class CommandBase {
/**
* The input string to match for this command
*/
@NotNull
public final String command;
/**
* Alias input strings for this command
*/
@NotNull
public final String[] aliases;
/**
* The permission node required to use this command
*/
@NotNull
@Pattern(Permission.PERMISSION_PATTERN)
public final String permission;
/**
* Instance of the implementing plugin
*/
@NotNull
protected final HuskHomes plugin;
protected CommandBase(@NotNull String command, @NotNull @Subst("huskhomes") Permission permission,
@NotNull HuskHomes implementor, @NotNull String... aliases) {
this.command = command;
this.permission = permission.node;
this.plugin = implementor;
this.aliases = aliases;
}
/**
* Fires when the command is executed
*
* @param onlineUser {@link OnlineUser} executing the command
* @param args Command arguments
*/
public abstract void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args);
/**
* Returns the localised description string of this command
*
* @return the command description
*/
@NotNull
public String getDescription() {
return plugin.getLocales().getRawLocale(command + "_command_description")
.orElse("A HuskHomes command");
}
}
@@ -1,17 +0,0 @@
package net.william278.huskhomes.command;
import org.jetbrains.annotations.NotNull;
/**
* Interface providing console execution of commands
*/
public interface ConsoleExecutable {
/**
* What to do when console executes a command
*
* @param args command argument strings
*/
void onConsoleExecute(@NotNull String[] args);
}
@@ -12,7 +12,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class DelHomeCommand extends CommandBase implements TabCompletable {
public class DelHomeCommand extends Command implements TabProvider {
protected DelHomeCommand(@NotNull HuskHomes implementor) {
super("delhome", Permission.COMMAND_DELETE_HOME, implementor);
@@ -120,7 +120,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
if (user == null) {
return Collections.emptyList();
}
@@ -10,7 +10,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class DelWarpCommand extends CommandBase implements TabCompletable {
public class DelWarpCommand extends Command implements TabProvider {
protected DelWarpCommand(@NotNull HuskHomes implementor) {
super("delwarp", Permission.COMMAND_DELETE_WARP, implementor);
@@ -72,7 +72,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length > 1 ? Collections.emptyList() : plugin.getCache().getWarps()
.stream()
.filter(s -> s.startsWith(args.length == 1 ? args[0] : ""))
@@ -5,7 +5,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
public class DisabledCommand extends CommandBase {
public class DisabledCommand extends Command {
public DisabledCommand(@NotNull HuskHomes implementor) {
super("", Permission.COMMAND_DISABLED_MESSAGE, implementor);
@@ -18,7 +18,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class EditHomeCommand extends CommandBase implements TabCompletable {
public class EditHomeCommand extends Command implements TabProvider {
private final String[] EDIT_HOME_COMPLETIONS = {"rename", "description", "relocate", "privacy"};
@@ -308,7 +308,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
plugin.getLocales().getLocale("edit_home_menu_description",
home.getMeta().getDescription().length() > 50
? home.getMeta().getDescription().substring(0, 49).trim() + "…" : home.getMeta().getDescription(),
plugin.getLocales().formatDescription(home.getMeta().getDescription()))
plugin.getLocales().wrapText(home.getMeta().getDescription()))
.ifPresent(this::add);
}
@@ -331,7 +331,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
formattedName)
.ifPresent(this::add);
}
final String escapedName = Locales.escapeMineDown(formattedName);
final String escapedName = Locales.escapeText(formattedName);
plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", escapedName,
showPrivacyToggleButton ? plugin.getLocales()
.getRawLocale("edit_home_menu_privacy_button_"
@@ -345,7 +345,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
if (user == null) {
return Collections.emptyList();
}
@@ -16,7 +16,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class EditWarpCommand extends CommandBase implements TabCompletable {
public class EditWarpCommand extends Command implements TabProvider {
private final String[] EDIT_WARP_COMPLETIONS = {"rename", "description", "relocate"};
@@ -171,7 +171,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
plugin.getLocales().getLocale("edit_warp_menu_description",
warp.getMeta().getDescription().length() > 50
? warp.getMeta().getDescription().substring(0, 49).trim() + "…" : warp.getMeta().getDescription(),
plugin.getLocales().formatDescription(warp.getMeta().getDescription()))
plugin.getLocales().wrapText(warp.getMeta().getDescription()))
.ifPresent(this::add);
}
@@ -198,7 +198,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return switch (args.length) {
case 0, 1 -> plugin.getCache().getWarps()
.stream()
@@ -0,0 +1,10 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
public interface Executable {
void execute(@NotNull CommandUser executor, @NotNull String[] args);
}
@@ -18,7 +18,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class HomeCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public class HomeCommand extends Command implements TabProvider, ConsoleExecutable {
protected HomeCommand(@NotNull HuskHomes implementor) {
super("home", Permission.COMMAND_HOME, implementor);
@@ -119,7 +119,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
if (user == null) {
return Collections.emptyList();
}
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -13,7 +13,7 @@ import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
public class HomeListCommand extends CommandBase implements ConsoleExecutable {
public class HomeListCommand extends Command implements ConsoleExecutable {
protected HomeListCommand(@NotNull HuskHomes implementor) {
super("homelist", Permission.COMMAND_HOME, implementor, "homes");
@@ -90,7 +90,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
return;
}
CompletableFuture.runAsync(() -> {
final Optional<UserData> userData = plugin.getDatabase().getUserDataByName(args[0]).join();
final Optional<SavedUser> userData = plugin.getDatabase().getUserDataByName(args[0]).join();
if (userData.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]);
return;
@@ -14,7 +14,7 @@ import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, TabCompletable {
public class HuskHomesCommand extends Command implements ConsoleExecutable, TabProvider {
private final String[] SUB_COMMANDS = {"about", "help", "reload", "update"};
private final AboutMenu aboutMenu;
@@ -158,7 +158,7 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
if (args.length == 0 || args.length == 1) {
return Arrays.stream(SUB_COMMANDS)
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
@@ -0,0 +1,115 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.ConsoleUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
public abstract class Node implements Executable {
protected static final String PERMISSION_PREFIX = "huskhomes.command";
protected final HuskHomes plugin;
private final String name;
private final List<String> aliases;
private boolean consoleExecutable = false;
private boolean operatorCommand = false;
protected Node(@NotNull String name, @NotNull List<String> aliases, @NotNull HuskHomes plugin) {
if (name.isBlank()) {
throw new IllegalArgumentException("Command name cannot be blank");
}
this.name = name;
this.aliases = aliases;
this.plugin = plugin;
}
@NotNull
public String getName() {
return name;
}
@NotNull
public List<String> getAliases() {
return aliases;
}
public final boolean matchesInput(@NotNull String input) {
return input.equalsIgnoreCase(getName()) || getAliases().contains(input.toLowerCase());
}
@NotNull
public String getPermission() {
return new StringJoiner(".")
.add(PERMISSION_PREFIX)
.add(getName()).toString();
}
public boolean canPerform(@NotNull CommandUser user) {
if (user instanceof ConsoleUser) {
return isConsoleExecutable();
}
return user.hasPermission(getPermission());
}
public boolean isConsoleExecutable() {
return consoleExecutable;
}
public void setConsoleExecutable(boolean consoleExecutable) {
this.consoleExecutable = consoleExecutable;
}
public boolean isOperatorCommand() {
return operatorCommand;
}
public void setOperatorCommand(boolean operatorCommand) {
this.operatorCommand = operatorCommand;
}
protected Optional<Integer> parseIntArg(@NotNull String[] args, int index) {
try {
if (args.length > index) {
return Optional.of(Integer.parseInt(args[index]));
}
} catch (NumberFormatException e) {
return Optional.empty();
}
return Optional.empty();
}
protected Optional<Double> parseDoubleArg(@NotNull String[] args, int index) {
try {
if (args.length > index) {
return Optional.of(Double.parseDouble(args[index]));
}
} catch (NumberFormatException e) {
return Optional.empty();
}
return Optional.empty();
}
protected Optional<String> parseStringArg(@NotNull String[] args, int index) {
if (args.length > index) {
return Optional.of(args[index]);
}
return Optional.empty();
}
protected Optional<String> parseGreedyString(@NotNull String[] args, int startIndex) {
if (args.length > startIndex) {
final StringJoiner sentence = new StringJoiner(" ");
for (int i = startIndex; i < args.length; i++) {
sentence.add(args[i]);
}
return Optional.of(sentence.toString().trim());
}
return Optional.empty();
}
}
@@ -19,7 +19,7 @@ import java.util.logging.Level;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class PublicHomeCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public class PublicHomeCommand extends Command implements TabProvider, ConsoleExecutable {
protected PublicHomeCommand(@NotNull HuskHomes implementor) {
super("publichome", Permission.COMMAND_PUBLIC_HOME, implementor, "phome");
@@ -133,7 +133,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
// Return every public home name as username.home_name from the cache
final List<String> publicHomes = new ArrayList<>();
plugin.getCache().getPublicHomes().forEach((ownerName, homeNames) ->
@@ -11,7 +11,7 @@ import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
public class PublicHomeListCommand extends CommandBase implements ConsoleExecutable {
public class PublicHomeListCommand extends Command implements ConsoleExecutable {
protected PublicHomeListCommand(@NotNull HuskHomes implementor) {
super("publichomelist", Permission.COMMAND_HOME, implementor, "phomelist", "phomes");
@@ -3,7 +3,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
@@ -16,7 +16,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
public class RtpCommand extends CommandBase implements ConsoleExecutable {
public class RtpCommand extends Command implements ConsoleExecutable {
protected RtpCommand(@NotNull HuskHomes implementor) {
super("rtp", Permission.COMMAND_RTP, implementor);
@@ -89,7 +89,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
.thenAccept(result -> {
if (isExecutorTeleporting &&
result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
plugin.getDatabase().updateUserData(new UserData(onlineUser,
plugin.getDatabase().updateUserData(new SavedUser(onlineUser,
userData.get().homeSlots(), userData.get().ignoringTeleports(),
Instant.now().plus(plugin.getSettings().getRtpCooldownLength(), ChronoUnit.MINUTES)));
}
@@ -3,7 +3,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
@@ -13,7 +13,7 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class SetHomeCommand extends CommandBase {
public class SetHomeCommand extends Command {
protected SetHomeCommand(@NotNull HuskHomes implementor) {
super("sethome", Permission.COMMAND_SET_HOME, implementor);
@@ -66,7 +66,7 @@ public class SetHomeCommand extends CommandBase {
plugin.getDatabase().getUserData(onlineUser.getUuid()).thenAccept(fetchedData -> {
// Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null);
final AtomicReference<SavedUser> userDataToUpdate = new AtomicReference<>(null);
if (plugin.getSettings().doEconomy()) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(),
plugin.getSettings().doStackPermissionLimits());
@@ -79,7 +79,7 @@ public class SetHomeCommand extends CommandBase {
if (!plugin.validateEconomyCheck(onlineUser, action)) {
return;
}
userDataToUpdate.set(new UserData(onlineUser, (currentHomes.size() + 1) - freeHomes,
userDataToUpdate.set(new SavedUser(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown()));
} else {
if (currentHomes.size() == freeHomes) {
@@ -7,7 +7,7 @@ import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
public class SetSpawnCommand extends CommandBase {
public class SetSpawnCommand extends Command {
protected SetSpawnCommand(@NotNull HuskHomes implementor) {
super("setspawn", Permission.COMMAND_SET_SPAWN, implementor);
@@ -6,7 +6,7 @@ import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
public class SetWarpCommand extends CommandBase {
public class SetWarpCommand extends Command {
protected SetWarpCommand(@NotNull HuskHomes implementor) {
super("setwarp", Permission.COMMAND_SET_WARP, implementor);
@@ -10,7 +10,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class SpawnCommand extends CommandBase {
public class SpawnCommand extends Command {
protected SpawnCommand(@NotNull HuskHomes implementor) {
super("spawn", Permission.COMMAND_SPAWN, implementor);
@@ -1,23 +0,0 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Interface providing tab completions for a command
*/
public interface TabCompletable {
/**
* What should be returned when the player attempts to TAB-complete the command
*
* @param args Current command arguments
* @return List of String arguments to offer TAB suggestions
*/
@NotNull
List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user);
}
@@ -0,0 +1,44 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.ConsoleUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface TabProvider {
@Nullable
List<String> suggest(@NotNull CommandUser user, @NotNull String[] args);
@NotNull
default List<String> getSuggestions(@NotNull CommandUser user, @NotNull String[] args) {
List<String> suggestions = suggest(user, args);
if (suggestions == null) {
suggestions = List.of();
}
return filter(suggestions, args);
}
@NotNull
default List<String> filter(@NotNull List<String> suggestions, @NotNull String[] args) {
return suggestions.stream()
.filter(suggestion -> args.length == 0 || suggestion.toLowerCase()
.startsWith(args[args.length - 1].toLowerCase().trim()))
.toList();
}
@NotNull
static List<String> getMatchingNames(@Nullable String argument, @NotNull CommandUser user,
@NotNull List<? extends Node> providers) {
return providers.stream()
.filter(command -> !(user instanceof ConsoleUser) || command.isConsoleExecutable())
.map(Node::getName)
.filter(commandName -> argument == null || argument.isBlank() || commandName.toLowerCase()
.startsWith(argument.toLowerCase().trim()))
.toList();
}
}
@@ -9,7 +9,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
public class TpAllCommand extends CommandBase {
public class TpAllCommand extends Command {
protected TpAllCommand(@NotNull HuskHomes implementor) {
super("tpall", Permission.COMMAND_TPALL, implementor);
@@ -14,7 +14,7 @@ import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class TpCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public class TpCommand extends Command implements TabProvider, ConsoleExecutable {
protected TpCommand(@NotNull HuskHomes implementor) {
super("tp", Permission.COMMAND_TP, implementor, "tpo");
@@ -203,7 +203,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
final boolean serveCoordinateCompletions = user != null && user.hasPermission(Permission.COMMAND_TP_TO_COORDINATES.node);
switch (args.length) {
case 0, 1 -> {
@@ -12,7 +12,7 @@ import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class TpHereCommand extends CommandBase implements TabCompletable {
public class TpHereCommand extends Command implements TabProvider {
protected TpHereCommand(@NotNull HuskHomes implementor) {
super("tphere", Permission.COMMAND_TPHERE, implementor, "tpohere");
@@ -52,7 +52,7 @@ public class TpHereCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
@@ -3,11 +3,11 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
public class TpIgnoreCommand extends CommandBase {
public class TpIgnoreCommand extends Command {
protected TpIgnoreCommand(@NotNull HuskHomes implementor) {
super("tpignore", Permission.COMMAND_TPIGNORE, implementor);
@@ -28,7 +28,7 @@ public class TpIgnoreCommand extends CommandBase {
// Update value on the database and send a message | todo: Clean this up
plugin.getDatabase().getUserData(onlineUser.getUuid())
.thenAcceptAsync(userData -> userData.ifPresent(data -> plugin.getDatabase()
.updateUserData(new UserData(onlineUser, data.homeSlots(), isIgnoringRequests, data.rtpCooldown()))
.updateUserData(new SavedUser(onlineUser, data.homeSlots(), isIgnoringRequests, data.rtpCooldown()))
.thenRun(() -> plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"),
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale))))));
@@ -11,7 +11,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class TpOfflineCommand extends CommandBase implements TabCompletable {
public class TpOfflineCommand extends Command implements TabProvider {
protected TpOfflineCommand(@NotNull HuskHomes implementor) {
super("tpoffline", Permission.COMMAND_TPOFFLINE, implementor);
@@ -53,7 +53,7 @@ public class TpOfflineCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
@@ -14,7 +14,7 @@ import java.util.stream.Collectors;
* A command used for responding to tp requests - can either be a /tpaccept or /tpdecline command, controlled by the
* acceptRequestCommand flag
*/
public class TpRespondCommand extends CommandBase implements TabCompletable {
public class TpRespondCommand extends Command implements TabProvider {
private final boolean acceptRequestCommand;
@@ -41,7 +41,7 @@ public class TpRespondCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
@@ -11,7 +11,7 @@ import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
public class TpaAllCommand extends CommandBase {
public class TpaAllCommand extends Command {
protected TpaAllCommand(@NotNull HuskHomes implementor) {
super("tpaall", Permission.COMMAND_TPA_ALL, implementor);
@@ -11,7 +11,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class TpaCommand extends CommandBase implements TabCompletable {
public class TpaCommand extends Command implements TabProvider {
protected TpaCommand(@NotNull HuskHomes implementor) {
super("tpa", Permission.COMMAND_TPA, implementor);
@@ -51,7 +51,7 @@ public class TpaCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
@@ -11,7 +11,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class TpaHereCommand extends CommandBase implements TabCompletable {
public class TpaHereCommand extends Command implements TabProvider {
protected TpaHereCommand(@NotNull HuskHomes implementor) {
super("tpahere", Permission.COMMAND_TPAHERE, implementor);
@@ -51,7 +51,7 @@ public class TpaHereCommand extends CommandBase implements TabCompletable {
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
@@ -13,7 +13,7 @@ import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class WarpCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public class WarpCommand extends Command implements TabProvider, ConsoleExecutable {
protected WarpCommand(@NotNull HuskHomes implementor) {
super("warp", Permission.COMMAND_WARP, implementor);
@@ -62,7 +62,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
}
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
public @NotNull List<String> suggest(@NotNull String[] args, @Nullable OnlineUser user) {
return plugin.getCache().getWarps().stream()
.filter(s -> user == null || Warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), user, s))
.filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : ""))
@@ -9,7 +9,7 @@ import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class WarpListCommand extends CommandBase implements ConsoleExecutable {
public class WarpListCommand extends Command implements ConsoleExecutable {
protected WarpListCommand(@NotNull HuskHomes implementor) {
super("warplist", Permission.COMMAND_WARP, implementor, "warps");
@@ -42,7 +42,7 @@ public class Locales {
/**
* Returns a raw, un-formatted locale loaded from the locales file, with replacements applied
* <p>
* Note that replacements will not be MineDown-escaped; use {@link #escapeMineDown(String)} to escape replacements
* Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
@@ -72,7 +72,7 @@ public class Locales {
* @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists
*/
public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) {
return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeMineDown)
return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText)
.toArray(String[]::new)).map(MineDown::new);
}
@@ -96,15 +96,12 @@ public class Locales {
/**
* Escape a string from {@link MineDown} formatting for use in a MineDown-formatted locale
* <p>
* Although MineDown provides {@link MineDown#escape(String)}, that method fails to escape events
* properly when using the escaped string in a replacement, so this is used instead
*
* @param string The string to escape
* @return The escaped string
*/
@NotNull
public static String escapeMineDown(@NotNull String string) {
public static String escapeText(@NotNull String string) {
final StringBuilder value = new StringBuilder();
for (int i = 0; i < string.length(); ++i) {
char c = string.charAt(i);
@@ -120,6 +117,14 @@ public class Locales {
return value.toString();
}
@NotNull
public String truncateText(@NotNull String string, int truncateAfter) {
if (string.isBlank()) {
return string;
}
return string.length() > truncateAfter ? string.substring(0, truncateAfter) + "…" : string;
}
/**
* Formats a description string, wrapping text on whitespace after 40 characters
*
@@ -127,7 +132,7 @@ public class Locales {
* @return The line-break formatted string, or a String literal {@code "N/A"} if the input string is empty
*/
@NotNull
public String formatDescription(@NotNull String string) {
public String wrapText(@NotNull String string) {
if (string.isBlank()) {
return this.getRawLocale("item_no_description").orElse("N/A");
}
@@ -157,6 +157,9 @@ public class Settings {
return Optional.ofNullable(getSoundEffects().get(action.name().toLowerCase()));
}
@YamlKey("general.brigadier_tab_completion")
private boolean brigadierTabCompletion = true;
// Cross-server settings
@YamlComment("Enable teleporting across proxied servers. Requires MySQL")
@@ -347,7 +350,7 @@ public class Settings {
return permissionRestrictWarps;
}
public boolean isOverwriteExistingHomesWarps() {
public boolean doOverwriteExistingHomesWarps() {
return overwriteExistingHomesWarps;
}
@@ -499,6 +502,10 @@ public class Settings {
return disabledCommands;
}
public boolean doBrigadierTabCompletion() {
return brigadierTabCompletion;
}
/**
* Represents where a chat message should display
*/
@@ -3,7 +3,7 @@ package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Logger;
@@ -218,27 +218,27 @@ public abstract class Database {
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition, @NotNull Connection connection) throws SQLException;
/**
* Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date
* Ensure a {@link User} has a {@link SavedUser} entry in the database and that their username is up-to-date
*
* @param user The {@link User} to ensure
*/
public abstract void ensureUser(@NotNull User user);
/**
* Get {@link UserData} for a user by their Minecraft username (<i>case-insensitive</i>)
* Get {@link SavedUser} for a user by their Minecraft username (<i>case-insensitive</i>)
*
* @param name Username of the {@link UserData} to get (<i>case-insensitive</i>)
* @return A future returning an optional with the {@link UserData} present if they exist
* @param name Username of the {@link SavedUser} to get (<i>case-insensitive</i>)
* @return A future returning an optional with the {@link SavedUser} present if they exist
*/
public abstract Optional<UserData> getUserDataByName(@NotNull String name);
public abstract Optional<SavedUser> getUserDataByName(@NotNull String name);
/**
* Get {@link UserData} for a user by their Minecraft account {@link UUID}
* Get {@link SavedUser} for a user by their Minecraft account {@link UUID}
*
* @param uuid Minecraft account {@link UUID} of the {@link UserData} to get
* @return A future returning an optional with the {@link UserData} present if they exist
* @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get
* @return A future returning an optional with the {@link SavedUser} present if they exist
*/
public abstract Optional<UserData> getUserData(@NotNull UUID uuid);
public abstract Optional<SavedUser> getUserData(@NotNull UUID uuid);
/**
@@ -331,11 +331,11 @@ public abstract class Database {
public abstract Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser);
/**
* Updates a user in the database with new {@link UserData}
* Updates a user in the database with new {@link SavedUser}
*
* @param userData The {@link UserData} to update
* @param savedUser The {@link SavedUser} to update
*/
public abstract void updateUserData(@NotNull UserData userData);
public abstract void updateUserData(@NotNull SavedUser savedUser);
/**
* Sets or clears the current {@link Teleport} being executed by a {@link User}
@@ -4,7 +4,7 @@ import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
@@ -278,7 +278,7 @@ public class MySqlDatabase extends Database {
}
@Override
public Optional<UserData> getUserDataByName(@NotNull String name) {
public Optional<SavedUser> getUserDataByName(@NotNull String name) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -288,7 +288,7 @@ public class MySqlDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
return Optional.of(new SavedUser(
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
@@ -303,7 +303,7 @@ public class MySqlDatabase extends Database {
}
@Override
public Optional<UserData> getUserData(@NotNull UUID uuid) {
public Optional<SavedUser> getUserData(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -314,7 +314,7 @@ public class MySqlDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
return Optional.of(new SavedUser(
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
@@ -622,21 +622,21 @@ public class MySqlDatabase extends Database {
}
@Override
public void updateUserData(@NotNull UserData userData) {
public void updateUserData(@NotNull SavedUser savedUser) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, userData.homeSlots());
statement.setBoolean(2, userData.ignoringTeleports());
statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown()));
statement.setString(4, userData.getUserUuid().toString());
statement.setInt(1, savedUser.homeSlots());
statement.setBoolean(2, savedUser.ignoringTeleports());
statement.setTimestamp(3, Timestamp.from(savedUser.rtpCooldown()));
statement.setString(4, savedUser.getUserUuid().toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e);
getLogger().log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e);
}
}
@@ -3,7 +3,7 @@ package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
@@ -274,7 +274,7 @@ public class SqLiteDatabase extends Database {
}
@Override
public Optional<UserData> getUserDataByName(@NotNull String name) {
public Optional<SavedUser> getUserDataByName(@NotNull String name) {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -284,7 +284,7 @@ public class SqLiteDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
return Optional.of(new SavedUser(
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
@@ -299,7 +299,7 @@ public class SqLiteDatabase extends Database {
}
@Override
public Optional<UserData> getUserData(@NotNull UUID uuid) {
public Optional<SavedUser> getUserData(@NotNull UUID uuid) {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -310,7 +310,7 @@ public class SqLiteDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
return Optional.of(new SavedUser(
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
@@ -618,19 +618,19 @@ public class SqLiteDatabase extends Database {
}
@Override
public void updateUserData(@NotNull UserData userData) {
public void updateUserData(@NotNull SavedUser savedUser) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, userData.homeSlots());
statement.setBoolean(2, userData.ignoringTeleports());
statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown()));
statement.setString(4, userData.getUserUuid().toString());
statement.setInt(1, savedUser.homeSlots());
statement.setBoolean(2, savedUser.ignoringTeleports());
statement.setTimestamp(3, Timestamp.from(savedUser.rtpCooldown()));
statement.setString(4, savedUser.getUserUuid().toString());
statement.executeUpdate();
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e);
getLogger().log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e);
}
}
@@ -7,7 +7,7 @@ import com.djrapitops.plan.extension.icon.Color;
import com.djrapitops.plan.extension.icon.Family;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.user.SavedUser;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@@ -107,7 +107,7 @@ public class PlanDataExtension implements DataExtension {
@Conditional("hasData")
public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) {
return database.getUserData(uuid)
.map(UserData::ignoringTeleports)
.map(SavedUser::ignoringTeleports)
.orElse(false);
}
@@ -44,6 +44,9 @@ public class Teleport {
public void execute() throws TeleportationException {
final Optional<OnlineUser> localTeleporter = resolveLocalTeleporter();
// Validate economy actions
validateEconomyActions();
// Teleport a user on another server
if (localTeleporter.isEmpty()) {
final Username teleporter = (Username) this.teleporter;
@@ -73,11 +76,13 @@ public class Teleport {
if (target instanceof Username username) {
final Optional<OnlineUser> localTarget = username.findLocally(plugin);
if (localTarget.isPresent()) {
economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action));
teleporter.teleportLocally(localTarget.get().getPosition(), async);
return;
}
if (plugin.getSettings().isCrossServer()) {
economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action));
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_POSITION)
.target(username.name())
@@ -87,6 +92,7 @@ public class Teleport {
throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND);
}
economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action));
teleporter.teleportLocally((Position) target, async);
}
@@ -98,6 +104,16 @@ public class Teleport {
return Optional.of((OnlineUser) this.teleporter);
}
// Check economy actions
protected void validateEconomyActions() throws TeleportationException {
economyActions.stream()
.map(action -> plugin.validateEconomyCheck(executor, action))
.filter(result -> !result).findFirst()
.ifPresent(result -> {
throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED);
});
}
@NotNull
public Type getType() {
return type;
@@ -117,7 +133,6 @@ public class Teleport {
* Represents the type of teleport being used
*/
public enum Type {
TELEPORT(0),
RESPAWN(1);
@@ -32,12 +32,7 @@ public class TimedTeleport extends Teleport {
this.teleporter = teleporter;
}
/**
* Execute the timed teleport, ticking the countdown and teleporting the player when the countdown is complete
*
* @return a {@link CompletableFuture} that completes when the teleport is complete or has been cancelled
*/
@Override
@Override
public void execute() throws TeleportationException {
// Check if the teleporter can bypass warmup
if (timeLeft == 0 || teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) {
@@ -50,12 +45,8 @@ public class TimedTeleport extends Teleport {
throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP);
}
// Check economy actions
for (EconomyHook.Action action : economyActions) {
if (!plugin.validateEconomyCheck(executor, action)) {
throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED);
}
}
// Validate economy actions
validateEconomyActions();
// Check if they are moving at the start of the teleport
if (teleporter.isMoving()) {
@@ -0,0 +1,23 @@
package net.william278.huskhomes.user;
import de.themoep.minedown.adventure.MineDown;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
public interface CommandUser {
@NotNull
Audience getAudience();
boolean hasPermission(@NotNull String permission);
default void sendMessage(@NotNull Component component) {
getAudience().sendMessage(component);
}
default void sendMessage(@NotNull MineDown mineDown) {
this.sendMessage(mineDown.toComponent());
}
}
@@ -0,0 +1,25 @@
package net.william278.huskhomes.user;
import net.kyori.adventure.audience.Audience;
import org.jetbrains.annotations.NotNull;
public final class ConsoleUser implements CommandUser {
@NotNull
private final Audience audience;
public ConsoleUser(@NotNull Audience console) {
this.audience = console;
}
@Override
@NotNull
public Audience getAudience() {
return audience;
}
@Override
public boolean hasPermission(@NotNull String permission) {
return true;
}
}
@@ -21,7 +21,7 @@ import java.util.concurrent.CompletableFuture;
/**
* A cross-platform representation of a logged-in {@link User}
*/
public abstract class OnlineUser extends User implements Teleportable {
public abstract class OnlineUser extends User implements Teleportable, CommandUser {
public OnlineUser(@NotNull UUID uuid, @NotNull String username) {
super(uuid, username);
@@ -134,7 +134,7 @@ public abstract class OnlineUser extends User implements Teleportable {
* @return the adventure {@link Audience} for this player
*/
@NotNull
protected abstract Audience getAudience();
public abstract Audience getAudience();
/**
* Teleport a player to the specified local {@link Location}
@@ -8,13 +8,14 @@ import java.util.UUID;
/**
* Represents data about a player on the server
*/
public record UserData(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) {
public record SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) {
@NotNull
public UUID getUserUuid() {
return user.getUuid();
}
@NotNull
public String getUsername() {
return user.getUsername();
}