Bump to v3.1, rewrite Teleport/TimedTeleport and add TeleportBuilder, expose new Teleport API, remove TeleportManager, minor database utility refactoring

This commit is contained in:
William committed 2022-10-18 17:45:44 +01:00
1 parent e7f8298b12
commit 9630e53613
35 files changed
+1070 -881

No files matched your search

@@ -1,35 +1,223 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.messenger.MessagePayload;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
/**
* Represents a teleport in the process of being executed
*
* @since 3.1
*/
public class Teleport {
/**
* The player involved in the teleport
* <b>Internal</b> - Instance of the implementing HuskHomes plugin
*/
@NotNull
public User player;
private final HuskHomes plugin;
/**
* The target position for the player
* The {@link User} who is doing the teleporting
*/
@NotNull
public Position target;
@Nullable
public final User teleporter;
/**
* The type of the teleport
* The {@link OnlineUser} on this server executing the teleport.
* </p>
* Can be the same as the {@link #teleporter}, but not necessarily
*/
@NotNull
public TeleportType type;
public final OnlineUser executor;
public Teleport(@NotNull User player, @NotNull Position target, @NotNull TeleportType type) {
this.player = player;
/**
* The target {@link Position} the teleporter should be teleported to
*/
@Nullable
public final Position target;
/**
* The {@link TeleportType type} of the teleport
*/
@NotNull
public final TeleportType type;
/**
* {@link Settings.EconomyAction}s to be checked against the {@link #executor executor}'s balance
*/
@NotNull
public final Set<Settings.EconomyAction> economyActions;
// Internal constructor -- use TeleportBuilder to instantiate a teleport
protected Teleport(@Nullable User teleporter, @NotNull OnlineUser executor, @Nullable Position target,
@NotNull TeleportType type, @NotNull Set<Settings.EconomyAction> economyActions,
@NotNull HuskHomes plugin) {
this.teleporter = teleporter;
this.executor = executor;
this.target = target;
this.type = type;
this.economyActions = economyActions;
this.plugin = plugin;
}
/**
* Create a teleport builder with an executor to carry it out
*
* @param plugin Instance of the implementing HuskHomes plugin
* @param executor The {@link OnlineUser} on this server executing the teleport.
* Not necessarily the person being teleported, which can be set independently with
* {{@link TeleportBuilder#setTeleporter(User)}}
* @return A new {@link TeleportBuilder} instance
*/
public static TeleportBuilder builder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) {
return new TeleportBuilder(plugin, executor);
}
/**
* Execute this teleport
*
* @return A {@link CompletableFuture} that completes when the teleport is finished
*/
public CompletableFuture<TeleportResult> execute() {
// Validate the teleporter
if (teleporter == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED);
}
// Validate the target
if (target == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED);
}
// Check economy actions
for (Settings.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY);
}
}
// Run the teleport and apply economy actions
return run(teleporter).thenApply(result -> {
if (teleporter instanceof OnlineUser user) {
finish(user, result);
}
return result;
});
}
/**
* Run the teleport, either locally or over the network
*
* @param teleporter The {@link User} who is doing the teleporting
* @return A {@link CompletableFuture} that completes when the teleport is finished
*/
private CompletableFuture<TeleportResult> run(@NotNull User teleporter) {
return teleporter instanceof OnlineUser onlineUser
? teleportLocalUser(onlineUser)
: teleportNetworkedUser();
}
/**
* Finish the teleport, finalize economy transactions if successful and send message
*
* @param teleporter The {@link OnlineUser} who was teleported
* @param result The {@link TeleportResult} of the teleport
*/
private void finish(@NotNull OnlineUser teleporter, @NotNull TeleportResult result) {
if (result.successful) {
// Complete economy transactions
economyActions.forEach(economyAction -> plugin.performEconomyTransaction(executor, economyAction));
// Play sound effect if successful
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(teleporter::playSound);
}
// Send result message
result.sendMessage(plugin.getLocales(), teleporter);
}
/**
* Teleport a local user
*
* @param teleporter The teleporter
* @return A {@link CompletableFuture} that completes when the teleport is finished
*/
private CompletableFuture<TeleportResult> teleportLocalUser(@NotNull OnlineUser teleporter) {
assert target != null;
// Dispatch the teleport event and update the player's last position
plugin.getEventDispatcher().dispatchTeleportEvent(this);
if (!plugin.getSettings().backCommandSaveOnTeleportEvent && type == TeleportType.TELEPORT) {
plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition());
}
// If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().crossServer || target.server.equals(plugin.getPluginServer())) {
return teleporter.teleportLocally(target, plugin.getSettings().asynchronousTeleports);
}
// If the target position is on another server, execute a cross-server teleport
final CompletableFuture<TeleportResult> teleportFuture = new CompletableFuture<>();
plugin.getDatabase()
.setCurrentTeleport(teleporter, this)
.thenApply(ignored -> plugin
.getNetworkMessenger()
.sendPlayer(teleporter, target.server)
.thenApply(completed -> completed
? TeleportResult.COMPLETED_CROSS_SERVER
: TeleportResult.FAILED_INVALID_SERVER))
.orTimeout(10, TimeUnit.SECONDS)
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Cross-server teleport timed out for " + teleporter.username);
plugin.getDatabase().setCurrentTeleport(teleporter, null);
return CompletableFuture.completedFuture(TeleportResult.FAILED_INVALID_SERVER);
})
.thenAccept(result -> result.thenAcceptAsync(teleportFuture::complete));
return teleportFuture;
}
/**
* Teleport a user not on this server but on the proxy network
*
* @return A {@link CompletableFuture} that completes when the teleport is finished.
* Successful cross-server teleports will return {@link TeleportResult#COMPLETED_CROSS_SERVER}.
* @implNote Cross-server teleports will return with a {@link TeleportResult#FAILED_INVALID_SERVER} result if the
* target server is not online, or connection timed out
*/
private CompletableFuture<TeleportResult> teleportNetworkedUser() {
assert target != null;
assert teleporter != null;
// Send a network message to a user on another server to teleport them to the target position
return plugin.getNetworkMessenger()
.sendMessage(executor,
new Message(Message.MessageType.TELEPORT_TO_POSITION_REQUEST,
executor.username,
teleporter.username,
MessagePayload.withPosition(target),
Message.RelayType.MESSAGE,
plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> null)
.thenApply(result -> {
if (result == null || result.payload.teleportResult == null) {
return TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED;
}
return result.payload.teleportResult;
});
}
}
@@ -0,0 +1,240 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.messenger.MessagePayload;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
/**
* A builder for {@link Teleport}s and {@link TimedTeleport}s
*
* @since 3.1
*/
@SuppressWarnings("unused")
public class TeleportBuilder {
// Instance of the implementing plugin
@NotNull
private final HuskHomes plugin;
/**
* The executor of the teleport; the one who triggered the teleport to happen;
* whom may not necessarily the person being <i>teleported</i>
*/
@NotNull
private final OnlineUser executor;
/**
* The teleporter; the one who is being teleported, to be resolved before construction
*/
private CompletableFuture<User> teleporter;
/**
* The target position for the teleporter, to be resolved before construction
*/
private CompletableFuture<Position> target;
/**
* List of {@link Settings.EconomyAction}s to check against.
* <p>
* Note that these are checked against the <i>{@link #executor executor}</i> of the teleport;
* not necessarily the one doing the teleporting
*/
private final Set<Settings.EconomyAction> economyActions = new HashSet<>();
/**
* The type of teleport. Defaults to {@link TeleportType#TELEPORT}
*/
private TeleportType type = TeleportType.TELEPORT;
protected TeleportBuilder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) {
this.plugin = plugin;
this.executor = executor;
this.teleporter = CompletableFuture.completedFuture(executor);
}
/**
* Set the person being teleported as a {@link User}
*
* @param teleporter The {@link User} who is doing the teleporting
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTeleporter(@NotNull User teleporter) {
this.teleporter = CompletableFuture.completedFuture(teleporter);
return this;
}
/**
* Set the person being teleported as the username of a player, which will attempt to be resolved
* into a user at the time of construction
*
* @param teleporterUsername The username of the player who is doing the teleporting
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTeleporter(@NotNull String teleporterUsername) {
this.teleporter = CompletableFuture.supplyAsync(() -> plugin
.findPlayer(teleporterUsername)
.map(onlineUser -> (User) onlineUser)
.or(() -> {
if (plugin.getSettings().crossServer) {
return plugin.getNetworkMessenger()
.findPlayer(executor, teleporterUsername).join()
.map(username -> new User(UUID.randomUUID(), username));
}
return Optional.empty();
})
.orElse(null));
return this;
}
/**
* Set the target as a {@link Position}
*
* @param position The {@link Position} the teleport is aiming to teleport the {@link #teleporter} to
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull Position position) {
this.target = CompletableFuture.completedFuture(position);
return this;
}
/**
* Set the target as a {@link Location} on this server
*
* @param location The {@link Location} on this server the teleport is aiming to teleport the {@link #teleporter} to
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull Location location) {
this.target = CompletableFuture.completedFuture(new Position(location, plugin.getPluginServer()));
return this;
}
/**
* Set the target as the position of a player, specified by their username, who may be on another server.
*
* @param targetUsername The username of the player on the target server the teleport is aiming to teleport the
* {@link #teleporter} to
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull String targetUsername) {
this.target = getPlayerPosition(targetUsername).thenApply(position -> position.orElse(null));
return this;
}
/**
* Set the type of teleport
*
* @param type The {@link TeleportType} of the teleport
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setType(@NotNull TeleportType type) {
this.type = type;
return this;
}
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link Settings.EconomyAction}s to check against
* @return The {@link TeleportBuilder} instance
* @implNote These are checked against the <i>{@link #executor executor}</i> of the teleport;
* not necessarily the one doing the teleporting
*/
public TeleportBuilder setEconomyActions(@NotNull Set<Settings.EconomyAction> economyActions) {
this.economyActions.addAll(economyActions);
return this;
}
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link Settings.EconomyAction}s to check against
* @return The {@link TeleportBuilder} instance
* @implNote These are checked against the <i>{@link #executor executor}</i> of the teleport;
* not necessarily the one doing the teleporting
*/
public TeleportBuilder setEconomyActions(@NotNull Settings.EconomyAction... economyActions) {
this.economyActions.addAll(Arrays.asList(economyActions));
return this;
}
/**
* Resolve the teleporter and target, and construct as an instantly-completing {@link Teleport}
*
* @return The constructed {@link Teleport}
*/
public CompletableFuture<Teleport> toTeleport() {
return CompletableFuture.supplyAsync(() -> {
final User teleporter = this.teleporter.join();
final Position target = this.target.join();
return new Teleport(teleporter, executor, target, type, economyActions, plugin);
}).exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create teleport", e);
return null;
});
}
/**
* Resolve the teleporter and target, and construct as a {@link TimedTeleport}
*
* @return The constructed {@link TimedTeleport}
*/
public CompletableFuture<TimedTeleport> toTimedTeleport() {
return CompletableFuture.supplyAsync(() -> {
final User teleporter = this.teleporter.join();
final Position target = this.target.join();
final int warmupTime = plugin.getSettings().teleportWarmupTime;
if (!(teleporter instanceof OnlineUser onlineUser)) {
throw new IllegalStateException("Timed teleports can only be executed for local users");
}
return new TimedTeleport(onlineUser, executor, target, type, warmupTime, economyActions, plugin);
}).exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create timed teleport", e);
return null;
});
}
/**
* Gets the position of a player by their username, including players on other servers
*
* @param playerName the username of the player being requested
* @return future optionally supplying the player's position, if the player could be found
*/
private CompletableFuture<Optional<Position>> getPlayerPosition(@NotNull String playerName) {
final Optional<OnlineUser> localPlayer = plugin.findPlayer(playerName);
if (localPlayer.isPresent()) {
return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition()));
}
if (plugin.getSettings().crossServer) {
return plugin.getNetworkMessenger()
.findPlayer(executor, playerName)
.thenApply(foundPlayer -> {
if (foundPlayer.isEmpty()) {
return Optional.empty();
}
return plugin.getNetworkMessenger()
.sendMessage(executor, new Message(Message.MessageType.POSITION_REQUEST, executor.username,
playerName, MessagePayload.empty(), Message.RelayType.MESSAGE,
plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> null)
.thenApply(reply -> Optional.ofNullable(reply.payload.position)).join();
});
}
return CompletableFuture.supplyAsync(Optional::empty);
}
}
@@ -1,512 +0,0 @@
package net.william278.huskhomes.teleport;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.messenger.MessagePayload;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
/**
* Cross-platform teleportation manager
*/
public class TeleportManager {
/**
* Instance of the implementing plugin
*/
@NotNull
protected final HuskHomes plugin;
/**
* A set of user UUIDs currently on warmup countdowns for {@link TimedTeleport}
*/
@NotNull
private final HashSet<UUID> currentlyOnWarmup = new HashSet<>();
public TeleportManager(@NotNull HuskHomes implementor) {
this.plugin = implementor;
}
/**
* Attempt to teleport a {@link OnlineUser} to a {@link User}'s home by the home name
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param homeOwner the {@link User} who owns the home
* @param homeName the name of the home
*/
public void teleportToHomeByName(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull String homeName) {
plugin.getDatabase().getHome(homeOwner, homeName).thenAccept(optionalHome ->
optionalHome.ifPresentOrElse(home -> teleportToHome(onlineUser, home), () -> {
if (homeOwner.uuid.equals(onlineUser.uuid)) {
plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(onlineUser::sendMessage);
}
}));
}
/**
* Attempt to teleport a {@link OnlineUser} to a {@link Home}
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param home the {@link Home} to teleport to
*/
public void teleportToHome(@NotNull OnlineUser onlineUser, @NotNull Home home) {
if (!home.owner.uuid.equals(onlineUser.uuid)) {
if (!home.isPublic && !onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_public_home_invalid", home.owner.username, home.meta.name)
.ifPresent(onlineUser::sendMessage);
return;
}
}
timedTeleport(onlineUser, home).thenAccept(result -> finishTeleport(onlineUser, result));
}
/**
* Attempt to teleport a {@link OnlineUser} to a server warp by its' given name
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param warpName the name of the warp
*/
public void teleportToWarpByName(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
plugin.getDatabase().getWarp(warpName).thenAccept(optionalWarp ->
optionalWarp.ifPresentOrElse(warp ->
teleportToWarp(onlineUser, warp), () ->
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(onlineUser::sendMessage)));
}
/**
* Attempt to teleport a {@link OnlineUser} to a server {@link Warp}.
* <p>
* If permission restricted warps are enabled, the user will not be teleported if they lack the
* required permission node ({@code huskhomes.warp.[warp_name]})
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param warp the {@link Warp} to teleport to
*/
public void teleportToWarp(@NotNull OnlineUser onlineUser, @NotNull Warp warp) {
// Check against warp permission restrictions if enabled (huskhomes.warp.<warp_name>)
if (plugin.getSettings().permissionRestrictWarps) {
if (!onlineUser.hasPermission(warp.getPermissionNode())) {
plugin.getLocales().getLocale("error_permission_restricted_warp", warp.meta.name)
.ifPresent(onlineUser::sendMessage);
return;
}
}
timedTeleport(onlineUser, warp).thenAccept(result -> finishTeleport(onlineUser, result));
}
/**
* Teleport a {@link OnlineUser} to another player by username
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param targetPlayer the name of the target player
* @param timed whether the teleport is timed ({@code true}), otherwise instant
*/
public void teleportToPlayerByName(@NotNull OnlineUser onlineUser, @NotNull String targetPlayer, boolean timed) {
CompletableFuture.runAsync(() -> {
final Optional<OnlineUser> localPlayer = plugin.findPlayer(targetPlayer);
if (localPlayer.isPresent()) {
(timed ? timedTeleport(onlineUser, localPlayer.get().getPosition()) : teleport(onlineUser, localPlayer.get().getPosition()))
.thenAccept(result -> finishTeleport(onlineUser, result));
} else if (plugin.getSettings().crossServer) {
getPlayerPositionByName(onlineUser, targetPlayer).thenAccept(optionalPosition -> {
if (optionalPosition.isPresent()) {
(timed ? timedTeleport(onlineUser, optionalPosition.get()) : teleport(onlineUser, optionalPosition.get()))
.thenAccept(teleportResult -> finishTeleport(onlineUser, teleportResult));
return;
}
plugin.getLocales().getLocale("error_player_not_found", targetPlayer)
.ifPresent(onlineUser::sendMessage);
});
} else {
plugin.getLocales().getLocale("error_player_not_found", targetPlayer)
.ifPresent(onlineUser::sendMessage);
}
});
}
/**
* Teleport a player by username to a {@link Position} by name
*
* @param playerName username of the target player to teleport
* @param position the {@link Position} to teleport to
* @param requester the {@link OnlineUser} performing the teleport action
* @param timed whether the teleport is timed ({@code true}), otherwise instant
* @return a {@link CompletableFuture} that completes when the teleport is complete with the {@link TeleportResult},
* if it was processed, otherwise an empty {@link Optional} if the player was not found
*/
public CompletableFuture<Optional<TeleportResult>> teleportPlayerByName(@NotNull String playerName, @NotNull Position position,
@NotNull OnlineUser requester, boolean timed) {
final Optional<OnlineUser> localPlayer = plugin.findPlayer(playerName);
if (localPlayer.isPresent()) {
return (timed ? timedTeleport(localPlayer.get(), position) : teleport(localPlayer.get(), position))
.thenApply(Optional::of);
}
if (plugin.getSettings().crossServer) {
// If the player is not online, cancel
if (plugin.getCache().players.stream().noneMatch(player -> player.equalsIgnoreCase(playerName))) {
return CompletableFuture.completedFuture(Optional.empty());
}
// Dispatch the message cross-server
return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.TELEPORT_TO_POSITION_REQUEST,
requester.username,
playerName,
MessagePayload.withPosition(position),
Message.RelayType.MESSAGE,
plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> null)
.thenApply(result -> {
if (result == null || result.payload.teleportResult == null) {
return Optional.empty();
}
return Optional.of(result.payload.teleportResult);
});
}
return CompletableFuture.supplyAsync(Optional::empty);
}
/**
* Teleport two players by username
*
* @param playerName the name of the player to teleport
* @param targetPlayer the name of the target player
* @param requester the {@link OnlineUser} performing the teleport action
* @param timed whether the teleport is timed ({@code true}), otherwise instant
* @return a {@link CompletableFuture} that completes when the teleport is complete with the {@link TeleportResult},
*/
public CompletableFuture<Optional<TeleportResult>> teleportNamedPlayers(@NotNull String playerName, @NotNull String targetPlayer,
@NotNull OnlineUser requester, final boolean timed) {
return getPlayerPositionByName(requester, targetPlayer).thenApplyAsync(position -> {
if (position.isEmpty()) {
return Optional.empty();
}
return teleportPlayerByName(playerName, position.get(), requester, timed).join();
});
}
/**
* Gets the position of a player by their username, including players on other servers
*
* @param requester the {@link OnlineUser} requesting their position
* @param playerName the username of the player being requested
* @return future optionally supplying the player's position, if the player could be found
*/
private CompletableFuture<Optional<Position>> getPlayerPositionByName(@NotNull OnlineUser requester,
@NotNull String playerName) {
final Optional<OnlineUser> localPlayer = plugin.findPlayer(playerName);
if (localPlayer.isPresent()) {
return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition()));
}
if (plugin.getSettings().crossServer) {
return plugin.getNetworkMessenger().findPlayer(requester, playerName).thenApply(foundPlayer -> {
if (foundPlayer.isEmpty()) {
return Optional.empty();
}
return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.POSITION_REQUEST,
requester.username,
playerName,
MessagePayload.empty(),
Message.RelayType.MESSAGE,
plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> null)
.thenApply(reply -> Optional.ofNullable(reply.payload.position)).join();
});
}
return CompletableFuture.supplyAsync(Optional::empty);
}
/**
* Teleport a {@link OnlineUser} to a specified {@link Position} after a warmup period
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param position the target {@link Position} to teleport to
* @param economyActions any economy actions to validate before the teleport.
* Note that this will not actually carry out the economy transactions, only validate them
*/
public CompletableFuture<TeleportResult> timedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position position,
@NotNull Settings.EconomyAction... economyActions) {
// Prevent players starting multiple timed teleports
if (currentlyOnWarmup.contains(onlineUser.uuid)) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING);
}
final int teleportWarmupTime = plugin.getSettings().teleportWarmupTime;
if (!onlineUser.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) {
// Cancel if the player is already moving
if (onlineUser.isMoving()) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_MOVING);
}
// Carry out the timed teleport
final TimedTeleport timedTeleport = new TimedTeleport(onlineUser, position, teleportWarmupTime);
return processTeleportWarmup(timedTeleport).thenApplyAsync(teleport -> {
if (!teleport.cancelled) {
for (final Settings.EconomyAction action : economyActions) {
if (!plugin.validateEconomyCheck(onlineUser, action)) {
return TeleportResult.CANCELLED;
}
}
return teleport(onlineUser, position).join();
} else {
return TeleportResult.CANCELLED;
}
});
} else {
return teleport(onlineUser, position);
}
}
/**
* Handles a completed {@link OnlineUser}'s {@link TeleportResult} with the appropriate message
*
* @param onlineUser the {@link OnlineUser} to send the teleport completion message to
* @param teleportResult the {@link TeleportResult} to handle
* @param economyActions any economy actions to complete the transaction of
*/
public void finishTeleport(@NotNull OnlineUser onlineUser, @NotNull TeleportResult teleportResult,
@NotNull Settings.EconomyAction... economyActions) {
// Display the teleport result message
switch (teleportResult) {
case COMPLETED_LOCALLY -> plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
case FAILED_ALREADY_TELEPORTING -> plugin.getLocales().getLocale("error_already_teleporting")
.ifPresent(onlineUser::sendMessage);
case FAILED_MOVING -> plugin.getLocales().getLocale("error_teleport_warmup_stand_still")
.ifPresent(onlineUser::sendMessage);
case FAILED_INVALID_WORLD -> plugin.getLocales().getLocale("error_invalid_world")
.ifPresent(onlineUser::sendMessage);
case FAILED_ILLEGAL_COORDINATES -> plugin.getLocales().getLocale("error_illegal_target_coordinates")
.ifPresent(onlineUser::sendMessage);
case FAILED_INVALID_SERVER -> plugin.getLocales().getLocale("error_invalid_server")
.ifPresent(onlineUser::sendMessage);
}
// If the result was successful
if (teleportResult.successful) {
// Play sound
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(onlineUser::playSound);
// Handle economy actions
for (final Settings.EconomyAction action : economyActions) {
plugin.performEconomyTransaction(onlineUser, action);
}
} else if (plugin.getSettings().crossServer) {
plugin.getDatabase().setCurrentTeleport(onlineUser, null);
}
}
/**
* 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
* @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) {
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);
// Call the teleport event
plugin.getEventDispatcher().dispatchTeleportEvent(teleport);
// Update the player's last position
if (!plugin.getSettings().backCommandSaveOnTeleportEvent && teleportType == TeleportType.TELEPORT) {
plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
}
// Teleport player locally, or across server depending on need
if (position.server.equals(plugin.getPluginServer())) {
return onlineUser.teleport(teleport.target, plugin.getSettings().asynchronousTeleports);
} else {
return teleportCrossServer(onlineUser, teleport);
}
}
/**
* Handles a cross-server teleport, setting database parameters and dispatching a player across the network
*
* @param onlineUser the {@link OnlineUser} to teleport
* @param teleport the {@link Teleport} to carry out
* @return future completing when the teleport is complete with a {@link TeleportResult}.
* Successful cross-server teleports will return {@link TeleportResult#COMPLETED_CROSS_SERVER}.
* <p>Note that cross-server teleports will return with a {@link TeleportResult#FAILED_INVALID_SERVER} result if the
* target server is not online, or connection timed out
*/
private CompletableFuture<TeleportResult> teleportCrossServer(@NotNull OnlineUser onlineUser, @NotNull Teleport teleport) {
final CompletableFuture<TeleportResult> teleportFuture = new CompletableFuture<>();
plugin.getDatabase().setCurrentTeleport(teleport.player, teleport)
.thenApply(ignored -> plugin.getNetworkMessenger()
.sendPlayer(onlineUser, teleport.target.server)
.thenApply(completed -> completed ? TeleportResult.COMPLETED_CROSS_SERVER
: TeleportResult.FAILED_INVALID_SERVER))
.orTimeout(10, TimeUnit.SECONDS)
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Cross-server teleport timed out for " + onlineUser.username);
plugin.getDatabase().setCurrentTeleport(teleport.player, null);
return CompletableFuture.completedFuture(TeleportResult.FAILED_INVALID_SERVER);
})
.thenAccept(result -> result.thenAcceptAsync(teleportFuture::complete));
return teleportFuture;
}
/**
* Start the processing of a {@link TimedTeleport} warmup
*
* @param teleport the {@link TimedTeleport} to process
* @return a future, returning when the teleport has finished
*/
private CompletableFuture<TimedTeleport> processTeleportWarmup(@NotNull final TimedTeleport teleport) {
// Execute the warmup start event
return plugin.getEventDispatcher().dispatchTeleportWarmupEvent(teleport, teleport.timeLeft).thenApplyAsync(event -> {
// Handle event cancellation
if (event.isCancelled()) {
teleport.cancelled = true;
return teleport;
}
// Mark the player as warming up
currentlyOnWarmup.add(teleport.getPlayer().uuid);
// Display the message
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(teleport.timeLeft))
.ifPresent(teleport.getPlayer()::sendMessage);
// Create a scheduled executor to tick the timed teleport
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
final CompletableFuture<TimedTeleport> timedTeleportFuture = new CompletableFuture<>();
executor.scheduleAtFixedRate(() -> {
// Display countdown action bar message
if (teleport.timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
.ifPresent(sound -> teleport.getPlayer().playSound(sound));
plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(teleport.timeLeft))
.ifPresent(message -> sendWarmupStatusMessage(teleport.getPlayer(), message));
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(message -> sendWarmupStatusMessage(teleport.getPlayer(), message));
}
// Tick (decrement) the timed teleport timer
final Optional<TimedTeleport> result = tickTeleportWarmup(teleport);
if (result.isPresent()) {
currentlyOnWarmup.remove(teleport.getPlayer().uuid);
timedTeleportFuture.complete(teleport);
executor.shutdown();
}
}, 0, 1, TimeUnit.SECONDS);
return timedTeleportFuture.join();
});
}
/**
* Ticks a timed teleport, decrementing the time left until the teleport is complete
* <p>
* A timed teleport will be cancelled if certain criteria are met:
* <ul>
* <li>The player has left the server</li>
* <li>The plugin is disabling</li>
* <li>The player has moved beyond the movement threshold from when the warmup started</li>
* <li>The player has taken damage (though they may heal, have status ailments or lose/gain hunger)</li>
* </ul>
*
* @param teleport the {@link TimedTeleport} being ticked
* @return Optional containing the {@link TimedTeleport} after it has been ticked,
* or {@link Optional#empty()} if the teleport has been cancelled
*/
private Optional<TimedTeleport> tickTeleportWarmup(@NotNull final TimedTeleport teleport) {
if (teleport.isDone()) {
return Optional.of(teleport);
}
// Cancel the timed teleport if the player takes damage
if (teleport.hasTakenDamage()) {
plugin.getLocales().getLocale("teleporting_cancelled_damage").ifPresent(locale ->
teleport.getPlayer().sendMessage(locale));
plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(message -> sendWarmupStatusMessage(teleport.getPlayer(), message));
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(sound -> teleport.getPlayer().playSound(sound));
teleport.cancelled = true;
return Optional.of(teleport);
}
// Cancel the timed teleport if the player moves
if (teleport.hasMoved()) {
plugin.getLocales().getLocale("teleporting_cancelled_movement").ifPresent(locale ->
teleport.getPlayer().sendMessage(locale));
plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(message -> sendWarmupStatusMessage(teleport.getPlayer(), message));
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(sound -> teleport.getPlayer().playSound(sound));
teleport.cancelled = true;
return Optional.of(teleport);
}
// Decrement the countdown timer
teleport.countDown();
return Optional.empty();
}
private void sendWarmupStatusMessage(@NotNull OnlineUser onlineUser, @NotNull MineDown message) {
switch (plugin.getSettings().teleportWarmupDisplay) {
case ACTION_BAR -> onlineUser.sendActionBar(message);
case SUBTITLE -> onlineUser.sendTitle(message, true);
case TITLE -> onlineUser.sendTitle(message, false);
case MESSAGE -> onlineUser.sendMessage(message);
}
}
/**
* Returns if the player is currently warming up to teleport
*
* @param uuid the player's {@link UUID}
* @return {@code true} if the player is warming up, {@code false} otherwise
*/
public boolean isWarmingUp(@NotNull final UUID uuid) {
return currentlyOnWarmup.contains(uuid);
}
}
@@ -1,7 +1,13 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Represents the result of a completed {@link Teleport}
@@ -11,53 +17,88 @@ public enum TeleportResult {
/**
* Returns if the {@link Teleport} was completed locally, successfully
*/
COMPLETED_LOCALLY(true),
COMPLETED_LOCALLY(true, "teleporting_complete"),
/**
* Returns if the {@link Teleport} was completed cross-server
*/
COMPLETED_CROSS_SERVER(true),
COMPLETED_CROSS_SERVER(true, "teleporting_complete"),
/**
* Returns if the {@link Teleport} failed because the user is already teleporting
*/
FAILED_ALREADY_TELEPORTING(false),
FAILED_ALREADY_TELEPORTING(false, "error_already_teleporting"),
/**
* Returns if the {@link TimedTeleport} warmup could not be started because they were moving
*/
FAILED_MOVING(false),
FAILED_MOVING(false, "error_teleport_warmup_stand_still"),
/**
* Returns if the {@link Teleport} failed because the {@link World} of the
* target {@link Position} could not be found
*/
FAILED_INVALID_WORLD(false),
FAILED_INVALID_WORLD(false, "error_invalid_world"),
/**
* Returns if the {@link Teleport} failed because the server of the target
* {@link Position} was invalid or not online
*/
FAILED_INVALID_SERVER(false),
FAILED_INVALID_SERVER(false, "error_invalid_server"),
/**
* Returns if the {@link Teleport} failed because the coordinates of the
* target {@link Position} were outside the world border limits
*/
FAILED_ILLEGAL_COORDINATES(false),
FAILED_ILLEGAL_COORDINATES(false, "error_illegal_target_coordinates"),
/**
* Returns if the {@link Teleport} failed because the teleporter could not be resolved or was offline
*/
FAILED_TELEPORTER_NOT_RESOLVED(false), //todo error message
/**
* Returns if the {@link Teleport} failed because the target {@link Position} could not be resolved
*/
FAILED_TARGET_NOT_RESOLVED(false), //todo error message
/**
* Returns if the teleport was cancelled, for example if a {@link TimedTeleport} in progress is cancelled
*/
CANCELLED(false);
CANCELLED(false),
/**
* Returns if the {@link Teleport} was cancelled due to failing economy checks
*/
CANCELLED_ECONOMY(false);
/**
* Is {@code true} if the teleport was a success
*/
public final boolean successful;
@Nullable
private final String messageId;
TeleportResult(boolean successful, @NotNull String messageId) {
this.successful = successful;
this.messageId = messageId;
}
TeleportResult(boolean successful) {
this.successful = successful;
this.messageId = null;
}
/**
* Send an {@link OnlineUser} the corresponding message for this {@link TeleportResult}, if there is one
*
* @param locales the {@link Locales} instance to use
* @param user the {@link OnlineUser} to send the message to
* @since 3.1
*/
public void sendMessage(@NotNull Locales locales, @NotNull OnlineUser user) {
Optional.ofNullable(messageId).flatMap(locales::getLocale).ifPresent(user::sendMessage);
}
}
@@ -1,44 +1,187 @@
package net.william278.huskhomes.teleport;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
/**
* Represents a {@link Teleport} due to occur after a warmup period
*/
public class TimedTeleport {
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public final OnlineUser onlineUser;
public final Position targetPosition;
public final Position startLocation;
public class TimedTeleport extends Teleport {
private final HuskHomes plugin;
private final OnlineUser teleporter;
private final Position startLocation;
private final double startHealth;
protected int timeLeft;
public boolean cancelled = false;
private int timeLeft;
private boolean cancelled = false;
protected TimedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position targetPosition, int duration) {
this.onlineUser = onlineUser;
this.targetPosition = targetPosition;
this.startLocation = onlineUser.getPosition();
this.startHealth = onlineUser.getHealth();
this.timeLeft = duration;
}
public final boolean isDone() {
return timeLeft <= 0;
}
public final void countDown() {
timeLeft--;
protected TimedTeleport(@NotNull OnlineUser teleporter, @NotNull OnlineUser executor, @NotNull Position target,
@NotNull TeleportType type, int warmupTime, @NotNull Set<Settings.EconomyAction> economyActions,
@NotNull HuskHomes plugin) {
super(teleporter, executor, target, type, economyActions, plugin);
this.plugin = plugin;
this.startLocation = teleporter.getPosition();
this.startHealth = teleporter.getHealth();
this.timeLeft = warmupTime;
this.teleporter = teleporter;
}
/**
* Get the teleporting player
* Execute the timed teleport, ticking the countdown and teleporting the player when the countdown is complete
*
* @return the {@link OnlineUser} who is teleporting
* @return a {@link CompletableFuture} that completes when the teleport is complete or has been cancelled
*/
public OnlineUser getPlayer() {
return onlineUser;
@Override
public CompletableFuture<TeleportResult> execute() {
// If the target has not been resolved, fail the teleport
if (target == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED);
}
// Check if the teleporter is already warming up to teleport
if (plugin.getCache().currentlyOnWarmup.contains(teleporter.uuid)) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING);
}
// Check if the teleporter can bypass warmup
if (teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) {
return super.execute();
}
// Check economy actions
for (Settings.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY);
}
}
// Check if they are moving at the start of the teleport
if (teleporter.isMoving()) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_MOVING);
}
// Process the warmup and execute the teleport
return process().thenApplyAsync(ignored -> {
if (cancelled) {
return TeleportResult.CANCELLED;
}
return super.execute().join();
});
}
/**
* Start the processing of a {@link TimedTeleport} warmup
*
* @return a future, returning when the teleport has finished
*/
private CompletableFuture<Void> process() {
final CompletableFuture<Void> timedTeleportFuture = new CompletableFuture<>();
// Execute the warmup start event
plugin.getEventDispatcher().dispatchTeleportWarmupEvent(this, timeLeft).thenAccept(event -> {
// Handle event cancellation
if (event.isCancelled()) {
this.cancelled = true;
return;
}
// Mark the player as warming up and display the message
plugin.getCache().currentlyOnWarmup.add(teleporter.uuid);
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft))
.ifPresent(teleporter::sendMessage);
// Create a scheduled executor to tick the timed teleport
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
// Display countdown action bar message
if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
.ifPresent(teleporter::playSound);
plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft))
.ifPresent(this::sendStatusMessage);
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(this::sendStatusMessage);
}
// Tick (decrement) the timed teleport timer and end it if done
if (tickWarmup()) {
plugin.getCache().currentlyOnWarmup.remove(teleporter.uuid);
timedTeleportFuture.complete(null);
executor.shutdown();
}
}, 0, 1, TimeUnit.SECONDS);
});
return timedTeleportFuture;
}
/**
* Ticks a timed teleport, decrementing the time left until the teleport is complete
* <p>
* A timed teleport will be cancelled if certain criteria are met:
* <ul>
* <li>The player has left the server</li>
* <li>The plugin is disabling</li>
* <li>The player has moved beyond the movement threshold from when the warmup started</li>
* <li>The player has taken damage (though they may heal, have status ailments or lose/gain hunger)</li>
* </ul>
*
* @return {@code true} if the warmup is complete, {@code false} otherwise
*/
private boolean tickWarmup() {
if (timeLeft <= 0) {
return true;
}
// Cancel the timed teleport if the player takes damage
if (hasTeleporterTakenDamage()) {
plugin.getLocales().getLocale("teleporting_cancelled_damage")
.ifPresent(teleporter::sendMessage);
plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
cancelled = true;
return true;
}
// Cancel the timed teleport if the player moves
if (hasTeleporterMoved()) {
plugin.getLocales().getLocale("teleporting_cancelled_movement")
.ifPresent(teleporter::sendMessage);
plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
cancelled = true;
return true;
}
// Decrement the countdown timer
timeLeft--;
return false;
}
/**
* Send a teleport warmup status message to the configured slot
*
* @param message the message to send
*/
private void sendStatusMessage(@NotNull MineDown message) {
switch (plugin.getSettings().teleportWarmupDisplay) {
case ACTION_BAR -> teleporter.sendActionBar(message);
case SUBTITLE -> teleporter.sendTitle(message, true);
case TITLE -> teleporter.sendTitle(message, false);
case MESSAGE -> teleporter.sendMessage(message);
}
}
/**
@@ -46,11 +189,11 @@ public class TimedTeleport {
*
* @return {@code true} if the player has moved; {@code false} otherwise
*/
public boolean hasMoved() {
private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.x - onlineUser.getPosition().x) +
Math.abs(startLocation.y - onlineUser.getPosition().y) +
Math.abs(startLocation.z - onlineUser.getPosition().z);
double movementDistance = Math.abs(startLocation.x - teleporter.getPosition().x) +
Math.abs(startLocation.y - teleporter.getPosition().y) +
Math.abs(startLocation.z - teleporter.getPosition().z);
return movementDistance > maxMovementDistance;
}
@@ -59,17 +202,8 @@ public class TimedTeleport {
*
* @return {@code true} if the player has taken damage
*/
public boolean hasTakenDamage() {
return onlineUser.getHealth() < startHealth;
}
/**
* Returns the target {@link Position} of this timed teleport
*
* @return the target {@link Position}
*/
public Position getTargetPosition() {
return targetPosition;
private boolean hasTeleporterTakenDamage() {
return teleporter.getHealth() < startHealth;
}
}