Further refactoring, move away from using future thread pool

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

No files matched your search

@@ -64,17 +64,17 @@ public class Cache {
getPlayers().addAll(plugin.getOnlineUsers()
.stream()
.filter(player -> !player.isVanished())
.map(onlineUser -> onlineUser.getUsername())
.map(User::getUsername)
.toList());
if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger()
.getOnlinePlayerNames(requester)
.thenApply(networkedPlayers -> {
getPlayers().addAll(Set.of(networkedPlayers));
return getPlayers();
});
}
//todo
// if (plugin.getSettings().isCrossServer()) {
// return plugin.getMessenger()
// .getOnlinePlayerNames(requester)
// .thenApply(networkedPlayers -> {
// getPlayers().addAll(Set.of(networkedPlayers));
// return getPlayers();
// });
// }
return CompletableFuture.completedFuture(getPlayers());
}
@@ -9,7 +9,7 @@ import net.william278.desertwell.Version;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.CachedSpawn;
import net.william278.huskhomes.config.Spawn;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.hook.EconomyHook;
@@ -17,11 +17,9 @@ import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.migrator.Migrator;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.TaskRunner;
@@ -76,29 +74,6 @@ public interface HuskHomes extends TaskRunner {
.findFirst());
}
/**
* Looks for a player logged in either on this server or the network of connected servers, by approximate name.
* Auto-completes partially typed names for the closest match.
*
* @param requester the player requesting the player to be found
* @param targetPlayerName the name of the player to find
* @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found
*/
@NotNull
default CompletableFuture<Optional<String>> findPlayer(@NotNull OnlineUser requester, @NotNull String targetPlayerName) {
if (requester.getUsername().equalsIgnoreCase(targetPlayerName)) {
return CompletableFuture.completedFuture(Optional.of(requester.getUsername()));
}
final Optional<OnlineUser> localPlayer = findOnlinePlayer(targetPlayerName);
if (localPlayer.isPresent()) {
return CompletableFuture.completedFuture(Optional.of(localPlayer.get().getUsername()));
}
if (getSettings().isCrossServer()) {
return getMessenger().findPlayer(requester, targetPlayerName);
}
return CompletableFuture.completedFuture(Optional.empty());
}
/**
* The plugin {@link Settings} loaded from file
*
@@ -131,14 +106,6 @@ public interface HuskHomes extends TaskRunner {
@NotNull
Cache getCache();
/**
* The {@link RequestManager} that manages player requests
*
* @return the plugin {@link RequestManager}
*/
@NotNull
RequestManager getRequestManager();
/**
* The {@link Validator} for validating thome names and descriptions
*
@@ -187,19 +154,12 @@ public interface HuskHomes extends TaskRunner {
EventDispatcher getEventDispatcher();
/**
* The list of available {@link Migrator}s
* The local {@link Spawn} location of this server, as cached to disk
*
* @return the list of available {@link Migrator}
*/
List<Migrator> getMigrators();
/**
* The local {@link CachedSpawn} location of this server, as cached to disk
*
* @return the {@link CachedSpawn} location data
* @return the {@link Spawn} location data
* @see #getSpawn() for the canonical spawn point to use
*/
Optional<CachedSpawn> getLocalCachedSpawn();
Optional<Spawn> getLocalCachedSpawn();
/**
* The canonical spawn {@link Position} of this server, if it has been set
@@ -229,9 +189,9 @@ public interface HuskHomes extends TaskRunner {
}
/**
* Update the {@link CachedSpawn} position to a location on the server
* Update the {@link Spawn} position to a location on the server
*
* @param location the new {@link CachedSpawn} location
* @param location the new {@link Spawn} location
*/
void setServerSpawn(@NotNull Location location);
@@ -263,7 +223,7 @@ public interface HuskHomes extends TaskRunner {
* @return the {@link MapHook} optionally being used
*/
default Optional<MapHook> getMapHook() {
return getSettings().isDoMapHook() ? getHook(MapHook.class) : Optional.empty();
return getSettings().doMapHook() ? getHook(MapHook.class) : Optional.empty();
}
/**
@@ -272,7 +232,7 @@ public interface HuskHomes extends TaskRunner {
* @return the {@link EconomyHook} optionally being used
*/
default Optional<EconomyHook> getEconomyHook() {
return getSettings().isEconomy() ? getHook(EconomyHook.class) : Optional.empty();
return getSettings().doEconomy() ? getHook(EconomyHook.class) : Optional.empty();
}
/**
@@ -283,7 +243,7 @@ public interface HuskHomes extends TaskRunner {
* @return {@code true} if the action passes the check, {@code false} if the user has insufficient funds
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull EconomyHook.EconomyAction action) {
default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) {
final Optional<EconomyHook> hook = getEconomyHook();
@@ -304,8 +264,8 @@ public interface HuskHomes extends TaskRunner {
* @param player the player to deduct the cost from if needed
* @param action the action to deduct the cost from if needed
*/
default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.EconomyAction action) {
if (!getSettings().isEconomy()) return;
default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
if (!getSettings().doEconomy()) return;
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) {
@@ -3,14 +3,15 @@ package net.william278.huskhomes.api;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.teleport.TeleportResult;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -116,7 +117,6 @@ public abstract class BaseHuskHomesAPI {
* Save {@link UserData} to the database, updating it if data for the user already exists, or adding new user data if it doesn't.
*
* @param userData The {@link UserData} to save
* @return A {@link CompletableFuture} that will complete when the data has been saved
* @since 3.0
*/
public final void saveUserData(@NotNull UserData userData) {
@@ -138,12 +138,12 @@ public abstract class BaseHuskHomesAPI {
*
* @param user The {@link User} to get the public homes of
* @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user that
* they have made public (where {@link Home#isPublic})
* they have made public (where {@link Home#isPublic()})
* @since 3.0
*/
public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) {
return getUserHomes(user).thenApply(homes -> homes.stream()
.filter(home -> home.isPublic())
.filter(Home::isPublic)
.collect(Collectors.toList()));
}
@@ -264,45 +264,9 @@ public abstract class BaseHuskHomesAPI {
*/
@NotNull
public final TeleportBuilder teleportBuilder(@NotNull OnlineUser onlineUser) {
return Teleport.builder(plugin, onlineUser);
return Teleport.builder(plugin).teleporter(onlineUser);
}
/**
* Attempt to teleport an {@link OnlineUser} to a target {@link Position}
*
* @param user The {@link OnlineUser} to teleport
* @param position The {@link Position} to teleport the user to
* @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still
* for a period of time)
* @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of
* completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}.
* @since 3.0
* @deprecated Use {@link #teleportBuilder(OnlineUser)} to construct a teleport
*/
@Deprecated(since = "3.1")
public final CompletableFuture<TeleportResult> teleportPlayer(@NotNull OnlineUser user,
@NotNull Position position,
final boolean timedTeleport) {
final TeleportBuilder builder = teleportBuilder(user).setTarget(position);
return timedTeleport
? builder.toTimedTeleport().thenApplyAsync(teleport -> teleport.execute().join().getState())
: builder.toTeleport().thenApplyAsync(teleport -> teleport.execute().join().getState());
}
/**
* Attempt to teleport an {@link OnlineUser} to a target {@link Position}
*
* @param user The {@link OnlineUser} to teleport
* @param position The {@link Position} to teleport the user to
* @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of
* completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}.
* @since 3.0
* @deprecated Use {@link #teleportBuilder(OnlineUser)} to construct a teleport
*/
@Deprecated(since = "3.1")
public final CompletableFuture<TeleportResult> teleportPlayer(@NotNull OnlineUser user, @NotNull Position position) {
return teleportPlayer(user, position, false);
}
/**
* Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be
@@ -312,26 +276,25 @@ public abstract class BaseHuskHomesAPI {
* @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still
* for a period of time)
* @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine}
* @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of
* completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}.
* @since 3.0
*/
public final CompletableFuture<TeleportResult> randomlyTeleportPlayer(@NotNull OnlineUser user,
final boolean timedTeleport,
@NotNull String... rtpArgs) {
return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().getWorld(), rtpArgs)
.map(position -> {
final TeleportBuilder builder = Teleport.builder(plugin, user)
.setTarget(position);
return timedTeleport
? builder.toTimedTeleport()
.thenApplyAsync(teleport -> teleport.execute().join().getState()).join()
: builder.toTeleport()
.thenApplyAsync(teleport -> teleport.execute().join().getState()).join();
public final void randomlyTeleportPlayer(@NotNull OnlineUser user, final boolean timedTeleport, @NotNull String... rtpArgs) {
plugin.runAsync(() -> {
final Optional<Position> position = plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().getWorld(), rtpArgs);
if (position.isEmpty()) {
throw new IllegalStateException("Random teleport engine returned an empty position");
}
})
.orElse(TeleportResult.CANCELLED));
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(user)
.target(position.get());
if (timedTeleport) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
});
}
/**
@@ -339,12 +302,10 @@ public abstract class BaseHuskHomesAPI {
* generated by the current {@link RandomTeleportEngine}
*
* @param user The {@link OnlineUser} to teleport
* @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of
* completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}.
* @since 3.0
*/
public final CompletableFuture<TeleportResult> randomlyTeleportPlayer(@NotNull OnlineUser user) {
return randomlyTeleportPlayer(user, false);
public final void randomlyTeleportPlayer(@NotNull OnlineUser user) {
this.randomlyTeleportPlayer(user, false);
}
/**
@@ -19,7 +19,7 @@ public class BackCommand extends CommandBase {
plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition ->
lastPosition.ifPresentOrElse(position -> Teleport.builder(plugin, onlineUser)
.setTarget(position)
.setEconomyActions(EconomyHook.EconomyAction.BACK_COMMAND)
.setEconomyActions(EconomyHook.Action.BACK_COMMAND)
.toTimedTeleport()
.thenApply(TimedTeleport::execute),
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage)));
@@ -4,7 +4,6 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -8,7 +8,6 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -226,7 +225,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, EconomyHook.EconomyAction.MAKE_HOME_PUBLIC)) {
if (!plugin.validateEconomyCheck(editor, EconomyHook.Action.MAKE_HOME_PUBLIC)) {
return;
}
}
@@ -244,7 +243,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, EconomyHook.EconomyAction.MAKE_HOME_PUBLIC);
plugin.performEconomyTransaction(editor, EconomyHook.Action.MAKE_HOME_PUBLIC);
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
@@ -7,7 +7,6 @@ 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;
import org.jetbrains.annotations.Nullable;
@@ -3,7 +3,6 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.desertwell.AboutMenu;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.migrator.Migrator;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -12,7 +11,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -147,50 +145,9 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
() -> plugin.getLoggingAdapter().log(Level.INFO,
"HuskHomes is up to date" +
" (Running v" + plugin.getVersion() + ")")));
case "migrate" -> {
if (args.length < 2) {
plugin.getLoggingAdapter().log(Level.INFO,
"Please choose a migrator, then run \"huskhomes migrate <migrator>\"");
logMigratorsList();
return;
}
final Optional<Migrator> selectedMigrator = plugin.getMigrators().stream().filter(availableMigrator ->
availableMigrator.getIdentifier().equalsIgnoreCase(args[1])).findFirst();
selectedMigrator.ifPresentOrElse(migrator -> {
if (args.length < 3) {
plugin.getLoggingAdapter().log(Level.INFO, migrator.getHelpMenu());
return;
}
switch (args[2]) {
case "start" -> migrator.start().thenAccept(succeeded -> {
if (succeeded) {
plugin.getLoggingAdapter().log(Level.INFO, "Migration completed successfully!");
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Migration failed!");
}
});
case "set" -> migrator.handleConfigurationCommand(Arrays.copyOfRange(args, 3, args.length));
default -> plugin.getLoggingAdapter().log(Level.INFO,
"Invalid syntax. Console usage: \"huskhomes migrate " + args[1] + " <start/set>");
}
}, () -> {
plugin.getLoggingAdapter().log(Level.INFO,
"Please specify a valid migrator.\n" +
"If a migrator is not available, please verify that you meet the prerequisites to use it.");
logMigratorsList();
});
}
}
}
private void logMigratorsList() {
plugin.getLoggingAdapter().log(Level.INFO,
"List of available migrators:\nMigrator ID / Migrator Name:\n" +
plugin.getMigrators().stream()
.map(migrator -> migrator.getIdentifier() + " - " + migrator.getName())
.collect(Collectors.joining("\n")));
}
private void sendAboutMenu(@NotNull OnlineUser onlineUser) {
if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_ABOUT.node)) {
plugin.getLocales().getLocale("error_no_permission")
@@ -7,7 +7,6 @@ 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;
import org.jetbrains.annotations.Nullable;
@@ -6,7 +6,6 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.position.Position;
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;
@@ -49,7 +48,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
}
// Perform economy check if necessary
if (!plugin.validateEconomyCheck(onlineUser, EconomyHook.EconomyAction.RANDOM_TELEPORT)) {
if (!plugin.validateEconomyCheck(onlineUser, EconomyHook.Action.RANDOM_TELEPORT)) {
return;
}
@@ -83,7 +82,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
final TeleportBuilder builder = Teleport.builder(plugin, userToTeleport)
.setTarget(position.get());
final CompletableFuture<? extends Teleport> teleportFuture = isExecutorTeleporting
? builder.setEconomyActions(EconomyHook.EconomyAction.RANDOM_TELEPORT).toTimedTeleport()
? builder.setEconomyActions(EconomyHook.Action.RANDOM_TELEPORT).toTimedTeleport()
: builder.toTeleport();
teleportFuture.thenAccept(teleport -> teleport.execute()
@@ -67,11 +67,11 @@ public class SetHomeCommand extends CommandBase {
// Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null);
if (plugin.getSettings().isEconomy()) {
if (plugin.getSettings().doEconomy()) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(),
plugin.getSettings().doStackPermissionLimits());
if (fetchedData.isPresent()) {
final EconomyHook.EconomyAction action = EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT;
final EconomyHook.Action action = EconomyHook.Action.ADDITIONAL_HOME_SLOT;
newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots()));
// If a new slot is needed, validate the user has enough funds to purchase one
@@ -105,7 +105,7 @@ public class SetHomeCommand extends CommandBase {
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded.get()) {
plugin.performEconomyTransaction(onlineUser, EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.performEconomyTransaction(onlineUser, EconomyHook.Action.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate.get());
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
@@ -6,7 +6,6 @@ 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;
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -44,7 +44,7 @@ public class TpaAllCommand extends CommandBase {
final AtomicInteger counter = new AtomicInteger(0);
final List<CompletableFuture<Void>> sentRequestsFuture = new ArrayList<>();
players.forEach(playerName -> sentRequestsFuture.add(plugin.getRequestManager()
.sendTeleportRequest(onlineUser, playerName, TeleportRequest.RequestType.TPA_HERE)
.sendTeleportRequest(onlineUser, playerName, TeleportRequest.Type.TPA_HERE)
.thenAccept(sent -> counter.addAndGet(sent.isPresent() ? 1 : 0))));
// Send a message when all requests have been sent
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -27,7 +27,7 @@ public class TpaCommand extends CommandBase implements TabCompletable {
if (args.length == 1) {
plugin.getRequestManager()
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA)
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.Type.TPA)
.thenAccept(sent -> {
if (sent.isEmpty()) {
if (args[0].equalsIgnoreCase(onlineUser.getUsername())) {
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -27,7 +27,7 @@ public class TpaHereCommand extends CommandBase implements TabCompletable {
if (args.length == 1) {
plugin.getRequestManager()
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA_HERE)
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.Type.TPA_HERE)
.thenAccept(sent -> {
if (sent.isEmpty()) {
if (args[0].equalsIgnoreCase(onlineUser.getUsername())) {
@@ -21,7 +21,7 @@ import java.util.Optional;
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits
┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/Translations""")
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""")
public class Locales {
/**
@@ -226,14 +226,14 @@ public class Settings {
@YamlKey("economy.costs")
private Map<String, Double> economyCosts = Map.of(
EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT.getDefaultCost(),
EconomyHook.EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyHook.EconomyAction.MAKE_HOME_PUBLIC.getDefaultCost(),
EconomyHook.EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyHook.EconomyAction.RANDOM_TELEPORT.getDefaultCost(),
EconomyHook.EconomyAction.BACK_COMMAND.name().toLowerCase(), EconomyHook.EconomyAction.BACK_COMMAND.getDefaultCost()
EconomyHook.Action.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyHook.Action.ADDITIONAL_HOME_SLOT.getDefaultCost(),
EconomyHook.Action.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyHook.Action.MAKE_HOME_PUBLIC.getDefaultCost(),
EconomyHook.Action.RANDOM_TELEPORT.name().toLowerCase(), EconomyHook.Action.RANDOM_TELEPORT.getDefaultCost(),
EconomyHook.Action.BACK_COMMAND.name().toLowerCase(), EconomyHook.Action.BACK_COMMAND.getDefaultCost()
);
public Optional<Double> getEconomyCost(@NotNull EconomyHook.EconomyAction action) {
if (!isEconomy()) {
public Optional<Double> getEconomyCost(@NotNull EconomyHook.Action action) {
if (!doEconomy()) {
return Optional.empty();
}
final Double cost = getEconomyCosts().get(action.name().toLowerCase());
@@ -363,7 +363,7 @@ public class Settings {
return teleportRequestExpiryTime;
}
public boolean isStrictTpaHereRequests() {
public boolean doStrictTpaHereRequests() {
return strictTpaHereRequests;
}
@@ -463,7 +463,7 @@ public class Settings {
return rtpRestrictedWorlds;
}
public boolean isEconomy() {
public boolean doEconomy() {
return economy;
}
@@ -479,7 +479,7 @@ public class Settings {
return economyCosts;
}
public boolean isDoMapHook() {
public boolean doMapHook() {
return doMapHook;
}
@@ -4,11 +4,9 @@ import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.UUID;
/**
@@ -16,10 +14,10 @@ import java.util.UUID;
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server /spawn location cache ┃
┃ Server /spawn location ┃
┃ Edit in-game using /setspawn ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
public class CachedSpawn {
public class Spawn {
public double x;
public double y;
@@ -47,7 +45,7 @@ public class CachedSpawn {
*
* @param location The {@link Location} of the spawn
*/
public CachedSpawn(@NotNull Location location) {
public Spawn(@NotNull Location location) {
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
@@ -58,6 +56,6 @@ public class CachedSpawn {
}
@SuppressWarnings("unused")
public CachedSpawn() {
public Spawn() {
}
}
@@ -261,19 +261,12 @@ public abstract class Database {
*
* @param plugin The plugin instance
* @return A future returning a list containing all {@link Warp}s set on this server
* @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs
*/
@NotNull
public final List<Warp> getLocalWarps(@NotNull HuskHomes plugin) {
try {
final Server server = plugin.getServerName();
return getWarps().stream()
.filter(warp -> warp.getServer().equals(server))
.collect(Collectors.toList());
} catch (IllegalStateException e) {
return getWarps().stream()
.filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.getWorld())))
.collect(Collectors.toList());
}
return getWarps().stream()
.filter(warp -> warp.getServer().equals(plugin.getServerName()))
.collect(Collectors.toList());
}
/**
@@ -288,19 +281,12 @@ public abstract class Database {
*
* @param plugin The plugin instance
* @return A future returning a list containing all publicly-set {@link Home}s on this server
* @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs
*/
@NotNull
public final List<Home> getLocalPublicHomes(@NotNull HuskHomes plugin) {
try {
final Server server = plugin.getServerName();
return getPublicHomes().stream()
.filter(home -> home.getServer().equals(server))
.collect(Collectors.toList());
} catch (IllegalStateException e) {
return plugin.getDatabase().getPublicHomes().stream()
.filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.getWorld())))
.collect(Collectors.toList());
}
return getPublicHomes().stream()
.filter(home -> home.getServer().equals(plugin.getServerName()))
.collect(Collectors.toList());
}
/**
@@ -7,7 +7,6 @@ import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -152,7 +151,7 @@ public class MySqlDatabase extends Database {
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getName());
statement.setString(7, position.getWorld().getUuid().toString());
statement.setString(8, position.getServer().getName());
statement.setString(8, position.getServer());
statement.executeUpdate();
final ResultSet resultSet = statement.getGeneratedKeys();
@@ -183,7 +182,7 @@ public class MySqlDatabase extends Database {
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getUuid().toString());
statement.setString(7, position.getWorld().getName());
statement.setString(8, position.getServer().getName());
statement.setString(8, position.getServer());
statement.setDouble(9, positionId);
statement.executeUpdate();
}
@@ -600,20 +599,20 @@ public class MySqlDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(Teleport.builder(plugin, onlineUser)
.setTarget(new Position(resultSet.getDouble("x"),
return Optional.of(Teleport.builder(plugin)
.teleporter(onlineUser)
.target(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"))))
.setType(TeleportType.getTeleportType(resultSet.getInt("type"))
.orElse(TeleportType.TELEPORT))
.doUpdateLastPosition(false)
.toTeleport()
.join());
resultSet.getString("server_name")))
.type(Teleport.Type.getTeleportType(resultSet.getInt("type"))
.orElse(Teleport.Type.TELEPORT))
.updateLastPosition(false)
.toTeleport());
}
}
} catch (SQLException e) {
@@ -657,13 +656,13 @@ public class MySqlDatabase extends Database {
}
// Set the user's teleport into the database (if it's not null)
if (teleport != null && teleport.target != null) {
if (teleport != null) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition(teleport.target, connection));
statement.setInt(3, teleport.type.typeId);
statement.setInt(2, setPosition((Position) teleport.getTarget(), connection));
statement.setInt(3, teleport.getType().getTypeId());
statement.executeUpdate();
}
@@ -692,7 +691,7 @@ public class MySqlDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))));
resultSet.getString("server_name")));
}
}
} catch (SQLException e) {
@@ -751,7 +750,7 @@ public class MySqlDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))));
resultSet.getString("server_name")));
}
}
} catch (SQLException e) {
@@ -809,7 +808,7 @@ public class MySqlDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))));
resultSet.getString("server_name")));
}
}
} catch (SQLException e) {
@@ -6,7 +6,6 @@ import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.sqlite.SQLiteConfig;
@@ -144,7 +143,7 @@ public class SqLiteDatabase extends Database {
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getName());
statement.setString(7, position.getWorld().getUuid().toString());
statement.setString(8, position.getServer().getName());
statement.setString(8, position.getServer());
statement.executeUpdate();
// Return the ID of the newly inserted row
@@ -177,7 +176,7 @@ public class SqLiteDatabase extends Database {
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getUuid().toString());
statement.setString(7, position.getWorld().getName());
statement.setString(8, position.getServer().getName());
statement.setString(8, position.getServer());
statement.setDouble(9, positionId);
statement.executeUpdate();
}
@@ -596,20 +595,20 @@ public class SqLiteDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(Teleport.builder(plugin, onlineUser)
.setTarget(new Position(resultSet.getDouble("x"),
return Optional.of(Teleport.builder(plugin)
.teleporter(onlineUser)
.target(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"))))
.setType(TeleportType.getTeleportType(resultSet.getInt("type"))
.orElse(TeleportType.TELEPORT))
.doUpdateLastPosition(false)
.toTeleport()
.join());
resultSet.getString("server_name")))
.type(Teleport.Type.getTeleportType(resultSet.getInt("type"))
.orElse(Teleport.Type.TELEPORT))
.updateLastPosition(false)
.toTeleport());
}
} catch (SQLException e) {
@@ -654,13 +653,13 @@ public class SqLiteDatabase extends Database {
}
// Set the user's teleport into the database (if it's not null)
if (teleport != null && teleport.target != null) {
if (teleport != null) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition(teleport.target, connection));
statement.setInt(3, teleport.type.typeId);
statement.setInt(2, setPosition((Position) teleport.getTarget(), connection));
statement.setInt(3, teleport.getType().getTypeId());
statement.executeUpdate();
@@ -688,7 +687,7 @@ public class SqLiteDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))));
resultSet.getString("server_name")));
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
@@ -745,7 +744,7 @@ public class SqLiteDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))));
resultSet.getString("server_name")));
}
} catch (SQLException e) {
@@ -800,7 +799,7 @@ public class SqLiteDatabase extends Database {
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name"))));
resultSet.getString("server_name")));
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
@@ -40,7 +40,7 @@ public abstract class EconomyHook extends PluginHook {
/**
* Identifies actions that incur an economic cost if economy is enabled
*/
public enum EconomyAction {
public enum Action {
ADDITIONAL_HOME_SLOT(100.00, "economy_action_additional_home_slot"),
MAKE_HOME_PUBLIC(50.00, "economy_action_make_home_public"),
RANDOM_TELEPORT(25.00, "economy_action_random_teleport"),
@@ -50,7 +50,7 @@ public abstract class EconomyHook extends PluginHook {
@NotNull
public final String confirmationLocaleId;
EconomyAction(final double defaultCost, @NotNull String confirmationLocaleId) {
Action(final double defaultCost, @NotNull String confirmationLocaleId) {
this.defaultCost = defaultCost;
this.confirmationLocaleId = confirmationLocaleId;
}
@@ -6,6 +6,7 @@ import com.djrapitops.plan.extension.annotation.*;
import com.djrapitops.plan.extension.icon.Color;
import com.djrapitops.plan.extension.icon.Family;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.UserData;
import org.jetbrains.annotations.NotNull;
@@ -77,8 +78,8 @@ public class PlanDataExtension implements DataExtension {
@Conditional("hasData")
public long getPublicHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid)
.map(userData -> database.getHomes(userData.user())
.stream().filter(home -> home.isPublic()).count())
.map(userData -> database.getHomes(userData.user()).stream()
.filter(Home::isPublic).count())
.orElse(0L);
}
@@ -123,7 +124,7 @@ public class PlanDataExtension implements DataExtension {
.map(userData -> database.getOfflinePosition(userData.user())
.map(position -> "x: " + (int) position.getX() + ", y: " + (int) position.getY() + ", z: " + (int) position.getZ()
+ " (" + position.getWorld().getName() +
((crossServer) ? "/" + position.getServer().getName() + ")" : ")"))
((crossServer) ? "/" + position.getServer() + ")" : ")"))
.orElse(UNKNOWN_STRING))
.orElse(UNKNOWN_STRING);
}
@@ -6,7 +6,6 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
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;
@@ -43,7 +42,7 @@ public class EventListener {
// Set their ignoring requests state
plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> {
final boolean ignoringRequests = userData.ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
plugin.getManager().requests().setIgnoringRequests(onlineUser, ignoringRequests);
// Send a reminder message if they are still ignoring requests
if (ignoringRequests) {
@@ -68,7 +67,7 @@ public class EventListener {
*/
private void handleInboundTeleport(@NotNull OnlineUser onlineUser) {
plugin.getDatabase().getCurrentTeleport(onlineUser).ifPresent(teleport -> {
if (teleport.type == TeleportType.RESPAWN) {
if (teleport.getType() == Teleport.Type.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn()
@@ -83,13 +82,8 @@ public class EventListener {
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null));
return;
}
teleport.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;
});
teleport.execute();
plugin.getDatabase().setCurrentTeleport(onlineUser, null);
});
}
@@ -146,11 +140,12 @@ public class EventListener {
if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) {
plugin.getDatabase().getRespawnPosition(onlineUser).ifPresent(respawnPosition -> {
if (!respawnPosition.getServer().equals(plugin.getServerName())) {
Teleport.builder(plugin, onlineUser)
.setType(TeleportType.RESPAWN)
.setTarget(respawnPosition)
Teleport.builder(plugin)
.teleporter(onlineUser)
.type(Teleport.Type.RESPAWN)
.target(respawnPosition)
.toTeleport()
.thenAccept(Teleport::execute);
.execute();
}
});
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.util.ValidationException;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
@@ -20,11 +20,11 @@ public class HomesManager {
public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException {
final Optional<Home> existingHome = plugin.getDatabase().getHome(owner, name);
if (existingHome.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.ValidationError.NAME_TAKEN);
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
}
if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
final Home home = existingHome
@@ -45,7 +45,7 @@ public class HomesManager {
public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException {
final Optional<Home> home = plugin.getDatabase().getHome(owner, name);
if (home.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
plugin.getDatabase().deleteHome(home.get().getUuid());
}
@@ -57,11 +57,11 @@ public class HomesManager {
public void renameHome(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
final Home home = optionalHome.get();
@@ -72,11 +72,11 @@ public class HomesManager {
public void updateHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
if (!plugin.getValidator().isValidDescription(description)) {
throw new ValidationException(ValidationException.ValidationError.DESCRIPTION_INVALID);
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID);
}
final Home home = optionalHome.get();
@@ -87,7 +87,7 @@ public class HomesManager {
public void updateHomePrivacy(@NotNull User owner, @NotNull String name, boolean isPublic) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
final Home home = optionalHome.get();
@@ -9,12 +9,14 @@ public class Manager {
private final HomesManager homes;
private final WarpsManager warps;
private final UsersManager users;
private final RequestsManager requests;
public Manager(@NotNull HuskHomes plugin) {
this.plugin = plugin;
this.homes = new HomesManager(plugin);
this.warps = new WarpsManager(plugin);
this.users = new UsersManager(plugin);
this.requests = new RequestsManager(plugin);
}
@NotNull
@@ -31,4 +33,9 @@ public class Manager {
public UsersManager users() {
return users;
}
@NotNull
public RequestsManager requests() {
return requests;
}
}
@@ -1,22 +1,22 @@
package net.william278.huskhomes.request;
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.network.Request;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* Manages {@link TeleportRequest}s between players
*/
public class RequestManager {
public class RequestsManager {
@NotNull
private final HuskHomes plugin;
@@ -31,7 +31,7 @@ public class RequestManager {
*/
private final Set<UUID> ignoringRequests;
public RequestManager(@NotNull HuskHomes implementation) {
public RequestsManager(@NotNull HuskHomes implementation) {
this.plugin = implementation;
this.requests = new HashMap<>();
this.ignoringRequests = new HashSet<>();
@@ -79,7 +79,7 @@ public class RequestManager {
*/
public void removeTeleportRequest(@NotNull String requesterName, @NotNull User recipient) {
this.requests.computeIfPresent(recipient.getUuid(), (uuid, requests) -> {
requests.removeIf(teleportRequest -> teleportRequest.requesterName.equalsIgnoreCase(requesterName));
requests.removeIf(teleportRequest -> teleportRequest.getRequesterName().equalsIgnoreCase(requesterName));
return requests.isEmpty() ? null : requests;
});
}
@@ -107,66 +107,44 @@ public class RequestManager {
*/
public Optional<TeleportRequest> getTeleportRequest(@NotNull String requesterName, @NotNull User recipient) {
return this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream()
.filter(request -> request.requesterName.equalsIgnoreCase(requesterName))
.filter(request -> request.getRequesterName().equalsIgnoreCase(requesterName))
.filter(request -> !request.hasExpired())
.findFirst()
.or(() -> this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream()
.filter(request -> request.requesterName.equalsIgnoreCase(requesterName))
.filter(request -> request.getRequesterName().equalsIgnoreCase(requesterName))
.findFirst());
}
/**
* Sends a teleport request of the given type to the specified user, by name, if they exist.
*
* @param requester The user making the request
* @param targetUser The user to send the request to
* @param requestType The type of request to send
* @return A {@link CompletableFuture} that will return the request that was sent if it was sent successfully,
* or an empty {@link Optional} if the request was not sent
* @param requester The user making the request
* @param targetUser The user to send the request to
* @param type The type of request to send
*/
public CompletableFuture<Optional<TeleportRequest>> sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser,
@NotNull TeleportRequest.RequestType requestType) {
final TeleportRequest request = new TeleportRequest(requester, requestType,
Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime());
public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, @NotNull TeleportRequest.Type type) throws IllegalArgumentException {
final long expiry = Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime();
final TeleportRequest request = new TeleportRequest(requester, type, expiry);
final Optional<OnlineUser> localTarget = plugin.findOnlinePlayer(targetUser);
if (localTarget.isPresent()) {
if (localTarget.get().equals(requester)) {
return CompletableFuture.completedFuture(Optional.empty());
throw new IllegalArgumentException("Cannot send a teleport request to yourself");
}
request.recipientName = localTarget.get().getUsername();
return CompletableFuture.completedFuture(sendLocalTeleportRequest(request, localTarget.get()));
request.setRecipientName(localTarget.get().getUsername());
sendLocalTeleportRequest(request, localTarget.get());
return;
}
// If the player couldn't be found locally, send the request cross-server
if (plugin.getSettings().isCrossServer()) {
// Find the matching networked target
return plugin.getMessenger().findPlayer(requester, targetUser).thenApplyAsync(networkedTarget -> {
if (networkedTarget.isEmpty()) {
return Optional.empty();
}
// Use the network messenger to send the request
request.recipientName = networkedTarget.get();
return Request.builder()
.withType(Request.MessageType.TELEPORT_REQUEST)
.withPayload(Payload.withTeleportRequest(request))
.withTargetPlayer(networkedTarget.get())
.build().send(requester, plugin)
.thenApply(reply -> {
if (reply.isPresent()) {
final TeleportRequest result = reply.get().getPayload().getTeleportRequest();
if (result == null || result.status == TeleportRequest.RequestStatus.IGNORED) {
return null;
}
return result;
}
return null;
})
.thenApply(Optional::ofNullable)
.join();
});
request.setRecipientName(targetUser);
Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request))
.target(targetUser)
.build().send(plugin.getMessenger(), requester);
}
return CompletableFuture.completedFuture(Optional.empty());
throw new IllegalArgumentException("Player not found");
}
/**
@@ -177,28 +155,28 @@ public class RequestManager {
* @return the {@link TeleportRequest} that was sent if it could be sent, otherwise an empty optional if it was not
* sent because the recipient is ignoring requests or is vanished ({@link OnlineUser#isVanished()})
*/
public Optional<TeleportRequest> sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) {
public void sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) {
// Silently ignore the request if the recipient is ignoring requests or is vanished
if (isIgnoringRequests(recipient) || recipient.isVanished()) {
request.status = TeleportRequest.RequestStatus.IGNORED;
return Optional.empty();
request.setStatus(TeleportRequest.Status.IGNORED);
return;
}
// If the person already has an unexpired request of the same type by this player, don't bother sending another
final Optional<TeleportRequest> existingRequest = getTeleportRequest(request.requesterName, recipient);
final Optional<TeleportRequest> existingRequest = getTeleportRequest(request.getRequesterName(), recipient);
if (existingRequest.isPresent()) {
if (existingRequest.get().type == request.type && !existingRequest.get().hasExpired()) {
return Optional.of(request);
if (existingRequest.get().getType() == request.getType() && !existingRequest.get().hasExpired()) {
return;
}
}
// Add the request and display a message to the recipient
addTeleportRequest(request, recipient);
plugin.getLocales().getLocale((request.type == TeleportRequest.RequestType.TPA ? "tpa" : "tpahere")
+ "_request_received", request.requesterName)
plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere")
+ "_request_received", request.getRequesterName())
.ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.requesterName)
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
.ifPresent(recipient::sendMessage);
return Optional.of(request);
}
/**
@@ -261,7 +239,7 @@ public class RequestManager {
private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient,
boolean accepted) {
// Remove the request(s) from the sender from the recipient's queue
removeTeleportRequest(request.requesterName, recipient);
removeTeleportRequest(request.getRequesterName(), recipient);
// Check if the request has expired
if (request.hasExpired()) {
@@ -271,39 +249,21 @@ public class RequestManager {
// Send request response confirmation to the recipient
plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation",
request.requesterName)
request.getRequesterName())
.ifPresent(recipient::sendMessage);
request.status = accepted ? TeleportRequest.RequestStatus.ACCEPTED : TeleportRequest.RequestStatus.DECLINED;
request.setStatus(accepted ? TeleportRequest.Status.ACCEPTED : TeleportRequest.Status.DECLINED);
// Send request response to the sender
final Optional<OnlineUser> localRequester = plugin.findOnlinePlayer(request.requesterName);
final Optional<OnlineUser> localRequester = plugin.findOnlinePlayer(request.getRequesterName());
if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().isCrossServer()) {
// Ensure the sender is still online
plugin.getMessenger()
.findPlayer(recipient, request.requesterName)
.thenApplyAsync(networkedTarget -> {
if (networkedTarget.isEmpty()) {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
return false;
}
return Request.builder()
.withType(Request.MessageType.TELEPORT_REQUEST_RESPONSE)
.withPayload(Payload.withTeleportRequest(request))
.withTargetPlayer(networkedTarget.get())
.build().send(recipient, plugin)
.thenApply(Optional::isPresent)
.join();
})
.thenAccept(online -> {
if (!online) {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
}
});
Message.builder()
.type(Message.Type.TELEPORT_REQUEST_RESPONSE)
.payload(Payload.withTeleportRequest(request))
.target(request.getRequesterName())
.build()
.send(plugin.getMessenger(), recipient);
} else {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
@@ -311,19 +271,18 @@ public class RequestManager {
}
// If the request is a tpa here request, teleport the recipient to the sender
if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) {
if (accepted && request.getType() == TeleportRequest.Type.TPA_HERE) {
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(recipient);
// Strict /tpahere requests will teleport to where the sender was when typing the command
if (plugin.getSettings().isStrictTpaHereRequests()) {
Teleport.builder(plugin, recipient)
.setTarget(request.requesterPosition)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
if (plugin.getSettings().doStrictTpaHereRequests()) {
builder.target(request.getRequesterPosition());
} else {
Teleport.builder(plugin, recipient)
.setTarget(request.requesterName)
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
builder.target(request.getRequesterName());
}
builder.toTimedTeleport().execute();
}
}
@@ -335,16 +294,17 @@ public class RequestManager {
* @param request The {@link TeleportRequest} to handle
*/
public void handleLocalRequestResponse(@NotNull OnlineUser requester, @NotNull TeleportRequest request) {
boolean accepted = request.status == TeleportRequest.RequestStatus.ACCEPTED;
boolean accepted = request.getStatus() == TeleportRequest.Status.ACCEPTED;
plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined"),
request.recipientName).ifPresent(requester::sendMessage);
request.getRecipientName()).ifPresent(requester::sendMessage);
// If the request is a tpa request, teleport the requester to the recipient
if (accepted && (request.type == TeleportRequest.RequestType.TPA)) {
Teleport.builder(plugin, requester)
.setTarget(request.recipientName)
if (accepted && (request.getType() == TeleportRequest.Type.TPA)) {
Teleport.builder(plugin)
.teleporter(requester)
.target(request.getRecipientName())
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
.execute();
}
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.util.ValidationException;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
@@ -18,11 +18,11 @@ public class WarpsManager {
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) {
final Optional<Warp> existingWarp = plugin.getDatabase().getWarp(name);
if (existingWarp.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.ValidationError.NAME_TAKEN);
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
}
if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
final Warp warp = existingWarp
@@ -43,7 +43,7 @@ public class WarpsManager {
public void deleteWarp(@NotNull String name) {
final Optional<Warp> warp = plugin.getDatabase().getWarp(name);
if (warp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
plugin.getDatabase().deleteWarp(warp.get().getUuid());
}
@@ -55,11 +55,11 @@ public class WarpsManager {
public void renameHome(@NotNull String name, @NotNull String newName) throws ValidationException {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
final Warp warp = optionalWarp.get();
@@ -70,7 +70,7 @@ public class WarpsManager {
public void setWarpDescription(@NotNull String name, @NotNull String description) {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
final Warp warp = optionalWarp.get();
@@ -1,68 +0,0 @@
package net.william278.huskhomes.migrator;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
/**
* A migrator that imports legacy and other plugin's data into HuskHomes' format.
*/
public abstract class Migrator {
protected final HuskHomes plugin;
protected Migrator(@NotNull HuskHomes implementor) {
this.plugin = implementor;
}
/**
* Start the migrator
*
* @return A future that will be completed when the migrator is done
*/
public abstract CompletableFuture<Boolean> start();
/**
* Handle a command that sets migrator configuration parameters
*
* @param args The command arguments
*/
public abstract void handleConfigurationCommand(@NotNull String[] args);
/**
* Obfuscates a data string to prevent important data from being logged to console
*
* @param dataString The data string to obfuscate
* @return The data string obfuscated with stars (*)
*/
@NotNull
protected final String obfuscateDataString(@NotNull String dataString) {
return (dataString.length() > 1 ? dataString.charAt(0) + "*".repeat(dataString.length() - 1) : "");
}
/**
* Get the unique identifier of the migrator
*
* @return The unique identifier of the migrator
*/
@NotNull
public abstract String getIdentifier();
/**
* Get the display name of the migrator
*
* @return The name of the migrator
*/
@NotNull
public abstract String getName();
/**
* Get the help splash menu of the migrator
*
* @return The help splash menu of the migrator
*/
@NotNull
public abstract String getHelpMenu();
}
@@ -1,19 +1,14 @@
package net.william278.huskhomes.network;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public abstract class Broker {
protected final HuskHomes plugin;
private final Map<UUID, CompletableFuture<Message>> outboundMessages = new HashMap<>();
/**
* Create a new broker
@@ -34,45 +29,31 @@ public abstract class Broker {
if (message.getSourceServer().equals(getServer()) || receiver == null) {
return;
}
if (message.getDirection() == Message.Direction.INBOUND) {
this.outboundMessages.getOrDefault(message.getUuid(), new CompletableFuture<>()).complete(message);
this.outboundMessages.remove(message.getUuid());
return;
}
switch (message.getType()) {
case TELEPORT_TO_POSITION_REQUEST -> {
if (message.getPayload().getPosition() != null) {
Teleport.builder(plugin, receiver)
.setTarget(message.getPayload().getPosition()).toTeleport()
.thenAccept(teleport -> teleport.execute()
.thenAccept(result -> message.reply(
this,
receiver,
Payload.withTeleportResult(result.getState())
)));
return;
}
}
case POSITION_REQUEST -> message.reply(this, receiver, Payload.withPosition(receiver.getPosition()));
case TELEPORT_REQUEST -> {
if (message.getPayload().getTeleportRequest() != null) {
message.reply(this, receiver, plugin.getRequestManager()
.sendLocalTeleportRequest(message.getPayload().getTeleportRequest(), receiver)
.map(Payload::withTeleportRequest)
.orElse(Payload.empty()));
return;
}
message.reply(this, receiver, Payload.empty());
}
case TELEPORT_REQUEST_RESPONSE -> {
if (message.getPayload().getTeleportRequest() != null) {
final TeleportRequest request = message.getPayload().getTeleportRequest();
plugin.getRequestManager().handleLocalRequestResponse(receiver, request);
message.reply(this, receiver, Payload.withTeleportRequest(request));
return;
}
message.reply(this, receiver, Payload.empty());
}
case TELEPORT_TO_POSITION -> message.getPayload()
.getPosition().ifPresent(position -> Teleport.builder(plugin)
.teleporter(receiver)
.target(position)
.toTeleport()
.execute());
case TELEPORT_TO_NETWORKED_POSITION -> Message.builder()
.type(Message.Type.TELEPORT_TO_POSITION)
.target(message.getSender())
.payload(Payload.withPosition(receiver.getPosition()))
.build().send(this, receiver);
case TELEPORT_TO_NETWORKED_USER -> message.getPayload()
.getString().ifPresent(target -> Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_POSITION)
.target(target)
.build().send(this, receiver));
case TELEPORT_REQUEST -> message.getPayload()
.getTeleportRequest()
.ifPresent(teleportRequest -> plugin.getManager().requests()
.sendLocalTeleportRequest(teleportRequest, receiver));
case TELEPORT_REQUEST_RESPONSE -> message.getPayload()
.getTeleportRequest()
.ifPresent(teleportRequest -> plugin.getManager().requests()
.handleLocalRequestResponse(receiver, teleportRequest));
}
}
@@ -99,11 +80,6 @@ public abstract class Broker {
*/
public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server);
@NotNull
protected Map<UUID, CompletableFuture<Message>> getOutboundMessages() {
return outboundMessages;
}
/**
* Terminate the broker
*/
@@ -120,23 +96,23 @@ public abstract class Broker {
return plugin.getServerName();
}
/**
* Identifies types of message brokers
*/
public enum Type {
PLUGIN_MESSAGE("Plugin Messages"),
REDIS("Redis");
@NotNull
private final String displayName;
/**
* Identifies types of message brokers
*/
public enum Type {
PLUGIN_MESSAGE("Plugin Messages"),
REDIS("Redis");
@NotNull
private final String displayName;
Type(@NotNull String displayName) {
this.displayName = displayName;
}
@NotNull
public String getDisplayName() {
return displayName;
}
Type(@NotNull String displayName) {
this.displayName = displayName;
}
@NotNull
public String getDisplayName() {
return displayName;
}
}
}
@@ -5,7 +5,6 @@ import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* Represents a message sent by a {@link Broker} cross-server. See {@link #builder()} for
@@ -27,8 +26,6 @@ public class Message {
private String sender;
@Expose
private String sourceServer;
@Expose
private Direction direction;
private Message(@NotNull Type type, @NotNull String target, @NotNull Payload payload) {
this.type = type;
@@ -45,22 +42,10 @@ public class Message {
return new Builder();
}
public CompletableFuture<Message> send(@NotNull Broker broker, @NotNull OnlineUser sender) {
public void send(@NotNull Broker broker, @NotNull OnlineUser sender) {
this.sender = sender.getUsername();
this.sourceServer = broker.getServer();
this.direction = Direction.OUTBOUND;
final CompletableFuture<Message> future = new CompletableFuture<>();
broker.getOutboundMessages().put(getUuid(), future);
broker.send(this, sender);
return future;
}
public void reply(@NotNull Broker broker, @NotNull OnlineUser receiver, @NotNull Payload payload) {
this.sender = receiver.getUsername();
this.sourceServer = broker.getServer();
this.direction = Direction.INBOUND;
this.payload = payload;
broker.send(this, receiver);
}
@NotNull
@@ -88,11 +73,6 @@ public class Message {
return sourceServer;
}
@NotNull
public Direction getDirection() {
return direction;
}
@NotNull
public UUID getUuid() {
return id;
@@ -138,21 +118,10 @@ public class Message {
* Different types of cross-server messages
*/
public enum Type {
TELEPORT_TO_POSITION_REQUEST,
POSITION_REQUEST,
TELEPORT_TO_POSITION,
TELEPORT_TO_NETWORKED_POSITION,
TELEPORT_REQUEST,
POSITION_RESPONSE, TELEPORT_REQUEST_RESPONSE
}
public enum Direction {
/**
* The message is being sent from the sender to the target
*/
OUTBOUND,
/**
* The message is being sent from the target to the sender
*/
INBOUND
POSITION_RESPONSE, TELEPORT_TO_NETWORKED_USER, TELEPORT_REQUEST_RESPONSE
}
}
@@ -1,28 +1,33 @@
package net.william278.huskhomes.network;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Represents a payload sent in a cross-server {@link Request}
* Represents a payload sent in a cross-server {@link Message}
*/
public class Payload {
@Nullable
@Expose
private Position position;
@Nullable
@SerializedName("teleport_result")
private TeleportResult resultState;
@Nullable
@Expose
@SerializedName("teleport_request")
private TeleportRequest teleportRequest;
@Nullable
@Expose
private String string;
/**
* Returns an empty cross-server message payload
*
@@ -46,19 +51,6 @@ public class Payload {
return payload;
}
/**
* Returns a payload containing a {@link TeleportResult}
*
* @param resultState the teleport to send
* @return a payload containing the teleport result
*/
@NotNull
public static Payload withTeleportResult(@NotNull TeleportResult resultState) {
final Payload payload = new Payload();
payload.resultState = resultState;
return payload;
}
/**
* Returns a payload containing a {@link TeleportRequest}
*
@@ -72,30 +64,35 @@ public class Payload {
return payload;
}
/**
* A string field
*/
@NotNull
public static Payload withString(@NotNull String target) {
final Payload payload = new Payload();
payload.string = target;
return payload;
}
private Payload() {
}
/**
* A position field
*/
@Nullable
public Position getPosition() {
return position;
public Optional<Position> getPosition() {
return Optional.ofNullable(position);
}
public Optional<TeleportRequest> getTeleportRequest() {
return Optional.ofNullable(teleportRequest);
}
/**
* A teleport result field
* A string field
*/
@Nullable
public TeleportResult getResultState() {
return resultState;
}
/**
* A teleport request field
*/
@Nullable
public TeleportRequest getTeleportRequest() {
return teleportRequest;
public Optional<String> getString() {
return Optional.ofNullable(string);
}
}
@@ -1,5 +1,6 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.teleport.Target;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
@@ -8,7 +9,7 @@ import java.util.UUID;
/**
* Represents a position - a {@link Location} somewhere on the proxy network or server
*/
public class Position extends Location {
public class Position extends Location implements Target {
private String server;
@@ -1,117 +0,0 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Represents the result of executing a {@link Teleport} or {@link TimedTeleport}
*
* @since 3.1
*/
public class CompletedTeleport {
/**
* The state of the {@link Teleport}
*/
@NotNull
private final TeleportResult state;
/**
* The {@link User} who is doing the teleporting
*/
@Nullable
private final User teleporter;
/**
* The {@link Position} the teleporter should be teleported to
*/
@Nullable
private final Position destination;
/**
* <b>Internal</b> - Create a new {@link CompletedTeleport} (use {@link #from(TeleportResult, Teleport)})
*
* @param state The {@link TeleportResult} of completing the teleport
* @param teleporter The {@link User} who is doing the teleporting
* @param destination The {@link Position} the teleporter should be teleported to
* @since 3.1
*/
private CompletedTeleport(@NotNull TeleportResult state, @Nullable User teleporter, @Nullable Position destination) {
this.state = state;
this.teleporter = teleporter;
this.destination = destination;
}
/**
* Create a new {@link CompletedTeleport} for a {@link Teleport} with an outcome {@link TeleportResult}
*
* @param state The outcome {@link TeleportResult}
* @param teleport The {@link Teleport} that was executed
* @return The {@link CompletedTeleport} of executing the supplied {@link Teleport}
* @since 3.1
*/
public static CompletedTeleport from(@NotNull TeleportResult state, @NotNull Teleport teleport) {
return new CompletedTeleport(state, teleport.teleporter, teleport.target);
}
/**
* Get the state of the {@link Teleport} after execution has finished
*
* @return The {@link TeleportResult} of the teleport
* @since 3.1
*/
@NotNull
public TeleportResult getState() {
return state;
}
/**
* Returns if the teleport was successful
*
* @return {@code true} if the teleport was successful, {@code false} otherwise
* @since 3.1
*/
public boolean successful() {
return state.successful;
}
/**
* Get the {@link User} who is doing the teleporting
*
* @return The teleporter, if they were resolved
* @implNote The optional will return empty if the state is {@link TeleportResult#FAILED_TELEPORTER_NOT_RESOLVED}
* @since 3.1
*/
public Optional<User> getTeleporter() {
return Optional.ofNullable(teleporter);
}
/**
* Get the target {@link Position} the teleporter should have been teleported to
*
* @return The target position, if it was resolved
* @implNote The optional will return empty if the state is {@link TeleportResult#FAILED_TARGET_NOT_RESOLVED}
* @since 3.1
*/
public Optional<Position> getDestination() {
return Optional.ofNullable(destination);
}
/**
* Send an {@link OnlineUser} the corresponding message indicating the state of the teleport once it has executred
*
* @param locales the {@link Locales} instance to use
* @param user the {@link OnlineUser} to send the message to
* @since 3.1
*/
public void sendResultMessage(@NotNull Locales locales, @NotNull OnlineUser user) {
this.state.sendResultMessage(locales, user);
}
}
@@ -0,0 +1,12 @@
package net.william278.huskhomes.teleport;
import org.jetbrains.annotations.NotNull;
public interface Target {
@NotNull
static Target username(@NotNull String target) {
return new Username(target);
}
}
@@ -1,213 +1,146 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
/**
* Represents a teleport in the process of being executed
*
* @since 3.1
*/
public class Teleport {
/**
* <b>Internal</b> - Instance of the implementing HuskHomes plugin
*/
@NotNull
private final HuskHomes plugin;
protected final OnlineUser executor;
protected final Teleportable teleporter;
protected final Target target;
protected final Type type;
protected final boolean updateLastPosition;
protected final List<EconomyHook.Action> economyActions;
private final boolean async;
/**
* The {@link User} who is doing the teleporting
*/
@Nullable
public final User teleporter;
/**
* The {@link OnlineUser} on this server executing the teleport.
* </p>
* Can be the same as the {@link #teleporter}, but not necessarily
*/
@NotNull
public final OnlineUser executor;
/**
* The target {@link Position} the teleporter should be teleported to
*/
@Nullable
public final Position target;
/**
* The {@link TeleportType type} of the teleport
*/
@NotNull
public final TeleportType type;
/**
* {@link EconomyHook.EconomyAction}s to be checked against the {@link #executor executor}'s balance
*/
@NotNull
public final Set<EconomyHook.EconomyAction> economyActions;
/**
* Whether to update the {@link #teleporter teleporter}'s last position (i.e. their {@code /back} position)
*/
public final boolean updateLastPosition;
/**
* <b>Internal</b> - use TeleportBuilder to instantiate a teleport
*/
protected Teleport(@Nullable User teleporter, @NotNull OnlineUser executor, @Nullable Position target,
@NotNull TeleportType type, @NotNull Set<EconomyHook.EconomyAction> economyActions,
final boolean updateLastPosition, @NotNull HuskHomes plugin) {
this.teleporter = teleporter;
protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target,
@NotNull Type type, boolean updateLastPosition, @NotNull List<EconomyHook.Action> actions,
@NotNull HuskHomes plugin) {
this.executor = executor;
this.teleporter = teleporter;
this.target = target;
this.type = type;
this.economyActions = economyActions;
this.plugin = plugin;
this.updateLastPosition = updateLastPosition;
this.economyActions = actions;
this.async = plugin.getSettings().isAsynchronousTeleports();
this.plugin = plugin;
}
/**
* Create a teleport builder with an executor to carry it out
*
* @param plugin Instance of the implementing HuskHomes plugin
* @param executor The {@link OnlineUser} on this server executing the teleport.
* Not necessarily the person being teleported, which can be set independently with
* {{@link TeleportBuilder#setTeleporter(User)}}
* @return A new {@link TeleportBuilder} instance
*/
public static TeleportBuilder builder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) {
return new TeleportBuilder(plugin, executor);
@NotNull
public static TeleportBuilder builder(@NotNull HuskHomes plugin) {
return new TeleportBuilder(plugin);
}
/**
* Execute this teleport
*
* @return A {@link CompletableFuture} that completes when the teleport is finished
*/
public CompletableFuture<CompletedTeleport> execute() {
// Validate the teleporter
if (teleporter == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
public void execute() throws TeleportationException {
final Optional<OnlineUser> localTeleporter = resolveLocalTeleporter();
// Validate the target
if (target == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
// Check economy actions
for (EconomyHook.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
// Teleport a user on another server
if (localTeleporter.isEmpty()) {
final Username teleporter = (Username) this.teleporter;
if (!plugin.getSettings().isCrossServer()) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND);
}
if (target instanceof Username username) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_USER)
.target(username.name())
.payload(Payload.withString(teleporter.name()))
.build().send(plugin.getMessenger(), executor);
return;
}
Message.builder()
.type(Message.Type.TELEPORT_TO_POSITION)
.target(teleporter.name())
.payload(Payload.withPosition((Position) target))
.build().send(plugin.getMessenger(), executor);
return;
}
// Run the teleport and apply economy actions
return run(teleporter)
.thenApply(resultState -> CompletedTeleport.from(resultState, this))
.thenApply(result -> {
if (teleporter instanceof OnlineUser user) {
finish(user, result);
}
return result;
});
// Teleport a local user
final OnlineUser teleporter = localTeleporter.get();
if (target instanceof Username username) {
final Optional<OnlineUser> localTarget = username.findLocally(plugin);
if (localTarget.isPresent()) {
teleporter.teleportLocally(localTarget.get().getPosition(), async);
return;
}
if (plugin.getSettings().isCrossServer()) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_POSITION)
.target(username.name())
.build().send(plugin.getMessenger(), executor);
return;
}
throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND);
}
teleporter.teleportLocally((Position) target, async);
}
@NotNull
private Optional<OnlineUser> resolveLocalTeleporter() throws TeleportationException {
if (this.teleporter instanceof Username username) {
return username.findLocally(plugin);
}
return Optional.of((OnlineUser) this.teleporter);
}
@NotNull
public Type getType() {
return type;
}
@NotNull
public Teleportable getTeleporter() {
return teleporter;
}
@NotNull
public Target getTarget() {
return target;
}
/**
* Run the teleport, either locally or over the network
*
* @param teleporter The {@link User} who is doing the teleporting
* @return A {@link CompletableFuture} that completes when the teleport is finished
* Represents the type of teleport being used
*/
private CompletableFuture<TeleportResult> run(@NotNull User teleporter) {
return teleporter instanceof OnlineUser onlineUser
? teleportLocalUser(onlineUser)
: teleportNetworkedUser();
}
public enum Type {
/**
* Finish the teleport, finalize economy transactions if successful and send message
*
* @param teleporter The {@link OnlineUser} who was teleported
* @param result The {@link TeleportResult} of the teleport
*/
private void finish(@NotNull OnlineUser teleporter, @NotNull CompletedTeleport result) {
if (result.successful()) {
// Complete economy transactions
economyActions.forEach(economyAction -> plugin.performEconomyTransaction(executor, economyAction));
TELEPORT(0),
RESPAWN(1);
// Play sound effect if successful
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(teleporter::playSound);
private final int typeId;
Type(final int typeId) {
this.typeId = typeId;
}
// Send result message
result.sendResultMessage(plugin.getLocales(), teleporter);
}
/**
* Teleport a local user
*
* @param teleporter The teleporter
* @return A {@link CompletableFuture} that completes when the teleport is finished
*/
private CompletableFuture<TeleportResult> teleportLocalUser(@NotNull OnlineUser teleporter) {
assert target != null;
// Dispatch the teleport event and update the player's last position
plugin.getEventDispatcher().dispatchTeleportEvent(this);
if (updateLastPosition && !plugin.getSettings().isBackCommandSaveOnTeleportEvent() && type == TeleportType.TELEPORT) {
plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition());
/**
* Returns a {@link Type} by its type id.
*
* @param typeId The type id of the {@link Type} to return.
* @return The {@link Type} of the given type id.
*/
public static Optional<Type> getTeleportType(int typeId) {
return Arrays.stream(values())
.filter(type -> type.getTypeId() == typeId)
.findFirst();
}
// If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().isCrossServer() || target.getServer().equals(plugin.getServerName())) {
return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports());
public int getTypeId() {
return typeId;
}
// If the target position is on another server, execute a cross-server teleport
plugin.getDatabase().setCurrentTeleport(teleporter, this);
plugin.getMessenger().changeServer(teleporter, target.getServer());
return CompletableFuture.completedFuture(TeleportResult.COMPLETED_CROSS_SERVER);
}
/**
* Teleport a user not on this server but on the proxy network
*
* @return A {@link CompletableFuture} that completes when the teleport is finished.
* Successful cross-server teleports will return {@link TeleportResult#COMPLETED_CROSS_SERVER}.
* @implNote Cross-server teleports will return with a {@link TeleportResult#FAILED_INVALID_SERVER} result if the
* target server is not online, or connection timed out
*/
private CompletableFuture<TeleportResult> teleportNetworkedUser() {
assert target != null;
assert teleporter != null;
// Send a network message to a user on another server to teleport them to the target position
return Message.builder()
.type(Message.Type.TELEPORT_TO_POSITION_REQUEST)
.payload(Payload.withPosition(target))
.target(teleporter.getUsername())
.build().send(plugin.getMessenger(), executor)
.thenApply(result -> Optional.ofNullable(result.getPayload().getResultState())
.orElse(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED));
}
}
}
@@ -2,240 +2,101 @@ package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.network.Request;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.List;
/**
* A builder for {@link Teleport}s and {@link TimedTeleport}s
*
* @since 3.1
*/
@SuppressWarnings("unused")
public class TeleportBuilder {
// Instance of the implementing plugin
@NotNull
private final HuskHomes plugin;
/**
* The executor of the teleport; the one who triggered the teleport to happen;
* whom may not necessarily the person being <i>teleported</i>
*/
@NotNull
private final OnlineUser executor;
/**
* The teleporter; the one who is being teleported, to be resolved before construction
*/
private CompletableFuture<User> teleporter;
/**
* The target position for the teleporter, to be resolved before construction
*/
private CompletableFuture<Position> target;
/**
* List of {@link EconomyHook.EconomyAction}s to check against.
* <p>
* Note that these are checked against the <i>{@link #executor executor}</i> of the teleport;
* not necessarily the one doing the teleporting
*/
private final Set<EconomyHook.EconomyAction> economyActions = new HashSet<>();
/**
* The type of teleport. Defaults to {@link TeleportType#TELEPORT}
*/
private TeleportType type = TeleportType.TELEPORT;
/**
* Whether this teleport should update the user's last position (i.e. their {@code /back} position)
*/
private OnlineUser executor;
private Teleportable teleporter;
private Target target;
private boolean updateLastPosition = true;
private Teleport.Type type = Teleport.Type.TELEPORT;
private List<EconomyHook.Action> economyActions = List.of();
protected TeleportBuilder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) {
protected TeleportBuilder(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
@NotNull
public Teleport toTeleport() throws IllegalStateException {
validateTeleport();
return new Teleport(executor, teleporter, target, type, updateLastPosition, economyActions, plugin);
}
@NotNull
public TimedTeleport toTimedTeleport() throws IllegalStateException {
validateTeleport();
if (!(teleporter instanceof OnlineUser onlineTeleporter)) {
throw new IllegalStateException("Teleporter must be an OnlineUser for timed teleportation");
}
return new TimedTeleport(executor, onlineTeleporter, target, type,
plugin.getSettings().getTeleportWarmupTime(), updateLastPosition, economyActions, plugin);
}
private void validateTeleport() throws IllegalStateException {
if (executor == null) {
if (teleporter instanceof OnlineUser onlineUser) {
executor = onlineUser;
} else {
throw new IllegalStateException("Executor must be set if teleporter is not an OnlineUser");
}
}
if (teleporter == null) {
throw new IllegalStateException("Teleporter must be set");
}
if (target == null) {
throw new IllegalStateException("Target must be set");
}
}
@NotNull
public TeleportBuilder executor(@NotNull OnlineUser executor) {
this.executor = executor;
this.teleporter = CompletableFuture.completedFuture(executor);
}
/**
* Set the person being teleported as a {@link User}
*
* @param teleporter The {@link User} who is doing the teleporting
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTeleporter(@NotNull User teleporter) {
this.teleporter = CompletableFuture.completedFuture(teleporter);
return this;
}
/**
* Set the person being teleported as the username of a player, which will attempt to be resolved
* into a user at the time of construction
*
* @param teleporterUsername The username of the player who is doing the teleporting
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTeleporter(@NotNull String teleporterUsername) {
this.teleporter = teleporterUsername;
@NotNull
public TeleportBuilder teleporter(@NotNull Teleportable teleporter) {
this.teleporter = teleporter;
return this;
}
/**
* Set the target as a {@link Position}
*
* @param position The {@link Position} the teleport is aiming to teleport the {@link #teleporter} to
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull Position position) {
this.target = CompletableFuture.completedFuture(position);
@NotNull
public TeleportBuilder teleporter(@NotNull String teleporter) {
this.teleporter = Teleportable.username(teleporter);
return this;
}
/**
* Set the target as a {@link Location} on this server
*
* @param location The {@link Location} on this server the teleport is aiming to teleport the {@link #teleporter} to
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull Location location) {
this.target = CompletableFuture.completedFuture(new Position(location, plugin.getServerName()));
@NotNull
public TeleportBuilder target(@NotNull Target target) {
this.target = target;
return this;
}
/**
* Set the target as the position of a player, specified by their username, who may be on another server.
*
* @param targetUsername The username of the player on the target server the teleport is aiming to teleport the
* {@link #teleporter} to
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull String targetUsername) {
this.target = getPlayerPosition(targetUsername).thenApply(position -> position.orElse(null));
@NotNull
public TeleportBuilder target(@NotNull String target) {
this.target = Target.username(target);
return this;
}
/**
* Set the type of teleport
*
* @param type The {@link TeleportType} of the teleport
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setType(@NotNull TeleportType type) {
this.type = type;
return this;
}
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link EconomyHook.EconomyAction}s to check against
* @return The {@link TeleportBuilder} instance
* @implNote These are checked against the <i>{@link #executor executor}</i> of the teleport;
* not necessarily the one doing the teleporting
*/
public TeleportBuilder setEconomyActions(@NotNull Set<EconomyHook.EconomyAction> economyActions) {
this.economyActions.addAll(economyActions);
return this;
}
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link EconomyHook.EconomyAction}s to check against
* @return The {@link TeleportBuilder} instance
* @implNote These are checked against the <i>{@link #executor executor}</i> of the teleport;
* not necessarily the one doing the teleporting
*/
public TeleportBuilder setEconomyActions(@NotNull EconomyHook.EconomyAction... economyActions) {
this.economyActions.addAll(Arrays.asList(economyActions));
return this;
}
/**
* Set whether this teleport should update the user's last position (i.e. their {@code /back} position)
*
* @param updateLastPosition Whether this teleport should update the user's last position
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder doUpdateLastPosition(boolean updateLastPosition) {
@NotNull
public TeleportBuilder updateLastPosition(boolean updateLastPosition) {
this.updateLastPosition = updateLastPosition;
return this;
}
/**
* Resolve the teleporter and target, and construct as an instantly-completing {@link Teleport}
*
* @return The constructed {@link Teleport}
*/
public CompletableFuture<Teleport> toTeleport() {
return CompletableFuture.supplyAsync(() -> {
final User teleporter = this.teleporter.join();
final Position target = this.target.join();
return new Teleport(teleporter, executor, target, type, economyActions, updateLastPosition, plugin);
}).exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create teleport", e);
return null;
});
@NotNull
public TeleportBuilder economyActions(@NotNull EconomyHook.Action... economyActions) {
this.economyActions = List.of(economyActions);
return this;
}
/**
* Resolve the teleporter and target, and construct as a {@link TimedTeleport}
*
* @return The constructed {@link TimedTeleport}
*/
public CompletableFuture<TimedTeleport> toTimedTeleport() {
return CompletableFuture.supplyAsync(() -> {
final User teleporter = this.teleporter.join();
final Position target = this.target.join();
final int warmupTime = plugin.getSettings().getTeleportWarmupTime();
if (!(teleporter instanceof OnlineUser onlineUser)) {
throw new IllegalStateException("Timed teleports can only be executed for local users");
}
return new TimedTeleport(onlineUser, executor, target, type, warmupTime, economyActions, updateLastPosition, plugin);
}).exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create timed teleport", e);
return null;
});
@NotNull
public TeleportBuilder type(@NotNull Teleport.Type type) {
this.type = type;
return this;
}
/**
* Gets the position of a player by their username, including players on other servers
*
* @param playerName the username of the player being requested
* @return future optionally supplying the player's position, if the player could be found
*/
private CompletableFuture<Optional<Position>> getPlayerPosition(@NotNull String playerName) {
final Optional<OnlineUser> localPlayer = plugin.findOnlinePlayer(playerName);
if (localPlayer.isPresent()) {
return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition()));
}
if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger()
.findPlayer(executor, playerName)
.thenApplyAsync(foundPlayer -> {
if (foundPlayer.isEmpty()) {
return Optional.empty();
}
return Request.builder()
.withType(Request.MessageType.POSITION_REQUEST)
.withTargetPlayer(playerName)
.build().send(executor, plugin)
.thenApply(reply -> reply.map(message -> message.getPayload().getPosition())).join();
});
}
return CompletableFuture.supplyAsync(Optional::empty);
}
}
@@ -1,5 +1,6 @@
package net.william278.huskhomes.request;
package net.william278.huskhomes.teleport;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
@@ -12,51 +13,37 @@ import java.time.Instant;
*/
public class TeleportRequest {
/**
* The user making the request
*/
@Expose
@SerializedName("requester_name")
protected String requesterName;
private String requesterName;
/**
* The position of the requester, relevant in the case of a {@link RequestType#TPA_HERE} request
*/
@Expose
@SerializedName("requester_position")
protected Position requesterPosition;
private Position requesterPosition;
/**
* Epoch timestamp when the request will expire
*/
@Expose
@SerializedName("expiry_time")
protected long expiryTime;
private long expiryTime;
/**
* The type of request; a {@link RequestType#TPA} or {@link RequestType#TPA_HERE}
*/
protected RequestType type;
@Expose
private Type type;
/**
* The status of the request; a {@link RequestStatus#PENDING}, {@link RequestStatus#ACCEPTED}
* or {@link RequestStatus#DECLINED}
*/
protected RequestStatus status;
@Expose
private Status status;
/**
* The name of the request recipient
*/
protected String recipientName;
@Expose
private String recipientName;
/**
* Create a teleport request
*
* @param requester The user making the request
*/
protected TeleportRequest(@NotNull OnlineUser requester, @NotNull RequestType requestType,
final long expiryTime) {
this.requesterName = requester.getUsername();
this.requesterPosition = requester.getPosition();
this.type = requestType;
this.status = RequestStatus.PENDING;
public TeleportRequest(@NotNull OnlineUser requester, @NotNull TeleportRequest.Type type, final long expiryTime) {
this.setRequesterName(requester.getUsername());
this.setRequesterPosition(requester.getPosition());
this.setType(type);
this.setStatus(Status.PENDING);
this.expiryTime = expiryTime;
}
@@ -73,15 +60,70 @@ public class TeleportRequest {
return Instant.now().isAfter(Instant.ofEpochSecond(expiryTime));
}
/**
* The name of the request recipient
*/
@NotNull
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(@NotNull String recipientName) {
this.recipientName = recipientName;
}
/**
* The user making the request
*/
public String getRequesterName() {
return requesterName;
}
public void setRequesterName(String requesterName) {
this.requesterName = requesterName;
}
/**
* The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request
*/
@NotNull
public Position getRequesterPosition() {
return requesterPosition;
}
public void setRequesterPosition(Position requesterPosition) {
this.requesterPosition = requesterPosition;
}
/**
* The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE}
*/
@NotNull
public TeleportRequest.Type getType() {
return type;
}
public void setType(@NotNull TeleportRequest.Type type) {
this.type = type;
}
/**
* The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED}
* or {@link Status#DECLINED}
*/
@NotNull
public TeleportRequest.Status getStatus() {
return status;
}
public void setStatus(@NotNull TeleportRequest.Status status) {
this.status = status;
}
/**
* Types of teleport requests ({@code /tpa} or {@code /tpahere})
*/
public enum RequestType {
public enum Type {
/**
* The request is a {@code /tpa} request, where the requester is requesting to teleport <i>to</i> the recipient
*/
@@ -95,7 +137,7 @@ public class TeleportRequest {
/**
* The current status of a teleport request
*/
protected enum RequestStatus {
public enum Status {
/**
* The request is currently pending and can be accepted or declined
*/
@@ -1,31 +0,0 @@
package net.william278.huskhomes.teleport;
import java.util.Arrays;
import java.util.Optional;
/**
* Represents the type of teleport being used
*/
public enum TeleportType {
TELEPORT(0),
RESPAWN(1);
public final int typeId;
TeleportType(final int typeId) {
this.typeId = typeId;
}
/**
* Returns a {@link TeleportType} by its type id.
*
* @param typeId The type id of the {@link TeleportType} to return.
* @return The {@link TeleportType} of the given type id.
*/
public static Optional<TeleportType> getTeleportType(int typeId) {
return Arrays.stream(values())
.filter(type -> type.typeId == typeId)
.findFirst();
}
}
@@ -0,0 +1,12 @@
package net.william278.huskhomes.teleport;
import org.jetbrains.annotations.NotNull;
public interface Teleportable {
@NotNull
static Teleportable username(@NotNull String teleporter) {
return new Username(teleporter);
}
}
@@ -0,0 +1,16 @@
package net.william278.huskhomes.teleport;
import org.jetbrains.annotations.NotNull;
public class TeleportationException extends IllegalArgumentException {
public TeleportationException(@NotNull Type error) {
super("Error during teleport operation: " + error.name());
}
public enum Type {
TELEPORTER_NOT_FOUND,
TARGET_NOT_FOUND,
ALREADY_WARMING_UP, ECONOMY_ACTION_FAILED, WARMUP_ALREADY_MOVING, CANNOT_TELEPORT_TO_SELF
}
}
@@ -9,11 +9,9 @@ import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class TimedTeleport extends Teleport {
@@ -22,12 +20,11 @@ public class TimedTeleport extends Teleport {
private final Position startLocation;
private final double startHealth;
private int timeLeft;
private boolean cancelled = false;
protected TimedTeleport(@NotNull OnlineUser teleporter, @NotNull OnlineUser executor, @NotNull Position target,
@NotNull TeleportType type, int warmupTime, @NotNull Set<EconomyHook.EconomyAction> economyActions,
final boolean updateLastPosition, @NotNull HuskHomes plugin) {
super(teleporter, executor, target, type, economyActions, updateLastPosition, plugin);
protected TimedTeleport(@NotNull OnlineUser executor, @NotNull OnlineUser teleporter, @NotNull Target target,
@NotNull Type type, int warmupTime, boolean updateLastPosition,
@NotNull List<EconomyHook.Action> actions, @NotNull HuskHomes plugin) {
super(teleporter, executor, target, type, updateLastPosition, actions, plugin);
this.plugin = plugin;
this.startLocation = teleporter.getPosition();
this.startHealth = teleporter.getHealth();
@@ -41,60 +38,38 @@ public class TimedTeleport extends Teleport {
* @return a {@link CompletableFuture} that completes when the teleport is complete or has been cancelled
*/
@Override
public CompletableFuture<CompletedTeleport> execute() {
// If the target has not been resolved, fail the teleport
if (target == null) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
public void execute() throws TeleportationException {
// Check if the teleporter can bypass warmup
if (timeLeft == 0 || teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) {
return super.execute();
super.execute();
return;
}
// Check if the teleporter is already warming up to teleport
if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.getUuid())) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP);
}
// Check economy actions
for (EconomyHook.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
for (EconomyHook.Action action : economyActions) {
if (!plugin.validateEconomyCheck(executor, action)) {
throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED);
}
}
// Check if they are moving at the start of the teleport
if (teleporter.isMoving()) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_MOVING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
throw new TeleportationException(TeleportationException.Type.WARMUP_ALREADY_MOVING);
}
// Process the warmup and execute the teleport
return process().thenApplyAsync(ignored -> {
if (cancelled) {
return CompletedTeleport.from(TeleportResult.CANCELLED, this);
}
return super.execute().join();
});
this.process();
}
/**
* Start the processing of a {@link TimedTeleport} warmup
*
* @return a future, returning when the teleport has finished
*/
private CompletableFuture<Void> process() {
final CompletableFuture<Void> timedTeleportFuture = new CompletableFuture<>();
private void process() {
// Execute the warmup start event
plugin.getEventDispatcher().dispatchTeleportWarmupEvent(this, timeLeft).thenAccept(event -> {
// Handle event cancellation
if (event.isCancelled()) {
this.cancelled = true;
return;
}
@@ -103,9 +78,9 @@ public class TimedTeleport extends Teleport {
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft))
.ifPresent(teleporter::sendMessage);
// Create a scheduled executor to tick the timed teleport
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
// Run the warmup
final AtomicInteger warmupTaskId = new AtomicInteger();
final Runnable delayRunnable = (() -> {
// Display countdown action bar message
if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
@@ -115,17 +90,17 @@ public class TimedTeleport extends Teleport {
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(this::sendStatusMessage);
super.execute();
}
// Tick (decrement) the timed teleport timer and end it if done
if (tickWarmup()) {
if (tickAndGetIfDone()) {
plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.getUuid());
timedTeleportFuture.complete(null);
executor.shutdown();
plugin.cancelTask(warmupTaskId.get());
}
}, 0, 1, TimeUnit.SECONDS);
});
warmupTaskId.set(plugin.runAsyncRepeating(delayRunnable, 20));
});
return timedTeleportFuture;
}
/**
@@ -141,7 +116,7 @@ public class TimedTeleport extends Teleport {
*
* @return {@code true} if the warmup is complete, {@code false} otherwise
*/
private boolean tickWarmup() {
private boolean tickAndGetIfDone() {
if (timeLeft <= 0) {
return true;
}
@@ -154,7 +129,6 @@ public class TimedTeleport extends Teleport {
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
cancelled = true;
return true;
}
@@ -166,7 +140,6 @@ public class TimedTeleport extends Teleport {
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
cancelled = true;
return true;
}
@@ -175,11 +148,6 @@ public class TimedTeleport extends Teleport {
return false;
}
/**
* Send a teleport warmup status message to the configured slot
*
* @param message the message to send
*/
private void sendStatusMessage(@NotNull MineDown message) {
switch (plugin.getSettings().getTeleportWarmupDisplay()) {
case ACTION_BAR -> teleporter.sendActionBar(message);
@@ -189,24 +157,14 @@ public class TimedTeleport extends Teleport {
}
}
/**
* Returns if the player has moved since the timed teleport started
*
* @return {@code true} if the player has moved; {@code false} otherwise
*/
private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) +
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
return movementDistance > maxMovementDistance;
}
/**
* Returns if the player has taken damage since the timed teleport started
*
* @return {@code true} if the player has taken damage
*/
private boolean hasTeleporterTakenDamage() {
return teleporter.getHealth() < startHealth;
}
@@ -0,0 +1,16 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public record Username(@NotNull String name) implements Teleportable, Target {
@NotNull
public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) throws TeleportationException {
return plugin.findOnlinePlayer(name);
}
}
@@ -11,6 +11,7 @@ import net.kyori.adventure.title.TitlePart;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.teleport.Teleportable;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
@@ -20,7 +21,7 @@ import java.util.concurrent.CompletableFuture;
/**
* A cross-platform representation of a logged-in {@link User}
*/
public abstract class OnlineUser extends User {
public abstract class OnlineUser extends User implements Teleportable {
public OnlineUser(@NotNull UUID uuid, @NotNull String username) {
super(uuid, username);
@@ -1,65 +0,0 @@
package net.william278.huskhomes.util;
import java.util.Optional;
import java.util.regex.Pattern;
import net.william278.huskhomes.position.PositionMeta;
import org.jetbrains.annotations.NotNull;
/**
* Provides a number of utility regular expressions for checking home name patterns
*/
public final class RegexUtil {
/**
* Pattern for checking home and warp {@link PositionMeta} description fields
*/
public static final Pattern DESCRIPTION_PATTERN = Pattern.compile("[a-zA-Z\\d\\-_\\s]*");
/**
* Pattern for checking home and warp {@link PositionMeta} name fields
*/
public static final Pattern NAME_PATTERN = Pattern.compile("[A-Za-z\\d_\\-]+");
/**
* Pattern for checking home input fields disambiguated by the owner's name
* <p>
* e.g. {@code ownerName.homeName}
*/
private static final Pattern OWNER_DISAMBIGUATED_HOME_IDENTIFIER_PATTERN = Pattern.compile("\\w+\\.[^.]{1,16}$");
/**
* Match pattern for checking home input fields disambiguated by the owner's name
*
* @param input input string to match
* @return An optional containing the {@link DisambiguatedHomeIdentifier} if matched, otherwise empty if not
*/
public static Optional<DisambiguatedHomeIdentifier> matchDisambiguatedHomeIdentifier(@NotNull String input) {
if (OWNER_DISAMBIGUATED_HOME_IDENTIFIER_PATTERN.matcher(input).matches()) {
final String[] separatedInput = input.split(Pattern.quote("."));
return Optional.of(new DisambiguatedHomeIdentifier(separatedInput[0], separatedInput[1]));
} else {
return Optional.empty();
}
}
/**
* Represents an identifier for a home or warp {@link PositionMeta} that is disambiguated by the owner's name
*
* @param ownerName the username of a home's owner
* @param homeName the name of a home
*/
public record DisambiguatedHomeIdentifier(String ownerName, String homeName) {
/**
* Get the period-separated formatted disambiguated home identifier
*
* @return the formatted disambiguated home identifier (e.g. {@code ownerName.homeName})
*/
public String toString() {
return ownerName + "." + homeName;
}
}
}
@@ -7,9 +7,11 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public interface TaskRunner {
void runAsync(@NotNull Runnable runnable);
int runAsync(@NotNull Runnable runnable);
<T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier);
void runSync(@NotNull Runnable runnable);
int runSync(@NotNull Runnable runnable);
int runAsyncRepeating(@NotNull Runnable runnable, long delay);
void cancelTask(int taskId);
@NotNull
HuskHomes getPlugin();
@@ -1,14 +1,14 @@
package net.william278.huskhomes;
package net.william278.huskhomes.util;
import org.jetbrains.annotations.NotNull;
public class ValidationException extends IllegalArgumentException {
public ValidationException(@NotNull ValidationError error) {
public ValidationException(@NotNull ValidationException.Type error) {
super("Error validating position: " + error.name());
}
public enum ValidationError {
public enum Type {
NOT_FOUND,
NAME_TAKEN,
NAME_INVALID,
@@ -3,6 +3,7 @@ package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public class Validator {
public static final int MAX_NAME_LENGTH = 16;