diff --git a/bukkit/src/main/resources/commodore/tp.commodore b/bukkit/src/main/resources/commodore/tp.commodore deleted file mode 100644 index 8c9ed542..00000000 --- a/bukkit/src/main/resources/commodore/tp.commodore +++ /dev/null @@ -1,13 +0,0 @@ -tp { - x|player brigadier:string single_word { - y|x|player brigadier:string single_word { - z|y brigadier:string single_word { - world|z brigadier:string single_word { - server|world brigadier:string single_word { - server brigadier:string single_word; - } - } - } - } - } -} \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 531941d6..860b65ba 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -61,13 +61,14 @@ public interface HuskHomes { * @param playerName the name of the player to find * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found */ + @NotNull default Optional findPlayer(@NotNull String playerName) { - return Optional.ofNullable(getOnlinePlayers().stream() + return getOnlinePlayers().stream() .filter(user -> user.username.equalsIgnoreCase(playerName)) .findFirst() - .orElse(getOnlinePlayers().stream() + .or(() -> getOnlinePlayers().stream() .filter(user -> user.username.toLowerCase().startsWith(playerName.toLowerCase())) - .findFirst().orElse(null))); + .findFirst()); } /** diff --git a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java index e791a18d..880b0942 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -1,7 +1,6 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.HuskHomesException; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; @@ -24,99 +23,119 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe @Override public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { CompletableFuture.runAsync(() -> { - String teleportingUserName = onlineUser.username; - TeleportCommandTarget targetPosition; - - // Validate argument length - if (args.length > 6 || args.length < 1) { + // Ensure a valid target was found + final Optional teleportTarget = getTeleportTarget(args, onlineUser); + if (teleportTarget.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", "/tp [destination]") .ifPresent(onlineUser::sendMessage); return; } - // If the first argument is a player target - if (args.length == 1) { - targetPosition = new TeleportCommandTarget(args[0]); - } else { - // Determine if a player argument has been passed before the destination argument - int coordinatesIndex = ((args.length > 3 && (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]))) - || (args.length == 2)) ? 1 : 0; - if (coordinatesIndex == 1) { - teleportingUserName = args[0]; - } + // Determine the player to teleport + final String targetPlayerToTeleport = ((teleportTarget.get() instanceof TargetPlayer) && args.length == 2) + ? args[0] : ((teleportTarget.get() instanceof TargetPosition) + ? (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]) ? args[0] : onlineUser.username) + : onlineUser.username); - // Determine the target position (player or coordinates) - if (args.length == 2) { - targetPosition = new TeleportCommandTarget(args[1]); - } else { - // Coordinate teleportation requires a permission node - if (!onlineUser.hasPermission(Permission.COMMAND_TP_TO_COORDINATES.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage); - return; - } + // Find the online user to teleport + plugin.getCache().fetchAndCacheGlobalPlayerList(plugin, onlineUser).join(); + final String playerToTeleport = plugin.getCache().players.stream() + .filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst() + .or(() -> plugin.getCache().players.stream() + .filter(user -> user.toLowerCase().startsWith(targetPlayerToTeleport)).findFirst()) + .orElse(null); - // Parse the coordinates and set the target position - final Position userPosition = onlineUser.getPosition(); - final Optional parsedPosition = Position.parse(userPosition, - Arrays.copyOfRange(args, coordinatesIndex, args.length)); - if (parsedPosition.isEmpty()) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/tp [world] [server]") - .ifPresent(onlineUser::sendMessage); - return; - } - targetPosition = new TeleportCommandTarget(parsedPosition.get()); + // Ensure the player to teleport exists + if (playerToTeleport == null) { + plugin.getLocales().getLocale("error_player_not_found", targetPlayerToTeleport) + .ifPresent(onlineUser::sendMessage); + return; + } + + // Ensure the user has permission to teleport the player to teleport + if (!playerToTeleport.equals(onlineUser.username)) { + if (!onlineUser.hasPermission(Permission.COMMAND_TP_OTHER.node)) { + plugin.getLocales().getLocale("error_no_permission") + .ifPresent(onlineUser::sendMessage); + return; } } // Execute the teleport - final String playerToTeleportName = teleportingUserName; - if (targetPosition.targetType == TeleportCommandTarget.TargetType.PLAYER) { - // Teleport players by usernames - assert targetPosition.targetPlayer != null; + if (teleportTarget.get() instanceof TargetPlayer targetPlayer) { + // Handle player teleport targets plugin.getTeleportManager() - .teleportPlayerToPlayerByName(playerToTeleportName, targetPosition.targetPlayer, onlineUser, false) + .teleportNamedPlayers(playerToTeleport, targetPlayer.playerName, onlineUser, false) .thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresentOrElse( result -> { - if (result.successful) { - plugin.getLocales().getLocale("teleporting_other_complete", - playerToTeleportName, targetPosition.targetPlayer) - .ifPresent(onlineUser::sendMessage); + if (!result.successful) { + plugin.getTeleportManager().finishTeleport(onlineUser, result); return; } - plugin.getTeleportManager().finishTeleport(onlineUser, result); + plugin.getLocales().getLocale("teleporting_other_complete", + playerToTeleport, targetPlayer.playerName) + .ifPresent(onlineUser::sendMessage); }, - () -> plugin.getLocales().getLocale("error_player_not_found", playerToTeleportName) + () -> plugin.getLocales().getLocale("error_player_not_found", targetPlayer.playerName) .ifPresent(onlineUser::sendMessage))); - return; - } else if (targetPosition.targetType == TeleportCommandTarget.TargetType.POSITION) { - // Teleport players by specified position - assert targetPosition.targetPosition != null; - plugin.getTeleportManager().teleportPlayerByName(playerToTeleportName, targetPosition.targetPosition, onlineUser, false) - .thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresentOrElse( + } else if (teleportTarget.get() instanceof TargetPosition targetPosition) { + // Handle coordinate teleport targets + if (!onlineUser.hasPermission(Permission.COMMAND_TP_TO_COORDINATES.node)) { + plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage); + return; + } + + plugin.getTeleportManager() + .teleportPlayerByName(playerToTeleport, targetPosition.position, onlineUser, false) + .thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresent( result -> { - if (result.successful && !playerToTeleportName.equalsIgnoreCase(onlineUser.username)) { - plugin.getLocales().getLocale("teleporting_other_complete_position", - playerToTeleportName, - Integer.toString((int) targetPosition.targetPosition.x), - Integer.toString((int) targetPosition.targetPosition.y), - Integer.toString((int) targetPosition.targetPosition.z)) - .ifPresent(onlineUser::sendMessage); + if (!result.successful || playerToTeleport.equalsIgnoreCase(onlineUser.username)) { + plugin.getTeleportManager().finishTeleport(onlineUser, result); return; } - plugin.getTeleportManager().finishTeleport(onlineUser, result); - }, - () -> plugin.getLocales().getLocale("error_player_not_found", playerToTeleportName) - .ifPresent(onlineUser::sendMessage))); - return; + plugin.getLocales().getLocale("teleporting_other_complete_position", + playerToTeleport, + Integer.toString((int) targetPosition.position.x), + Integer.toString((int) targetPosition.position.y), + Integer.toString((int) targetPosition.position.z)) + .ifPresent(onlineUser::sendMessage); + })); } - throw new HuskHomesException("Attempted to execute invalid teleport command operation"); }).exceptionally(throwable -> { plugin.getLoggingAdapter().log(Level.SEVERE, "An error occurred whilst executing a teleport command", throwable); return null; }); } + /** + * Determines the teleport target from a set of arguments, which may be comprised of usernames and/or position + * coordinates with a world and server. + * + * @param args The arguments to parse. + * @param relativeTo The position to use as a relative reference. This is used for relative coordinate handling + * (e.g. {@code ~-10 ~ ~20}) + * @return The teleport target, if it could be parsed, otherwise and empty {@link Optional}. + */ + @NotNull + private Optional getTeleportTarget(@NotNull String[] args, @NotNull OnlineUser relativeTo) { + if (args.length == 1 || args.length == 2) { + return Optional.of(new TargetPlayer(args[args.length - 1])); + } + if (args.length > 2 && args.length < 7) { + final Optional targetPosition = Position.parse(args, relativeTo.getPosition()) + .map(TargetPosition::new); + return targetPosition.or(() -> Position.parse(Arrays.copyOfRange(args, 1, args.length), + relativeTo.getPosition()).map(TargetPosition::new)); + } + return Optional.empty(); + } + + /** + * Determines if a string is a valid (relative) position coordinate double target. + * + * @param coordinate The string to check. + * @return {@code true} if the string is a valid coordinate, otherwise {@code false}. + */ private boolean isCoordinate(@NotNull String coordinate) { try { if (coordinate.startsWith("~")) { @@ -143,12 +162,12 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); return; } - final TeleportCommandTarget teleportCommandTarget; + final TeleportTarget teleportTarget; if (args.length == 2) { - teleportCommandTarget = new TeleportCommandTarget(args[1]); + teleportTarget = new TargetPlayer(args[1]); } else { try { - teleportCommandTarget = new TeleportCommandTarget(new Position( + teleportTarget = new TargetPosition(new Position( Double.parseDouble(args[1]), Double.parseDouble(args[2]), Double.parseDouble(args[3]), @@ -162,14 +181,13 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe } // Execute the console teleport - if (teleportCommandTarget.targetType == TeleportCommandTarget.TargetType.PLAYER) { - assert teleportCommandTarget.targetPlayer != null; + if (teleportTarget instanceof TargetPlayer targetPlayer) { plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username - + " to " + teleportCommandTarget.targetPlayer); - plugin.getTeleportManager().teleportToPlayerByName(playerToTeleport, teleportCommandTarget.targetPlayer, false); + + " to " + targetPlayer.playerName); + plugin.getTeleportManager().teleportToPlayerByName(playerToTeleport, targetPlayer.playerName, false); } else { - assert teleportCommandTarget.targetPosition != null; - plugin.getTeleportManager().teleport(playerToTeleport, teleportCommandTarget.targetPosition) + final TargetPosition targetPosition = (TargetPosition) teleportTarget; + plugin.getTeleportManager().teleport(playerToTeleport, targetPosition.position) .thenAccept(teleportResult -> { if (teleportResult.successful) { plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.username); @@ -257,30 +275,37 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe } /** - * Identifies the target of a teleport command operation + * Represents a target position to teleport to */ - private static class TeleportCommandTarget { + private static final class TargetPosition extends TeleportTarget { + /** + * The target {@link Position} + */ + private final Position position; - @NotNull - private final TargetType targetType; - @Nullable - private String targetPlayer; - @Nullable - private Position targetPosition; - - public TeleportCommandTarget(@NotNull String targetPlayer) { - this.targetPlayer = targetPlayer; - this.targetType = TargetType.PLAYER; + private TargetPosition(@NotNull Position position) { + this.position = position; } - public TeleportCommandTarget(@NotNull Position targetPosition) { - this.targetPosition = targetPosition; - this.targetType = TargetType.POSITION; - } + } - public enum TargetType { - PLAYER, - POSITION + /** + * Represents a target player to teleport to + */ + private static final class TargetPlayer extends TeleportTarget { + /** + * Name of the target player + */ + private final String playerName; + + private TargetPlayer(@NotNull String playerName) { + this.playerName = playerName; } } + + /** + * Identifies the target of a teleport command operation + */ + private static abstract class TeleportTarget { + } } diff --git a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java index a3ef4c2b..ca64d904 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java @@ -75,12 +75,12 @@ public abstract class NetworkMessenger { */ public final CompletableFuture> findPlayer(@NotNull OnlineUser requester, @NotNull String playerName) { return getOnlinePlayerNames(requester).thenApply(networkedPlayers -> - Optional.ofNullable(Arrays.stream(networkedPlayers) + Arrays.stream(networkedPlayers) .filter(user -> user.equalsIgnoreCase(playerName)) .findFirst() - .orElse(Arrays.stream(networkedPlayers) + .or(() -> Arrays.stream(networkedPlayers) .filter(user -> user.toLowerCase().startsWith(playerName)) - .findFirst().orElse(null)))); + .findFirst())); } /** diff --git a/common/src/main/java/net/william278/huskhomes/position/Position.java b/common/src/main/java/net/william278/huskhomes/position/Position.java index ad14916f..6fdee487 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Position.java +++ b/common/src/main/java/net/william278/huskhomes/position/Position.java @@ -33,24 +33,24 @@ public class Position extends Location { /** * Parses the position from a set of values * - * @param values The values to parse + * @param args The values to parse + * @param relativeTo The {@link Position} to use as a reference for relative coordinates * @return The position if it could be parsed, otherwise an empty optional */ - public static Optional parse(@NotNull Position currentPosition, @NotNull String... values) { + public static Optional parse(@NotNull String[] args, @NotNull Position relativeTo) { // Validate argument length - if (values.length < 3 || values.length > 5) { - System.out.println("Invalid syntax"); + if (args.length < 3 || args.length > 5) { return Optional.empty(); } // Parse, handle relatives, and return, catching NumberFormatExceptions and returning an empty optional try { - final double x = parseCoordinate(values[0], currentPosition.x); - final double y = parseCoordinate(values[1], currentPosition.y); - final double z = parseCoordinate(values[2], currentPosition.z); - final World world = values.length > 3 ? new World(values[3], UUID.randomUUID()) : currentPosition.world; - final Server server = values.length > 4 ? new Server(values[4]) : currentPosition.server; - return Optional.of(new Position(x, y, z, currentPosition.yaw, currentPosition.pitch, world, server)); + final double x = parseCoordinate(args[0], relativeTo.x); + final double y = parseCoordinate(args[1], relativeTo.y); + final double z = parseCoordinate(args[2], relativeTo.z); + final World world = args.length > 3 ? new World(args[3], UUID.randomUUID()) : relativeTo.world; + final Server server = args.length > 4 ? new Server(args[4]) : relativeTo.server; + return Optional.of(new Position(x, y, z, relativeTo.yaw, relativeTo.pitch, world, server)); } catch (NumberFormatException ignored) { return Optional.empty(); } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java index 035c27a7..0b61d414 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java @@ -195,15 +195,8 @@ public class TeleportManager { * @param timed whether the teleport is timed ({@code true}), otherwise instant * @return a {@link CompletableFuture} that completes when the teleport is complete with the {@link TeleportResult}, */ - public CompletableFuture> teleportPlayerToPlayerByName(@NotNull String playerName, - @NotNull String targetPlayer, - @NotNull OnlineUser requester, - final boolean timed) { - final Optional localPlayer = plugin.findPlayer(playerName); - final Optional localPositionTarget = localPlayer.map(OnlineUser::getPosition); - if (localPositionTarget.isPresent()) { - return teleportPlayerByName(playerName, localPositionTarget.get(), requester, timed); - } + public CompletableFuture> teleportNamedPlayers(@NotNull String playerName, @NotNull String targetPlayer, + @NotNull OnlineUser requester, final boolean timed) { return getPlayerPositionByName(requester, targetPlayer).thenApply(position -> { if (position.isEmpty()) { return Optional.empty(); diff --git a/common/src/main/java/net/william278/huskhomes/util/Permission.java b/common/src/main/java/net/william278/huskhomes/util/Permission.java index e7276c1e..7b80e344 100644 --- a/common/src/main/java/net/william278/huskhomes/util/Permission.java +++ b/common/src/main/java/net/william278/huskhomes/util/Permission.java @@ -31,7 +31,6 @@ public enum Permission { * Lets the user view the "disabled command" message for disabled commands */ COMMAND_DISABLED_MESSAGE("huskhomes.disabled_command_message", DefaultAccess.EVERYONE), - /** * Lets the user teleport to their homes ({@code /home [home_name]}) */ @@ -92,6 +91,11 @@ public enum Permission { * Lets the user instantly tp to a set of coordinates ({@code /tp [x] [y] [z] [world] [server]}) */ COMMAND_TP_TO_COORDINATES("huskhomes.command.tp.coordinates", DefaultAccess.OPERATORS), + /** + * Lets the user instantly tp another user to a player (and, if they have the {@link Permission#COMMAND_TP_TO_COORDINATES} + * permission, to a set of coordinates) ({@code /tp [player_to_teleport] [target]}) + */ + COMMAND_TP_OTHER("huskhomes.command.tp.other", DefaultAccess.OPERATORS), /** * Lets the user instantly tp another player to them ({@code /tphere [player_name]}) */