From 713bf2ea42262be517d1a369879f736ab0eea05f Mon Sep 17 00:00:00 2001 From: William Date: Tue, 23 Aug 2022 00:27:04 +0100 Subject: [PATCH] Finish cross-server respawning, close #123 --- .../william278/huskhomes/BukkitHuskHomes.java | 19 +++++--- .../listener/BukkitEventListener.java | 6 ++- .../huskhomes/player/BukkitPlayer.java | 12 +++-- .../net/william278/huskhomes/HuskHomes.java | 4 +- .../huskhomes/command/SetSpawnCommand.java | 2 +- .../huskhomes/command/SpawnCommand.java | 2 +- .../william278/huskhomes/config/Settings.java | 6 +-- .../huskhomes/database/MySqlDatabase.java | 7 +-- .../huskhomes/database/SqLiteDatabase.java | 5 +- .../huskhomes/listener/EventListener.java | 46 ++++++++++--------- .../huskhomes/player/OnlineUser.java | 9 +++- common/src/main/resources/locales/en-gb.yml | 3 +- 12 files changed, 70 insertions(+), 51 deletions(-) diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 06585294..9e93b45a 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -4,7 +4,6 @@ import io.papermc.lib.PaperLib; import net.william278.annotaml.Annotaml; import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.BukkitCommandType; -import net.william278.huskhomes.command.ConsoleExecutable; import net.william278.huskhomes.command.DisabledCommand; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; @@ -61,7 +60,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { private SavedPositionManager savedPositionManager; private EventListener eventListener; private RtpEngine rtpEngine; - private Spawn spawn; + private Spawn serverSpawn; private Set pluginHooks; @Nullable @@ -302,15 +301,21 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } @Override - public Optional getSpawn() { - return Optional.ofNullable(spawn); + public Optional getServerSpawn() { + return Optional.ofNullable(serverSpawn); } @Override - public void setSpawn(@NotNull Location location) { + public void setServerSpawn(@NotNull Location location) { final Spawn newSpawn = new Spawn(location); - this.spawn = newSpawn; + this.serverSpawn = newSpawn; Annotaml.save(newSpawn, new File(getDataFolder(), "spawn.yml")); + + // Update the world spawn location, too + BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> { + assert bukkitLocation.getWorld() != null; + bukkitLocation.getWorld().setSpawnLocation(bukkitLocation); + }); } @Override @@ -399,7 +404,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Load spawn location from file final File spawnFile = new File(getDataFolder(), "spawn.yml"); if (spawnFile.exists()) { - this.spawn = Annotaml.load(spawnFile, Spawn.class); + this.serverSpawn = Annotaml.load(spawnFile, Spawn.class); } return true; }).exceptionally(throwable -> { diff --git a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java index 752fd769..97c90e46 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java +++ b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java @@ -16,6 +16,8 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.*; import org.jetbrains.annotations.NotNull; +import java.util.concurrent.CompletableFuture; + public class BukkitEventListener extends EventListener implements Listener { public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) { @@ -54,13 +56,13 @@ public class BukkitEventListener extends EventListener implements Listener { if (location == null) return; // Update the player's respawn location - BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> { + CompletableFuture.runAsync(() -> BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> { final OnlineUser user = BukkitPlayer.adapt(event.getPlayer()); super.handlePlayerUpdateSpawnPoint(user, new Position( adaptedLocation.x, adaptedLocation.y, adaptedLocation.z, adaptedLocation.yaw, adaptedLocation.pitch, adaptedLocation.world, plugin.getServer(user).join())); - }); + })); } } 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 7862e02c..56d741aa 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java +++ b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java @@ -4,7 +4,6 @@ import de.themoep.minedown.MineDown; import io.papermc.lib.PaperLib; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.TranslatableComponent; import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.position.Location; @@ -12,15 +11,15 @@ import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.TeleportResult; import net.william278.huskhomes.util.BukkitAdapter; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Color; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @@ -127,6 +126,11 @@ public class BukkitPlayer extends OnlineUser { player.spigot().sendMessage(messageComponents); } + @Override + public void sendMinecraftMessage(@NotNull String translationKey) { + player.spigot().sendMessage(new TranslatableComponent(translationKey)); + } + @Override public CompletableFuture teleport(Location location) { return CompletableFuture.supplyAsync(() -> { diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 2d981d14..7c087489 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -135,14 +135,14 @@ public interface HuskHomes { * * @return the {@link Spawn} location data */ - Optional getSpawn(); + Optional getServerSpawn(); /** * Update the {@link Spawn} position to a location on the server * * @param location the new {@link Spawn} location */ - void setSpawn(@NotNull Location location); + void setServerSpawn(@NotNull Location location); /** * Set of active {@link PluginHook}s running on the server diff --git a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java index 84f85c25..a39761e7 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java @@ -34,7 +34,7 @@ public class SetSpawnCommand extends CommandBase { .orElse("")), position).join(); } } else { - plugin.setSpawn(position); + plugin.setServerSpawn(position); } }).thenRun(() -> plugin.getLocales().getLocale("set_spawn_success").ifPresent(onlineUser::sendMessage)); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java index 45bb2986..6de57791 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java @@ -26,7 +26,7 @@ public class SpawnCommand extends CommandBase { CompletableFuture.runAsync(() -> { final Optional position = (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn ? plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join() - : plugin.getSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser).join()))); + : plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser).join()))); if (position.isEmpty()) { plugin.getLocales().getLocale("error_spawn_not_set").ifPresent(onlineUser::sendMessage); return; diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index d31bca64..1f264e59 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -146,7 +146,7 @@ public class Settings { @KeyPath("cross_server.global_spawn.warp_name") public String globalSpawnName = "Spawn"; - @KeyPath("cross_server_global_respawning") + @KeyPath("cross_server.global_respawning") public boolean globalRespawning = false; @KeyPath("cross_server.redis_credentials.host") @@ -195,9 +195,9 @@ public class Settings { @KeyPath("economy.costs") public Map economyCosts = Map.of( EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost, - EconomyAction.MAKE_HOME_PUBLIC.name(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost, + EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost, EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyAction.RANDOM_TELEPORT.defaultCost, - EconomyAction.BACK_COMMAND.name(), EconomyAction.BACK_COMMAND.defaultCost + EconomyAction.BACK_COMMAND.name().toLowerCase(), EconomyAction.BACK_COMMAND.defaultCost ); public Optional getEconomyCost(@NotNull EconomyAction action) { diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index bd3c145e..4903c65b 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -566,7 +566,7 @@ public class MySqlDatabase extends Database { return CompletableFuture.supplyAsync(() -> { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` FROM `%teleports_table%` INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` WHERE `player_uuid`=?"""))) { @@ -637,10 +637,11 @@ public class MySqlDatabase extends Database { if (teleport != null) { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`) - VALUES (?,?);"""))) { + INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + VALUES (?,?,?);"""))) { statement.setString(1, user.uuid.toString()); statement.setInt(2, setPosition(teleport.target, connection)); + statement.setInt(3, teleport.type.typeId); statement.executeUpdate(); } diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 23da8a1c..6634baff 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -649,10 +649,11 @@ public class SqLiteDatabase extends Database { if (teleport != null) { try { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`) - VALUES (?,?);"""))) { + INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + VALUES (?,?,?);"""))) { statement.setString(1, user.uuid.toString()); statement.setInt(2, setPosition(teleport.target, connection)); + statement.setInt(3, teleport.type.typeId); statement.executeUpdate(); } diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 521a37f0..d77bcad1 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -53,18 +53,20 @@ public class EventListener { plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> { // If the server is in proxy mode, check if the player is teleporting cross-server and handle if (plugin.getSettings().crossServer) { - plugin.getDatabase().getCurrentTeleport(onlineUser) - .thenAccept(teleport -> teleport.ifPresent(activeTeleport -> { - // Handle respawn + plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> teleport.ifPresent(activeTeleport -> { + // Handle cross-server respawn if (activeTeleport.type == TeleportType.RESPAWN) { final Optional bedPosition = onlineUser.getBedSpawnPosition().join(); if (bedPosition.isEmpty()) { - plugin.getLocales().getLocale("error_respawn_invalid") - .ifPresent(onlineUser::sendMessage); - plugin.getDatabase().setRespawnPosition(onlineUser, null).join(); - return; + plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser).join())) + .ifPresent(onlineUser::teleport); + onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid"); + } else { + onlineUser.teleport(bedPosition.get()).join(); } - onlineUser.teleport(bedPosition.get()).join(); + plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRun(() -> + plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)) + .join()).join(); return; } @@ -156,20 +158,20 @@ public class EventListener { * @param onlineUser the respawning {@link OnlineUser} */ protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) { + // Display the return by death via /back notification + if (plugin.getSettings().backCommandReturnByDeath && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { + plugin.getLocales().getLocale("return_by_death_notification") + .ifPresent(onlineUser::sendMessage); + } + + // Respawn the player cross-server if needed if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { - plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> { - position.ifPresent(respawnPosition -> { - if (!respawnPosition.server.equals(plugin.getServer(onlineUser).join())) { - plugin.getTeleportManager().teleport(onlineUser, respawnPosition).thenAccept( - result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)); - } - }); - }); - } else { - if (plugin.getSettings().backCommandReturnByDeath && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { - plugin.getLocales().getLocale("back_return_by_death") - .ifPresent(onlineUser::sendMessage); - } + plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> { + if (!respawnPosition.server.equals(plugin.getServer(onlineUser).join())) { + plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept( + result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)); + } + })); } } @@ -181,7 +183,7 @@ public class EventListener { */ protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) { if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { - plugin.getDatabase().setRespawnPosition(onlineUser, position); + plugin.getDatabase().setRespawnPosition(onlineUser, position).join(); } } diff --git a/common/src/main/java/net/william278/huskhomes/player/OnlineUser.java b/common/src/main/java/net/william278/huskhomes/player/OnlineUser.java index 5f7b18c7..37e9fa17 100644 --- a/common/src/main/java/net/william278/huskhomes/player/OnlineUser.java +++ b/common/src/main/java/net/william278/huskhomes/player/OnlineUser.java @@ -82,6 +82,13 @@ public abstract class OnlineUser extends User { */ public abstract void sendMessage(@NotNull MineDown mineDown); + /** + * Dispatch a Minecraft translatable keyed-message to this player + * + * @param translationKey the translation key of the message to send + */ + public abstract void sendMinecraftMessage(@NotNull String translationKey); + /** * Teleport a player to the specified {@link Location} * @@ -168,6 +175,4 @@ public abstract class OnlineUser extends User { .map(permission -> Integer.parseInt(permission.getKey().substring(nodePrefix.length()))) .sorted().toList(); } - - } \ No newline at end of file diff --git a/common/src/main/resources/locales/en-gb.yml b/common/src/main/resources/locales/en-gb.yml index b2e53db4..1d1b6dfa 100644 --- a/common/src/main/resources/locales/en-gb.yml +++ b/common/src/main/resources/locales/en-gb.yml @@ -83,7 +83,7 @@ teleport_request_declined: '[%1% has declined your teleport request.](#ff7e5e)' set_home_used_free_slots: '[You''ve used all of your free set home slots (%1%); setting additional homes will cost %2% each.](gray)' set_home_success: '[Successfully set a new home called](#00fb9a) [%1%](#00fb9a bold)' set_warp_success: '[Successfully set a new warp called](#00fb9a) [%1%](#00fb9a bold)' -set_spawn_success: '[Updated spawn position for this server to your current location.](#00fb9a)' +set_spawn_success: '[Updated the spawn position to your current location.](#00fb9a)' return_by_death_notification: '[Return to where you died?](gray) [[⏪ Teleport…]](#00fb9a show_text=�fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)' home_default_description: '%1%''s home.' @@ -159,7 +159,6 @@ error_home_invalid_other: '[Error:](#ff3300) [%1% does not have a home set named error_edit_home_maximum_public_homes: '[Error:](#ff3300) [You can only make a maximum of %1% homes public.](#ff7e5e)' error_illegal_target_coordinates: '[Error:](#ff3300) [Cancelled teleport as it exceeds the possible game world limits.](#ff7e5e)' error_no_other_online_players: '[Error:](#ff3300) [There are no other online players who could teleport to you.](#ff7e5e)' -error_respawn_invalid: '[You have no home bed or charged respawn anchor, or it was obstructed.](#ff7e5e)' home_command_description: 'Teleport to one of your homes' sethome_command_description: 'Set a new home with given name'