From 9ca141a58fd0fe206f1dd7c204203723c6d5cde9 Mon Sep 17 00:00:00 2001 From: William278 Date: Tue, 14 Mar 2023 16:21:26 +0000 Subject: [PATCH] More command refactoring work --- .../william278/huskhomes/BukkitHuskHomes.java | 20 +-- .../huskhomes/command/BukkitCommand.java | 2 +- .../william278/huskhomes/hook/DynMapHook.java | 8 +- .../java/net/william278/huskhomes/Cache.java | 5 +- .../huskhomes/command/HomeCommand.java | 147 ++++------------ .../huskhomes/command/HuskHomesCommand.java | 158 ++++-------------- .../william278/huskhomes/command/Node.java | 6 +- .../huskhomes/command/PrivateHomeCommand.java | 14 ++ .../huskhomes/command/PublicHomeCommand.java | 147 ++-------------- .../command/SavedPositionCommand.java | 4 +- 10 files changed, 116 insertions(+), 395 deletions(-) create mode 100644 common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index b968b449..23747a85 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -7,9 +7,9 @@ import net.william278.desertwell.Version; import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.Command; import net.william278.huskhomes.command.DisabledCommand; -import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; +import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.MySqlDatabase; import net.william278.huskhomes.database.SqLiteDatabase; @@ -22,21 +22,20 @@ import net.william278.huskhomes.manager.Manager; 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; import net.william278.huskhomes.position.World; import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.RandomTeleportEngine; +import net.william278.huskhomes.user.BukkitUser; +import net.william278.huskhomes.user.ConsoleUser; +import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.util.*; import org.bstats.bukkit.Metrics; import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; import org.bukkit.ChunkSnapshot; import org.bukkit.Material; -import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.Plugin; @@ -203,24 +202,19 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Register commands this.registeredCommands = new ArrayList<>(); Arrays.stream(BukkitCommand.Type.values()).forEach(commandType -> { - final PluginCommand pluginCommand = getCommand(commandType.getCommand().getName()); - if (pluginCommand == null) { - return; - } - // 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.getCommand().command) || Arrays.stream(commandType.getCommand().aliases).anyMatch(alias -> alias.equalsIgnoreCase(command)); + return command.equalsIgnoreCase(commandType.getCommand().getName()) || commandType.getCommand().getAliases().stream().anyMatch(alias -> alias.equalsIgnoreCase(command)); })) { - new BukkitCommand(new DisabledCommand(this), this).register(pluginCommand); + new BukkitCommand(new DisabledCommand(this), this).register(); return; } // Otherwise, register the command final Command command = commandType.getCommand(); this.registeredCommands.add(command); - new BukkitCommand(command, this).register(pluginCommand); + new BukkitCommand(command, this).register(); }); log(Level.INFO, "Successfully registered permissions & commands."); diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java index c5726f36..e6dc0e9b 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java @@ -63,7 +63,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { * Commands available on the Bukkit HuskHomes implementation */ public enum Type { - HOME_COMMAND(new HomeCommand(BukkitHuskHomes.getInstance())), + HOME_COMMAND(new PrivateHomeCommand(BukkitHuskHomes.getInstance())), SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())), HOME_LIST_COMMAND(new HomeListCommand(BukkitHuskHomes.getInstance())), DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())), diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java index 9a41af46..670c9fdd 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java @@ -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().wrapText(home.getMeta().getDescription())) - .addField("Command", "/" + BukkitCommand.Type.PUBLIC_HOME_COMMAND.getCommand().command + " " + home.getMeta().getName()) + .addField("Description", plugin.getLocales().wrapText(home.getMeta().getDescription(), 60)) + .addField("Command", "/" + BukkitCommand.Type.PUBLIC_HOME_COMMAND.getCommand().getName() + " " + 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().wrapText(warp.getMeta().getDescription())) - .addField("Command", "/" + BukkitCommand.Type.WARP_COMMAND.getCommand().command + " " + warp.getMeta().getName()) + .addField("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60)) + .addField("Command", "/" + BukkitCommand.Type.WARP_COMMAND.getCommand().getName() + " " + warp.getMeta().getName()) .toHtml()); updatedFuture.complete(null); })); diff --git a/common/src/main/java/net/william278/huskhomes/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java index 5e0f4557..6f930461 100644 --- a/common/src/main/java/net/william278/huskhomes/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/Cache.java @@ -4,6 +4,7 @@ import de.themoep.minedown.adventure.MineDown; import net.william278.huskhomes.command.Command; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.position.Home; @@ -175,10 +176,10 @@ public class Cache { } @NotNull - public MineDown getCommandList(@NotNull OnlineUser onlineUser, @NotNull Locales locales, + public MineDown getCommandList(@NotNull CommandUser user, @NotNull Locales locales, @NotNull List commands, final int itemsPerPage, final int page) { return PaginatedList.of(commands.stream() - .filter(command -> onlineUser.hasPermission(command.getPermission())) + .filter(command -> user.hasPermission(command.getPermission())) .map(command -> locales.getRawLocale("command_list_item", Locales.escapeText(command.getName()), Locales.escapeText(command.getDescription().length() > 50 diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java index f058ab2d..289480ae 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -1,134 +1,53 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TimedTeleport; +import net.william278.huskhomes.teleport.Teleportable; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.Level; -import java.util.stream.Collectors; +import java.util.Optional; -public class HomeCommand extends Command implements TabProvider, ConsoleExecutable { +public abstract class HomeCommand extends SavedPositionCommand { - protected HomeCommand(@NotNull HuskHomes implementor) { - super("home", Permission.COMMAND_HOME, implementor); + protected HomeCommand(@NotNull String name, @NotNull List aliases, @NotNull HuskHomes plugin) { + super(name, aliases, Home.class, List.of(), plugin); } @Override - public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { - switch (args.length) { - case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAcceptAsync(homes -> { - // Send the home list if they have homes set. If they have just one home set, teleport the player - switch (homes.size()) { - case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage); - case 1 -> Teleport.builder(plugin, onlineUser) - .setTarget(homes.get(0)) - .toTimedTeleport().thenAccept(TimedTeleport::execute); - default -> plugin.getCache().getHomeList(onlineUser, onlineUser, - plugin.getLocales(), homes, plugin.getSettings().getListItemsPerPage(), 1) - .ifPresent(onlineUser::sendMessage); - } - }); - case 1 -> { - // Parse the home name input and teleport the player to the home - final String homeName = args[0]; - RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse( - homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName()) - .thenAccept(optionalUserData -> optionalUserData.ifPresentOrElse( - userData -> teleportToNamedHome(onlineUser, userData.user(), homeIdentifier.homeName()), - () -> plugin.getLocales().getLocale("error_home_invalid_other", homeIdentifier.ownerName(), homeIdentifier.homeName()) - .ifPresent(onlineUser::sendMessage))), - () -> teleportToNamedHome(onlineUser, onlineUser, homeName)); - } - default -> plugin.getLocales().getLocale("error_invalid_syntax", "/home [name]") - .ifPresent(onlineUser::sendMessage); - } - } - - private void teleportToNamedHome(@NotNull OnlineUser teleporter, @NotNull User owner, @NotNull String homeName) { - final boolean otherHome = !owner.equals(teleporter); - plugin.getDatabase() - .getHome(owner, homeName) - .thenAccept(homeResult -> homeResult.ifPresentOrElse(home -> { - if (otherHome && !home.isPublic) { - if (!teleporter.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { - plugin.getLocales().getLocale("error_no_permission") - .ifPresent(teleporter::sendMessage); - return; - } - } - Teleport.builder(plugin, teleporter) - .setTarget(home) - .toTimedTeleport() - .thenAccept(TimedTeleport::execute); - }, () -> { - if (otherHome) { - plugin.getLocales().getLocale("error_home_invalid_other", owner.getUsername(), homeName) - .ifPresent(teleporter::sendMessage); - } else { - plugin.getLocales().getLocale("error_home_invalid", homeName) - .ifPresent(teleporter::sendMessage); - } - })); - } - - @Override - public void onConsoleExecute(@NotNull String[] args) { - if (args.length != 2) { - plugin.log(Level.WARNING, "Invalid syntax. Usage: home "); + public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) { + final Optional optionalTeleporter = parseStringArg(args, 0).map(Teleportable::username) + .or(() -> executor instanceof Teleportable ? Optional.of((Teleportable) executor) : Optional.empty()); + if (optionalTeleporter.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) + .ifPresent(executor::sendMessage); return; } - CompletableFuture.runAsync(() -> { - final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); - if (playerToTeleport == null) { - plugin.log(Level.WARNING, "Player not found: " + args[0]); - return; - } - final AtomicReference matchedHome = new AtomicReference<>(null); - RegexUtil.matchDisambiguatedHomeIdentifier(args[1]).ifPresentOrElse( - identifier -> matchedHome.set(plugin.getDatabase().getUserDataByName(identifier.ownerName()).join() - .flatMap(user -> plugin.getDatabase().getHome(user.user(), identifier.homeName()).join()) - .orElse(null)), - () -> matchedHome.set(plugin.getDatabase().getUserDataByName(playerToTeleport.getUsername()).join() - .flatMap(user -> plugin.getDatabase().getHome(user.user(), args[1]).join()) - .orElse(null))); - final Home home = matchedHome.get(); - if (home == null) { - plugin.log(Level.WARNING, "Could not find home '" + args[1] + "'"); - return; - } - - plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " - + home.getOwner().getUsername() + "." + home.getMeta().getName()); - Teleport.builder(plugin, playerToTeleport) - .setTarget(home) - .toTeleport() - .thenAccept(Teleport::execute); - }); - } - - @Override - @NotNull - public final List suggest(@NotNull CommandUser user, @NotNull String[] args) { - if (user == null) { - return Collections.emptyList(); + if (executor instanceof OnlineUser user && !user.hasPermission(getOtherPermission()) + && (!home.getOwner().equals(user) && !home.isPublic())) { + plugin.getLocales().getLocale("error_public_home_invalid", + home.getOwner().getUsername(), home.getName()) + .ifPresent(executor::sendMessage); + return; } - return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes() - .getOrDefault(user.getUuid(), new ArrayList<>()) - .stream() - .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) - .sorted() - .collect(Collectors.toList()); + + final Teleportable teleporter = optionalTeleporter.get(); + if (!teleporter.equals(executor) && !executor.hasPermission(Permission.COMMAND_TP_OTHER.node)) { + plugin.getLocales().getLocale("error_no_permission") + .ifPresent(executor::sendMessage); + return; + } + + Teleport.builder(plugin) + .teleporter(teleporter) + .target(home) + .toTimedTeleport() + .execute(); } + } diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index 7edbac1f..e51a349f 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -3,24 +3,18 @@ package net.william278.huskhomes.command; import de.themoep.minedown.adventure.MineDown; import net.william278.desertwell.AboutMenu; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.util.Permission; +import net.william278.huskhomes.user.CommandUser; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.util.Arrays; -import java.util.Collections; import java.util.List; -import java.util.logging.Level; -import java.util.stream.Collectors; -public class HuskHomesCommand extends Command implements ConsoleExecutable, TabProvider { +public class HuskHomesCommand extends Command { - private final String[] SUB_COMMANDS = {"about", "help", "reload", "update"}; + private static final List SUB_COMMANDS = List.of("about", "help", "reload", "update"); private final AboutMenu aboutMenu; protected HuskHomesCommand(@NotNull HuskHomes implementor) { - super("huskhomes", Permission.COMMAND_HUSKHOMES, implementor); + super("huskhomes", List.of(), "[" + String.join("|", SUB_COMMANDS) + "]", implementor); this.aboutMenu = AboutMenu.create("HuskHomes") .withDescription("A powerful, intuitive and flexible teleportation suite") .withVersion(implementor.getVersion()) @@ -47,124 +41,46 @@ public class HuskHomesCommand extends Command implements ConsoleExecutable, TabP } @Override - public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { - if (args.length == 0) { - sendAboutMenu(onlineUser); - return; - } - if (args.length > 2) { - plugin.getLocales().getLocale("error_invalid_syntax", "/huskhomes [about|help|reload|update]") - .ifPresent(onlineUser::sendMessage); - return; - } - switch (args[0].toLowerCase()) { - case "about" -> sendAboutMenu(onlineUser); - case "help" -> { - if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_HELP.node)) { - plugin.getLocales().getLocale("error_no_permission") - .ifPresent(onlineUser::sendMessage); - return; - } - int page = 1; - if (args.length == 2) { - try { - page = Integer.parseInt(args[1]); - } catch (NumberFormatException ignored) { - plugin.getLocales().getLocale("error_invalid_syntax", "/huskhomes help ") - .ifPresent(onlineUser::sendMessage); - return; - } - } - onlineUser.sendMessage(plugin.getCache().getCommandList(onlineUser, - plugin.getLocales(), plugin.getCommands(), plugin.getSettings().getListItemsPerPage(), page)); - } - case "reload" -> { - if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_RELOAD.node)) { - plugin.getLocales().getLocale("error_no_permission") - .ifPresent(onlineUser::sendMessage); - return; - } - if (!plugin.reload()) { - onlineUser.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)")); - return; - } - onlineUser.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) �fb9a&| Reloaded config & message files.")); - } - case "update" -> { - if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_UPDATE.node)) { - plugin.getLocales().getLocale("error_no_permission") - .ifPresent(onlineUser::sendMessage); - return; - } - plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresentOrElse( - newVersion -> onlineUser.sendMessage( - new MineDown("[HuskHomes](#00fb9a bold) [| A new version of HuskHomes is available!" - + " (v" + newVersion + " (Running: v" + plugin.getVersion() + ")](#00fb9a)")), - () -> onlineUser.sendMessage( - new MineDown("[HuskHomes](#00fb9a bold) [| HuskHomes is up-to-date." - + " (Running: v" + plugin.getVersion() + ")](#00fb9a)")))); - } - case "migrate" -> plugin.getLocales().getLocale("error_console_command_only") - .ifPresent(onlineUser::sendMessage); - default -> plugin.getLocales().getLocale("error_invalid_syntax", "/huskhomes [about|help|reload|update]") - .ifPresent(onlineUser::sendMessage); - } - } - - @Override - public void onConsoleExecute(@NotNull String[] args) { - if (args.length == 0) { - Arrays.stream(aboutMenu.toString().split("\n")).forEach(message -> - plugin.log(Level.INFO, message)); - return; - } - switch (args[0].toLowerCase()) { - case "about" -> Arrays.stream(aboutMenu.toString().split("\n")).forEach(message -> - plugin.log(Level.INFO, message)); - case "help" -> { - plugin.log(Level.INFO, "List of enabled console-executable commands:"); - plugin.getCommands() - .stream().filter(command -> command instanceof ConsoleExecutable) - .forEach(command -> plugin.log(Level.INFO, - command.command + - (command.command.length() < 16 ? " ".repeat(16 - command.command.length()) : "") - + " - " + command.getDescription())); - } - case "reload" -> { - if (!plugin.reload()) { - plugin.log(Level.SEVERE, "Failed to reload the plugin."); - return; - } - plugin.log(Level.INFO, "Reloaded config & message files."); - } - case "update" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresentOrElse(newVersion -> plugin.log(Level.WARNING, - "An update is available for HuskHomes, v" + newVersion - + " (Running v" + plugin.getVersion() + ")"), - () -> plugin.log(Level.INFO, - "HuskHomes is up to date" + - " (Running v" + plugin.getVersion() + ")"))); - } - } - - private void sendAboutMenu(@NotNull OnlineUser onlineUser) { - if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_ABOUT.node)) { + public void execute(@NotNull CommandUser executor, @NotNull String[] args) { + final String action = parseStringArg(args, 0).orElse("about"); + if (SUB_COMMANDS.contains(action) && !executor.hasPermission(getPermission(action))) { plugin.getLocales().getLocale("error_no_permission") - .ifPresent(onlineUser::sendMessage); + .ifPresent(executor::sendMessage); return; } - onlineUser.sendMessage(aboutMenu.toMineDown()); + + switch (action.toLowerCase()) { + case "about" -> executor.sendMessage(aboutMenu.toMineDown()); + case "help" -> executor.sendMessage(plugin.getCache().getCommandList(executor, plugin.getLocales(), + plugin.getCommands(), plugin.getSettings().getListItemsPerPage(), + parseIntArg(args, 1).orElse(1))); + case "reload" -> { + if (!plugin.reload()) { + executor.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)")); + return; + } + executor.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) �fb9a&| Reloaded config & message files.")); + } + case "update" -> plugin.getLatestVersionIfOutdated() + .thenAccept(newestVersion -> newestVersion.ifPresentOrElse( + newVersion -> executor.sendMessage( + new MineDown("[HuskHomes](#00fb9a bold) [| A new version of HuskHomes is available!" + + " (v" + newVersion + " (Running: v" + plugin.getVersion() + ")](#00fb9a)")), + () -> executor.sendMessage( + new MineDown("[HuskHomes](#00fb9a bold) [| HuskHomes is up-to-date." + + " (Running: v" + plugin.getVersion() + ")](#00fb9a)")))); + default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) + .ifPresent(executor::sendMessage); + } } @Override @NotNull - public final List suggest(@NotNull CommandUser user, @NotNull String[] args) { - if (args.length == 0 || args.length == 1) { - return Arrays.stream(SUB_COMMANDS) - .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) - .sorted().collect(Collectors.toList()); + public List suggest(@NotNull CommandUser user, @NotNull String[] args) { + if (args.length < 2) { + return filter(SUB_COMMANDS, args); } - return Collections.emptyList(); + return List.of(); } + } diff --git a/common/src/main/java/net/william278/huskhomes/command/Node.java b/common/src/main/java/net/william278/huskhomes/command/Node.java index fd561ee6..fb6b9d1a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/Node.java +++ b/common/src/main/java/net/william278/huskhomes/command/Node.java @@ -43,10 +43,12 @@ public abstract class Node implements Executable { } @NotNull - public String getPermission() { + public String getPermission(@NotNull String... child) { return new StringJoiner(".") .add(PERMISSION_PREFIX) - .add(getName()).toString(); + .add(getName()) + .add(String.join(".", child)) + .toString(); } public boolean canPerform(@NotNull CommandUser user) { diff --git a/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java new file mode 100644 index 00000000..8a41cdfc --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java @@ -0,0 +1,14 @@ +package net.william278.huskhomes.command; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class PrivateHomeCommand extends HomeCommand { + + protected PrivateHomeCommand(@NotNull HuskHomes plugin) { + super("home", List.of(), plugin); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java index 797b312e..a188c406 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -1,149 +1,24 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.User; -import net.william278.huskhomes.position.Home; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.Level; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -public class PublicHomeCommand extends Command implements TabProvider, ConsoleExecutable { +public class PublicHomeCommand extends HomeCommand { - protected PublicHomeCommand(@NotNull HuskHomes implementor) { - super("publichome", Permission.COMMAND_PUBLIC_HOME, implementor, "phome"); - } - - @Override - public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { - switch (args.length) { - case 0 -> plugin.getDatabase().getPublicHomes().thenAcceptAsync(publicHomes -> { - // Display the public home list if there are any public home set - if (publicHomes.size() == 0) { - plugin.getLocales().getLocale("error_no_public_homes_set").ifPresent(onlineUser::sendMessage); - return; - } - - plugin.getCache().getPublicHomeList(onlineUser, plugin.getLocales(), - publicHomes, plugin.getSettings().getListItemsPerPage(), 1) - .ifPresent(onlineUser::sendMessage); - }); - case 1 -> { - final String homeName = args[0]; - // Match the input to a home identifier and teleport - RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse( - homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName()) - .thenAccept(optionalUserData -> optionalUserData.ifPresentOrElse( - userData -> teleportToNamedHome(onlineUser, userData.user(), homeIdentifier.homeName()), - () -> plugin.getLocales().getLocale("error_home_invalid_other", homeIdentifier.ownerName(), homeIdentifier.homeName()) - .ifPresent(onlineUser::sendMessage))), - () -> plugin.getDatabase().getPublicHomes().thenAccept(publicHomes -> { - // If the identifier format was not used, attempt to teleport the player to the closest match - final List homeMatches = publicHomes.stream() - .filter(home -> home.meta.name.equalsIgnoreCase(homeName)).toList(); - if ((long) homeMatches.size() == 1) { - Teleport.builder(plugin, onlineUser) - .setTarget(homeMatches.get(0)) - .toTimedTeleport().thenAccept(TimedTeleport::execute); - } else { - plugin.getLocales().getLocale("error_invalid_syntax", "/publichome [.]") - .ifPresent(onlineUser::sendMessage); - } - })); - } - default -> plugin.getLocales().getLocale("error_invalid_syntax", "/publichome [.]") - .ifPresent(onlineUser::sendMessage); - } - } - - private void teleportToNamedHome(@NotNull OnlineUser teleporter, @NotNull User owner, @NotNull String homeName) { - final boolean otherHome = !owner.equals(teleporter); - plugin.getDatabase() - .getHome(owner, homeName) - .thenAccept(homeResult -> homeResult.ifPresentOrElse(home -> { - if (otherHome && !home.isPublic) { - if (!teleporter.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { - plugin.getLocales().getLocale("error_no_permission") - .ifPresent(teleporter::sendMessage); - return; - } - } - Teleport.builder(plugin, teleporter) - .setTarget(home) - .toTimedTeleport() - .thenAccept(TimedTeleport::execute); - }, () -> { - if (otherHome) { - plugin.getLocales().getLocale("error_home_invalid_other", owner.getUsername(), homeName) - .ifPresent(teleporter::sendMessage); - } else { - plugin.getLocales().getLocale("error_home_invalid", homeName) - .ifPresent(teleporter::sendMessage); - } - })); - } - - @Override - public void onConsoleExecute(@NotNull String[] args) { - if (args.length != 2) { - plugin.log(Level.WARNING, "Invalid syntax. Usage: publichome <[owner_name].[home_name]>"); - return; - } - CompletableFuture.runAsync(() -> { - final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); - if (playerToTeleport == null) { - plugin.log(Level.WARNING, "Player not found: " + args[0]); - return; - } - final AtomicReference matchedHome = new AtomicReference<>(null); - RegexUtil.matchDisambiguatedHomeIdentifier(args[1]).ifPresentOrElse( - identifier -> matchedHome.set(plugin.getDatabase().getUserDataByName(identifier.ownerName()).join() - .flatMap(user -> plugin.getDatabase().getHome(user.user(), identifier.homeName()).join()) - .orElse(null)), - () -> matchedHome.set(plugin.getDatabase().getPublicHomes().join() - .stream() - .filter(home -> home.owner.equals(playerToTeleport) && home.meta.name.equalsIgnoreCase(args[1])) - .findFirst() - .orElse(null))); - - final Home home = matchedHome.get(); - if (home == null) { - plugin.log(Level.WARNING, "Could not find public home '" + args[1] + "'"); - return; - } - - plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " - + home.getOwner().getUsername() + "." + home.getMeta().getName()); - Teleport.builder(plugin, playerToTeleport) - .setTarget(home) - .toTeleport() - .thenAccept(Teleport::execute); - }); + protected PublicHomeCommand(@NotNull HuskHomes plugin) { + super("phome", List.of("publichome"), plugin); } @Override @NotNull - public final List suggest(@NotNull CommandUser user, @NotNull String[] args) { - // Return every public home name as username.home_name from the cache - final List publicHomes = new ArrayList<>(); - plugin.getCache().getPublicHomes().forEach((ownerName, homeNames) -> - homeNames.forEach(homeName -> publicHomes.add(ownerName + "." + homeName))); - return args.length > 1 ? Collections.emptyList() : publicHomes - .stream() - .filter(publicHomeIdentifier -> publicHomeIdentifier.split(Pattern.quote("."))[1].toLowerCase() - .startsWith(args.length == 1 ? args[0].toLowerCase() : "")) - .sorted() - .collect(Collectors.toList()); + public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { + if (args.length <= 2) { + return filter(reduceHomeList(plugin.getCache().getHomes()), args); + } + return List.of(); } -} + +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index 54e9c433..bd2acd0c 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -27,7 +27,7 @@ public abstract class SavedPositionCommand extends Comm @NotNull public String getOtherPermission() { - return (positionType == Home.class ? super.getPermission() + ".other" : super.getPermission()); + return (positionType == Home.class ? super.getPermission("other") : super.getPermission()); } @SuppressWarnings("unchecked") @@ -120,7 +120,7 @@ public abstract class SavedPositionCommand extends Comm } @NotNull - private static List reduceHomeList(@NotNull Map> cachedMap) { + protected static List reduceHomeList(@NotNull Map> cachedMap) { final List homeNames = new ArrayList<>(); cachedMap.forEach((key, value) -> value.forEach(home -> homeNames.add(key + "." + home))); return homeNames;