Teleport types, cross-server respawn handling

This commit is contained in:
William committed 2022-08-22 23:28:46 +01:00
1 parent 8dff4a123a
commit f74f77c62d
17 files changed
+192 -33

No files matched your search

@@ -2,13 +2,18 @@ package net.william278.huskhomes.listener;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.player.BukkitPlayer;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.data.type.Bed;
import org.bukkit.block.data.type.RespawnAnchor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.*;
import org.jetbrains.annotations.NotNull;
public class BukkitEventListener extends EventListener implements Listener {
@@ -33,4 +38,29 @@ public class BukkitEventListener extends EventListener implements Listener {
super.handlePlayerDeath(BukkitPlayer.adapt(event.getEntity()));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerRespawn(PlayerRespawnEvent event) {
super.handlePlayerRespawn(BukkitPlayer.adapt(event.getPlayer()));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) {
if (!(plugin.getSettings().crossServer && plugin.getSettings().globalRespawning)) return;
if (event.getClickedBlock() == null) return;
if (!(event.getClickedBlock().getBlockData() instanceof Bed
|| event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return;
final Location location = event.getPlayer().getBedSpawnLocation();
if (location == null) return;
// Update the player's respawn location
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()));
});
}
}
@@ -4,12 +4,16 @@ 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;
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;
@@ -79,6 +83,14 @@ public class BukkitPlayer extends OnlineUser {
}
@Override
public CompletableFuture<Optional<Position>> getBedSpawnPosition() {
return BukkitHuskHomes.getInstance().getServer(this).thenApply(server ->
Optional.ofNullable(player.getBedSpawnLocation()).flatMap(BukkitAdapter::adaptLocation)
.map(location -> new Position(location.x, location.y, location.z,
location.yaw, location.pitch, location.world, server)));
}
@Override
public Location getLocation() {
return BukkitAdapter.adaptLocation(player.getLocation()).orElse(null);
+4
View File
@@ -61,5 +61,9 @@ commands:
usage: /tpignore
tpoffline:
usage: /tpoffline <player>
spawn:
usage: /spawn
setspawn:
usage: /setspawn
back:
usage: /back
@@ -1,5 +1,6 @@
package net.william278.huskhomes.command;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
@@ -146,6 +146,9 @@ public class Settings {
@KeyPath("cross_server.global_spawn.warp_name")
public String globalSpawnName = "Spawn";
@KeyPath("cross_server_global_respawning")
public boolean globalRespawning = false;
@KeyPath("cross_server.redis_credentials.host")
public String redisHost = "localhost";
@@ -6,6 +6,7 @@ import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
@@ -581,7 +582,8 @@ public class MySqlDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")))));
new Server(resultSet.getString("server_name"))),
TeleportType.getTeleportType(resultSet.getInt("type")).orElse(TeleportType.TELEPORT)));
}
}
} catch (SQLException e) {
@@ -5,6 +5,7 @@ import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
@@ -577,7 +578,7 @@ public class SqLiteDatabase extends Database {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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`=?"""))) {
@@ -593,7 +594,8 @@ public class SqLiteDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")))));
new Server(resultSet.getString("server_name"))),
TeleportType.getTeleportType(resultSet.getInt("type")).orElse(TeleportType.TELEPORT)));
}
}
} catch (SQLException e) {
@@ -3,9 +3,12 @@ package net.william278.huskhomes.listener;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -51,17 +54,32 @@ public class EventListener {
// 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(currentTeleport ->
// Teleport the player locally
onlineUser.teleport(currentTeleport.target).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_on_arrival")
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
}
}).thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))))
.thenAccept(teleport -> teleport.ifPresent(activeTeleport -> {
// Handle respawn
if (activeTeleport.type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition().join();
if (bedPosition.isEmpty()) {
plugin.getLocales().getLocale("error_respawn_invalid")
.ifPresent(onlineUser::sendMessage);
plugin.getDatabase().setRespawnPosition(onlineUser, null).join();
return;
}
onlineUser.teleport(bedPosition.get()).join();
return;
}
// Teleport the player locally
onlineUser.teleport(activeTeleport.target).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_on_arrival")
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
}
}).thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
.join();
}))
.join();
// Update the player list
assert plugin.getNetworkMessenger() != null;
@@ -76,7 +94,7 @@ public class EventListener {
// Send a reminder message if they are still ignoring requests
if (ignoringRequests) {
plugin.getLocales().getRawLocale("tpignore_on_reminder",
plugin.getLocales().getRawLocale("tpignore_on_notification",
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
}
@@ -138,7 +156,33 @@ public class EventListener {
* @param onlineUser the respawning {@link OnlineUser}
*/
protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) {
//todo
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);
}
}
}
/**
* Handle when an {@link OnlineUser}'s spawn point is updated
*
* @param onlineUser the {@link OnlineUser} whose spawn point was updated
* @param position the new spawn point
*/
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().setRespawnPosition(onlineUser, position);
}
}
/**
@@ -8,6 +8,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -28,6 +29,14 @@ public abstract class OnlineUser extends User {
*/
public abstract CompletableFuture<Position> getPosition();
/**
* Returns the player's current bed or respawn anchor {@link Position}
*
* @return an optional with the player's current bed or respawn anchor {@link Position} if it has been set,
* otherwise an {@link Optional#empty()}
*/
public abstract CompletableFuture<Optional<Position>> getBedSpawnPosition();
/**
* Returns the current local {@link Location} of this player
*
@@ -103,7 +112,7 @@ public abstract class OnlineUser extends User {
* Get the number of homes this user may make public
*
* @param defaultPublicHomes the default number of homes this user may make public
* @param stack whether to stack numerical permissions that grant the user extra public homes
* @param stack whether to stack numerical permissions that grant the user extra public homes
* @return the number of public home slots this user may set
*/
public int getMaxPublicHomes(final int defaultPublicHomes, final boolean stack) {
@@ -1,6 +1,7 @@
package net.william278.huskhomes.position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Represents a server on a proxied network
@@ -12,8 +13,8 @@ public class Server {
*/
public String name;
public Server(@NotNull String name) {
this.name = name;
public Server(@Nullable String name) {
this.name = (name != null ? name : "server");
}
public Server() {
@@ -21,8 +21,15 @@ public class Teleport {
@NotNull
public Position target;
public Teleport(@NotNull User player, @NotNull Position target) {
/**
* The type of the teleport
*/
@NotNull
public TeleportType type;
public Teleport(@NotNull User player, @NotNull Position target, @NotNull TeleportType type) {
this.player = player;
this.target = target;
this.type = type;
}
}
@@ -301,15 +301,29 @@ public class TeleportManager {
}
/**
* Carries out a teleport, teleporting a {@link OnlineUser} to a specified {@link Position} and returning
* a future that will return a {@link TeleportResult}
* Carries out a teleport, teleporting a {@link OnlineUser} to a specified {@link Position} with a TeleportType of
* {@link TeleportType#TELEPORT} and returning a future that will return a {@link TeleportResult}
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param position the target {@link Position} to teleport to#
* @param position the target {@link Position} to teleport to
* @return a {@link CompletableFuture} that completes when the teleport is complete with the {@link TeleportResult}
*/
public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position) {
final Teleport teleport = new Teleport(onlineUser, position);
return teleport(onlineUser, position, TeleportType.TELEPORT);
}
/**
* Carries out a teleport, teleporting a {@link OnlineUser} to a specified {@link Position} and returning
* a future that will return a {@link TeleportResult}
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param position the target {@link Position} to teleport to
* @param teleportType the {@link TeleportType} of the teleport
* @return a {@link CompletableFuture} that completes when the teleport is complete with the {@link TeleportResult}
*/
public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position,
@NotNull TeleportType teleportType) {
final Teleport teleport = new Teleport(onlineUser, position, teleportType);
return onlineUser.getPosition().thenApply(preTeleportPosition -> plugin.getDatabase()
.setLastPosition(onlineUser, preTeleportPosition) // Update the player's last position
.thenApply(ignored -> plugin.getServer(onlineUser).thenApply(server -> {
@@ -0,0 +1,31 @@
package net.william278.huskhomes.teleport;
import java.util.Arrays;
import java.util.Optional;
/**
* Represents the type of teleport being used
*/
public enum TeleportType {
TELEPORT(0),
RESPAWN(1);
public final int typeId;
TeleportType(final int typeId) {
this.typeId = typeId;
}
/**
* Returns a {@link TeleportType} by its type id.
*
* @param typeId The type id of the {@link TeleportType} to return.
* @return The {@link TeleportType} of the given type id.
*/
public static Optional<TeleportType> getTeleportType(int typeId) {
return Arrays.stream(values())
.filter(type -> type.typeId == typeId)
.findFirst();
}
}
@@ -6,19 +6,15 @@ import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
/**
* Represents a {@link Teleport} due to occur
* Represents a {@link Teleport} due to occur after a warmup period
*/
public class TimedTeleport {
private final OnlineUser onlineUser;
private final Position targetPosition;
private final Location startLocation;
private final double startHealth;
private final int duration;
protected int timeLeft;
public boolean cancelled = false;
protected TimedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position targetPosition, int duration) {
@@ -26,7 +22,6 @@ public class TimedTeleport {
this.targetPosition = targetPosition;
this.startLocation = onlineUser.getLocation();
this.startHealth = onlineUser.getHealth();
this.duration = duration;
this.timeLeft = duration;
}
@@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS `%teleports_table%`
(
`player_uuid` char(36) NOT NULL UNIQUE,
`destination_id` integer NOT NULL,
`type` integer NOT NULL DEFAULT 0,
PRIMARY KEY (`player_uuid`),
FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE,
@@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS `%teleports_table%`
(
`player_uuid` char(36) NOT NULL UNIQUE,
`destination_id` integer NOT NULL,
`type` integer NOT NULL DEFAULT 0,
PRIMARY KEY (`player_uuid`),
FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE,
+3 -1
View File
@@ -84,6 +84,7 @@ set_home_used_free_slots: '[You''ve used all of your free set home slots (%1%);
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)'
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.'
warp_default_description: 'A publicly accessible warp.'
@@ -96,7 +97,7 @@ spawn_warp_default_description: 'The /spawn position of the server'
tpignore_toggle_on: '[You are now](#00fb9a) [ignoring](#00fb9a bold) [incoming teleport requests.](#00fb9a) %1%'
tpignore_toggle_off: '[You are now](#00fb9a) [listening](#00fb9a bold) [to incoming teleport requests.](#00fb9a) %1%'
tpignore_on_reminder: '[You are currently ignoring incoming teleport requests!](gray) %1%'
tpignore_on_notification: '[You are currently ignoring incoming teleport requests!](gray) %1%'
tpignore_toggle_button: '[[🔔 Toggle…]](#ffc43b show_text=&#ffc43b&Click to toggle:\n&7Toggle ignoring/listening to incoming teleport requests run_command=/huskhomes:tpignore)'
teleporting_all_players: '[Teleporting all players to your position…](#00fb9a)'
@@ -158,6 +159,7 @@ 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'