Refactor player location and server name fetching, prune unused locales

This commit is contained in:
William committed 2022-08-23 16:19:18 +01:00
1 parent 571f35429d
commit 7e3dab918f
23 files changed
+151 -200

No files matched your search

@@ -337,17 +337,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
return future; return future;
} }
@Override
public boolean isValidPositionOnServer(@NotNull Position position) {
final Optional<org.bukkit.Location> adaptedLocation = BukkitAdapter.adaptLocation(position);
if (adaptedLocation.isEmpty()) {
return false;
}
final org.bukkit.Location location = adaptedLocation.get();
assert location.getWorld() != null;
return location.getWorld().getWorldBorder().isInside(location);
}
@Override @Override
public @NotNull Version getPluginVersion() { public @NotNull Version getPluginVersion() {
return Version.pluginVersion(getDescription().getVersion()); return Version.pluginVersion(getDescription().getVersion());
@@ -366,23 +355,20 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
/** /**
* Returns the {@link Server} the plugin is on * Returns the {@link Server} the plugin is on
* *
* @param onlineUser {@link OnlineUser} to request the server
* @return The {@link Server} object * @return The {@link Server} object
*/ */
@Override @Override
public CompletableFuture<Server> getServer(@NotNull OnlineUser onlineUser) { @NotNull
public Server getServer(@NotNull OnlineUser requester) {
if (server != null) { if (server != null) {
return CompletableFuture.supplyAsync(() -> server); return server;
} }
if (!getSettings().crossServer) { if (getSettings().crossServer && getNetworkMessenger() != null) {
server = getNetworkMessenger().getServerName(requester).thenApply(Server::new).join();
} else {
server = new Server("server"); server = new Server("server");
return CompletableFuture.supplyAsync(() -> server);
} }
assert networkMessenger != null; return server;
return networkMessenger.getServerName(onlineUser).thenApplyAsync(server -> {
this.server = new Server(server);
return this.server;
});
} }
@Override @Override
@@ -55,11 +55,11 @@ public class BukkitEventListener extends EventListener implements Listener {
if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND
|| event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) return; || event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) return;
final BukkitPlayer bukkitPlayer = BukkitPlayer.adapt(player); CompletableFuture.runAsync(() -> {
BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation -> final BukkitPlayer bukkitPlayer = BukkitPlayer.adapt(player);
handlePlayerTeleport(bukkitPlayer, new Position(sourceLocation.x, sourceLocation.y, sourceLocation.z, BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation ->
sourceLocation.yaw, sourceLocation.pitch, sourceLocation.world, handlePlayerTeleport(bukkitPlayer, new Position(sourceLocation, plugin.getServer(bukkitPlayer))));
plugin.getServer(bukkitPlayer).join()))); });
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
@@ -74,11 +74,11 @@ public class BukkitEventListener extends EventListener implements Listener {
// Update the player's respawn location // Update the player's respawn location
CompletableFuture.runAsync(() -> BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> { CompletableFuture.runAsync(() -> BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> {
final OnlineUser user = BukkitPlayer.adapt(event.getPlayer()); final OnlineUser onlineUser = BukkitPlayer.adapt(event.getPlayer());
super.handlePlayerUpdateSpawnPoint(user, new Position( super.handlePlayerUpdateSpawnPoint(onlineUser, 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(onlineUser)));
})); }));
} }
@@ -6,6 +6,7 @@ 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.TranslatableComponent; import net.md_5.bungee.api.chat.TranslatableComponent;
import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomesException;
import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult; import net.william278.huskhomes.teleport.TeleportResult;
@@ -19,7 +20,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.Map; import java.util.Map;
import java.util.Optional; 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;
@@ -46,20 +46,6 @@ public class BukkitPlayer extends OnlineUser {
return new BukkitPlayer(player); return new BukkitPlayer(player);
} }
/**
* Get an online {@link BukkitPlayer} by their UUID
*
* @param uuid the UUID of the player to find
* @return an {@link Optional} containing the {@link BukkitPlayer} if found; {@link Optional#empty()} otherwise
*/
public static Optional<BukkitPlayer> get(@NotNull UUID uuid) {
final Player player = Bukkit.getPlayer(uuid);
if (player != null) {
return Optional.of(adapt(player));
}
return Optional.empty();
}
/** /**
* Get an online {@link BukkitPlayer} by their exact username * Get an online {@link BukkitPlayer} by their exact username
* *
@@ -75,24 +61,17 @@ public class BukkitPlayer extends OnlineUser {
} }
@Override @Override
public CompletableFuture<Position> getPosition() { public Position getPosition() {
final Location location = getLocation(); return new Position(BukkitAdapter.adaptLocation(player.getLocation())
return BukkitHuskHomes.getInstance().getServer(this).thenApply(server -> new Position( .orElseThrow(() -> new HuskHomesException("Failed to get the position of a BukkitPlayer (null)")),
location.x, location.y, location.z, location.yaw, location.pitch, location.world, server)); BukkitHuskHomes.getInstance().getServer(this));
} }
@Override @Override
public CompletableFuture<Optional<Position>> getBedSpawnPosition() { public Optional<Position> getBedSpawnPosition() {
return BukkitHuskHomes.getInstance().getServer(this).thenApply(server -> return Optional.ofNullable(player.getBedSpawnLocation()).flatMap(BukkitAdapter::adaptLocation)
Optional.ofNullable(player.getBedSpawnLocation()).flatMap(BukkitAdapter::adaptLocation) .map(location -> new Position(location, BukkitHuskHomes.getInstance().getServer(this)));
.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);
} }
@Override @Override
@@ -132,7 +111,7 @@ public class BukkitPlayer extends OnlineUser {
} }
@Override @Override
public CompletableFuture<TeleportResult> teleport(Location location) { public CompletableFuture<TeleportResult> teleport(@NotNull Location location, boolean asynchronous) {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
final Optional<org.bukkit.Location> bukkitLocation = BukkitAdapter.adaptLocation(location); final Optional<org.bukkit.Location> bukkitLocation = BukkitAdapter.adaptLocation(location);
if (bukkitLocation.isEmpty()) { if (bukkitLocation.isEmpty()) {
@@ -143,15 +122,16 @@ public class BukkitPlayer extends OnlineUser {
return TeleportResult.FAILED_ILLEGAL_COORDINATES; return TeleportResult.FAILED_ILLEGAL_COORDINATES;
} }
final CompletableFuture<TeleportResult> resultCompletableFuture = new CompletableFuture<>(); final CompletableFuture<TeleportResult> resultCompletableFuture = new CompletableFuture<>();
Bukkit.getScheduler().runTask(BukkitHuskHomes.getInstance(), () -> Bukkit.getScheduler().runTask(BukkitHuskHomes.getInstance(), () -> {
PaperLib.teleportAsync(player, bukkitLocation.get(), PlayerTeleportEvent.TeleportCause.COMMAND) if (asynchronous) {
.thenAccept(result -> { PaperLib.teleportAsync(player, bukkitLocation.get(), PlayerTeleportEvent.TeleportCause.PLUGIN)
if (result) { .thenAccept(result -> resultCompletableFuture.complete(
resultCompletableFuture.complete(TeleportResult.COMPLETED_LOCALLY); result ? TeleportResult.COMPLETED_LOCALLY : TeleportResult.FAILED_INVALID_WORLD));
} else { } else {
resultCompletableFuture.complete(TeleportResult.FAILED_INVALID_WORLD); player.teleport(bukkitLocation.get(), PlayerTeleportEvent.TeleportCause.PLUGIN);
} resultCompletableFuture.complete(TeleportResult.COMPLETED_LOCALLY);
})); }
});
return resultCompletableFuture.join(); return resultCompletableFuture.join();
}); });
} }
@@ -209,7 +209,8 @@ public interface HuskHomes {
* *
* @return The server * @return The server
*/ */
CompletableFuture<Server> getServer(@NotNull OnlineUser requester); @NotNull
Server getServer(@NotNull OnlineUser requester);
/** /**
* Returns a list of worlds on the server * Returns a list of worlds on the server
@@ -219,14 +220,6 @@ public interface HuskHomes {
@NotNull @NotNull
List<World> getWorlds(); List<World> getWorlds();
/**
* Returns true if the position is a valid location on the server
*
* @param position The {@link Position} to check
* @return {@code true} if the position is a valid one on the server; {@code false} otherwise
*/
boolean isValidPositionOnServer(Position position);
/** /**
* Returns the plugin version * Returns the plugin version
* *
@@ -164,8 +164,8 @@ public class EditHomeCommand extends CommandBase implements TabCompletable, Cons
default -> Optional.of(new MineDown("")); default -> Optional.of(new MineDown(""));
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "relocate" -> editor.getPosition().thenAccept(position -> case "relocate" ->
plugin.getSavedPositionManager().updateHomePosition(home, position).thenRun(() -> { plugin.getSavedPositionManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> {
if (home.owner.uuid.equals(editor.uuid)) { if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location",
home.meta.name).orElse(new MineDown(""))); home.meta.name).orElse(new MineDown("")));
@@ -181,7 +181,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable, Cons
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage); .forEach(editor::sendMessage);
} }
})); });
case "privacy" -> { case "privacy" -> {
boolean newIsPublic = !home.isPublic; boolean newIsPublic = !home.isPublic;
if (editArgs != null && !editArgs.isBlank()) { if (editArgs != null && !editArgs.isBlank()) {
@@ -114,8 +114,8 @@ public class EditWarpCommand extends CommandBase implements TabCompletable, Cons
default -> Optional.of(new MineDown("")); default -> Optional.of(new MineDown(""));
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "relocate" -> editor.getPosition().thenAccept(position -> case "relocate" ->
plugin.getSavedPositionManager().updateWarpPosition(warp, position).thenRun(() -> { plugin.getSavedPositionManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> {
editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location", editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location",
warp.meta.name).orElse(new MineDown(""))); warp.meta.name).orElse(new MineDown("")));
@@ -124,7 +124,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable, Cons
getWarpEditorWindow(warp, false, editor.hasPermission(Permission.COMMAND_WARP.node)) getWarpEditorWindow(warp, false, editor.hasPermission(Permission.COMMAND_WARP.node))
.forEach(editor::sendMessage); .forEach(editor::sendMessage);
} }
})); });
default -> plugin.getLocales().getLocale("error_invalid_syntax", default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp <name> [" + String.join("|", EDIT_WARP_COMPLETIONS) + "] [args]") "/editwarp <name> [" + String.join("|", EDIT_WARP_COMPLETIONS) + "] [args]")
.ifPresent(editor::sendMessage); .ifPresent(editor::sendMessage);
@@ -58,7 +58,12 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
} }
plugin.getDatabase().getHomes(userData.user()).thenAccept(homes -> { plugin.getDatabase().getHomes(userData.user()).thenAccept(homes -> {
if (homes.isEmpty()) { if (homes.isEmpty()) {
plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage); if (!onlineUser.uuid.equals(userData.user().uuid)) {
plugin.getLocales().getLocale("error_no_homes_set_other",
userData.user().username).ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage);
}
return; return;
} }
onlineUser.sendMessage(plugin.getCache().getHomeList(onlineUser, userData.user(), onlineUser.sendMessage(plugin.getCache().getHomeList(onlineUser, userData.user(),
@@ -39,7 +39,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
return; return;
} }
final Position userPosition = target.getPosition().join(); final Position userPosition = target.getPosition();
if (plugin.getSettings().rtpRestrictedWorlds.stream() if (plugin.getSettings().rtpRestrictedWorlds.stream()
.anyMatch(worldName -> worldName.equals(userPosition.world.name))) { .anyMatch(worldName -> worldName.equals(userPosition.world.name))) {
plugin.getLocales().getLocale("error_rtp_restricted_world") plugin.getLocales().getLocale("error_rtp_restricted_world")
@@ -85,7 +85,7 @@ public class SetHomeCommand extends CommandBase {
// Set the home in the saved position manager // Set the home in the saved position manager
final SavedPositionManager.SaveResult setResult = plugin.getSavedPositionManager() final SavedPositionManager.SaveResult setResult = plugin.getSavedPositionManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition().join()).join(); .setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition()).join();
// Display feedback of the result of the set operation // Display feedback of the result of the set operation
(switch (setResult.resultType()) { (switch (setResult.resultType()) {
@@ -2,12 +2,14 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class SetSpawnCommand extends CommandBase { public class SetSpawnCommand extends CommandBase {
@@ -23,7 +25,8 @@ public class SetSpawnCommand extends CommandBase {
return; return;
} }
onlineUser.getPosition().thenAccept(position -> { CompletableFuture.runAsync(() -> {
final Position position = onlineUser.getPosition();
if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) { if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) {
final Optional<Warp> warp = plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join(); final Optional<Warp> warp = plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join();
if (warp.isPresent()) { if (warp.isPresent()) {
@@ -26,8 +26,8 @@ public class SetWarpCommand extends CommandBase {
} }
private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) { private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
onlineUser.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setWarp( plugin.getSavedPositionManager().setWarp(
new PositionMeta(warpName, ""), position).thenAccept(setResult -> new PositionMeta(warpName, ""), onlineUser.getPosition()).thenAccept(setResult ->
(switch (setResult.resultType()) { (switch (setResult.resultType()) {
case SUCCESS -> { case SUCCESS -> {
assert setResult.savedPosition().isPresent(); assert setResult.savedPosition().isPresent();
@@ -38,7 +38,7 @@ public class SetWarpCommand extends CommandBase {
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_warp_name_length"); case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_warp_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_warp_name_characters"); case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_warp_name_characters");
default -> Optional.of(new MineDown("")); default -> Optional.of(new MineDown(""));
}).ifPresent(onlineUser::sendMessage))); }).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.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser).join()))); : plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser))));
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;
@@ -12,7 +12,6 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class TpCommand extends CommandBase implements TabCompletable, ConsoleExecutable { public class TpCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
@@ -54,11 +53,12 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
} }
// Parse the coordinates and set the target position // Parse the coordinates and set the target position
final Position userPosition = onlineUser.getPosition().join(); final Position userPosition = onlineUser.getPosition();
final Optional<Position> parsedPosition = Position.parse(userPosition, final Optional<Position> parsedPosition = Position.parse(userPosition,
Arrays.copyOfRange(args, coordinatesIndex, args.length)); Arrays.copyOfRange(args, coordinatesIndex, args.length));
if (parsedPosition.isEmpty()) { if (parsedPosition.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", "/tp <target> <x> <y> <z> [world] [server]") plugin.getLocales().getLocale("error_invalid_syntax",
"/tp <target> <x> <y> <z> [world] [server]")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
return; return;
} }
@@ -71,12 +71,12 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (targetPosition.targetType == TeleportCommandTarget.TargetType.PLAYER) { if (targetPosition.targetType == TeleportCommandTarget.TargetType.PLAYER) {
// Teleport players by usernames // Teleport players by usernames
assert targetPosition.targetPlayer != null; assert targetPosition.targetPlayer != null;
CompletableFuture.runAsync(() -> plugin.getTeleportManager() plugin.getTeleportManager()
.teleportPlayerToPlayerByName(playerToTeleportName, targetPosition.targetPlayer, onlineUser) .teleportPlayerToPlayerByName(playerToTeleportName, targetPosition.targetPlayer, onlineUser)
.thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresentOrElse( .thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresentOrElse(
result -> plugin.getTeleportManager().finishTeleport(onlineUser, result), result -> plugin.getTeleportManager().finishTeleport(onlineUser, result),
() -> plugin.getLocales().getLocale("error_player_not_found", playerToTeleportName) () -> plugin.getLocales().getLocale("error_player_not_found", playerToTeleportName)
.ifPresent(onlineUser::sendMessage)))); .ifPresent(onlineUser::sendMessage)));
return; return;
} else if (targetPosition.targetType == TeleportCommandTarget.TargetType.POSITION) { } else if (targetPosition.targetType == TeleportCommandTarget.TargetType.POSITION) {
// Teleport players by specified position // Teleport players by specified position
@@ -22,7 +22,7 @@ public class TpHereCommand extends CommandBase implements TabCompletable {
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
return; return;
} }
plugin.getTeleportManager().teleportPlayerByName(args[0], onlineUser.getPosition().join(), onlineUser); plugin.getTeleportManager().teleportPlayerByName(args[0], onlineUser.getPosition(), onlineUser);
} }
@Override @Override
@@ -109,14 +109,14 @@ public class Settings {
@KeyPath("general.back_command_return_by_death") @KeyPath("general.back_command_return_by_death")
public boolean backCommandReturnByDeath = true; public boolean backCommandReturnByDeath = true;
@KeyPath("general.back_command_on_teleport_event") @KeyPath("general.back_command_save_teleport_event")
public boolean backCommandOnTeleportEvent = true; public boolean backCommandSaveOnTeleportEvent = false;
@KeyPath("general.list_items_per_page") @KeyPath("general.list_items_per_page")
public int listItemsPerPage = 12; public int listItemsPerPage = 12;
@KeyPath("general.use_paper_lib") @KeyPath("general.asynchronous_teleports")
public boolean usePaperLib = true; public boolean asynchronousTeleports = true;
@KeyPath("general.play_sound_effects") @KeyPath("general.play_sound_effects")
public boolean playSoundEffects = true; public boolean playSoundEffects = true;
@@ -3,13 +3,13 @@ package net.william278.huskhomes.listener;
import de.themoep.minedown.MineDown; import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportType; import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -28,16 +28,6 @@ public class EventListener {
this.plugin = implementor; this.plugin = implementor;
} }
/**
* Handle when the first {@link OnlineUser} joins the server
*
* @param onlineUser {@link OnlineUser} joining the server
*/
private void handleFirstPlayerJoin(@NotNull OnlineUser onlineUser) {
// Cache the server name
plugin.getServer(onlineUser);
}
/** /**
* Handle when a {@link OnlineUser} joins the server * Handle when a {@link OnlineUser} joins the server
* *
@@ -45,50 +35,52 @@ public class EventListener {
*/ */
protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) { protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) {
// Handle the first player joining the server // Handle the first player joining the server
if (firstUser) { CompletableFuture.runAsync(() -> {
handleFirstPlayerJoin(onlineUser); if (firstUser) {
firstUser = false; plugin.getServer(onlineUser);
} firstUser = false;
}
// Ensure the player is present on the database first }).thenRun(() -> {
plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> { // Ensure the player is present on the database first
plugin.getDatabase().ensureUser(onlineUser).join();
}).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).thenAccept(teleport -> teleport.ifPresent(activeTeleport -> { plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> teleport.ifPresent(activeTeleport -> {
// Handle cross-server respawn // Handle cross-server respawn
if (activeTeleport.type == TeleportType.RESPAWN) { if (activeTeleport.type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition().join(); final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) { if (bedPosition.isEmpty()) {
plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser).join())) plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser)))
.ifPresent(onlineUser::teleport); .ifPresent(position -> onlineUser.teleport(position, plugin.getSettings().asynchronousTeleports));
onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid"); onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleport(bedPosition.get(), plugin.getSettings().asynchronousTeleports).join();
}
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRun(() ->
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null))
.join()).join();
return;
}
// Teleport the player locally
onlineUser.teleport(activeTeleport.target, plugin.getSettings().asynchronousTeleports).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_on_arrival")
.ifPresent(onlineUser::sendMessage);
} else { } else {
onlineUser.teleport(bedPosition.get()).join(); plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
} }
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRun(() -> }).thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)) .join();
.join()).join(); })).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 // Update the player list
assert plugin.getNetworkMessenger() != null; assert plugin.getNetworkMessenger() != null;
plugin.getCache().updateOnlinePlayerList(plugin, onlineUser); plugin.getCache().updateOnlinePlayerList(plugin, onlineUser);
} }
}).thenRun(() -> {
// Get this user's tp-ignore state and set locally // Get this user's tp-ignore state and set locally
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> { plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
if (userData.isPresent()) { if (userData.isPresent()) {
@@ -103,17 +95,12 @@ public class EventListener {
} }
} }
}).join(); }).join();
}).thenRun(() -> {
// Cache this user's homes // Cache this user's homes
plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> plugin.getCache() plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> plugin.getCache().homes.put(onlineUser.uuid,
.homes.put(onlineUser.uuid, homes homes.stream()
.stream().map(home -> home.meta.name) .map(home -> home.meta.name)
.collect(Collectors.toList()))).join(); .collect(Collectors.toList()))).join();
// Ensure the server has been set
if (plugin.getOnlinePlayers().size() == 1) {
plugin.getServer(onlineUser);
}
}); });
} }
@@ -136,8 +123,7 @@ public class EventListener {
} }
// Set offline position // Set offline position
onlineUser.getPosition().thenAcceptAsync(position -> plugin.getDatabase() plugin.getDatabase().setOfflinePosition(onlineUser, onlineUser.getPosition());
.setOfflinePosition(onlineUser, position));
} }
/** /**
@@ -149,7 +135,7 @@ public class EventListener {
// Set the player's last position to where they died // Set the player's last position to where they died
if (plugin.getSettings().backCommandReturnByDeath if (plugin.getSettings().backCommandReturnByDeath
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
onlineUser.getPosition().thenAccept(position -> plugin.getDatabase().setLastPosition(onlineUser, position).join()); plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
} }
} }
@@ -168,7 +154,7 @@ public class EventListener {
// Respawn the player cross-server if needed // 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 -> position.ifPresent(respawnPosition -> { plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getServer(onlineUser).join())) { if (!respawnPosition.server.equals(plugin.getServer(onlineUser))) {
plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept( plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept(
result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)); result -> plugin.getTeleportManager().finishTeleport(onlineUser, result));
} }
@@ -183,10 +169,12 @@ public class EventListener {
* @param sourcePosition the source {@link Position} they came from * @param sourcePosition the source {@link Position} they came from
*/ */
protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) { protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) {
if (!plugin.getSettings().backCommandOnTeleportEvent) return; if (!plugin.getSettings().backCommandSaveOnTeleportEvent) return;
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> plugin.getDatabase().getUserData(onlineUser.uuid)
userData.ifPresent(data -> plugin.getDatabase().setLastPosition(data.user(), sourcePosition).join())); .thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase()
.setLastPosition(data.user(), sourcePosition).join()))
.join();
} }
/** /**
@@ -155,7 +155,7 @@ public abstract class NetworkMessenger {
message.payload = MessagePayload.empty(); message.payload = MessagePayload.empty();
} }
} }
case POSITION_REQUEST -> message.payload = MessagePayload.withPosition(receiver.getPosition().join()); case POSITION_REQUEST -> message.payload = MessagePayload.withPosition(receiver.getPosition());
case TELEPORT_REQUEST -> { case TELEPORT_REQUEST -> {
if (message.payload.teleportRequest != null) { if (message.payload.teleportRequest != null) {
plugin.getRequestManager().sendLocalTeleportRequest(message.payload.teleportRequest, receiver); plugin.getRequestManager().sendLocalTeleportRequest(message.payload.teleportRequest, receiver);
@@ -27,7 +27,7 @@ public abstract class OnlineUser extends User {
* *
* @return the player's current {@link Position} * @return the player's current {@link Position}
*/ */
public abstract CompletableFuture<Position> getPosition(); public abstract Position getPosition();
/** /**
* Returns the player's current bed or respawn anchor {@link Position} * Returns the player's current bed or respawn anchor {@link Position}
@@ -35,14 +35,7 @@ public abstract class OnlineUser extends User {
* @return an optional with the player's current bed or respawn anchor {@link Position} if it has been set, * @return an optional with the player's current bed or respawn anchor {@link Position} if it has been set,
* otherwise an {@link Optional#empty()} * otherwise an {@link Optional#empty()}
*/ */
public abstract CompletableFuture<Optional<Position>> getBedSpawnPosition(); public abstract Optional<Position> getBedSpawnPosition();
/**
* Returns the current local {@link Location} of this player
*
* @return the player's current {@link Location} on the server
*/
public abstract Location getLocation();
/** /**
* Returns the health of this player * Returns the health of this player
@@ -92,9 +85,10 @@ public abstract class OnlineUser extends User {
/** /**
* Teleport a player to the specified {@link Location} * Teleport a player to the specified {@link Location}
* *
* @param location the {@link Location} to teleport the player to * @param location the {@link Location} to teleport the player to
* @param asynchronous if the teleport should be asynchronous
*/ */
public abstract CompletableFuture<TeleportResult> teleport(Location location); public abstract CompletableFuture<TeleportResult> teleport(@NotNull Location location, boolean asynchronous);
/** /**
* Get the maximum number of homes this user may set * Get the maximum number of homes this user may set
@@ -21,6 +21,11 @@ public class Position extends Location {
this.server = server; this.server = server;
} }
public Position(@NotNull Location location, @NotNull Server server) {
super(location.x, location.y, location.z, location.yaw, location.pitch, location.world);
this.server = server;
}
@SuppressWarnings("unused") @SuppressWarnings("unused")
public Position() { public Position() {
} }
@@ -54,7 +54,7 @@ public class TeleportRequest {
protected TeleportRequest(@NotNull OnlineUser requester, @NotNull RequestType requestType, protected TeleportRequest(@NotNull OnlineUser requester, @NotNull RequestType requestType,
final long expiryTime) { final long expiryTime) {
this.requesterName = requester.username; this.requesterName = requester.username;
this.requesterPosition = requester.getPosition().join(); this.requesterPosition = requester.getPosition();
this.type = requestType; this.type = requestType;
this.status = RequestStatus.PENDING; this.status = RequestStatus.PENDING;
this.expiryTime = expiryTime; this.expiryTime = expiryTime;
@@ -122,8 +122,8 @@ public class TeleportManager {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final Optional<OnlineUser> localPlayer = plugin.findPlayer(targetPlayer); final Optional<OnlineUser> localPlayer = plugin.findPlayer(targetPlayer);
if (localPlayer.isPresent()) { if (localPlayer.isPresent()) {
timedTeleport(onlineUser, localPlayer.get().getPosition().join()) timedTeleport(onlineUser, localPlayer.get().getPosition()).thenAccept(
.thenAccept(result -> finishTeleport(onlineUser, result)); result -> finishTeleport(onlineUser, result));
} else if (plugin.getSettings().crossServer) { } else if (plugin.getSettings().crossServer) {
assert plugin.getNetworkMessenger() != null; assert plugin.getNetworkMessenger() != null;
getPlayerPositionByName(onlineUser, targetPlayer).thenAccept(optionalPosition -> { getPlayerPositionByName(onlineUser, targetPlayer).thenAccept(optionalPosition -> {
@@ -157,8 +157,7 @@ public class TeleportManager {
if (localPlayer.isPresent()) { if (localPlayer.isPresent()) {
return teleport(localPlayer.get(), position).thenApply(Optional::of); return teleport(localPlayer.get(), position).thenApply(Optional::of);
} }
if (plugin.getSettings().crossServer) { if (plugin.getSettings().crossServer && plugin.getNetworkMessenger() != null) {
assert plugin.getNetworkMessenger() != null;
return plugin.getNetworkMessenger().sendMessage(requester, return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.TELEPORT_TO_POSITION_REQUEST, new Message(Message.MessageType.TELEPORT_TO_POSITION_REQUEST,
requester.username, requester.username,
@@ -187,8 +186,7 @@ public class TeleportManager {
public CompletableFuture<Optional<TeleportResult>> teleportPlayerToPlayerByName(@NotNull String playerName, public CompletableFuture<Optional<TeleportResult>> teleportPlayerToPlayerByName(@NotNull String playerName,
@NotNull String targetPlayer, @NotNull String targetPlayer,
@NotNull OnlineUser requester) { @NotNull OnlineUser requester) {
final Optional<Position> localPositionTarget = plugin.findPlayer(targetPlayer) final Optional<Position> localPositionTarget = plugin.findPlayer(targetPlayer).map(OnlineUser::getPosition);
.map(onlineUser -> onlineUser.getPosition().join());
if (localPositionTarget.isPresent()) { if (localPositionTarget.isPresent()) {
return teleportPlayerByName(playerName, localPositionTarget.get(), requester); return teleportPlayerByName(playerName, localPositionTarget.get(), requester);
} }
@@ -211,7 +209,7 @@ public class TeleportManager {
@NotNull String playerName) { @NotNull String playerName) {
final Optional<OnlineUser> localPlayer = plugin.findPlayer(playerName); final Optional<OnlineUser> localPlayer = plugin.findPlayer(playerName);
if (localPlayer.isPresent()) { if (localPlayer.isPresent()) {
return localPlayer.get().getPosition().thenApply(Optional::of); return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition()));
} }
if (plugin.getSettings().crossServer) { if (plugin.getSettings().crossServer) {
assert plugin.getNetworkMessenger() != null; assert plugin.getNetworkMessenger() != null;
@@ -324,16 +322,18 @@ public class TeleportManager {
public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position, public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position,
@NotNull TeleportType teleportType) { @NotNull TeleportType teleportType) {
final Teleport teleport = new Teleport(onlineUser, position, 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 // Update the player's last position
.thenApply(ignored -> plugin.getServer(onlineUser).thenApply(server -> { if (!plugin.getSettings().backCommandSaveOnTeleportEvent) {
// Teleport player locally, or across server depending on need plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
if (position.server.equals(server)) { }
return onlineUser.teleport(teleport.target).join();
} else { // Teleport player locally, or across server depending on need
return teleportCrossServer(onlineUser, teleport).join(); if (position.server.equals(plugin.getServer(onlineUser))) {
} return onlineUser.teleport(teleport.target, plugin.getSettings().asynchronousTeleports);
}).join()).join()); } else {
return teleportCrossServer(onlineUser, teleport);
}
} }
/** /**
@@ -1,7 +1,6 @@
package net.william278.huskhomes.teleport; package net.william278.huskhomes.teleport;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -12,7 +11,7 @@ public class TimedTeleport {
private final OnlineUser onlineUser; private final OnlineUser onlineUser;
private final Position targetPosition; private final Position targetPosition;
private final Location startLocation; private final Position startLocation;
private final double startHealth; private final double startHealth;
protected int timeLeft; protected int timeLeft;
public boolean cancelled = false; public boolean cancelled = false;
@@ -20,7 +19,7 @@ public class TimedTeleport {
protected TimedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position targetPosition, int duration) { protected TimedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position targetPosition, int duration) {
this.onlineUser = onlineUser; this.onlineUser = onlineUser;
this.targetPosition = targetPosition; this.targetPosition = targetPosition;
this.startLocation = onlineUser.getLocation(); this.startLocation = onlineUser.getPosition();
this.startHealth = onlineUser.getHealth(); this.startHealth = onlineUser.getHealth();
this.timeLeft = duration; this.timeLeft = duration;
} }
@@ -49,9 +48,9 @@ public class TimedTeleport {
*/ */
public boolean hasMoved() { public boolean hasMoved() {
final double maxMovementDistance = 0.1d; final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.x - onlineUser.getLocation().x) + double movementDistance = Math.abs(startLocation.x - onlineUser.getPosition().x) +
Math.abs(startLocation.y - onlineUser.getLocation().y) + Math.abs(startLocation.y - onlineUser.getPosition().y) +
Math.abs(startLocation.z - onlineUser.getLocation().z); Math.abs(startLocation.z - onlineUser.getPosition().z);
return movementDistance > maxMovementDistance; return movementDistance > maxMovementDistance;
} }
@@ -152,14 +152,12 @@ error_console_only: '[Error:](#ff3300) [That command can only be run from the se
error_tp_invalid_world: '[Error:](#ff3300) [Please specify a valid server world.](#ff7e5e)' error_tp_invalid_world: '[Error:](#ff3300) [Please specify a valid server world.](#ff7e5e)'
error_rtp_randomization_timeout: '[Error:](#ff3300) [Failed to find a safe random location to teleport you.](#ff7e5e)' error_rtp_randomization_timeout: '[Error:](#ff3300) [Failed to find a safe random location to teleport you.](#ff7e5e)'
error_permission_restricted_warp: '[Error:](#ff3300) [You do not have permission to warp to %1%!](#ff7e5e)' error_permission_restricted_warp: '[Error:](#ff3300) [You do not have permission to warp to %1%!](#ff7e5e)'
error_invalid_page_number: '[Error:](#ff3300) [Please specify a valid page number.](#ff7e5e)'
error_invalid_on_arrival: '[Error:](#ff3300) [Failed to finish teleportation as the target world could not be found.](#ff7e5e)' error_invalid_on_arrival: '[Error:](#ff3300) [Failed to finish teleportation as the target world could not be found.](#ff7e5e)'
error_no_offline_position: '[Error:](#ff3300) [Could not find where %1% last logged out.](#ff7e5e)' error_no_offline_position: '[Error:](#ff3300) [Could not find where %1% last logged out.](#ff7e5e)'
error_no_homes_set_other: '[Error:](#ff3300) [%1% has not set any homes!](#ff7e5e)' error_no_homes_set_other: '[Error:](#ff3300) [%1% has not set any homes!](#ff7e5e)'
error_home_invalid_other: '[Error:](#ff3300) [%1% does not have a home set named "%2%"](#ff7e5e)' error_home_invalid_other: '[Error:](#ff3300) [%1% does not have a home set named "%2%"](#ff7e5e)'
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)'
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'