From ace4e48827f975f365ac61ef3d2be750d669ad4f Mon Sep 17 00:00:00 2001 From: William Date: Sat, 28 May 2022 00:01:09 +0100 Subject: [PATCH] Sethome and home implementation --- .../william278/huskhomes/HuskHomesBukkit.java | 14 +- .../huskhomes/player/BukkitPlayer.java | 12 +- .../net/william278/huskhomes/HuskHomes.java | 8 + .../huskhomes/command/HomeCommand.java | 18 +- .../huskhomes/command/SetHomeCommand.java | 62 +++++++ .../huskhomes/listener/EventProcessor.java | 42 +++-- .../william278/huskhomes/player/Player.java | 18 ++ .../position/SavedPositionManager.java | 155 ++++++++++++++++++ .../huskhomes/teleport/TeleportManager.java | 135 +++++++++------ .../huskhomes/teleport/TeleportResult.java | 7 +- .../util/EconomyUnsupportedException.java | 12 ++ common/src/main/resources/languages/en-gb.yml | 3 +- 12 files changed, 413 insertions(+), 73 deletions(-) create mode 100644 common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java create mode 100644 common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/EconomyUnsupportedException.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java index 1636b542..7eaaab14 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java +++ b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java @@ -10,6 +10,7 @@ import net.william278.huskhomes.cache.Cache; import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.CommandBase; import net.william278.huskhomes.command.HomeCommand; +import net.william278.huskhomes.command.SetHomeCommand; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.data.Database; @@ -22,6 +23,7 @@ import net.william278.huskhomes.player.Player; import net.william278.huskhomes.player.BukkitPlayer; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; +import net.william278.huskhomes.position.SavedPositionManager; import net.william278.huskhomes.teleport.BukkitTeleportManager; import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.util.BukkitLogger; @@ -58,7 +60,7 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { private Database database; private Cache cache; private TeleportManager teleportManager; - + private SavedPositionManager savedPositionManager; @Nullable private NetworkMessenger networkMessenger; @@ -136,8 +138,11 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { // Prepare the teleport manager this.teleportManager = new BukkitTeleportManager(this); + // Prepare the home and warp position manager + this.savedPositionManager = new SavedPositionManager(database, cache); + // Register commands - todo add all here - final CommandBase[] commands = new CommandBase[]{new HomeCommand(this)}; + final CommandBase[] commands = new CommandBase[]{new HomeCommand(this), new SetHomeCommand(this)}; for (CommandBase commandBase : commands) { final PluginCommand pluginCommand = getCommand(commandBase.command); if (pluginCommand != null) { @@ -192,6 +197,11 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { return teleportManager; } + @Override + public SavedPositionManager getSettingManager() { + return savedPositionManager; + } + @Override public @Nullable NetworkMessenger getNetworkMessenger() { return networkMessenger; diff --git a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java index 5a617e9c..728b8869 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java +++ b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java @@ -5,8 +5,8 @@ import io.papermc.lib.PaperLib; import net.william278.huskhomes.HuskHomesBukkit; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.TeleportResult; +import net.william278.huskhomes.util.EconomyUnsupportedException; import org.bukkit.Bukkit; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.plugin.Plugin; @@ -118,6 +118,16 @@ public class BukkitPlayer implements Player { return null; //todo } + @Override + public double getEconomyBalance() throws EconomyUnsupportedException { + return 0; + } + + @Override + public void deductEconomyBalance() throws EconomyUnsupportedException { + + } + /** * Send a Bukkit plugin message */ diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index dfc86712..b46dc795 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -8,6 +8,7 @@ import net.william278.huskhomes.messenger.NetworkMessenger; import net.william278.huskhomes.player.Player; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; +import net.william278.huskhomes.position.SavedPositionManager; import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.util.Logger; import org.jetbrains.annotations.NotNull; @@ -71,6 +72,13 @@ public interface HuskHomes { */ TeleportManager getTeleportManager(); + /** + * The {@link SavedPositionManager} that manages setting homes and warps + * + * @return the {@link SavedPositionManager} implementation + */ + SavedPositionManager getSettingManager(); + /** * The {@link NetworkMessenger} that sends cross-network messages * 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 53bade1a..70fd9874 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -4,6 +4,7 @@ import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.list.PrivateHomeList; import net.william278.huskhomes.player.Player; import net.william278.huskhomes.player.User; +import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -23,7 +24,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE case 0 -> plugin.getDatabase().getHomes(new User(player)).thenAccept(homes -> { switch (homes.size()) { case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(player::sendMessage); - case 1 -> plugin.getTeleportManager().executeTeleport(player, homes.get(0)).thenAccept(result -> + case 1 -> plugin.getTeleportManager().teleport(player, homes.get(0)).thenAccept(result -> plugin.getTeleportManager().finishTeleport(player, result)); default -> { final User user = new User(player.getUuid(), player.getName()); @@ -36,8 +37,17 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE } }); case 1 -> { - //todo check if its a public home, process. Support sending a player - plugin.getTeleportManager().teleportToHome(player, new User(player), args[0]); + final String homeName = args[0]; + if (RegexUtil.OWNER_NAME_PATTERN.matcher(homeName).matches()) { + final String ownerName = homeName.split("\\.")[0]; + final String ownersHomeName = homeName.split("\\.")[1]; + plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData + .ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(player, userData, ownersHomeName), + () -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName) + .ifPresent(player::sendMessage))); + } else { + plugin.getTeleportManager().teleportToHome(player, new User(player), homeName); + } } default -> plugin.getLocales().getLocale("error_invalid_syntax", "/home [name]") .ifPresent(player::sendMessage); @@ -53,6 +63,6 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE @Override public void onConsoleExecute(@NotNull String[] args) { - + //todo } } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java new file mode 100644 index 00000000..7c0b3af8 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java @@ -0,0 +1,62 @@ +package net.william278.huskhomes.command; + +import de.themoep.minedown.MineDown; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.list.PrivateHomeList; +import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.PositionMeta; +import net.william278.huskhomes.util.RegexUtil; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.stream.Collectors; + +public class SetHomeCommand extends CommandBase { + + private final static String PERMISSION = "huskhomes.command.sethome"; + + public SetHomeCommand(@NotNull HuskHomes implementor) { + super("sethome", PERMISSION, implementor); + } + + @Override + public void onExecute(@NotNull Player player, @NotNull String[] args) { + final User user = new User(player); + switch (args.length) { + case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> { + if (homes.isEmpty()) { + setHome(player, user, "home"); + } else { + plugin.getLocales().getLocale("error_invalid_syntax", "/sethome ") + .ifPresent(player::sendMessage); + } + }); + case 1 -> setHome(player, user, args[0]); + default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome ") + .ifPresent(player::sendMessage); + } + } + + private void setHome(@NotNull Player player, @NotNull User user, @NotNull String homeName) { + player.getPosition().thenAccept(position -> plugin.getSettingManager().setHome(new PositionMeta(homeName, + plugin.getLocales().getRawLocale("home_default_description").orElse("")), + user, position).thenAcceptAsync(setResult -> { + player.sendMessage(switch (setResult.resultType()) { + case SUCCESS -> { + assert setResult.setPosition() != null; + yield plugin.getLocales().getLocale("set_home_success", setResult.setPosition().meta.name) + .orElse(new MineDown("")); + } + case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_set_home_name_taken") + .orElse(new MineDown("")); + case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_set_home_invalid_length") + .orElse(new MineDown("")); + case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_set_home_invalid_characters") + .orElse(new MineDown("")); + default -> new MineDown(""); + }); + })); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java b/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java index b181ded7..2d0ead85 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java @@ -14,10 +14,10 @@ import java.util.stream.Collectors; public class EventProcessor { @NotNull - protected final HuskHomes implementor; + protected final HuskHomes plugin; public EventProcessor(@NotNull HuskHomes implementor) { - this.implementor = implementor; + this.plugin = implementor; } /** @@ -27,30 +27,36 @@ public class EventProcessor { */ public void onPlayerJoin(@NotNull Player player) { // Ensure the player is present on the database first - implementor.getDatabase().ensureUser(player).thenRun(() -> { + plugin.getDatabase().ensureUser(player).thenRun(() -> { // If the server is in proxy mode, check if the player is teleporting cross-server and handle - if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { - implementor.getDatabase().getCurrentTeleport(new User(player)) + if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + plugin.getDatabase().getCurrentTeleport(new User(player)) .thenAccept(teleport -> teleport.ifPresent(currentTeleport -> + // Teleport the player locally player.teleport(currentTeleport.target).thenAccept(teleportResult -> { if (!teleportResult.successful) { - implementor.getLocales().getLocale("error_invalid_on_arrival") + plugin.getLocales().getLocale("error_invalid_on_arrival") .ifPresent(player::sendMessage); } else { - implementor.getLocales().getLocale("teleporting_complete") + plugin.getLocales().getLocale("teleporting_complete") .ifPresent(player::sendMessage); } }))); // Update the player list - assert implementor.getNetworkMessenger() != null; - implementor.getCache().updatePlayerList(implementor, player); + assert plugin.getNetworkMessenger() != null; + plugin.getCache().updatePlayerList(plugin, player); } // Cache this user's homes - implementor.getDatabase().getHomes(new User(player)).thenAccept(homes -> - implementor.getCache().homes.put(player.getUuid(), + plugin.getDatabase().getHomes(new User(player)).thenAccept(homes -> + plugin.getCache().homes.put(player.getUuid(), homes.stream().map(home -> home.meta.name).collect(Collectors.toList()))); + + // Ensure the server has been set + if (plugin.getOnlinePlayers().size() == 1) { + plugin.getServer(player); + } }); } @@ -61,16 +67,20 @@ public class EventProcessor { */ public void onPlayerLeave(@NotNull Player player) { // Remove this user's home cache - implementor.getCache().homes.remove(player.getUuid()); + plugin.getCache().homes.remove(player.getUuid()); // Update the player list - if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { - assert implementor.getNetworkMessenger() != null; - implementor.getOnlinePlayers().stream().filter( + if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + assert plugin.getNetworkMessenger() != null; + plugin.getOnlinePlayers().stream().filter( onlinePlayer -> !onlinePlayer.getUuid().equals(player.getUuid())) .findAny().ifPresent(updater -> - implementor.getCache().updatePlayerList(implementor, updater)); + plugin.getCache().updatePlayerList(plugin, updater)); } + + // Set offline position + player.getPosition().thenAcceptAsync(position -> plugin.getDatabase().setOfflinePosition( + new User(player.getUuid(), player.getName()), position)); } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/player/Player.java b/common/src/main/java/net/william278/huskhomes/player/Player.java index fc2d5952..26348c0b 100644 --- a/common/src/main/java/net/william278/huskhomes/player/Player.java +++ b/common/src/main/java/net/william278/huskhomes/player/Player.java @@ -3,7 +3,9 @@ package net.william278.huskhomes.player; import de.themoep.minedown.MineDown; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.Server; import net.william278.huskhomes.teleport.TeleportResult; +import net.william278.huskhomes.util.EconomyUnsupportedException; import org.jetbrains.annotations.NotNull; import java.util.UUID; @@ -85,4 +87,20 @@ public interface Player { */ CompletableFuture getFreeHomes(); + /** + * Get this player's economy balance + * + * @return the player's economy balance + * @throws EconomyUnsupportedException if the economy integration is not enabled + */ + double getEconomyBalance() throws EconomyUnsupportedException; + + /** + * Deduct money from this player's economy balance + * + * @throws EconomyUnsupportedException if the economy integration is not enabled + */ + void deductEconomyBalance() throws EconomyUnsupportedException; + + } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java new file mode 100644 index 00000000..f136b851 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java @@ -0,0 +1,155 @@ +package net.william278.huskhomes.position; + +import net.william278.huskhomes.cache.Cache; +import net.william278.huskhomes.data.Database; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.util.RegexUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * Cross-platform manager for validating homes and warps and updating them as neccessary + */ +public class SavedPositionManager { + + /** + * The {@link Database} implementation used to add homes to the database + */ + private final Database database; + + /** + * The {@link Cache} the holds cached home and warp data, updated when setting home + */ + private final Cache cache; + + public SavedPositionManager(@NotNull Database database, @NotNull Cache cache) { + this.database = database; + this.cache = cache; + } + + /** + * Tries to create a {@link Home} for a {@link User} at the specified {@link Position} from supplied + * {@link PositionMeta} data and add it to the database + * + * @param homeMeta metadata about the home + * @param homeOwner the owner of the home + * @param position where the home should be set + * @return a future supplying the {@link SetResult}; the result of setting the home + */ + public CompletableFuture setHome(@NotNull PositionMeta homeMeta, @NotNull User homeOwner, + @NotNull Position position) { + return CompletableFuture.supplyAsync(() -> + validateMeta(homeMeta).map(resultType -> new SetResult(resultType, null)).orElseGet(() -> + database.getHome(homeOwner, homeMeta.name).thenApply(optionalWarp -> { + if (optionalWarp.isEmpty()) { + final Home home = new Home(position, homeMeta, homeOwner); + cache.homes.computeIfAbsent(home.owner.uuid, key -> + new ArrayList<>()).add(home.meta.name); + return database.setHome(home).thenApply(ignored -> + new SetResult(SetResult.ResultType.SUCCESS, home)).join(); + } + return new SetResult(SetResult.ResultType.FAILED_DUPLICATE, null); + }).join())); + } + + /** + * Tries to create a server {@link Warp} at the specified {@link Position} from supplied + * {@link PositionMeta} data and add it to the database + * + * @param warpMeta metadata about the warp + * @param position where the warp should be set + * @return a future supplying the {@link SetResult}; the result of setting the warp + */ + public CompletableFuture setWarp(@NotNull PositionMeta warpMeta, @NotNull Position position) { + return CompletableFuture.supplyAsync(() -> + validateMeta(warpMeta).map(resultType -> new SetResult(resultType, null)).orElseGet(() -> + database.getWarp(warpMeta.name).thenApply(optionalWarp -> { + if (optionalWarp.isEmpty()) { + final Warp warp = new Warp(position, warpMeta); + cache.warps.add(warp.meta.name); + return database.setWarp(warp).thenApply(ignored -> + new SetResult(SetResult.ResultType.SUCCESS, warp)).join(); + } + return new SetResult(SetResult.ResultType.FAILED_DUPLICATE, null); + }).join())); + } + + /** + * Validates {@link PositionMeta} to ensure it can be added to the database + * + * @param positionMeta the {@link PositionMeta} to validate + * @return An optional. If the {@link PositionMeta} is invalid, this will contain a {@link SetResult.ResultType} + * identifying which constraint is violated by the metadata + */ + private Optional validateMeta(PositionMeta positionMeta) { + //todo options for allowing unicode names / descriptions + if (positionMeta.name.length() > 16) { + return Optional.of(SetResult.ResultType.FAILED_NAME_LENGTH); + } + if (!RegexUtil.NAME_PATTERN.matcher(positionMeta.name).matches()) { + return Optional.of(SetResult.ResultType.FAILED_NAME_CHARACTERS); + } + if (positionMeta.description.length() > 255) { + return Optional.of(SetResult.ResultType.FAILED_DESCRIPTION_LENGTH); + } + if (!RegexUtil.DESCRIPTION_PATTERN.matcher(positionMeta.name).matches()) { + return Optional.of(SetResult.ResultType.FAILED_DESCRIPTION_CHARACTERS); + } + return Optional.empty(); + } + + /** + * Holds information about the result of setting a warp or home + * + * @param resultType + * @param setPosition + */ + public record SetResult(@NotNull ResultType resultType, @Nullable SavedPosition setPosition) { + + /** + * Indicates the result of setting a warp or home + */ + public enum ResultType { + /** + * The home or warp was successfully set + */ + SUCCESS(true), + + /** + * The position was not set; one by this name has already been set (for the user in the case of homes) + */ + FAILED_DUPLICATE(false), + + /** + * The position was not set; the name exceeds the maximum length + */ + FAILED_NAME_LENGTH(false), + + /** + * The position was not set; the description exceeds the maximum length + */ + FAILED_DESCRIPTION_LENGTH(false), + + /** + * The position was not set; the name uses illegal characters + */ + FAILED_NAME_CHARACTERS(false), + + /** + * The position was not set; the description uses illegal characters + */ + FAILED_DESCRIPTION_CHARACTERS(false); + + public final boolean successful; + + ResultType(final boolean successful) { + this.successful = successful; + } + } + } + +} 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 bf284c3e..41214ffe 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java @@ -13,6 +13,7 @@ import net.william278.huskhomes.util.MatcherUtil; import org.jetbrains.annotations.NotNull; import java.util.Optional; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; /** @@ -27,6 +28,7 @@ public abstract class TeleportManager { protected final HuskHomes plugin; private static final String WARMUP_BYPASS_PERMISSION = "huskhomes.bypass.teleport_warmup"; + private static final String PRIVACY_BYPASS_PERMISSION = "huskhomes.command.home.other"; public TeleportManager(@NotNull HuskHomes implementor) { this.plugin = implementor; @@ -41,8 +43,16 @@ public abstract class TeleportManager { */ public void teleportToHome(@NotNull Player player, @NotNull User homeOwner, @NotNull String homeName) { plugin.getDatabase().getHome(homeOwner, homeName).thenAccept(optionalHome -> - optionalHome.ifPresentOrElse(home -> - executeTeleport(player, home).thenAccept(result -> finishTeleport(player, result)), () -> { + optionalHome.ifPresentOrElse(home -> { + if (!homeOwner.uuid.equals(player.getUuid())) { + if (!home.isPublic && !player.hasPermission(PRIVACY_BYPASS_PERMISSION)) { + plugin.getLocales().getLocale("error_public_home_invalid", homeOwner.username, homeName) + .ifPresent(player::sendMessage); + return; + } + } + teleport(player, home).thenAccept(result -> finishTeleport(player, result)); + }, () -> { if (homeOwner.uuid.equals(player.getUuid())) { plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(player::sendMessage); } else { @@ -59,8 +69,8 @@ public abstract class TeleportManager { */ public void teleportToWarp(@NotNull Player player, @NotNull String warpName) { plugin.getDatabase().getWarp(warpName).thenAccept(optionalWarp -> - optionalWarp.ifPresentOrElse(warp -> - executeTeleport(player, warp).thenAccept(result -> finishTeleport(player, result)), () -> + optionalWarp.ifPresentOrElse(warp -> //todo permission restricted warps + teleport(player, warp).thenAccept(result -> finishTeleport(player, result)), () -> plugin.getLocales().getLocale("error_warp_invalid", warpName) .ifPresent(player::sendMessage))); } @@ -75,13 +85,20 @@ public abstract class TeleportManager { MatcherUtil.matchPlayerName(targetPlayer, plugin).ifPresentOrElse(playerName -> getPlayerPosition(player, playerName).thenAccept(optionalPosition -> optionalPosition.ifPresentOrElse(targetPosition -> - executeTeleport(player, targetPosition).thenAccept(result -> + teleport(player, targetPosition).thenAccept(result -> finishTeleport(player, result)), () -> plugin.getLocales().getLocale("error_invalid_player"). ifPresent(player::sendMessage))), () -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(player::sendMessage)); } + /** + * Gets the position of a player by their username, including players on other servers + * + * @param requester the {@link Player} requesting their position + * @param playerName the username of the player being requested + * @return future optionally supplying the player's position, if the player could be found + */ private CompletableFuture> getPlayerPosition(@NotNull Player requester, @NotNull String playerName) { final Optional localPlayer = plugin.getOnlinePlayers().stream().filter(player -> player.getName().equalsIgnoreCase(playerName)).findFirst(); @@ -102,60 +119,76 @@ public abstract class TeleportManager { return CompletableFuture.supplyAsync(Optional::empty); } - public CompletableFuture executeTeleport(@NotNull Player player, @NotNull Position position) { - final int teleportWarmupTime = plugin.getSettings().getIntegerValue(Settings.ConfigOption.TELEPORT_WARMUP_TIME); - CompletableFuture completableTeleport; - if (!player.hasPermission(WARMUP_BYPASS_PERMISSION) && teleportWarmupTime > 0) { - completableTeleport = processTimedTeleport(new TimedTeleport(player, position, teleportWarmupTime)) - .thenApplyAsync(teleport -> teleport.getPlayer().teleport(teleport.getTargetPosition()).join()); - } else { - completableTeleport = player.teleport(position); - } - return completableTeleport; - } - - public void finishTeleport(@NotNull Player player, @NotNull TeleportResult teleportResult) { - switch (teleportResult) { - case COMPLETED_LOCALLY -> { - plugin.getLocales().getLocale("teleporting_complete").ifPresent(player::sendMessage); - } - case FAILED_INVALID_WORLD -> { - plugin.getLocales().getLocale("error_invalid_on_arrival").ifPresent(player::sendMessage); - } - case FAILED_UNSAFE -> { - //todo - } - case FAILED_ILLEGAL_COORDINATES -> { - plugin.getLocales().getLocale("error_illegal_target_coordinates").ifPresent(player::sendMessage); - } - case FAILED_INVALID_SERVER -> { - //todo - } - } - } - /** - * Teleport a {@link Player} to a specified {@link Position} + * Teleport a {@link Player} to a specified {@link Position}. Respects timed teleport. * * @param player the {@link Player} to teleport * @param position the target {@link Position} to teleport to */ - public CompletableFuture teleport(Player player, Position position) { - final Teleport teleport = new Teleport(new User(player), position); - return plugin.getServer(player).thenApplyAsync(server -> { - if (position.server.equals(server)) { - return player.teleport(teleport.target).join(); - } else { - return teleportCrossServer(player, teleport).join(); + public CompletableFuture teleport(@NotNull Player player, @NotNull Position position) { + final int teleportWarmupTime = plugin.getSettings().getIntegerValue(Settings.ConfigOption.TELEPORT_WARMUP_TIME); + CompletableFuture completableTeleport; + if (!player.hasPermission(WARMUP_BYPASS_PERMISSION) && teleportWarmupTime > 0) { + try { + completableTeleport = processTimedTeleport(new TimedTeleport(player, position, teleportWarmupTime)) + .thenApplyAsync(teleport -> teleport.getPlayer().teleport(teleport.getTargetPosition()).join()); + } catch (CancellationException cancellationException) { + return CompletableFuture.supplyAsync(() -> TeleportResult.CANCELLED); } - }); + } else { + completableTeleport = teleportNow(player, position); + } + return completableTeleport; + } + + /** + * Handles a completed {@link Player}'s {@link TeleportResult} with the appropriate message + * + * @param player the {@link Player} who just completed a teleport + * @param teleportResult the {@link TeleportResult} to handle + */ + public void finishTeleport(@NotNull Player player, @NotNull TeleportResult teleportResult) { + switch (teleportResult) { + case COMPLETED_LOCALLY -> plugin.getLocales().getLocale("teleporting_complete") + .ifPresent(player::sendMessage); + case FAILED_INVALID_WORLD -> plugin.getLocales().getLocale("error_invalid_on_arrival") + .ifPresent(player::sendMessage); + case FAILED_UNSAFE -> { + //todo + } + case FAILED_ILLEGAL_COORDINATES -> plugin.getLocales().getLocale("error_illegal_target_coordinates") + .ifPresent(player::sendMessage); + case FAILED_INVALID_SERVER -> plugin.getLocales().getLocale("error_invalid_server") + .ifPresent(player::sendMessage); + } + } + + /** + * Executes a teleport now, teleporting a {@link Player} to a specified {@link Position} + * + * @param player the {@link Player} to teleport + * @param position the target {@link Position} to teleport to + */ + private CompletableFuture teleportNow(@NotNull Player player, @NotNull Position position) { + final User user = new User(player); + final Teleport teleport = new Teleport(user, position); + return player.getPosition().thenApplyAsync(preTeleportPosition -> plugin.getDatabase(). + setLastPosition(user, preTeleportPosition). + thenApply(ignored -> plugin.getServer(player).thenApply(server -> { + // Teleport player locally, or across server depending on need + if (position.server.equals(server)) { + return player.teleport(teleport.target).join(); + } else { + return teleportCrossServer(player, teleport).join(); + } + }).join()).join()); } private CompletableFuture teleportCrossServer(Player player, Teleport teleport) { assert plugin.getNetworkMessenger() != null; return CompletableFuture.supplyAsync(() -> plugin.getDatabase().setCurrentTeleport(teleport.player, teleport) - .thenApplyAsync(ignored -> plugin.getNetworkMessenger().sendPlayer(player, teleport.target.server) - .thenApplyAsync(completed -> completed ? TeleportResult.COMPLETED_CROSS_SERVER : + .thenApply(ignored -> plugin.getNetworkMessenger().sendPlayer(player, teleport.target.server) + .thenApply(completed -> completed ? TeleportResult.COMPLETED_CROSS_SERVER : TeleportResult.FAILED_INVALID_SERVER) .join()).join()); } @@ -195,6 +228,12 @@ public abstract class TeleportManager { return false; } + /** + * Process a timed teleport, implemented by platform-specific schedulers + * + * @param teleport the {@link TimedTeleport} to process + * @return a future, returning when the teleport has finished + */ public abstract CompletableFuture processTimedTeleport(TimedTeleport teleport); } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportResult.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportResult.java index 2deccd22..9fbcc949 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportResult.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportResult.java @@ -44,7 +44,12 @@ public enum TeleportResult { * target {@link Position} were in an unsafe spot *

*/ - FAILED_UNSAFE(false); + FAILED_UNSAFE(false), + + /** + * Returns if the teleport was cancelled, for example if a {@link TimedTeleport} in progress is cancelled + */ + CANCELLED(false); /** * Is {@code true} if the teleport was a success diff --git a/common/src/main/java/net/william278/huskhomes/util/EconomyUnsupportedException.java b/common/src/main/java/net/william278/huskhomes/util/EconomyUnsupportedException.java new file mode 100644 index 00000000..b6a4ebd8 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/EconomyUnsupportedException.java @@ -0,0 +1,12 @@ +package net.william278.huskhomes.util; + +/** + * Signals that economy features of the plugin have tried to be accessed when they are not enabled. + */ +public class EconomyUnsupportedException extends IllegalStateException { + + public EconomyUnsupportedException(String message) { + super(message); + } + +} diff --git a/common/src/main/resources/languages/en-gb.yml b/common/src/main/resources/languages/en-gb.yml index b8ee4915..eb567cfe 100644 --- a/common/src/main/resources/languages/en-gb.yml +++ b/common/src/main/resources/languages/en-gb.yml @@ -151,4 +151,5 @@ setspawn_command_description: 'Set the spawn position' tpaall_command_description: 'Request that everyone teleports to you' tpall_command_description: 'Teleport everyone to your position' huskhomes_command_description: 'View plugin information & reload configs' -error_in_game_only: '[Error:](#ff3300) [That command can only be run in-game.](#ff7e5e)' \ No newline at end of file +error_in_game_only: '[Error:](#ff3300) [That command can only be run in-game.](#ff7e5e)' +error_invalid_server: '[Error:](#ff3300) [Failed to finish your teleportation as the target server could not be found or was offline.](#ff7e5e)' \ No newline at end of file