refactor: Simplify teleport execution logic (#565)

* refactor: simplify teleport execution logic

* docs: document better way of executing a teleport

* fix: TimedTeleport should still handle internal errors

* fix: Wrong builder method calls

* fix: Typos

* fix: More typos

* fix: Cancel timed teleport on failed execute
This commit is contained in:
William authored and GitHub committed 2024-02-13 15:56:55 +00:00
1 parent 1723aa44fc
commit d79fcaacb6
17 files changed
+159 -209

No files matched your search

@@ -29,7 +29,6 @@ import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
@@ -773,18 +772,10 @@ public class BaseHuskHomesAPI {
throw new IllegalStateException("Random teleport engine returned an empty position");
}
final TeleportBuilder builder = Teleport.builder(plugin)
Teleport.builder(plugin)
.teleporter(user)
.target(position.get());
try {
if (timedTeleport) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(user, rtpArgs);
}
.target(position.get())
.buildAndComplete(timedTeleport);
}).exceptionally(e -> {
throw new IllegalStateException("Random teleport engine threw an exception", e);
});
@@ -22,7 +22,6 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.NotNull;
@@ -50,17 +49,12 @@ public class BackCommand extends InGameCommand {
return;
}
try {
Teleport.builder(plugin)
.teleporter(executor)
.target(lastPosition.get())
.actions(TransactionResolver.Action.BACK_COMMAND)
.type(Teleport.Type.BACK)
.toTimedTeleport()
.execute();
} catch (TeleportationException e) {
e.displayMessage(executor, args);
}
Teleport.builder(plugin)
.teleporter(executor)
.target(lastPosition.get())
.actions(TransactionResolver.Action.BACK_COMMAND)
.type(Teleport.Type.BACK)
.buildAndComplete(true);
}
}
@@ -23,7 +23,6 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.TransactionResolver;
@@ -154,15 +153,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
.teleporter(teleporter)
.actions(TransactionResolver.Action.RANDOM_TELEPORT)
.target(position.get());
try {
if (executor.equals(teleporter)) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, args);
}
builder.buildAndComplete(executor.equals(teleporter), args);
});
}
@@ -24,9 +24,7 @@ import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
@@ -166,19 +164,11 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
return;
}
final TeleportBuilder builder = Teleport.builder(plugin)
Teleport.builder(plugin)
.teleporter(teleporter)
.actions(actions)
.target(position);
try {
if (executor.equals(teleporter)) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, teleporter.getUsername());
}
.target(position)
.buildAndComplete(executor.equals(teleporter), teleporter.getUsername());
}
@NotNull
@@ -22,9 +22,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.NotNull;
@@ -67,19 +65,11 @@ public class SpawnCommand extends Command {
return;
}
final TeleportBuilder builder = Teleport.builder(plugin)
Teleport.builder(plugin)
.teleporter(teleporter)
.actions(TransactionResolver.Action.SPAWN_TELEPORT)
.target(spawn);
try {
if (teleporter.equals(executor)) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, args);
}
.target(spawn)
.buildAndComplete(teleporter.equals(executor), args);
}
}
@@ -88,15 +88,10 @@ public class TpCommand extends Command implements TabProvider {
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(teleportable)
.target(target);
try {
if (executor instanceof OnlineUser user) {
builder.executor(user);
}
builder.toTeleport().execute();
} catch (TeleportationException e) {
e.displayMessage(executor, args);
return;
if (executor instanceof OnlineUser user) {
builder.executor(user);
}
builder.buildAndComplete(false, args);
// Display a teleport completion message
final String teleporterName = teleportable instanceof OnlineUser user
@@ -21,7 +21,6 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
@@ -44,18 +43,15 @@ public class TpHereCommand extends InGameCommand implements UserListTabProvider
return;
}
try {
Teleport.builder(plugin)
.executor(executor)
.teleporter(optionalTarget.get())
.target(executor.getPosition())
.toTeleport().execute();
// Teleport the user
final String target = optionalTarget.get();
Teleport.builder(plugin)
.executor(executor)
.teleporter(target)
.target(executor.getPosition())
.buildAndComplete(false, target);
plugin.getLocales().getLocale("teleporting_other_complete",
optionalTarget.get(), executor.getUsername());
} catch (TeleportationException e) {
e.displayMessage(executor, args);
}
plugin.getLocales().getLocale("teleporting_other_complete", target, executor.getUsername());
}
}
@@ -22,7 +22,6 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
@@ -69,14 +68,10 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid
plugin.getLocales().getLocale("teleporting_offline_player", target.getUsername())
.ifPresent(user::sendMessage);
try {
Teleport.builder(plugin)
.teleporter(user)
.target(position.get())
.toTeleport().execute();
} catch (TeleportationException e) {
e.displayMessage(user, args);
}
Teleport.builder(plugin)
.teleporter(user)
.target(position.get())
.buildAndComplete(false, args);
}
}
@@ -59,6 +59,7 @@ public class EventListener {
plugin.runAsync(() -> {
// Ensure the user is in the database
plugin.getDatabase().ensureUser(onlineUser);
plugin.getCurrentlyOnWarmup().remove(onlineUser.getUuid());
// Handle cross-server checks
if (plugin.getSettings().getCrossServer().isEnabled()) {
@@ -161,17 +162,11 @@ public class EventListener {
plugin.getSpawn().ifPresent(spawn -> {
if (plugin.getSettings().getCrossServer().isEnabled()
&& !spawn.getServer().equals(plugin.getServerName())) {
plugin.runSyncDelayed(() -> {
try {
Teleport.builder(plugin)
.teleporter(teleporter)
.target(spawn)
.updateLastPosition(false)
.toTeleport().execute();
} catch (TeleportationException e) {
e.displayMessage(teleporter);
}
}, 40L);
plugin.runSyncDelayed(() -> Teleport.builder(plugin)
.teleporter(teleporter)
.target(spawn)
.updateLastPosition(false)
.buildAndComplete(false), 40L);
} else {
try {
teleporter.teleportLocally(spawn, plugin.getSettings().getGeneral().isTeleportAsync());
@@ -26,7 +26,6 @@ import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
@@ -323,12 +322,7 @@ public class RequestsManager {
} else {
builder.target(request.getRequesterName());
}
try {
builder.toTimedTeleport().execute();
} catch (TeleportationException e) {
e.displayMessage(recipient);
}
builder.buildAndComplete(true);
}
}));
}
@@ -354,16 +348,11 @@ public class RequestsManager {
// If the request is a tpa request, teleport the requester to the recipient
if (accepted && (request.getType() == TeleportRequest.Type.TPA)) {
try {
Teleport.builder(plugin)
.teleporter(requester)
.target(request.getRecipientName())
.actions(TransactionResolver.Action.ACCEPT_TELEPORT_REQUEST)
.toTimedTeleport()
.execute();
} catch (TeleportationException e) {
e.displayMessage(requester);
}
Teleport.builder(plugin)
.teleporter(requester)
.target(request.getRecipientName())
.actions(TransactionResolver.Action.ACCEPT_TELEPORT_REQUEST)
.buildAndComplete(true);
}
}
@@ -24,7 +24,6 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
@@ -58,17 +57,11 @@ public abstract class Broker {
}
switch (message.getType()) {
case TELEPORT_TO_POSITION -> message.getPayload()
.getPosition().ifPresent(position -> {
try {
Teleport.builder(plugin)
.teleporter(receiver)
.target(position)
.toTeleport()
.execute();
} catch (TeleportationException e) {
e.displayMessage(plugin.getConsole());
}
});
.getPosition().ifPresent(position -> Teleport.builder(plugin)
.teleporter(receiver)
.target(position)
.toTeleport()
.complete());
case TELEPORT_TO_NETWORKED_POSITION -> Message.builder()
.type(Message.Type.TELEPORT_TO_POSITION)
.target(message.getSender())
@@ -0,0 +1,48 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
/**
* Represents a Teleport that is completable
*/
public interface Completable {
void execute() throws TeleportationException;
@NotNull
OnlineUser getExecutor();
/**
* Complete the teleport and handle exceptions
*
* @param args Optional args to pass to the teleport exception handler
*/
default void complete(@NotNull String... args) {
try {
execute();
} catch (TeleportationException e) {
e.displayMessage(getExecutor(), args);
}
}
}
@@ -42,7 +42,8 @@ import java.util.Optional;
*
* @see Teleport#builder(HuskHomes)
*/
public class Teleport {
@Getter
public class Teleport implements Completable {
protected final HuskHomes plugin;
protected final OnlineUser executor;
@@ -74,41 +75,17 @@ public class Teleport {
return new TeleportBuilder(plugin);
}
/**
* Execute a teleport, throwing a {@link TeleportationException on an exception}
*
* @throws TeleportationException if
*/
public void execute() throws TeleportationException {
final Optional<OnlineUser> localTeleporter = resolveLocalTeleporter();
// Validate economy actions
validateTransactions();
resolveLocalTeleporter().ifPresentOrElse(this::executeLocal, this::executeRemote);
}
// Teleport a user on another server
if (localTeleporter.isEmpty()) {
final Username teleporter = (Username) this.teleporter;
if (!plugin.getSettings().getCrossServer().isEnabled()) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin);
}
fireEvent((event) -> {
performTransactions();
if (target instanceof Username username) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_USER)
.target(teleporter.name())
.payload(Payload.withString(username.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;
}
// Teleport a local user
final OnlineUser teleporter = localTeleporter.get();
private void executeLocal(@NotNull OnlineUser teleporter) throws TeleportationException {
if (target instanceof Username username) {
final Optional<OnlineUser> localTarget = username.name().equals("@s")
? Optional.of(executor) : username.findLocally(plugin);
@@ -119,12 +96,7 @@ public class Teleport {
plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition());
}
try {
teleporter.teleportLocally(localTarget.get().getPosition(), async);
} catch (TeleportationException e) {
e.displayMessage(teleporter);
return;
}
teleporter.teleportLocally(localTarget.get().getPosition(), async);
this.displayTeleportingComplete(teleporter);
});
return;
@@ -153,12 +125,7 @@ public class Teleport {
final Position target = (Position) this.target;
if (!plugin.getSettings().getCrossServer().isEnabled()
|| target.getServer().equals(plugin.getServerName())) {
try {
teleporter.teleportLocally(target, async);
} catch (TeleportationException e) {
e.displayMessage(teleporter);
return;
}
teleporter.teleportLocally(target, async);
this.displayTeleportingComplete(teleporter);
return;
}
@@ -168,6 +135,31 @@ public class Teleport {
});
}
private void executeRemote() throws TeleportationException {
final Username teleporter = (Username) this.teleporter;
if (!plugin.getSettings().getCrossServer().isEnabled()) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin);
}
fireEvent((event) -> {
performTransactions();
if (target instanceof Username username) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_USER)
.target(teleporter.name())
.payload(Payload.withString(username.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);
});
}
@NotNull
private Optional<OnlineUser> resolveLocalTeleporter() throws TeleportationException {
if (this.teleporter instanceof Username username) {
@@ -202,21 +194,6 @@ public class Teleport {
actions.forEach(action -> plugin.performTransaction(executor, action));
}
@NotNull
public Type getType() {
return type;
}
@NotNull
public Teleportable getTeleporter() {
return teleporter;
}
@NotNull
public Target getTarget() {
return target;
}
/**
* Represents the type of teleport being used.
*/
@@ -71,6 +71,14 @@ public class TeleportBuilder {
);
}
public void buildAndComplete(boolean timed, @NotNull String... args) {
try {
(timed ? toTimedTeleport() : toTeleport()).complete(args);
} catch (TeleportationException e) {
e.displayMessage(executor);
}
}
private void validateTeleport() throws TeleportationException {
if (teleporter == null) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin);
@@ -19,6 +19,7 @@
package net.william278.huskhomes.teleport;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
@@ -26,6 +27,7 @@ import org.jetbrains.annotations.NotNull;
public class TeleportationException extends IllegalStateException {
private final HuskHomes plugin;
@Getter
private final Type type;
public TeleportationException(@NotNull Type cause, @NotNull HuskHomes plugin) {
@@ -60,12 +62,6 @@ public class TeleportationException extends IllegalStateException {
}
}
@NotNull
@SuppressWarnings("unused")
public Type getType() {
return type;
}
/**
* Represents different causes of {@link TeleportationException}s.
*/
@@ -36,7 +36,7 @@ import java.util.List;
*
* @see Teleport#builder(HuskHomes)
*/
public class TimedTeleport extends Teleport implements Runnable {
public class TimedTeleport extends Teleport implements Runnable, Completable {
public static final String BYPASS_PERMISSION = "huskhomes.bypass_teleport_warmup";
private final OnlineUser teleporter;
@@ -104,10 +104,14 @@ public class TimedTeleport extends Teleport implements Runnable {
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(this::sendStatusMessage);
try {
super.execute();
} catch (TeleportationException e) {
e.displayMessage(teleporter);
task.cancel();
plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid());
return;
}
}
+11 -13
View File
@@ -148,7 +148,7 @@ public class HuskHomesAPIHook {
</details>
## Creating Teleports
The API provides a method for getting a `TeleportBuilder`, which can be used to build a `Teleport` (with `#toTeleport`) or `TimedTeleport` (with toTimedTeleport; a teleport that requires the user to stand still for a period of time first). Teleports can be cross-server.
The API provides a method for getting a `TeleportBuilder`, which can be used to build a `Teleport` (with `#toTeleport`) or `TimedTeleport` (a teleport that requires the user to stand still for a period of time first). Teleports can be cross-server.
<details>
<summary>Building a teleport</summary>
@@ -171,15 +171,12 @@ public class HuskHomesAPIHook {
);
// To construct a teleport, get a TeleportBuilder with #teleportBuilder
try {
huskHomesAPI.teleportBuilder()
.teleporter(onlineUser) // The person being teleported
.target(position) // The target position
.toTimedTeleport()
.execute(); // #execute() can throw a TeleportationException
} catch(TeleportationException e) {
e.printStackTrace(); // This exception will contain the reason why the teleport failed, so you can handle it gracefully.
}
huskHomesAPI.teleportBuilder()
.teleporter(onlineUser) // The person being teleported
.target(position) // The target position
.buildAndComplete(false); // This builds and executes the teleport instantly.
// The `true` flag we passed above indicates we want an instant teleport (as opposed to a timed teleport)
}
}
@@ -206,10 +203,11 @@ public class HuskHomesAPIHook {
huskHomesAPI.teleportBuilder()
.teleporter(onlineUser)
.target(targetUsername)
.toTimedTeleport()
.toTimedTeleport() // Instead of running buildAndComplete, we can get the Teleport object itself this way.
.execute(); // A timed teleport will throw a TeleportationException if the player moves/takes damage during the warmup, or if the target is not found.
} catch(TeleportationException e) {
e.printStackTrace(); // Note that the TimedTeleport will catch internal exceptions when executing the resultant Teleport (e.g. if the teleport is to an illegal position).
} catch(TeleportationException e) { // Since this doesn't catch the TeleportException (buildAndComplete does!), we need to do this.
// Use TeleportException#displayMessage() to display why the teleport failed to the user.
e.displayMessage(onlineUser);
}
}