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

@@ -34,7 +34,6 @@ import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.*;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.SimplePie;
@@ -70,7 +69,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private BukkitLogger logger;
private Database database;
private Cache cache;
private TeleportManager teleportManager;
private RequestManager requestManager;
private SavedPositionManager savedPositionManager;
private EventListener eventListener;
@@ -134,10 +132,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
// Initialize the database
getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database...");
final Settings.DatabaseType databaseType = settings.databaseType;
final BukkitResourceReader resourceReader = new BukkitResourceReader(this);
this.database = switch (databaseType == null ? Settings.DatabaseType.MYSQL : databaseType) {
case MYSQL -> new MySqlDatabase(settings, logger, resourceReader);
case SQLITE -> new SqLiteDatabase(settings, logger, resourceReader);
case MYSQL -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this);
};
initialized.set(this.database.initialize());
if (initialized.get()) {
@@ -158,9 +155,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger.");
}
// Prepare the teleport manager
this.teleportManager = new TeleportManager(this);
// Prepare the request manager
this.requestManager = new RequestManager(this);
@@ -358,12 +352,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
return cache;
}
@NotNull
@Override
public TeleportManager getTeleportManager() {
return teleportManager;
}
@Override
public @NotNull RequestManager getRequestManager() {
return requestManager;
@@ -29,7 +29,7 @@ public class BukkitEventDispatcher implements EventDispatcher {
}
@Override
public CompletableFuture<ITeleportWarmupEvent> dispatchTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
public CompletableFuture<ITeleportWarmupEvent> dispatchTeleportWarmupEvent(TimedTeleport teleport, int duration) {
final CompletableFuture<ITeleportWarmupEvent> dispatchFuture = new CompletableFuture<>();
Bukkit.getScheduler().runTask(plugin, () -> {
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleport, duration);
@@ -101,7 +101,7 @@ public class BukkitPlayer extends OnlineUser {
}
@Override
public CompletableFuture<TeleportResult> teleport(@NotNull Location location, boolean asynchronous) {
public CompletableFuture<TeleportResult> teleportLocally(@NotNull Location location, boolean asynchronous) {
final Optional<org.bukkit.Location> bukkitLocation = BukkitAdapter.adaptLocation(location);
if (bukkitLocation.isEmpty()) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_INVALID_WORLD);
@@ -1,26 +0,0 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.BukkitHuskHomes;
import java.io.File;
import java.io.InputStream;
public class BukkitResourceReader implements ResourceReader {
private final BukkitHuskHomes plugin;
public BukkitResourceReader(BukkitHuskHomes plugin) {
this.plugin = plugin;
}
@Override
public InputStream getResource(String fileName) {
return plugin.getResource(fileName);
}
@Override
public File getDataFolder() {
return plugin.getDataFolder();
}
}
@@ -9,6 +9,7 @@ import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.paginedown.ListOptions;
import net.william278.paginedown.PaginatedList;
import org.jetbrains.annotations.NotNull;
@@ -57,6 +58,11 @@ public class Cache {
*/
public final HashMap<UUID, PaginatedList> warpLists;
/**
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
*/
public final HashSet<UUID> currentlyOnWarmup;
/**
* Plugin event dispatcher
*/
@@ -73,6 +79,7 @@ public class Cache {
this.privateHomeLists = new HashMap<>();
this.publicHomeLists = new HashMap<>();
this.warpLists = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.eventDispatcher = eventDispatcher;
}
@@ -115,6 +122,17 @@ public class Cache {
}
}
/**
* Returns if the given user is currently warming up to teleport to a home.
*
* @param userUuid The user to check.
* @return If the user is currently warming up.
* @since 3.1
*/
public boolean isWarmingUp(@NotNull UUID userUuid) {
return this.currentlyOnWarmup.contains(userUuid);
}
@NotNull
private ListOptions.Builder getBaseList(@NotNull Locales locales, int itemsPerPage) {
return new ListOptions.Builder().setFooterFormat(locales.getRawLocale("list_footer",
@@ -17,12 +17,12 @@ import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
@@ -100,14 +100,6 @@ public interface HuskHomes {
@NotNull
Cache getCache();
/**
* The {@link TeleportManager} that manages player teleports
*
* @return the plugin {@link TeleportManager}
*/
@NotNull
TeleportManager getTeleportManager();
/**
* The {@link RequestManager} that manages player requests
*
@@ -306,6 +298,14 @@ public interface HuskHomes {
@Nullable
InputStream getResource(@NotNull String name);
/**
* Returns the plugin data folder containing the plugin config, etc
*
* @return the plugin data folder
*/
@NotNull
File getDataFolder();
/**
* Returns a list of worlds on the server
*
@@ -7,6 +7,8 @@ import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.random.RandomTeleportEngine;
import org.jetbrains.annotations.NotNull;
@@ -107,7 +109,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0.2
*/
public boolean isUserWarmingUp(@NotNull User user) {
return plugin.getTeleportManager().isWarmingUp(user.uuid);
return plugin.getCache().isWarmingUp(user.uuid);
}
/**
@@ -322,6 +324,18 @@ public abstract class BaseHuskHomesAPI {
return user.getMaxPublicHomes(plugin.getSettings().maxPublicHomes, plugin.getSettings().stackPermissionLimits);
}
/**
* Get a {@link TeleportBuilder} to construct and dispatch a (timed) teleport
*
* @param onlineUser The {@link OnlineUser} to teleport
* @return A {@link TeleportBuilder} to construct and dispatch a (timed) teleport
* @since 3.1
*/
@NotNull
public final TeleportBuilder teleportBuilder(@NotNull OnlineUser onlineUser) {
return Teleport.builder(plugin, onlineUser);
}
/**
* Attempt to teleport an {@link OnlineUser} to a target {@link Position}
*
@@ -336,8 +350,10 @@ public abstract class BaseHuskHomesAPI {
public final CompletableFuture<TeleportResult> teleportPlayer(@NotNull OnlineUser user,
@NotNull Position position,
final boolean timedTeleport) {
return timedTeleport ? plugin.getTeleportManager().timedTeleport(user, position)
: plugin.getTeleportManager().teleport(user, position);
final TeleportBuilder builder = teleportBuilder(user).setTarget(position);
return timedTeleport
? builder.toTimedTeleport().thenApplyAsync(teleport -> teleport.execute().join())
: builder.toTeleport().thenApplyAsync(teleport -> teleport.execute().join());
}
/**
@@ -3,6 +3,8 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -15,17 +17,11 @@ public class BackCommand extends CommandBase {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition ->
lastPosition.ifPresentOrElse(position -> {
// Validate the /back command economy action and that the user has sufficient funds if needed
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.BACK_COMMAND)) {
return;
}
// Teleport the player
plugin.getTeleportManager().timedTeleport(onlineUser, position, Settings.EconomyAction.BACK_COMMAND)
.thenAccept(result -> plugin.getTeleportManager()
.finishTeleport(onlineUser, result, Settings.EconomyAction.BACK_COMMAND));
},
lastPosition.ifPresentOrElse(position -> Teleport.builder(plugin, onlineUser)
.setTarget(position)
.setEconomyActions(Settings.EconomyAction.BACK_COMMAND)
.toTimedTeleport()
.thenApply(TimedTeleport::execute),
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage)));
}
@@ -2,7 +2,10 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
@@ -29,8 +32,9 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
// Send the home list if they have homes set. If they have just one home set, teleport the player
switch (homes.size()) {
case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage);
case 1 -> plugin.getTeleportManager().timedTeleport(onlineUser, homes.get(0)).thenAccept(result ->
plugin.getTeleportManager().finishTeleport(onlineUser, result));
case 1 -> Teleport.builder(plugin, onlineUser)
.setTarget(homes.get(0))
.toTimedTeleport().thenAccept(TimedTeleport::execute);
default -> plugin.getCache().getHomeList(onlineUser, onlineUser,
plugin.getLocales(), homes, plugin.getSettings().listItemsPerPage, 1)
.ifPresent(onlineUser::sendMessage);
@@ -42,16 +46,42 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse(
homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName())
.thenAccept(optionalUserData -> optionalUserData.ifPresentOrElse(
userData -> plugin.getTeleportManager().teleportToHomeByName(onlineUser, userData.user(), homeIdentifier.homeName()),
userData -> teleportToNamedHome(onlineUser, userData.user(), homeIdentifier.homeName()),
() -> plugin.getLocales().getLocale("error_home_invalid_other", homeIdentifier.ownerName(), homeIdentifier.homeName())
.ifPresent(onlineUser::sendMessage))),
() -> plugin.getTeleportManager().teleportToHomeByName(onlineUser, onlineUser, homeName));
() -> teleportToNamedHome(onlineUser, onlineUser, homeName));
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/home [name]")
.ifPresent(onlineUser::sendMessage);
}
}
private void teleportToNamedHome(@NotNull OnlineUser teleporter, @NotNull User owner, @NotNull String homeName) {
final boolean otherHome = owner.uuid.equals(teleporter.uuid);
plugin.getDatabase()
.getHome(owner, homeName)
.thenAccept(homeResult -> homeResult.ifPresentOrElse(home -> {
if (otherHome && !home.isPublic) {
if (!teleporter.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(teleporter::sendMessage);
}
}
Teleport.builder(plugin, teleporter)
.setTarget(home)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
}, () -> {
if (otherHome) {
plugin.getLocales().getLocale("error_home_invalid", homeName)
.ifPresent(teleporter::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid_other", owner.username, homeName)
.ifPresent(teleporter::sendMessage);
}
}));
}
@Override
public void onConsoleExecute(@NotNull String[] args) {
if (args.length != 2) {
@@ -80,9 +110,11 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
}
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.owner.username + "." + home.meta.name);
plugin.getTeleportManager().teleport(playerToTeleport, home)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(playerToTeleport, result));
+ home.owner.username + "." + home.meta.name);
Teleport.builder(plugin, playerToTeleport)
.setTarget(home)
.toTeleport()
.thenAccept(Teleport::execute);
});
}
@@ -2,7 +2,10 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
@@ -43,7 +46,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse(
homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName())
.thenAccept(optionalUserData -> optionalUserData.ifPresentOrElse(
userData -> plugin.getTeleportManager().teleportToHomeByName(onlineUser, userData.user(), homeIdentifier.homeName()),
userData -> teleportToNamedHome(onlineUser, userData.user(), homeIdentifier.homeName()),
() -> plugin.getLocales().getLocale("error_home_invalid_other", homeIdentifier.ownerName(), homeIdentifier.homeName())
.ifPresent(onlineUser::sendMessage))),
() -> plugin.getDatabase().getPublicHomes().thenAccept(publicHomes -> {
@@ -51,7 +54,9 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
final List<Home> homeMatches = publicHomes.stream()
.filter(home -> home.meta.name.equalsIgnoreCase(homeName)).toList();
if ((long) homeMatches.size() == 1) {
plugin.getTeleportManager().teleportToHome(onlineUser, homeMatches.get(0));
Teleport.builder(plugin, onlineUser)
.setTarget(homeMatches.get(0))
.toTimedTeleport().thenAccept(TimedTeleport::execute);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/publichome [<owner_name>.<home_name>]")
.ifPresent(onlineUser::sendMessage);
@@ -63,6 +68,32 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
}
}
private void teleportToNamedHome(@NotNull OnlineUser teleporter, @NotNull User owner, @NotNull String homeName) {
final boolean otherHome = owner.uuid.equals(teleporter.uuid);
plugin.getDatabase()
.getHome(owner, homeName)
.thenAccept(homeResult -> homeResult.ifPresentOrElse(home -> {
if (otherHome && !home.isPublic) {
if (!teleporter.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(teleporter::sendMessage);
}
}
Teleport.builder(plugin, teleporter)
.setTarget(home)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
}, () -> {
if (otherHome) {
plugin.getLocales().getLocale("error_home_invalid", homeName)
.ifPresent(teleporter::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid_other", owner.username, homeName)
.ifPresent(teleporter::sendMessage);
}
}));
}
@Override
public void onConsoleExecute(@NotNull String[] args) {
if (args.length != 2) {
@@ -93,9 +124,11 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
}
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.owner.username + "." + home.meta.name);
plugin.getTeleportManager().teleport(playerToTeleport, home)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(playerToTeleport, result));
+ home.owner.username + "." + home.meta.name);
Teleport.builder(plugin, playerToTeleport)
.setTarget(home)
.toTeleport()
.thenAccept(Teleport::execute);
});
}
@@ -5,7 +5,8 @@ import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.util.Permission;
import org.apache.commons.lang3.ArrayUtils;
import org.jetbrains.annotations.NotNull;
@@ -76,19 +77,21 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
return;
}
final CompletableFuture<TeleportResult> randomTeleport = isExecutorTeleporting ? plugin.getTeleportManager()
.timedTeleport(userToTeleport, position.get(), Settings.EconomyAction.RANDOM_TELEPORT)
: plugin.getTeleportManager().teleport(userToTeleport, position.get());
randomTeleport.thenAccept(result -> {
if (isExecutorTeleporting &&
result.successful && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
plugin.getDatabase().updateUserData(new UserData(onlineUser,
userData.get().homeSlots(), userData.get().ignoringTeleports(),
Instant.now().plus(plugin.getSettings().rtpCooldownLength, ChronoUnit.MINUTES)));
}
plugin.getTeleportManager().finishTeleport(userToTeleport, result,
Settings.EconomyAction.RANDOM_TELEPORT);
});
final TeleportBuilder builder = Teleport.builder(plugin, userToTeleport)
.setTarget(position.get());
final CompletableFuture<? extends Teleport> teleportFuture = isExecutorTeleporting
? builder.setEconomyActions(Settings.EconomyAction.RANDOM_TELEPORT).toTimedTeleport()
: builder.toTeleport();
teleportFuture.thenAccept(teleport -> teleport.execute()
.thenAccept(result -> {
if (isExecutorTeleporting &&
result.successful && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
plugin.getDatabase().updateUserData(new UserData(onlineUser,
userData.get().homeSlots(), userData.get().ignoringTeleports(),
Instant.now().plus(plugin.getSettings().rtpCooldownLength, ChronoUnit.MINUTES)));
}
}));
});
});
}
@@ -111,15 +114,16 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!");
return;
}
plugin.getTeleportManager().teleport(foundUser.get(), position.get())
.thenAccept(result -> {
Teleport.builder(plugin, foundUser.get())
.setTarget(position.get())
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful) {
plugin.getLoggingAdapter().log(Level.INFO, "Teleported " + foundUser.get().username + " to a random position.");
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport" + foundUser.get().username + " to a random position.");
}
plugin.getTeleportManager().finishTeleport(foundUser.get(), result);
});
}));
});
}
@@ -2,6 +2,8 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -25,7 +27,9 @@ public class SpawnCommand extends CommandBase {
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getTeleportManager().timedTeleport(onlineUser, position.get());
Teleport.builder(plugin, onlineUser)
.setTarget(position.get())
.toTimedTeleport().thenAccept(TimedTeleport::execute);
});
}
}
@@ -2,6 +2,8 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -35,8 +37,12 @@ public class TpAllCommand extends CommandBase {
.ifPresent(onlineUser::sendMessage);
// Teleport every player
players.forEach(playerName -> plugin.getTeleportManager()
.teleportPlayerByName(playerName, onlineUser.getPosition(), onlineUser, false));
final Position targetPosition = onlineUser.getPosition();
players.forEach(playerName -> Teleport.builder(plugin, onlineUser)
.setTeleporter(playerName)
.setTarget(targetPosition)
.toTeleport()
.thenAccept(Teleport::execute));
});
}
@@ -5,6 +5,8 @@ import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -61,21 +63,21 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// Execute the teleport
if (teleportTarget.get() instanceof TargetPlayer targetPlayer) {
// Handle player teleport targets
plugin.getTeleportManager()
.teleportNamedPlayers(playerToTeleport, targetPlayer.playerName, onlineUser, false)
.thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresentOrElse(
result -> {
if (!result.successful) {
plugin.getTeleportManager().finishTeleport(onlineUser, result);
return;
}
plugin.getLocales().getLocale("teleporting_other_complete",
playerToTeleport, targetPlayer.playerName)
.ifPresent(onlineUser::sendMessage);
},
() -> plugin.getLocales().getLocale("error_player_not_found", targetPlayer.playerName)
.ifPresent(onlineUser::sendMessage)));
// Carry out the teleport to a player, by name
Teleport.builder(plugin, onlineUser)
.setTeleporter(playerToTeleport)
.setTarget(targetPlayer.playerName)
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful) {
plugin.getLocales().getLocale("teleporting_other_complete",
playerToTeleport, targetPlayer.playerName)
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("error_player_not_found", targetPlayer.playerName)
.ifPresent(onlineUser::sendMessage);
}
}));
} else if (teleportTarget.get() instanceof TargetPosition targetPosition) {
// Handle coordinate teleport targets
if (!onlineUser.hasPermission(Permission.COMMAND_TP_TO_COORDINATES.node)) {
@@ -83,21 +85,22 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
return;
}
plugin.getTeleportManager()
.teleportPlayerByName(playerToTeleport, targetPosition.position, onlineUser, false)
.thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresent(
result -> {
if (!result.successful || playerToTeleport.equalsIgnoreCase(onlineUser.username)) {
plugin.getTeleportManager().finishTeleport(onlineUser, result);
return;
}
plugin.getLocales().getLocale("teleporting_other_complete_position",
playerToTeleport,
Integer.toString((int) targetPosition.position.x),
Integer.toString((int) targetPosition.position.y),
Integer.toString((int) targetPosition.position.z))
.ifPresent(onlineUser::sendMessage);
}));
// Carry out the teleport to a position
Teleport.builder(plugin, onlineUser)
.setTeleporter(playerToTeleport)
.setTarget(targetPosition.position)
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (!result.successful || playerToTeleport.equalsIgnoreCase(onlineUser.username)) {
return;
}
plugin.getLocales().getLocale("teleporting_other_complete_position",
playerToTeleport,
Integer.toString((int) targetPosition.position.x),
Integer.toString((int) targetPosition.position.y),
Integer.toString((int) targetPosition.position.z))
.ifPresent(onlineUser::sendMessage);
}));
}
});
}
@@ -176,23 +179,20 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
}
// Execute the console teleport
final TeleportBuilder builder = Teleport.builder(plugin, playerToTeleport)
.setTeleporter(playerToTeleport.username);
if (teleportTarget instanceof TargetPlayer targetPlayer) {
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username
+ " to " + targetPlayer.playerName);
plugin.getTeleportManager().teleportToPlayerByName(playerToTeleport, targetPlayer.playerName, false);
builder.setTarget(targetPlayer.playerName);
} else {
final TargetPosition targetPosition = (TargetPosition) teleportTarget;
plugin.getTeleportManager().teleport(playerToTeleport, targetPosition.position)
.thenAccept(teleportResult -> {
if (teleportResult.successful) {
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.username);
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.username
+ " (" + teleportResult.name() + ")");
}
plugin.getTeleportManager().finishTeleport(playerToTeleport, teleportResult);
});
builder.setTarget(((TargetPosition) teleportTarget).position);
}
builder.toTeleport().thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful) {
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.username);
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.username + " to " + teleportTarget);
}
}));
}
@Override
@@ -2,6 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -26,19 +27,17 @@ public class TpHereCommand extends CommandBase implements TabCompletable {
return;
}
final String targetPlayerName = args[0];
plugin.getTeleportManager().teleportPlayerByName(targetPlayerName, onlineUser.getPosition(), onlineUser, false)
.thenAccept(resultIfPlayerExists -> resultIfPlayerExists.ifPresentOrElse(
result -> {
if (result.successful) {
plugin.getLocales().getLocale("teleporting_other_complete",
targetPlayerName, onlineUser.username)
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getTeleportManager().finishTeleport(onlineUser, result);
},
() -> plugin.getLocales().getLocale("error_player_not_found", targetPlayerName)
.ifPresent(onlineUser::sendMessage)));
Teleport.builder(plugin, onlineUser)
.setTeleporter(targetPlayerName)
.setTarget(onlineUser.getPosition())
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful) {
plugin.getLocales().getLocale("teleporting_other_complete",
targetPlayerName, onlineUser.username)
.ifPresent(onlineUser::sendMessage);
}
}));
});
}
@@ -2,6 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -38,8 +39,15 @@ public class TpOfflineCommand extends CommandBase implements TabCompletable {
}
plugin.getLocales().getLocale("teleporting_offline_player", targetUser)
.ifPresent(onlineUser::sendMessage);
plugin.getTeleportManager().teleport(onlineUser, offlinePosition.get()).thenAccept(
result -> plugin.getTeleportManager().finishTeleport(onlineUser, result));
Teleport.builder(plugin, onlineUser)
.setTarget(offlinePosition.get())
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful) {
plugin.getLocales().getLocale("teleporting_offline_complete", targetUser)
.ifPresent(onlineUser::sendMessage);
}
}));
});
});
}
@@ -20,20 +20,22 @@ public class TpaCommand extends CommandBase implements TabCompletable {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
plugin.getRequestManager().sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA).thenAccept(sent -> {
if (sent.isPresent()) {
plugin.getLocales().getLocale("tpa_request_sent", sent.get().getRecipientName())
.ifPresent(onlineUser::sendMessage);
} else {
if (plugin.findPlayer(args[0]).isPresent()) {
plugin.getLocales().getLocale("error_teleport_request_self")
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("error_player_not_found", args[0])
.ifPresent(onlineUser::sendMessage);
}
});
plugin.getRequestManager()
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA)
.thenAccept(sent -> {
if (sent.isPresent()) {
plugin.getLocales().getLocale("tpa_request_sent", sent.get().getRecipientName())
.ifPresent(onlineUser::sendMessage);
} else {
if (plugin.findPlayer(args[0]).isPresent()) {
plugin.getLocales().getLocale("error_teleport_request_self")
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("error_player_not_found", args[0])
.ifPresent(onlineUser::sendMessage);
}
});
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/tpa <player>")
.ifPresent(onlineUser::sendMessage);
@@ -20,20 +20,22 @@ public class TpaHereCommand extends CommandBase implements TabCompletable {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
plugin.getRequestManager().sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA_HERE).thenAccept(sent -> {
if (sent.isEmpty()) {
if (plugin.findPlayer(args[0]).isPresent()) {
plugin.getLocales().getLocale("error_teleport_request_self")
plugin.getRequestManager()
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA_HERE)
.thenAccept(sent -> {
if (sent.isEmpty()) {
if (plugin.findPlayer(args[0]).isPresent()) {
plugin.getLocales().getLocale("error_teleport_request_self")
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("error_player_not_found", args[0])
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("tpahere_request_sent", sent.get().getRecipientName())
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("error_player_not_found", args[0])
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("tpahere_request_sent", sent.get().getRecipientName())
.ifPresent(onlineUser::sendMessage);
});
});
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/tpahere <player>")
.ifPresent(onlineUser::sendMessage);
@@ -3,12 +3,13 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -33,7 +34,15 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
});
case 1 -> {
final String warpName = args[0];
plugin.getTeleportManager().teleportToWarpByName(onlineUser, warpName);
plugin.getDatabase()
.getWarp(warpName)
.thenAccept(warpResult -> warpResult.ifPresentOrElse(warp ->
Teleport.builder(plugin, onlineUser)
.setTarget(warp)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute),
() -> plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(onlineUser::sendMessage)));
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/warp [name]")
.ifPresent(onlineUser::sendMessage);
@@ -68,9 +77,10 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
final Warp warp = optionalWarp.get();
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.meta.name);
plugin.getTeleportManager()
.teleport(playerToTeleport, warp)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(playerToTeleport, result));
Teleport.builder(plugin, playerToTeleport)
.setTarget(warp)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
});
}
@@ -3,12 +3,12 @@ package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.HuskHomesException;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -17,10 +17,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@@ -103,6 +100,11 @@ public abstract class Database {
*/
protected final String teleportsTableName;
/**
* Instance of the implementing plugin
*/
protected final HuskHomes plugin;
/**
* Logger instance used for database error logging
*/
@@ -117,8 +119,6 @@ public abstract class Database {
return logger;
}
private final ResourceReader resourceReader;
/**
* Loads SQL table creation schema statements from a resource file as a string array
*
@@ -128,8 +128,8 @@ public abstract class Database {
*/
protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException {
return formatStatementTables(
new String(resourceReader.getResource(schemaFileName)
.readAllBytes(), StandardCharsets.UTF_8))
new String(Objects.requireNonNull(plugin.getResource(schemaFileName)).readAllBytes(),
StandardCharsets.UTF_8))
.split(";");
}
@@ -150,19 +150,19 @@ public abstract class Database {
}
/**
* Create a database instance with specified table data {@link Settings}
* Create a database instance, pulling table names from the plugin config
*
* @param settings {@link Settings} to fetch database configuration data from
* @param implementor the implementing plugin instance
*/
protected Database(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
this.playerTableName = settings.getTableName(Settings.TableName.PLAYER_DATA);
this.positionsTableName = settings.getTableName(Settings.TableName.POSITION_DATA);
this.savedPositionsTableName = settings.getTableName(Settings.TableName.SAVED_POSITION_DATA);
this.homesTableName = settings.getTableName(Settings.TableName.HOME_DATA);
this.warpsTableName = settings.getTableName(Settings.TableName.WARP_DATA);
this.teleportsTableName = settings.getTableName(Settings.TableName.TELEPORT_DATA);
this.logger = logger;
this.resourceReader = resourceReader;
protected Database(@NotNull HuskHomes implementor) {
this.plugin = implementor;
this.playerTableName = implementor.getSettings().getTableName(Settings.TableName.PLAYER_DATA);
this.positionsTableName = implementor.getSettings().getTableName(Settings.TableName.POSITION_DATA);
this.savedPositionsTableName = implementor.getSettings().getTableName(Settings.TableName.SAVED_POSITION_DATA);
this.homesTableName = implementor.getSettings().getTableName(Settings.TableName.HOME_DATA);
this.warpsTableName = implementor.getSettings().getTableName(Settings.TableName.WARP_DATA);
this.teleportsTableName = implementor.getSettings().getTableName(Settings.TableName.TELEPORT_DATA);
this.logger = implementor.getLoggingAdapter();
}
/**
@@ -342,12 +342,12 @@ public abstract class Database {
public abstract CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid);
/**
* Get the current {@link Teleport} being executed by the specified {@link User}
* Get the current {@link Teleport} being executed by the specified {@link OnlineUser}
*
* @param user The {@link User} to check
* @param onlineUser The {@link OnlineUser} to check
* @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server
*/
public abstract CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull User user);
public abstract CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull OnlineUser onlineUser);
/**
* Updates a user in the database with new {@link UserData}
@@ -1,14 +1,13 @@
package net.william278.huskhomes.database;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -34,32 +33,27 @@ public class MySqlDatabase extends Database {
public String connectionParameters;
public int connectionPoolSize;
public int connectionPoolIdle;
public long connectionPoolLifetime;
public long connectionPoolKeepAlive;
public long connectionPoolTimeout;
private static final String DATA_POOL_NAME = "HuskHomesHikariPool";
private HikariDataSource dataSource;
public MySqlDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
super(settings, logger, resourceReader);
this.host = settings.mySqlHost;
this.port = settings.mySqlPort;
this.database = settings.mySqlDatabase;
this.username = settings.mySqlUsername;
this.password = settings.mySqlPassword;
this.connectionParameters = settings.mySqlConnectionParameters;
this.connectionPoolSize = settings.mySqlConnectionPoolSize;
this.connectionPoolIdle = settings.mySqlConnectionPoolIdle;
this.connectionPoolLifetime = settings.mySqlConnectionPoolLifetime;
this.connectionPoolKeepAlive = settings.mySqlConnectionPoolKeepAlive;
this.connectionPoolTimeout = settings.mySqlConnectionPoolTimeout;
public MySqlDatabase(@NotNull HuskHomes plugin) {
super(plugin);
this.host = plugin.getSettings().mySqlHost;
this.port = plugin.getSettings().mySqlPort;
this.database = plugin.getSettings().mySqlDatabase;
this.username = plugin.getSettings().mySqlUsername;
this.password = plugin.getSettings().mySqlPassword;
this.connectionParameters = plugin.getSettings().mySqlConnectionParameters;
this.connectionPoolSize = plugin.getSettings().mySqlConnectionPoolSize;
this.connectionPoolIdle = plugin.getSettings().mySqlConnectionPoolIdle;
this.connectionPoolLifetime = plugin.getSettings().mySqlConnectionPoolLifetime;
this.connectionPoolKeepAlive = plugin.getSettings().mySqlConnectionPoolKeepAlive;
this.connectionPoolTimeout = plugin.getSettings().mySqlConnectionPoolTimeout;
}
/**
@@ -617,7 +611,7 @@ public class MySqlDatabase extends Database {
}
@Override
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull User user) {
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull OnlineUser onlineUser) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -625,24 +619,27 @@ public class MySqlDatabase extends Database {
FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, onlineUser.uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Teleport(user,
new Position(resultSet.getDouble("x"),
return Optional.of(Teleport.builder(plugin, onlineUser)
.setTarget(new Position(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))),
TeleportType.getTeleportType(resultSet.getInt("type")).orElse(TeleportType.TELEPORT)));
new Server(resultSet.getString("server_name"))))
.setType(TeleportType.getTeleportType(resultSet.getInt("type"))
.orElse(TeleportType.TELEPORT))
.toTeleport()
.join());
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e);
}
return Optional.empty();
});
@@ -686,7 +683,7 @@ public class MySqlDatabase extends Database {
}
// Set the user's teleport into the database (if it's not null)
if (teleport != null) {
if (teleport != null && teleport.target != null) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
@@ -1,13 +1,12 @@
package net.william278.huskhomes.database;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.sqlite.SQLiteConfig;
@@ -43,9 +42,9 @@ public class SqLiteDatabase extends Database {
private Connection connection;
public SqLiteDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
super(settings, logger, resourceReader);
this.databaseFile = new File(resourceReader.getDataFolder(), DATABASE_FILE_NAME);
public SqLiteDatabase(@NotNull HuskHomes implementor) {
super(implementor);
this.databaseFile = new File(implementor.getDataFolder(), DATABASE_FILE_NAME);
}
private Connection getConnection() throws SQLException {
@@ -608,7 +607,7 @@ public class SqLiteDatabase extends Database {
}
@Override
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull User user) {
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull OnlineUser onlineUser) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -616,24 +615,27 @@ public class SqLiteDatabase extends Database {
FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, onlineUser.uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Teleport(user,
new Position(resultSet.getDouble("x"),
return Optional.of(Teleport.builder(plugin, onlineUser)
.setTarget(new Position(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))),
TeleportType.getTeleportType(resultSet.getInt("type")).orElse(TeleportType.TELEPORT)));
new Server(resultSet.getString("server_name"))))
.setType(TeleportType.getTeleportType(resultSet.getInt("type"))
.orElse(TeleportType.TELEPORT))
.toTeleport()
.join());
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e);
}
return Optional.empty();
});
@@ -680,7 +682,7 @@ public class SqLiteDatabase extends Database {
}
// Set the user's teleport into the database (if it's not null)
if (teleport != null) {
if (teleport != null && teleport.target != null) {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
@@ -17,7 +17,7 @@ public interface EventDispatcher {
void dispatchTeleportEvent(@NotNull Teleport teleport);
CompletableFuture<ITeleportWarmupEvent> dispatchTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration);
CompletableFuture<ITeleportWarmupEvent> dispatchTeleportWarmupEvent(TimedTeleport teleport, int duration);
CompletableFuture<IHomeSaveEvent> dispatchHomeSaveEvent(@NotNull Home home);
@@ -2,9 +2,9 @@ package net.william278.huskhomes.listener;
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.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -99,10 +99,10 @@ public class EventListener {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getPluginServer()))
.ifPresent(position -> onlineUser.teleport(position, plugin.getSettings().asynchronousTeleports));
.ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().asynchronousTeleports));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleport(bedPosition.get(), plugin.getSettings().asynchronousTeleports);
onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().asynchronousTeleports);
}
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() ->
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)));
@@ -110,20 +110,13 @@ public class EventListener {
}
// Teleport the player locally
onlineUser.teleport(teleport.get().target, plugin.getSettings().asynchronousTeleports).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_world")
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(onlineUser::playSound);
}
}).thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null)).exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "An error occurred while teleporting an inbound player", throwable);
return null;
});
teleport.get().execute()
.thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE,
"An error occurred while teleporting an inbound player", throwable);
return null;
});
});
}
return CompletableFuture.completedFuture(null);
@@ -181,8 +174,11 @@ public class EventListener {
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getPluginServer())) {
plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept(
result -> plugin.getTeleportManager().finishTeleport(onlineUser, result));
Teleport.builder(plugin, onlineUser)
.setType(TeleportType.RESPAWN)
.setTarget(respawnPosition)
.toTeleport()
.thenAccept(Teleport::execute);
}
}));
}
@@ -3,6 +3,7 @@ package net.william278.huskhomes.messenger;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
import java.util.*;
@@ -149,8 +150,9 @@ public abstract class NetworkMessenger {
switch (message.type) {
case TELEPORT_TO_POSITION_REQUEST -> {
if (message.payload.position != null) {
message.payload = MessagePayload.withTeleportResult(plugin.getTeleportManager()
.teleport(receiver, message.payload.position).join());
message.payload = MessagePayload.withTeleportResult(Teleport.builder(plugin, receiver)
.setTarget(message.payload.position)
.toTeleport().join().execute().join());
} else {
message.payload = MessagePayload.empty();
}
@@ -139,12 +139,12 @@ public abstract class OnlineUser extends User {
protected abstract Audience getAudience();
/**
* Teleport a player to the specified {@link Location}
* Teleport a player to the specified local {@link Location}
*
* @param location the {@link Location} to teleport the player to
* @param asynchronous if the teleport should be asynchronous
*/
public abstract CompletableFuture<TeleportResult> teleport(@NotNull Location location, boolean asynchronous);
public abstract CompletableFuture<TeleportResult> teleportLocally(@NotNull Location location, boolean asynchronous);
/**
* Returns if a player is moving (i.e. they have momentum)
@@ -5,6 +5,8 @@ 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.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
@@ -316,10 +318,15 @@ public class RequestManager {
if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) {
// Strict /tpahere requests will teleport to where the sender was when typing the command
if (plugin.getSettings().strictTpaHereRequests) {
plugin.getTeleportManager().timedTeleport(recipient, request.requesterPosition).thenAccept(
teleportResult -> plugin.getTeleportManager().finishTeleport(recipient, teleportResult));
Teleport.builder(plugin, recipient)
.setTarget(request.requesterPosition)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
} else {
plugin.getTeleportManager().teleportToPlayerByName(recipient, request.requesterName, true);
Teleport.builder(plugin, recipient)
.setTarget(request.requesterName)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
}
}
@@ -338,7 +345,10 @@ public class RequestManager {
// If the request is a tpa request, teleport the requester to the recipient
if (accepted && (request.type == TeleportRequest.RequestType.TPA)) {
plugin.getTeleportManager().teleportToPlayerByName(requester, request.recipientName, true);
Teleport.builder(plugin, requester)
.setTarget(request.recipientName)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
}
}
@@ -78,15 +78,40 @@ public class TeleportRequest {
return recipientName;
}
/**
* Types of teleport requests ({@code /tpa} or {@code /tpahere})
*/
public enum RequestType {
/**
* 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
*/
protected enum RequestStatus {
/**
* 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,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;
}
}
@@ -1,26 +0,0 @@
package net.william278.huskhomes.util;
import java.io.File;
import java.io.InputStream;
/**
* Abstract representation of a reader that reads internal resource files by name
*/
public interface ResourceReader {
/**
* Gets the resource with given filename and reads it as an {@link InputStream}
*
* @param fileName Name of the resource file to read
* @return The resource, read as an {@link InputStream}
*/
InputStream getResource(String fileName);
/**
* Gets the plugin data folder where plugin configuration and data are kept
*
* @return the plugin data directory
*/
File getDataFolder();
}
+1 -1
View File
@@ -3,7 +3,7 @@ org.gradle.jvmargs='-Dfile.encoding=UTF-8'
org.gradle.daemon=true
javaVersion=16
plugin_version=3.0.5
plugin_version=3.1
plugin_archive=huskhomes
jedis_version=4.2.3