From e335a48888e780ec672d3f72906ec88d379fbf42 Mon Sep 17 00:00:00 2001 From: William Date: Thu, 26 May 2022 15:54:19 +0100 Subject: [PATCH] More implementation, timed teleports, regex, etc --- .../william278/huskhomes/HuskHomesBukkit.java | 26 ++- .../huskhomes/command/BukkitCommand.java | 33 ++++ .../huskhomes/player/BukkitPlayer.java | 32 +++- .../teleport/BukkitTeleportManager.java | 34 ++++ .../net/william278/huskhomes/HuskHomes.java | 25 ++- .../net/william278/huskhomes/cache/Cache.java | 30 ++++ .../huskhomes/command/CommandBase.java | 25 ++- .../huskhomes/command/ConsoleExecutable.java | 9 + .../huskhomes/command/HomeCommand.java | 44 +++++ .../william278/huskhomes/config/Locales.java | 97 ++++++++++ .../william278/huskhomes/config/Messages.java | 97 ---------- .../huskhomes/listener/EventProcessor.java | 26 ++- .../huskhomes/messenger/EmptyPayload.java | 10 ++ .../huskhomes/messenger/Message.java | 6 +- ...ePayload.java => MessageSerializable.java} | 2 +- .../huskhomes/messenger/NetworkMessenger.java | 35 ++-- .../william278/huskhomes/player/Player.java | 14 ++ .../huskhomes/position/Location.java | 4 +- .../huskhomes/position/Position.java | 89 ++++++++- .../william278/huskhomes/position/Server.java | 5 +- .../william278/huskhomes/position/World.java | 5 +- .../huskhomes/teleport/TeleportManager.java | 170 ++++++++++++++++-- .../huskhomes/teleport/TimedTeleport.java | 79 ++++++++ .../huskhomes/util/MatcherUtil.java | 35 ++++ .../william278/huskhomes/util/RegexUtil.java | 28 +++ 25 files changed, 803 insertions(+), 157 deletions(-) create mode 100644 bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java create mode 100644 bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java create mode 100644 common/src/main/java/net/william278/huskhomes/command/ConsoleExecutable.java create mode 100644 common/src/main/java/net/william278/huskhomes/command/HomeCommand.java create mode 100644 common/src/main/java/net/william278/huskhomes/config/Locales.java delete mode 100644 common/src/main/java/net/william278/huskhomes/config/Messages.java create mode 100644 common/src/main/java/net/william278/huskhomes/messenger/EmptyPayload.java rename common/src/main/java/net/william278/huskhomes/messenger/{MessagePayload.java => MessageSerializable.java} (79%) create mode 100644 common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/MatcherUtil.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/RegexUtil.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java index 252cc5ff..fb786b19 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java +++ b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java @@ -7,7 +7,7 @@ import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; import net.william278.huskhomes.cache.Cache; -import net.william278.huskhomes.config.Messages; +import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.data.Database; import net.william278.huskhomes.data.MySqlDatabase; @@ -19,6 +19,8 @@ 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.teleport.BukkitTeleportManager; +import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.util.BukkitLogger; import net.william278.huskhomes.util.BukkitResourceReader; import net.william278.huskhomes.util.Logger; @@ -46,11 +48,12 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { } private Settings settings; - private Messages messages; + private Locales locales; private BukkitLogger logger; private BukkitResourceReader resourceReader; private Database database; private Cache cache; + private TeleportManager teleportManager; @Nullable private NetworkMessenger networkMessenger; @@ -125,6 +128,9 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { cache = new Cache(); cache.initialize(database); }); + + // Prepare the teleport manager + this.teleportManager = new BukkitTeleportManager(this); } @Override @@ -154,8 +160,8 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { } @Override - public Messages getMessages() { - return messages; + public Locales getLocales() { + return locales; } @Override @@ -168,6 +174,16 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { return cache; } + @Override + public TeleportManager getTeleportManager() { + return teleportManager; + } + + @Override + public @Nullable NetworkMessenger getNetworkMessenger() { + return networkMessenger; + } + @Override public boolean isValidPositionOnServer(Position position) { final Optional adaptedLocation = BukkitAdapter.adaptLocation(position); @@ -188,7 +204,7 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.builder().setEncoding(DumperSettings.Encoding.UNICODE).build(), UpdaterSettings.builder().setVersioning(new BasicVersioning("config_version")).build())); - messages = Messages.load(YamlDocument.create(new File(getDataFolder(), + locales = Locales.load(YamlDocument.create(new File(getDataFolder(), "messages-" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml"), Objects.requireNonNull(resourceReader.getResource( "languages/" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml")))); diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java new file mode 100644 index 00000000..1fe91524 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java @@ -0,0 +1,33 @@ +package net.william278.huskhomes.command; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabExecutor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.List; + +public class BukkitCommand extends Command implements TabExecutor { + + protected BukkitCommand(CommandBase command) { + super(command.command, command.getDescription(), command.permission, Arrays.asList(command.aliases)); + } + + @Override + public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { + return false; + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + return false; + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { + return null; + } +} 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 9e8a704d..627d06b1 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java +++ b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java @@ -5,6 +5,7 @@ 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 org.bukkit.Bukkit; import org.bukkit.event.player.PlayerTeleportEvent; @@ -47,7 +48,7 @@ public class BukkitPlayer implements Player { return new BukkitPlayer(player); } - public org.bukkit.entity.Player getBukkitPlayer() { + public org.bukkit.entity.Player toBukkitPlayer() { return bukkitPlayer; } @@ -63,14 +64,24 @@ public class BukkitPlayer implements Player { @Override public CompletableFuture getPosition() { - final org.bukkit.Location location = bukkitPlayer.getLocation(); - return HuskHomesBukkit.getInstance().getServer(this).thenApplyAsync(server -> - new Position(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), - new net.william278.huskhomes.position.World(bukkitPlayer.getWorld().getName(), - bukkitPlayer.getWorld().getUID()), server)); + final Location location = getLocation(); + return HuskHomesBukkit.getInstance().getServer(this).thenApplyAsync(server -> new Position( + location.x, location.y, location.z, location.yaw, location.pitch, location.world, server)); } + @Override + public Location getLocation() { + final org.bukkit.Location location = bukkitPlayer.getLocation(); + return new Location(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), + new World(bukkitPlayer.getWorld().getName(), bukkitPlayer.getWorld().getUID())); + } + + @Override + public double getHealth() { + return bukkitPlayer.getHealth(); + } + @Override public boolean hasPermission(@NotNull String node) { return bukkitPlayer.hasPermission(node); @@ -91,9 +102,12 @@ public class BukkitPlayer implements Player { if (!bukkitLocation.get().getWorld().getWorldBorder().isInside(bukkitLocation.get())) { return CompletableFuture.supplyAsync(() -> TeleportResult.FAILED_ILLEGAL_COORDINATES); } - return PaperLib.teleportAsync(bukkitPlayer, bukkitLocation.get(), - PlayerTeleportEvent.TeleportCause.COMMAND) - .thenApplyAsync(result -> TeleportResult.COMPLETED_LOCALLY); + final CompletableFuture resultCompletableFuture = new CompletableFuture<>(); + Bukkit.getScheduler().runTask(HuskHomesBukkit.getInstance(), () -> + resultCompletableFuture.complete(PaperLib.teleportAsync(bukkitPlayer, bukkitLocation.get(), + PlayerTeleportEvent.TeleportCause.COMMAND) + .thenApply(result -> TeleportResult.COMPLETED_LOCALLY).join())); + return resultCompletableFuture; } @Override diff --git a/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java b/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java new file mode 100644 index 00000000..80ea17ff --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java @@ -0,0 +1,34 @@ +package net.william278.huskhomes.teleport; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.HuskHomesBukkit; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; + +/** + * Bukkit implementation of a {@link TeleportManager}, handling timed teleports through a BukkitRunnable + */ +public class BukkitTeleportManager extends TeleportManager { + + public BukkitTeleportManager(@NotNull HuskHomes implementor) { + super(implementor); + } + + @Override + public CompletableFuture processTimedTeleport(@NotNull final TimedTeleport teleport) { + final CompletableFuture timedTeleportCompletableFuture = new CompletableFuture<>(); + new BukkitRunnable() { + @Override + public void run() { + // Tick (decrement) the timed teleport timer + if (tickTimedTeleport(teleport, timedTeleportCompletableFuture)) { + this.cancel(); + } + } + }.runTaskTimerAsynchronously((HuskHomesBukkit) plugin, 0L, 20L); + return timedTeleportCompletableFuture; + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index d0d2251d..dfc86712 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -1,14 +1,17 @@ package net.william278.huskhomes; import net.william278.huskhomes.cache.Cache; -import net.william278.huskhomes.config.Messages; +import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.data.Database; +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.teleport.TeleportManager; import net.william278.huskhomes.util.Logger; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; @@ -43,9 +46,9 @@ public interface HuskHomes { /** * The plugin messages loaded from file * - * @return The plugin {@link Messages} + * @return The plugin {@link Locales} */ - Messages getMessages(); + Locales getLocales(); /** * The {@link Database} that stores persistent plugin data @@ -61,8 +64,24 @@ public interface HuskHomes { */ Cache getCache(); + /** + * The {@link TeleportManager} that manages player teleports + * + * @return the {@link TeleportManager} implementation + */ + TeleportManager getTeleportManager(); + + /** + * The {@link NetworkMessenger} that sends cross-network messages + * + * @return the {@link NetworkMessenger} implementation + */ + @Nullable + NetworkMessenger getNetworkMessenger(); + /** * Get the {@link Server} this server is on + * * @return The server */ CompletableFuture getServer(@NotNull Player requester); diff --git a/common/src/main/java/net/william278/huskhomes/cache/Cache.java b/common/src/main/java/net/william278/huskhomes/cache/Cache.java index 6512d46d..dffdf8a2 100644 --- a/common/src/main/java/net/william278/huskhomes/cache/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/cache/Cache.java @@ -1,6 +1,10 @@ package net.william278.huskhomes.cache; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.data.Database; +import net.william278.huskhomes.messenger.NetworkMessenger; +import net.william278.huskhomes.player.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -8,6 +12,7 @@ import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; /** * A cache used to hold persistently used data @@ -29,6 +34,11 @@ public class Cache { */ public final List warps; + /** + * Cached player list + */ + public final List players; + /** * Create a new cache */ @@ -36,6 +46,7 @@ public class Cache { this.homes = new HashMap<>(); this.publicHomes = new HashMap<>(); this.warps = new ArrayList<>(); + this.players = new ArrayList<>(); } /** @@ -52,4 +63,23 @@ public class Cache { }); } + /** + * Updates the cached list of online players + * + * @param plugin the implementing plugin + */ + public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull Player requester) { + if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + assert plugin.getNetworkMessenger() != null; + CompletableFuture.runAsync(() -> plugin.getNetworkMessenger(). + getOnlinePlayerNames(requester).thenAcceptAsync(returnedPlayerList -> { + players.clear(); + players.addAll(List.of(returnedPlayerList)); + })); + } else { + players.clear(); + players.addAll(plugin.getOnlinePlayers().stream().map(Player::getName).toList()); + } + } + } diff --git a/common/src/main/java/net/william278/huskhomes/command/CommandBase.java b/common/src/main/java/net/william278/huskhomes/command/CommandBase.java index 34953350..33660f45 100644 --- a/common/src/main/java/net/william278/huskhomes/command/CommandBase.java +++ b/common/src/main/java/net/william278/huskhomes/command/CommandBase.java @@ -2,6 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.Player; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -26,15 +27,15 @@ public abstract class CommandBase { public final String[] aliases; /** - * Instance of the proxy plugin implementor + * Instance of the implementing plugin */ - public final HuskHomes implementor; + public final HuskHomes plugin; - public CommandBase(String command, String permission, HuskHomes implementingPlugin, String... aliases) { + public CommandBase(@NotNull String command, @NotNull String permission, @NotNull HuskHomes implementor, String... aliases) { this.command = command; this.permission = permission; - this.implementor = implementingPlugin; + this.plugin = implementor; this.aliases = aliases; } @@ -44,15 +45,25 @@ public abstract class CommandBase { * @param player {@link Player} executing the command * @param args Command arguments */ - public abstract void onExecute(Player player, String[] args); + public abstract void onExecute(@NotNull Player player, @NotNull String[] args); /** - * What should be returned when the player attempts to TAB complete the command + * What should be returned when the player attempts to TAB-complete the command * * @param player {@link Player} doing the TAB completion * @param args Current command arguments * @return List of String arguments to offer TAB suggestions */ - public abstract List onTabComplete(Player player, String[] args); + public abstract List onTabComplete(@NotNull Player player, @NotNull String[] args); + + /** + * Returns the localised description string of this command + * + * @return the command description + */ + public String getDescription() { + return plugin.getLocales().getRawLocale(command + "_command_description") + .orElse("A HuskHomes command"); + } } diff --git a/common/src/main/java/net/william278/huskhomes/command/ConsoleExecutable.java b/common/src/main/java/net/william278/huskhomes/command/ConsoleExecutable.java new file mode 100644 index 00000000..8a36dfa9 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/command/ConsoleExecutable.java @@ -0,0 +1,9 @@ +package net.william278.huskhomes.command; + +import org.jetbrains.annotations.NotNull; + +public interface ConsoleExecutable { + + void onConsoleExecute(@NotNull String[] args); + +} diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java new file mode 100644 index 00000000..8bd97a5f --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -0,0 +1,44 @@ +package net.william278.huskhomes.command; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.User; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.stream.Collectors; + +public class HomeCommand extends CommandBase { + + private final static String PERMISSION = "huskhomes.command.home"; + + public HomeCommand(@NotNull HuskHomes implementor) { + super("home", PERMISSION, implementor); + } + + @Override + public void onExecute(@NotNull Player player, @NotNull String[] args) { + if (args.length >= 1) { + //todo check if its a public home, process. Support sending a player + plugin.getTeleportManager().teleportToHome(player, new User(player), args[0]); + } else { + 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 -> + plugin.getTeleportManager().finishTeleport(player, result)); + default -> { + //todo show home list + } + } + }); + } + } + + @Override + public List onTabComplete(@NotNull Player player, @NotNull String[] args) { + return plugin.getCache().homes.get(player.getUuid()).stream() + .filter(s -> s.startsWith(args.length >= 1 ? args[0] : "")) + .sorted().collect(Collectors.toList()); + } +} diff --git a/common/src/main/java/net/william278/huskhomes/config/Locales.java b/common/src/main/java/net/william278/huskhomes/config/Locales.java new file mode 100644 index 00000000..98d2c602 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/config/Locales.java @@ -0,0 +1,97 @@ +package net.william278.huskhomes.config; + +import de.themoep.minedown.MineDown; +import dev.dejvokep.boostedyaml.YamlDocument; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Optional; + +/** + * Loaded locales used by the plugin to display various locales + */ +public class Locales { + + @NotNull + private final HashMap rawLocales; + + private Locales(YamlDocument localesConfig) { + this.rawLocales = new HashMap<>(); + for (String localeId : localesConfig.getRoutesAsStrings(false)) { + rawLocales.put(localeId, localesConfig.getString(localeId)); + } + } + + /** + * Returns an unformatted locale loaded from the locales file + * + * @param localeId String identifier of the locale, corresponding to a key in the file + * @return An {@link Optional} containing the locale corresponding to the id, if it exists + */ + public Optional getRawLocale(String localeId) { + if (rawLocales.containsKey(localeId)) { + return Optional.of(rawLocales.get(localeId)); + } + return Optional.empty(); + } + + /** + * Returns an unformatted locale loaded from the locales file, with replacements applied + * + * @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 + * @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists + */ + public Optional getRawLocale(String localeId, String... replacements) { + return getRawLocale(localeId).map(locale -> applyReplacements(locale, replacements)); + } + + /** + * Returns a MineDown-formatted locale from the locales file + * + * @param localeId String identifier of the locale, corresponding to a key in the file + * @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists + */ + public Optional getLocale(String localeId) { + return getRawLocale(localeId).map(MineDown::new); + } + + /** + * Returns a MineDown-formatted locale from the locales file, with replacements applied + * + * @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 + * @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists + */ + public Optional getLocale(String localeId, String... replacements) { + return getRawLocale(localeId, replacements).map(MineDown::new); + } + + /** + * Apply placeholder replacements to a raw locale + * + * @param rawLocale The raw, unparsed locale + * @param replacements Ordered array of replacement strings to fill in placeholders with + * @return the raw locale, with inserted placeholders + */ + private String applyReplacements(String rawLocale, String... replacements) { + int replacementIndexer = 1; + for (String replacement : replacements) { + String replacementString = "%" + replacementIndexer + "%"; + rawLocale = rawLocale.replace(replacementString, replacement); + replacementIndexer = replacementIndexer + 1; + } + return rawLocale; + } + + /** + * Load the locales from a BoostedYaml {@link YamlDocument} locales file + * + * @param localesConfig The loaded {@link YamlDocument} locales.yml file + * @return the loaded {@link Locales} + */ + public static Locales load(YamlDocument localesConfig) { + return new Locales(localesConfig); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/config/Messages.java b/common/src/main/java/net/william278/huskhomes/config/Messages.java deleted file mode 100644 index 8d707a8b..00000000 --- a/common/src/main/java/net/william278/huskhomes/config/Messages.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.william278.huskhomes.config; - -import de.themoep.minedown.MineDown; -import dev.dejvokep.boostedyaml.YamlDocument; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Optional; - -/** - * Loaded locales used by the plugin to display various messages - */ -public class Messages { - - @NotNull - private final HashMap rawMessages; - - private Messages(YamlDocument messagesConfig) { - this.rawMessages = new HashMap<>(); - for (String messageId : messagesConfig.getRoutesAsStrings(false)) { - rawMessages.put(messageId, messagesConfig.getString(messageId)); - } - } - - /** - * Returns an unformatted message loaded from the messages file - * - * @param messageId String identifier of the message, corresponding to a key in the file - * @return An {@link Optional} containing the message corresponding to the id, if it exists - */ - public Optional getRawMessage(String messageId) { - if (rawMessages.containsKey(messageId)) { - return Optional.of(rawMessages.get(messageId)); - } - return Optional.empty(); - } - - /** - * Returns an unformatted message loaded from the messages file, with replacements applied - * - * @param messageId String identifier of the message, corresponding to a key in the file - * @param replacements Ordered array of replacement strings to fill in placeholders with - * @return An {@link Optional} containing the replacement-applied message corresponding to the id, if it exists - */ - public Optional getRawMessage(String messageId, String... replacements) { - return getRawMessage(messageId).map(message -> applyReplacements(message, replacements)); - } - - /** - * Returns a MineDown-formatted message from the messages file - * - * @param messageId String identifier of the message, corresponding to a key in the file - * @return An {@link Optional} containing the formatted message corresponding to the id, if it exists - */ - public Optional getMessage(String messageId) { - return getRawMessage(messageId).map(MineDown::new); - } - - /** - * Returns a MineDown-formatted message from the messages file, with replacements applied - * - * @param messageId String identifier of the message, corresponding to a key in the file - * @param replacements Ordered array of replacement strings to fill in placeholders with - * @return An {@link Optional} containing the replacement-applied, formatted message corresponding to the id, if it exists - */ - public Optional getMessage(String messageId, String... replacements) { - return getRawMessage(messageId, replacements).map(MineDown::new); - } - - /** - * Apply placeholder replacements to a raw message - * - * @param rawMessage The raw, unparsed message - * @param replacements Ordered array of replacement strings to fill in placeholders with - * @return the raw message, with inserted placeholders - */ - private String applyReplacements(String rawMessage, String... replacements) { - int replacementIndexer = 1; - for (String replacement : replacements) { - String replacementString = "%" + replacementIndexer + "%"; - rawMessage = rawMessage.replace(replacementString, replacement); - replacementIndexer = replacementIndexer + 1; - } - return rawMessage; - } - - /** - * Load the messages from a BoostedYaml {@link YamlDocument} messages file - * - * @param messagesConfig The loaded {@link YamlDocument} messages.yml file - * @return the loaded {@link Messages} - */ - public static Messages load(YamlDocument messagesConfig) { - return new Messages(messagesConfig); - } - -} 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 2cd7f4aa..b181ded7 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java @@ -29,18 +29,22 @@ public class EventProcessor { // Ensure the player is present on the database first implementor.getDatabase().ensureUser(player).thenRun(() -> { - // If the server is in proxy mode, check if the player is teleporting cross-server + // 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)) .thenAccept(teleport -> teleport.ifPresent(currentTeleport -> player.teleport(currentTeleport.target).thenAccept(teleportResult -> { if (!teleportResult.successful) { - //todo error handling if the teleport was not successful on arrival - return; + implementor.getLocales().getLocale("error_invalid_on_arrival") + .ifPresent(player::sendMessage); } else { - //todo display teleport complete ^-^ + implementor.getLocales().getLocale("teleporting_complete") + .ifPresent(player::sendMessage); } }))); + // Update the player list + assert implementor.getNetworkMessenger() != null; + implementor.getCache().updatePlayerList(implementor, player); } // Cache this user's homes @@ -50,9 +54,23 @@ public class EventProcessor { }); } + /** + * Handle when a {@link Player} leaves the server + * + * @param player the leaving {@link Player} + */ public void onPlayerLeave(@NotNull Player player) { // Remove this user's home cache implementor.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( + onlinePlayer -> !onlinePlayer.getUuid().equals(player.getUuid())) + .findAny().ifPresent(updater -> + implementor.getCache().updatePlayerList(implementor, updater)); + } } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/messenger/EmptyPayload.java b/common/src/main/java/net/william278/huskhomes/messenger/EmptyPayload.java new file mode 100644 index 00000000..16377916 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/messenger/EmptyPayload.java @@ -0,0 +1,10 @@ +package net.william278.huskhomes.messenger; + +import com.google.gson.GsonBuilder; + +public class EmptyPayload implements MessageSerializable { + @Override + public String toJson() { + return new GsonBuilder().setPrettyPrinting().create().toJson(this); + } +} diff --git a/common/src/main/java/net/william278/huskhomes/messenger/Message.java b/common/src/main/java/net/william278/huskhomes/messenger/Message.java index e692e66d..34d4508a 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/Message.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/Message.java @@ -55,7 +55,7 @@ public class Message { public String payload; public Message(@NotNull MessageType type, @NotNull String sender, @NotNull String targetPlayer, - @NotNull MessagePayload payload, @NotNull MessageKind messageKind, int clusterId) { + @NotNull MessageSerializable payload, @NotNull MessageKind messageKind, int clusterId) { this.type = type; this.sender = sender; this.targetPlayer = targetPlayer; @@ -74,7 +74,9 @@ public class Message { } public enum MessageType { - TP_REQUEST + TP_REQUEST, + + POSITION_REQUEST } public enum MessageKind { diff --git a/common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java b/common/src/main/java/net/william278/huskhomes/messenger/MessageSerializable.java similarity index 79% rename from common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java rename to common/src/main/java/net/william278/huskhomes/messenger/MessageSerializable.java index e35062dc..5bc51b77 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/MessageSerializable.java @@ -3,7 +3,7 @@ package net.william278.huskhomes.messenger; /** * Represents data that can be sent as a payload in a {@link Message} */ -public interface MessagePayload { +public interface MessageSerializable { String toJson(); 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 9a67b1b2..2dc105cb 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java @@ -3,6 +3,7 @@ package net.william278.huskhomes.messenger; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; import org.jetbrains.annotations.NotNull; @@ -111,19 +112,7 @@ public abstract class NetworkMessenger { protected final void handleMessage(@NotNull Player receiver, @NotNull Message message) { switch (message.kind) { // Handle a message and send reply - case MESSAGE -> { - // Handle different message types and apply changes for reply message - switch (message.type) { - case TP_REQUEST -> { - message = message; - } - } - - // Reply with the modified message - message.targetPlayer = message.sender; - message.sender = receiver.getName(); - sendReply(receiver, message); - } + case MESSAGE -> prepareReply(receiver, message).thenAccept(reply -> sendReply(receiver, message)); // Handle a reply message case REPLY -> { if (processingMessages.containsKey(message.uuid)) { @@ -134,6 +123,26 @@ public abstract class NetworkMessenger { } } + private CompletableFuture prepareReply(@NotNull final Player receiver, @NotNull final Message message) { + return CompletableFuture.supplyAsync(() -> { + // Handle different message types and apply changes for reply message + switch (message.type) { + case TP_REQUEST -> { + + } + case POSITION_REQUEST -> { + message.payload = receiver.getPosition().join().toJson(); + } + } + + // Prepare reply message + message.targetPlayer = message.sender; + message.sender = receiver.getName(); + message.kind = Message.MessageKind.REPLY; + return message; + }); + } + /** * Close the network messenger */ 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 b0ebd8c5..fc2d5952 100644 --- a/common/src/main/java/net/william278/huskhomes/player/Player.java +++ b/common/src/main/java/net/william278/huskhomes/player/Player.java @@ -35,6 +35,20 @@ public interface Player { */ CompletableFuture getPosition(); + /** + * Returns the current local {@link Location} of this player + * + * @return the player's current {@link Location} on the server + */ + Location getLocation(); + + /** + * Returns the health of this player + * + * @return the player's health points + */ + double getHealth(); + /** * Returns if the player has the permission node * diff --git a/common/src/main/java/net/william278/huskhomes/position/Location.java b/common/src/main/java/net/william278/huskhomes/position/Location.java index 69babef3..1674a8b5 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Location.java +++ b/common/src/main/java/net/william278/huskhomes/position/Location.java @@ -35,7 +35,6 @@ public class Location { /** * The {@link World} the location is on */ - @NotNull public World world; public Location(double x, double y, double z, float yaw, float pitch, @@ -48,4 +47,7 @@ public class Location { this.world = world; } + public Location() { + } + } 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 67263d88..00cf90d7 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Position.java +++ b/common/src/main/java/net/william278/huskhomes/position/Position.java @@ -1,16 +1,24 @@ package net.william278.huskhomes.position; +import com.google.gson.GsonBuilder; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import net.william278.huskhomes.messenger.MessageSerializable; import org.jetbrains.annotations.NotNull; +import java.io.IOException; +import java.util.UUID; + /** * Represents a position - a location somewhere on the proxy network or server */ -public class Position extends Location { +public class Position extends Location implements MessageSerializable { /** * The {@link Server} the position is on */ - @NotNull public Server server; public Position(double x, double y, double z, float yaw, float pitch, @@ -19,4 +27,81 @@ public class Position extends Location { this.server = server; } + public Position() { + } + + public String toJson() { + return new GsonBuilder().setPrettyPrinting().create().toJson(this); + } + + public static Position fromJson(String json) { + return new GsonBuilder().setPrettyPrinting() + .registerTypeAdapter(World.class, new TypeAdapter() { + @Override + public void write(JsonWriter jsonWriter, World world) throws IOException { + jsonWriter.beginObject(); + jsonWriter.name("name"); + jsonWriter.value(world.name); + jsonWriter.name("uuid"); + jsonWriter.value(world.uuid.toString()); + jsonWriter.endObject(); + } + + @Override + public World read(JsonReader jsonReader) throws IOException { + final World readWorld = new World(); + jsonReader.beginObject(); + String fieldName = null; + while (jsonReader.hasNext()) { + JsonToken token = jsonReader.peek(); + if (token.equals(JsonToken.NAME)) { + fieldName = jsonReader.nextName(); + } + if (fieldName != null) { + if (fieldName.equals("name")) { + jsonReader.peek(); + readWorld.name = jsonReader.nextString(); + } + if (fieldName.equals("uuid")) { + jsonReader.peek(); + readWorld.uuid = UUID.fromString(jsonReader.nextString()); + } + } + } + jsonReader.endObject(); + return readWorld; + } + }) + .registerTypeAdapter(Server.class, new TypeAdapter() { + @Override + public void write(JsonWriter jsonWriter, Server world) throws IOException { + jsonWriter.beginObject(); + jsonWriter.name("name"); + jsonWriter.value(world.name); + jsonWriter.endObject(); + } + + @Override + public Server read(JsonReader jsonReader) throws IOException { + final Server readServer = new Server(); + jsonReader.beginObject(); + String fieldName = null; + while (jsonReader.hasNext()) { + JsonToken token = jsonReader.peek(); + if (token.equals(JsonToken.NAME)) { + fieldName = jsonReader.nextName(); + } + if (fieldName != null) { + if (fieldName.equals("name")) { + jsonReader.peek(); + readServer.name = jsonReader.nextString(); + } + } + } + jsonReader.endObject(); + return readServer; + } + }) + .create().fromJson(json, Position.class); + } } diff --git a/common/src/main/java/net/william278/huskhomes/position/Server.java b/common/src/main/java/net/william278/huskhomes/position/Server.java index 649298bd..a7312a1d 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Server.java +++ b/common/src/main/java/net/william278/huskhomes/position/Server.java @@ -10,13 +10,15 @@ public class Server { /** * Proxy-defined name of this server */ - @NotNull public String name; public Server(@NotNull String name) { this.name = name; } + public Server() { + } + @Override public boolean equals(Object other) { if (other instanceof Server server) { @@ -25,4 +27,5 @@ public class Server { } return super.equals(other); } + } diff --git a/common/src/main/java/net/william278/huskhomes/position/World.java b/common/src/main/java/net/william278/huskhomes/position/World.java index 7e88a863..f23f6e79 100644 --- a/common/src/main/java/net/william278/huskhomes/position/World.java +++ b/common/src/main/java/net/william278/huskhomes/position/World.java @@ -12,13 +12,11 @@ public class World { /** * The name of this world, as defined by the world directory name */ - @NotNull public String name; /** * UUID of this world, as defined by the {@code uid.dat} file in the world directory */ - @NotNull public UUID uuid; public World(@NotNull String name, @NotNull UUID uuid) { @@ -26,4 +24,7 @@ public class World { this.uuid = uuid; } + public World() { + } + } 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 78da5e9b..bf284c3e 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java @@ -1,26 +1,137 @@ package net.william278.huskhomes.teleport; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.config.Settings; +import net.william278.huskhomes.messenger.EmptyPayload; +import net.william278.huskhomes.messenger.Message; import net.william278.huskhomes.player.Player; import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.util.MatcherUtil; import org.jetbrains.annotations.NotNull; +import java.util.Optional; import java.util.concurrent.CompletableFuture; /** * Cross-platform teleportation manager */ -public class TeleportManager { +public abstract class TeleportManager { /** * Instance of the implementing plugin */ @NotNull - private final HuskHomes plugin; + protected final HuskHomes plugin; - public TeleportManager(@NotNull HuskHomes plugin) { - this.plugin = plugin; + private static final String WARMUP_BYPASS_PERMISSION = "huskhomes.bypass.teleport_warmup"; + + public TeleportManager(@NotNull HuskHomes implementor) { + this.plugin = implementor; + } + + /** + * Teleport a {@link Player} to another {@link User}'s {@link Home} + * + * @param player the {@link Player} to teleport + * @param homeOwner the {@link User} who owns the home + * @param homeName the name of the home + */ + 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)), () -> { + if (homeOwner.uuid.equals(player.getUuid())) { + plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(player::sendMessage); + } else { + plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(player::sendMessage); + } + })); + } + + /** + * Teleport a {@link Player} to a server {@link Warp} + * + * @param player the {@link Player} to teleport + * @param warpName the name of the warp + */ + 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)), () -> + plugin.getLocales().getLocale("error_warp_invalid", warpName) + .ifPresent(player::sendMessage))); + } + + /** + * Teleport a {@link Player} to another player by given input name + * + * @param player the {@link Player} to teleport + * @param targetPlayer the name of the target player + */ + public void teleportToPlayer(@NotNull Player player, @NotNull String targetPlayer) { + MatcherUtil.matchPlayerName(targetPlayer, plugin).ifPresentOrElse(playerName -> + getPlayerPosition(player, playerName).thenAccept(optionalPosition -> + optionalPosition.ifPresentOrElse(targetPosition -> + executeTeleport(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)); + } + + private CompletableFuture> getPlayerPosition(@NotNull Player requester, @NotNull String playerName) { + final Optional localPlayer = plugin.getOnlinePlayers().stream().filter(player -> + player.getName().equalsIgnoreCase(playerName)).findFirst(); + if (localPlayer.isPresent()) { + return localPlayer.get().getPosition().thenApply(Optional::of); + } + if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + assert plugin.getNetworkMessenger() != null; + return plugin.getNetworkMessenger().sendMessage(requester, + new Message(Message.MessageType.POSITION_REQUEST, + requester.getName(), + playerName, + new EmptyPayload(), + Message.MessageKind.MESSAGE, + plugin.getSettings().getIntegerValue(Settings.ConfigOption.CLUSTER_ID))) + .thenApplyAsync(reply -> Optional.of(Position.fromJson(reply.payload))); + } + 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 + } + } } /** @@ -35,16 +146,55 @@ public class TeleportManager { if (position.server.equals(server)) { return player.teleport(teleport.target).join(); } else { - return teleportCrossServer(teleport).join(); + return teleportCrossServer(player, teleport).join(); } }); } - private CompletableFuture teleportCrossServer(Teleport teleport) { - return CompletableFuture.supplyAsync(() -> { - //todo - return TeleportResult.COMPLETED_CROSS_SERVER; - }); + 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 : + TeleportResult.FAILED_INVALID_SERVER) + .join()).join()); } + /** + * Process a timed teleport, ticking it + * + * @param teleport the {@link TimedTeleport} being ticked + * @param timedTeleportCompletableFuture a future tracking the {@link TimedTeleport}'s completion + * @return {@code true} if the implementor should cancel the timedTeleport + */ + protected final boolean tickTimedTeleport(@NotNull final TimedTeleport teleport, + @NotNull final CompletableFuture timedTeleportCompletableFuture) { + if (teleport.isDone()) { + timedTeleportCompletableFuture.completeAsync(() -> teleport); + return true; + } + + // Cancel the timed teleport if the player takes damage + if (teleport.hasTakenDamage()) { + plugin.getLocales().getLocale("teleporting_cancelled_damage").ifPresent(locale -> + teleport.getPlayer().sendMessage(locale)); + timedTeleportCompletableFuture.cancel(true); + return true; + } + + // Cancel the timed teleport if the player moves + if (teleport.hasMoved()) { + plugin.getLocales().getLocale("teleporting_cancelled_movement").ifPresent(locale -> + teleport.getPlayer().sendMessage(locale)); + timedTeleportCompletableFuture.cancel(true); + return true; + } + + // Decrement the countdown timer + teleport.countDown(); + return false; + } + + public abstract CompletableFuture processTimedTeleport(TimedTeleport teleport); + } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java new file mode 100644 index 00000000..1877753d --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -0,0 +1,79 @@ +package net.william278.huskhomes.teleport; + +import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.position.Location; +import net.william278.huskhomes.position.Position; +import org.jetbrains.annotations.NotNull; + +/** + * Represents a {@link Teleport} due to occur + */ +public class TimedTeleport { + + private final Player player; + private final Position targetPosition; + + private final Location startLocation; + private final double startHealth; + + private final int duration; + private int timeLeft; + + protected TimedTeleport(@NotNull Player player, @NotNull Position targetPosition, int duration) { + this.player = player; + this.targetPosition = targetPosition; + this.startLocation = player.getLocation(); + this.startHealth = player.getHealth(); + this.duration = duration; + this.timeLeft = duration; + } + + public final boolean isDone() { + return timeLeft <= duration; + } + + public final void countDown() { + timeLeft--; + } + + /** + * Get the teleporting player + * + * @return the {@link Player} who is teleporting + */ + public Player getPlayer() { + return player; + } + + /** + * Returns if the player has moved since the timed teleport started + * + * @return {@code true} if the player has moved; {@code false} otherwise + */ + public boolean hasMoved() { + final double maxMovementDistance = 0.1d; + double movementDistance = Math.abs(startLocation.x - player.getLocation().x) + + Math.abs(startLocation.y - player.getLocation().y) + + Math.abs(startLocation.z - player.getLocation().z); + return movementDistance > maxMovementDistance; + } + + /** + * Returns if the player has taken damage since the timed teleport started + * + * @return {@code true} if the player has taken damage + */ + public boolean hasTakenDamage() { + return player.getHealth() < startHealth; + } + + /** + * Returns the target {@link Position} of this timed teleport + * + * @return the target {@link Position} + */ + public Position getTargetPosition() { + return targetPosition; + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/MatcherUtil.java b/common/src/main/java/net/william278/huskhomes/util/MatcherUtil.java new file mode 100644 index 00000000..0eccd44e --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/MatcherUtil.java @@ -0,0 +1,35 @@ +package net.william278.huskhomes.util; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.Comparator; +import java.util.Optional; + +/** + * Utility for matching a username based on an input name + */ +public final class MatcherUtil { + + /** + * Match a player's username from a user-supplied input name + * + * @param inputName the user input name + * @param plugin the implementing plugin + * @return an optional, containing a matched username if one was found + */ + public static Optional matchPlayerName(@NotNull String inputName, @NotNull HuskHomes plugin) { + // Return an exact match if there is one present + final Optional exactPlayer = plugin.getCache().players.stream().filter(username -> + username.equalsIgnoreCase(inputName)).findFirst(); + if (exactPlayer.isPresent()) { + return exactPlayer; + } + + // Return most likely match, if present + return plugin.getCache().players.stream().filter(username -> username.toLowerCase() + .startsWith(inputName.toLowerCase())).min(Comparator.comparingInt(username -> + username.length() - inputName.toLowerCase().length())); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/RegexUtil.java b/common/src/main/java/net/william278/huskhomes/util/RegexUtil.java new file mode 100644 index 00000000..188aaaed --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/RegexUtil.java @@ -0,0 +1,28 @@ +package net.william278.huskhomes.util; + +import java.util.regex.Pattern; + +import net.william278.huskhomes.position.PositionMeta; + +/** + * Provides a number of utility regular expressions for checking home name patterns + */ +public final class RegexUtil { + + /** + * Pattern for checking home and warp {@link PositionMeta} description fields + */ + public static final Pattern DESCRIPTION_PATTERN = Pattern.compile("[a-zA-Z\\d\\-_\\s]+"); + + /** + * Pattern for checking home and warp {@link PositionMeta} name fields + */ + public static final Pattern NAME_PATTERN = Pattern.compile("[A-Za-z\\d_\\-]+"); + + /** + * Pattern for checking public home input fields + * e.g. {@code ownerName.homeName} + */ + public static final Pattern OWNER_NAME_PATTERN = Pattern.compile("\\w+\\.[A-Za-z\\d_\\-]+"); + +}