Finish cross-server respawning, close #123

This commit is contained in:
William committed 2022-08-23 00:27:04 +01:00
1 parent f0d9807ee4
commit 713bf2ea42
12 files changed
+70 -51

No files matched your search

@@ -4,7 +4,6 @@ import io.papermc.lib.PaperLib;
import net.william278.annotaml.Annotaml; import net.william278.annotaml.Annotaml;
import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.BukkitCommandType; import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.ConsoleExecutable;
import net.william278.huskhomes.command.DisabledCommand; import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Settings;
@@ -61,7 +60,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private SavedPositionManager savedPositionManager; private SavedPositionManager savedPositionManager;
private EventListener eventListener; private EventListener eventListener;
private RtpEngine rtpEngine; private RtpEngine rtpEngine;
private Spawn spawn; private Spawn serverSpawn;
private Set<PluginHook> pluginHooks; private Set<PluginHook> pluginHooks;
@Nullable @Nullable
@@ -302,15 +301,21 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
} }
@Override @Override
public Optional<Spawn> getSpawn() { public Optional<Spawn> getServerSpawn() {
return Optional.ofNullable(spawn); return Optional.ofNullable(serverSpawn);
} }
@Override @Override
public void setSpawn(@NotNull Location location) { public void setServerSpawn(@NotNull Location location) {
final Spawn newSpawn = new Spawn(location); final Spawn newSpawn = new Spawn(location);
this.spawn = newSpawn; this.serverSpawn = newSpawn;
Annotaml.save(newSpawn, new File(getDataFolder(), "spawn.yml")); 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 @Override
@@ -399,7 +404,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
// Load spawn location from file // Load spawn location from file
final File spawnFile = new File(getDataFolder(), "spawn.yml"); final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists()) { if (spawnFile.exists()) {
this.spawn = Annotaml.load(spawnFile, Spawn.class); this.serverSpawn = Annotaml.load(spawnFile, Spawn.class);
} }
return true; return true;
}).exceptionally(throwable -> { }).exceptionally(throwable -> {
@@ -16,6 +16,8 @@ import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*; import org.bukkit.event.player.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public class BukkitEventListener extends EventListener implements Listener { public class BukkitEventListener extends EventListener implements Listener {
public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) { public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) {
@@ -54,13 +56,13 @@ public class BukkitEventListener extends EventListener implements Listener {
if (location == null) return; if (location == null) return;
// Update the player's respawn location // 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()); final OnlineUser user = BukkitPlayer.adapt(event.getPlayer());
super.handlePlayerUpdateSpawnPoint(user, new Position( super.handlePlayerUpdateSpawnPoint(user, new Position(
adaptedLocation.x, adaptedLocation.y, adaptedLocation.z, adaptedLocation.x, adaptedLocation.y, adaptedLocation.z,
adaptedLocation.yaw, adaptedLocation.pitch, adaptedLocation.yaw, adaptedLocation.pitch,
adaptedLocation.world, plugin.getServer(user).join())); adaptedLocation.world, plugin.getServer(user).join()));
}); }));
} }
} }
@@ -4,7 +4,6 @@ import de.themoep.minedown.MineDown;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.BaseComponent; 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.md_5.bungee.api.chat.TranslatableComponent;
import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.position.Location; 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.teleport.TeleportResult;
import net.william278.huskhomes.util.BukkitAdapter; import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull; 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.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -127,6 +126,11 @@ public class BukkitPlayer extends OnlineUser {
player.spigot().sendMessage(messageComponents); player.spigot().sendMessage(messageComponents);
} }
@Override
public void sendMinecraftMessage(@NotNull String translationKey) {
player.spigot().sendMessage(new TranslatableComponent(translationKey));
}
@Override @Override
public CompletableFuture<TeleportResult> teleport(Location location) { public CompletableFuture<TeleportResult> teleport(Location location) {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
@@ -135,14 +135,14 @@ public interface HuskHomes {
* *
* @return the {@link Spawn} location data * @return the {@link Spawn} location data
*/ */
Optional<Spawn> getSpawn(); Optional<Spawn> getServerSpawn();
/** /**
* Update the {@link Spawn} position to a location on the server * Update the {@link Spawn} position to a location on the server
* *
* @param location the new {@link Spawn} location * @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 * Set of active {@link PluginHook}s running on the server
@@ -34,7 +34,7 @@ public class SetSpawnCommand extends CommandBase {
.orElse("")), position).join(); .orElse("")), position).join();
} }
} else { } else {
plugin.setSpawn(position); plugin.setServerSpawn(position);
} }
}).thenRun(() -> plugin.getLocales().getLocale("set_spawn_success").ifPresent(onlineUser::sendMessage)); }).thenRun(() -> plugin.getLocales().getLocale("set_spawn_success").ifPresent(onlineUser::sendMessage));
} }
@@ -26,7 +26,7 @@ public class SpawnCommand extends CommandBase {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final Optional<? extends Position> position = (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn final Optional<? extends Position> position = (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn
? plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join() ? 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()) { if (position.isEmpty()) {
plugin.getLocales().getLocale("error_spawn_not_set").ifPresent(onlineUser::sendMessage); plugin.getLocales().getLocale("error_spawn_not_set").ifPresent(onlineUser::sendMessage);
return; return;
@@ -146,7 +146,7 @@ public class Settings {
@KeyPath("cross_server.global_spawn.warp_name") @KeyPath("cross_server.global_spawn.warp_name")
public String globalSpawnName = "Spawn"; public String globalSpawnName = "Spawn";
@KeyPath("cross_server_global_respawning") @KeyPath("cross_server.global_respawning")
public boolean globalRespawning = false; public boolean globalRespawning = false;
@KeyPath("cross_server.redis_credentials.host") @KeyPath("cross_server.redis_credentials.host")
@@ -195,9 +195,9 @@ public class Settings {
@KeyPath("economy.costs") @KeyPath("economy.costs")
public Map<String, Double> economyCosts = Map.of( public Map<String, Double> economyCosts = Map.of(
EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost, 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.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<Double> getEconomyCost(@NotNull EconomyAction action) { public Optional<Double> getEconomyCost(@NotNull EconomyAction action) {
@@ -566,7 +566,7 @@ public class MySqlDatabase extends Database {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" 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%` FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
WHERE `player_uuid`=?"""))) { WHERE `player_uuid`=?"""))) {
@@ -637,10 +637,11 @@ public class MySqlDatabase extends Database {
if (teleport != null) { if (teleport != null) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`) INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?);"""))) { VALUES (?,?,?);"""))) {
statement.setString(1, user.uuid.toString()); statement.setString(1, user.uuid.toString());
statement.setInt(2, setPosition(teleport.target, connection)); statement.setInt(2, setPosition(teleport.target, connection));
statement.setInt(3, teleport.type.typeId);
statement.executeUpdate(); statement.executeUpdate();
} }
@@ -649,10 +649,11 @@ public class SqLiteDatabase extends Database {
if (teleport != null) { if (teleport != null) {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`) INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?);"""))) { VALUES (?,?,?);"""))) {
statement.setString(1, user.uuid.toString()); statement.setString(1, user.uuid.toString());
statement.setInt(2, setPosition(teleport.target, connection)); statement.setInt(2, setPosition(teleport.target, connection));
statement.setInt(3, teleport.type.typeId);
statement.executeUpdate(); statement.executeUpdate();
} }
@@ -53,18 +53,20 @@ public class EventListener {
plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> { plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> {
// If the server is in proxy mode, check if the player is teleporting cross-server and handle // If the server is in proxy mode, check if the player is teleporting cross-server and handle
if (plugin.getSettings().crossServer) { if (plugin.getSettings().crossServer) {
plugin.getDatabase().getCurrentTeleport(onlineUser) plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> teleport.ifPresent(activeTeleport -> {
.thenAccept(teleport -> teleport.ifPresent(activeTeleport -> { // Handle cross-server respawn
// Handle respawn
if (activeTeleport.type == TeleportType.RESPAWN) { if (activeTeleport.type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition().join(); final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition().join();
if (bedPosition.isEmpty()) { if (bedPosition.isEmpty()) {
plugin.getLocales().getLocale("error_respawn_invalid") plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser).join()))
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::teleport);
plugin.getDatabase().setRespawnPosition(onlineUser, null).join(); onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid");
return; } 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; return;
} }
@@ -156,20 +158,20 @@ public class EventListener {
* @param onlineUser the respawning {@link OnlineUser} * @param onlineUser the respawning {@link OnlineUser}
*/ */
protected final void handlePlayerRespawn(@NotNull OnlineUser 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) { if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> { plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
position.ifPresent(respawnPosition -> { if (!respawnPosition.server.equals(plugin.getServer(onlineUser).join())) {
if (!respawnPosition.server.equals(plugin.getServer(onlineUser).join())) { plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept(
plugin.getTeleportManager().teleport(onlineUser, respawnPosition).thenAccept( result -> plugin.getTeleportManager().finishTeleport(onlineUser, result));
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);
}
} }
} }
@@ -181,7 +183,7 @@ public class EventListener {
*/ */
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) { protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().setRespawnPosition(onlineUser, position); plugin.getDatabase().setRespawnPosition(onlineUser, position).join();
} }
} }
@@ -82,6 +82,13 @@ public abstract class OnlineUser extends User {
*/ */
public abstract void sendMessage(@NotNull MineDown mineDown); 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} * 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()))) .map(permission -> Integer.parseInt(permission.getKey().substring(nodePrefix.length())))
.sorted().toList(); .sorted().toList();
} }
} }
+1 -2
View File
@@ -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_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_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_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=&#00fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)' return_by_death_notification: '[Return to where you died?](gray) [[⏪ Teleport…]](#00fb9a show_text=&#00fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)'
home_default_description: '%1%''s home.' 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_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_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_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' home_command_description: 'Teleport to one of your homes'
sethome_command_description: 'Set a new home with given name' sethome_command_description: 'Set a new home with given name'