Further refactoring, move away from using future thread pool

This commit is contained in:
William278 committed 2023-03-04 21:38:53 +00:00
1 parent 4c90e5498c
commit 39e0b25d46
56 files changed
+737 -1713

No files matched your search

@@ -1,117 +0,0 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Represents the result of executing a {@link Teleport} or {@link TimedTeleport}
*
* @since 3.1
*/
public class CompletedTeleport {
/**
* The state of the {@link Teleport}
*/
@NotNull
private final TeleportResult state;
/**
* The {@link User} who is doing the teleporting
*/
@Nullable
private final User teleporter;
/**
* The {@link Position} the teleporter should be teleported to
*/
@Nullable
private final Position destination;
/**
* <b>Internal</b> - Create a new {@link CompletedTeleport} (use {@link #from(TeleportResult, Teleport)})
*
* @param state The {@link TeleportResult} of completing the teleport
* @param teleporter The {@link User} who is doing the teleporting
* @param destination The {@link Position} the teleporter should be teleported to
* @since 3.1
*/
private CompletedTeleport(@NotNull TeleportResult state, @Nullable User teleporter, @Nullable Position destination) {
this.state = state;
this.teleporter = teleporter;
this.destination = destination;
}
/**
* Create a new {@link CompletedTeleport} for a {@link Teleport} with an outcome {@link TeleportResult}
*
* @param state The outcome {@link TeleportResult}
* @param teleport The {@link Teleport} that was executed
* @return The {@link CompletedTeleport} of executing the supplied {@link Teleport}
* @since 3.1
*/
public static CompletedTeleport from(@NotNull TeleportResult state, @NotNull Teleport teleport) {
return new CompletedTeleport(state, teleport.teleporter, teleport.target);
}
/**
* Get the state of the {@link Teleport} after execution has finished
*
* @return The {@link TeleportResult} of the teleport
* @since 3.1
*/
@NotNull
public TeleportResult getState() {
return state;
}
/**
* Returns if the teleport was successful
*
* @return {@code true} if the teleport was successful, {@code false} otherwise
* @since 3.1
*/
public boolean successful() {
return state.successful;
}
/**
* Get the {@link User} who is doing the teleporting
*
* @return The teleporter, if they were resolved
* @implNote The optional will return empty if the state is {@link TeleportResult#FAILED_TELEPORTER_NOT_RESOLVED}
* @since 3.1
*/
public Optional<User> getTeleporter() {
return Optional.ofNullable(teleporter);
}
/**
* Get the target {@link Position} the teleporter should have been teleported to
*
* @return The target position, if it was resolved
* @implNote The optional will return empty if the state is {@link TeleportResult#FAILED_TARGET_NOT_RESOLVED}
* @since 3.1
*/
public Optional<Position> getDestination() {
return Optional.ofNullable(destination);
}
/**
* Send an {@link OnlineUser} the corresponding message indicating the state of the teleport once it has executred
*
* @param locales the {@link Locales} instance to use
* @param user the {@link OnlineUser} to send the message to
* @since 3.1
*/
public void sendResultMessage(@NotNull Locales locales, @NotNull OnlineUser user) {
this.state.sendResultMessage(locales, user);
}
}
@@ -0,0 +1,12 @@
package net.william278.huskhomes.teleport;
import org.jetbrains.annotations.NotNull;
public interface Target {
@NotNull
static Target username(@NotNull String target) {
return new Username(target);
}
}
@@ -1,213 +1,146 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
/**
* Represents a teleport in the process of being executed
*
* @since 3.1
*/
public class Teleport {
/**
* <b>Internal</b> - Instance of the implementing HuskHomes plugin
*/
@NotNull
private final HuskHomes plugin;
protected final OnlineUser executor;
protected final Teleportable teleporter;
protected final Target target;
protected final Type type;
protected final boolean updateLastPosition;
protected final List<EconomyHook.Action> economyActions;
private final boolean async;
/**
* The {@link User} who is doing the teleporting
*/
@Nullable
public final User teleporter;
/**
* The {@link OnlineUser} on this server executing the teleport.
* </p>
* Can be the same as the {@link #teleporter}, but not necessarily
*/
@NotNull
public final OnlineUser executor;
/**
* 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 EconomyHook.EconomyAction}s to be checked against the {@link #executor executor}'s balance
*/
@NotNull
public final Set<EconomyHook.EconomyAction> economyActions;
/**
* Whether to update the {@link #teleporter teleporter}'s last position (i.e. their {@code /back} position)
*/
public final boolean updateLastPosition;
/**
* <b>Internal</b> - use TeleportBuilder to instantiate a teleport
*/
protected Teleport(@Nullable User teleporter, @NotNull OnlineUser executor, @Nullable Position target,
@NotNull TeleportType type, @NotNull Set<EconomyHook.EconomyAction> economyActions,
final boolean updateLastPosition, @NotNull HuskHomes plugin) {
this.teleporter = teleporter;
protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target,
@NotNull Type type, boolean updateLastPosition, @NotNull List<EconomyHook.Action> actions,
@NotNull HuskHomes plugin) {
this.executor = executor;
this.teleporter = teleporter;
this.target = target;
this.type = type;
this.economyActions = economyActions;
this.plugin = plugin;
this.updateLastPosition = updateLastPosition;
this.economyActions = actions;
this.async = plugin.getSettings().isAsynchronousTeleports();
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);
@NotNull
public static TeleportBuilder builder(@NotNull HuskHomes plugin) {
return new TeleportBuilder(plugin);
}
/**
* Execute this teleport
*
* @return A {@link CompletableFuture} that completes when the teleport is finished
*/
public CompletableFuture<CompletedTeleport> execute() {
// Validate the teleporter
if (teleporter == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
public void execute() throws TeleportationException {
final Optional<OnlineUser> localTeleporter = resolveLocalTeleporter();
// Validate the target
if (target == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
// Check economy actions
for (EconomyHook.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
// Teleport a user on another server
if (localTeleporter.isEmpty()) {
final Username teleporter = (Username) this.teleporter;
if (!plugin.getSettings().isCrossServer()) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND);
}
if (target instanceof Username username) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_USER)
.target(username.name())
.payload(Payload.withString(teleporter.name()))
.build().send(plugin.getMessenger(), executor);
return;
}
Message.builder()
.type(Message.Type.TELEPORT_TO_POSITION)
.target(teleporter.name())
.payload(Payload.withPosition((Position) target))
.build().send(plugin.getMessenger(), executor);
return;
}
// Run the teleport and apply economy actions
return run(teleporter)
.thenApply(resultState -> CompletedTeleport.from(resultState, this))
.thenApply(result -> {
if (teleporter instanceof OnlineUser user) {
finish(user, result);
}
return result;
});
// Teleport a local user
final OnlineUser teleporter = localTeleporter.get();
if (target instanceof Username username) {
final Optional<OnlineUser> localTarget = username.findLocally(plugin);
if (localTarget.isPresent()) {
teleporter.teleportLocally(localTarget.get().getPosition(), async);
return;
}
if (plugin.getSettings().isCrossServer()) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_POSITION)
.target(username.name())
.build().send(plugin.getMessenger(), executor);
return;
}
throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND);
}
teleporter.teleportLocally((Position) target, async);
}
@NotNull
private Optional<OnlineUser> resolveLocalTeleporter() throws TeleportationException {
if (this.teleporter instanceof Username username) {
return username.findLocally(plugin);
}
return Optional.of((OnlineUser) this.teleporter);
}
@NotNull
public Type getType() {
return type;
}
@NotNull
public Teleportable getTeleporter() {
return teleporter;
}
@NotNull
public Target getTarget() {
return target;
}
/**
* 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
* Represents the type of teleport being used
*/
private CompletableFuture<TeleportResult> run(@NotNull User teleporter) {
return teleporter instanceof OnlineUser onlineUser
? teleportLocalUser(onlineUser)
: teleportNetworkedUser();
}
public enum Type {
/**
* 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 CompletedTeleport result) {
if (result.successful()) {
// Complete economy transactions
economyActions.forEach(economyAction -> plugin.performEconomyTransaction(executor, economyAction));
TELEPORT(0),
RESPAWN(1);
// Play sound effect if successful
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(teleporter::playSound);
private final int typeId;
Type(final int typeId) {
this.typeId = typeId;
}
// Send result message
result.sendResultMessage(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 (updateLastPosition && !plugin.getSettings().isBackCommandSaveOnTeleportEvent() && type == TeleportType.TELEPORT) {
plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition());
/**
* Returns a {@link Type} by its type id.
*
* @param typeId The type id of the {@link Type} to return.
* @return The {@link Type} of the given type id.
*/
public static Optional<Type> getTeleportType(int typeId) {
return Arrays.stream(values())
.filter(type -> type.getTypeId() == typeId)
.findFirst();
}
// If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().isCrossServer() || target.getServer().equals(plugin.getServerName())) {
return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports());
public int getTypeId() {
return typeId;
}
// If the target position is on another server, execute a cross-server teleport
plugin.getDatabase().setCurrentTeleport(teleporter, this);
plugin.getMessenger().changeServer(teleporter, target.getServer());
return CompletableFuture.completedFuture(TeleportResult.COMPLETED_CROSS_SERVER);
}
/**
* 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 Message.builder()
.type(Message.Type.TELEPORT_TO_POSITION_REQUEST)
.payload(Payload.withPosition(target))
.target(teleporter.getUsername())
.build().send(plugin.getMessenger(), executor)
.thenApply(result -> Optional.ofNullable(result.getPayload().getResultState())
.orElse(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED));
}
}
}
@@ -2,240 +2,101 @@ package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.network.Request;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.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.logging.Level;
import java.util.List;
/**
* 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 EconomyHook.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<EconomyHook.EconomyAction> economyActions = new HashSet<>();
/**
* The type of teleport. Defaults to {@link TeleportType#TELEPORT}
*/
private TeleportType type = TeleportType.TELEPORT;
/**
* Whether this teleport should update the user's last position (i.e. their {@code /back} position)
*/
private OnlineUser executor;
private Teleportable teleporter;
private Target target;
private boolean updateLastPosition = true;
private Teleport.Type type = Teleport.Type.TELEPORT;
private List<EconomyHook.Action> economyActions = List.of();
protected TeleportBuilder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) {
protected TeleportBuilder(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
@NotNull
public Teleport toTeleport() throws IllegalStateException {
validateTeleport();
return new Teleport(executor, teleporter, target, type, updateLastPosition, economyActions, plugin);
}
@NotNull
public TimedTeleport toTimedTeleport() throws IllegalStateException {
validateTeleport();
if (!(teleporter instanceof OnlineUser onlineTeleporter)) {
throw new IllegalStateException("Teleporter must be an OnlineUser for timed teleportation");
}
return new TimedTeleport(executor, onlineTeleporter, target, type,
plugin.getSettings().getTeleportWarmupTime(), updateLastPosition, economyActions, plugin);
}
private void validateTeleport() throws IllegalStateException {
if (executor == null) {
if (teleporter instanceof OnlineUser onlineUser) {
executor = onlineUser;
} else {
throw new IllegalStateException("Executor must be set if teleporter is not an OnlineUser");
}
}
if (teleporter == null) {
throw new IllegalStateException("Teleporter must be set");
}
if (target == null) {
throw new IllegalStateException("Target must be set");
}
}
@NotNull
public TeleportBuilder executor(@NotNull OnlineUser executor) {
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 = teleporterUsername;
@NotNull
public TeleportBuilder teleporter(@NotNull Teleportable teleporter) {
this.teleporter = teleporter;
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);
@NotNull
public TeleportBuilder teleporter(@NotNull String teleporter) {
this.teleporter = Teleportable.username(teleporter);
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.getServerName()));
@NotNull
public TeleportBuilder target(@NotNull Target target) {
this.target = target;
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));
@NotNull
public TeleportBuilder target(@NotNull String target) {
this.target = Target.username(target);
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 EconomyHook.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<EconomyHook.EconomyAction> economyActions) {
this.economyActions.addAll(economyActions);
return this;
}
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link EconomyHook.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 EconomyHook.EconomyAction... economyActions) {
this.economyActions.addAll(Arrays.asList(economyActions));
return this;
}
/**
* Set whether this teleport should update the user's last position (i.e. their {@code /back} position)
*
* @param updateLastPosition Whether this teleport should update the user's last position
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder doUpdateLastPosition(boolean updateLastPosition) {
@NotNull
public TeleportBuilder updateLastPosition(boolean updateLastPosition) {
this.updateLastPosition = updateLastPosition;
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, updateLastPosition, plugin);
}).exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create teleport", e);
return null;
});
@NotNull
public TeleportBuilder economyActions(@NotNull EconomyHook.Action... economyActions) {
this.economyActions = List.of(economyActions);
return this;
}
/**
* 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().getTeleportWarmupTime();
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, updateLastPosition, plugin);
}).exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create timed teleport", e);
return null;
});
@NotNull
public TeleportBuilder type(@NotNull Teleport.Type type) {
this.type = type;
return this;
}
/**
* 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.findOnlinePlayer(playerName);
if (localPlayer.isPresent()) {
return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition()));
}
if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger()
.findPlayer(executor, playerName)
.thenApplyAsync(foundPlayer -> {
if (foundPlayer.isEmpty()) {
return Optional.empty();
}
return Request.builder()
.withType(Request.MessageType.POSITION_REQUEST)
.withTargetPlayer(playerName)
.build().send(executor, plugin)
.thenApply(reply -> reply.map(message -> message.getPayload().getPosition())).join();
});
}
return CompletableFuture.supplyAsync(Optional::empty);
}
}
@@ -0,0 +1,160 @@
package net.william278.huskhomes.teleport;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
/**
* Represents a request between players for one user to teleport to another, or vice versa
*/
public class TeleportRequest {
@Expose
@SerializedName("requester_name")
private String requesterName;
@Expose
@SerializedName("requester_position")
private Position requesterPosition;
@Expose
@SerializedName("expiry_time")
private long expiryTime;
@Expose
private Type type;
@Expose
private Status status;
@Expose
private String recipientName;
/**
* Create a teleport request
*
* @param requester The user making the request
*/
public TeleportRequest(@NotNull OnlineUser requester, @NotNull TeleportRequest.Type type, final long expiryTime) {
this.setRequesterName(requester.getUsername());
this.setRequesterPosition(requester.getPosition());
this.setType(type);
this.setStatus(Status.PENDING);
this.expiryTime = expiryTime;
}
@SuppressWarnings("unused")
private TeleportRequest() {
}
/**
* Returns if the request has now expired
*
* @return {@code true} the request has passed its expiry time
*/
public boolean hasExpired() {
return Instant.now().isAfter(Instant.ofEpochSecond(expiryTime));
}
/**
* The name of the request recipient
*/
@NotNull
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(@NotNull String recipientName) {
this.recipientName = recipientName;
}
/**
* The user making the request
*/
public String getRequesterName() {
return requesterName;
}
public void setRequesterName(String requesterName) {
this.requesterName = requesterName;
}
/**
* The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request
*/
@NotNull
public Position getRequesterPosition() {
return requesterPosition;
}
public void setRequesterPosition(Position requesterPosition) {
this.requesterPosition = requesterPosition;
}
/**
* The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE}
*/
@NotNull
public TeleportRequest.Type getType() {
return type;
}
public void setType(@NotNull TeleportRequest.Type type) {
this.type = type;
}
/**
* The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED}
* or {@link Status#DECLINED}
*/
@NotNull
public TeleportRequest.Status getStatus() {
return status;
}
public void setStatus(@NotNull TeleportRequest.Status status) {
this.status = status;
}
/**
* Types of teleport requests ({@code /tpa} or {@code /tpahere})
*/
public enum Type {
/**
* The request is a {@code /tpa} request, where the requester is requesting to teleport <i>to</i> the recipient
*/
TPA,
/**
* The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport <i>to them</i>
*/
TPA_HERE
}
/**
* The current status of a teleport request
*/
public enum Status {
/**
* The request is currently pending and can be accepted or declined
*/
PENDING,
/**
* The teleport request has been accepted by the recipient and teleportation will commence
*/
ACCEPTED,
/**
* The teleport request has been declined by the recipient
*/
DECLINED,
/**
* The recipient was ignoring teleport requests at the time it was sent;
* the request has been automatically declined
*/
IGNORED
}
}
@@ -1,31 +0,0 @@
package net.william278.huskhomes.teleport;
import java.util.Arrays;
import java.util.Optional;
/**
* Represents the type of teleport being used
*/
public enum TeleportType {
TELEPORT(0),
RESPAWN(1);
public final int typeId;
TeleportType(final int typeId) {
this.typeId = typeId;
}
/**
* Returns a {@link TeleportType} by its type id.
*
* @param typeId The type id of the {@link TeleportType} to return.
* @return The {@link TeleportType} of the given type id.
*/
public static Optional<TeleportType> getTeleportType(int typeId) {
return Arrays.stream(values())
.filter(type -> type.typeId == typeId)
.findFirst();
}
}
@@ -0,0 +1,12 @@
package net.william278.huskhomes.teleport;
import org.jetbrains.annotations.NotNull;
public interface Teleportable {
@NotNull
static Teleportable username(@NotNull String teleporter) {
return new Username(teleporter);
}
}
@@ -0,0 +1,16 @@
package net.william278.huskhomes.teleport;
import org.jetbrains.annotations.NotNull;
public class TeleportationException extends IllegalArgumentException {
public TeleportationException(@NotNull Type error) {
super("Error during teleport operation: " + error.name());
}
public enum Type {
TELEPORTER_NOT_FOUND,
TARGET_NOT_FOUND,
ALREADY_WARMING_UP, ECONOMY_ACTION_FAILED, WARMUP_ALREADY_MOVING, CANNOT_TELEPORT_TO_SELF
}
}
@@ -9,11 +9,9 @@ import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class TimedTeleport extends Teleport {
@@ -22,12 +20,11 @@ public class TimedTeleport extends Teleport {
private final Position startLocation;
private final double startHealth;
private int timeLeft;
private boolean cancelled = false;
protected TimedTeleport(@NotNull OnlineUser teleporter, @NotNull OnlineUser executor, @NotNull Position target,
@NotNull TeleportType type, int warmupTime, @NotNull Set<EconomyHook.EconomyAction> economyActions,
final boolean updateLastPosition, @NotNull HuskHomes plugin) {
super(teleporter, executor, target, type, economyActions, updateLastPosition, plugin);
protected TimedTeleport(@NotNull OnlineUser executor, @NotNull OnlineUser teleporter, @NotNull Target target,
@NotNull Type type, int warmupTime, boolean updateLastPosition,
@NotNull List<EconomyHook.Action> actions, @NotNull HuskHomes plugin) {
super(teleporter, executor, target, type, updateLastPosition, actions, plugin);
this.plugin = plugin;
this.startLocation = teleporter.getPosition();
this.startHealth = teleporter.getHealth();
@@ -41,60 +38,38 @@ public class TimedTeleport extends Teleport {
* @return a {@link CompletableFuture} that completes when the teleport is complete or has been cancelled
*/
@Override
public CompletableFuture<CompletedTeleport> execute() {
// If the target has not been resolved, fail the teleport
if (target == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
public void execute() throws TeleportationException {
// Check if the teleporter can bypass warmup
if (timeLeft == 0 || teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) {
return super.execute();
super.execute();
return;
}
// Check if the teleporter is already warming up to teleport
if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.getUuid())) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP);
}
// Check economy actions
for (EconomyHook.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
for (EconomyHook.Action action : economyActions) {
if (!plugin.validateEconomyCheck(executor, action)) {
throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED);
}
}
// Check if they are moving at the start of the teleport
if (teleporter.isMoving()) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_MOVING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
throw new TeleportationException(TeleportationException.Type.WARMUP_ALREADY_MOVING);
}
// Process the warmup and execute the teleport
return process().thenApplyAsync(ignored -> {
if (cancelled) {
return CompletedTeleport.from(TeleportResult.CANCELLED, this);
}
return super.execute().join();
});
this.process();
}
/**
* 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<>();
private void process() {
// Execute the warmup start event
plugin.getEventDispatcher().dispatchTeleportWarmupEvent(this, timeLeft).thenAccept(event -> {
// Handle event cancellation
if (event.isCancelled()) {
this.cancelled = true;
return;
}
@@ -103,9 +78,9 @@ public class TimedTeleport extends Teleport {
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(() -> {
// Run the warmup
final AtomicInteger warmupTaskId = new AtomicInteger();
final Runnable delayRunnable = (() -> {
// Display countdown action bar message
if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
@@ -115,17 +90,17 @@ public class TimedTeleport extends Teleport {
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(this::sendStatusMessage);
super.execute();
}
// Tick (decrement) the timed teleport timer and end it if done
if (tickWarmup()) {
if (tickAndGetIfDone()) {
plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.getUuid());
timedTeleportFuture.complete(null);
executor.shutdown();
plugin.cancelTask(warmupTaskId.get());
}
}, 0, 1, TimeUnit.SECONDS);
});
warmupTaskId.set(plugin.runAsyncRepeating(delayRunnable, 20));
});
return timedTeleportFuture;
}
/**
@@ -141,7 +116,7 @@ public class TimedTeleport extends Teleport {
*
* @return {@code true} if the warmup is complete, {@code false} otherwise
*/
private boolean tickWarmup() {
private boolean tickAndGetIfDone() {
if (timeLeft <= 0) {
return true;
}
@@ -154,7 +129,6 @@ public class TimedTeleport extends Teleport {
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
cancelled = true;
return true;
}
@@ -166,7 +140,6 @@ public class TimedTeleport extends Teleport {
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
cancelled = true;
return true;
}
@@ -175,11 +148,6 @@ public class TimedTeleport extends Teleport {
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().getTeleportWarmupDisplay()) {
case ACTION_BAR -> teleporter.sendActionBar(message);
@@ -189,24 +157,14 @@ public class TimedTeleport extends Teleport {
}
}
/**
* Returns if the player has moved since the timed teleport started
*
* @return {@code true} if the player has moved; {@code false} otherwise
*/
private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) +
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
return movementDistance > maxMovementDistance;
}
/**
* Returns if the player has taken damage since the timed teleport started
*
* @return {@code true} if the player has taken damage
*/
private boolean hasTeleporterTakenDamage() {
return teleporter.getHealth() < startHealth;
}
@@ -0,0 +1,16 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public record Username(@NotNull String name) implements Teleportable, Target {
@NotNull
public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) throws TeleportationException {
return plugin.findOnlinePlayer(name);
}
}