Reduce future join call usage

This commit is contained in:
William committed 2022-09-24 22:00:48 +01:00
1 parent 8a4ed7c565
commit 649d4c0600
18 files changed
+316 -291

No files matched your search

@@ -121,9 +121,9 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
for (final Home toDelete : homes) {
homeDeletionFuture.add(plugin.getSavedPositionManager().deleteHome(homeOwner, toDelete.meta.name));
}
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0])).thenRunAsync(() ->
plugin.getLocales().getLocale("delete_all_homes_success", Integer.toString(homeDeletionFuture.size()))
.ifPresent(deleter::sendMessage)).join();
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0]))
.thenRun(() -> plugin.getLocales().getLocale("delete_all_homes_success",
Integer.toString(homeDeletionFuture.size())).ifPresent(deleter::sendMessage));
});
}
@@ -68,9 +68,9 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
for (final Warp toDelete : warps) {
homeDeletionFuture.add(plugin.getSavedPositionManager().deleteWarp(toDelete.meta.name));
}
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0])).thenRunAsync(() ->
plugin.getLocales().getLocale("delete_all_warps_success", Integer.toString(homeDeletionFuture.size()))
.ifPresent(deleter::sendMessage)).join();
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0]))
.thenRun(() -> plugin.getLocales().getLocale("delete_all_warps_success",
Integer.toString(homeDeletionFuture.size())).ifPresent(deleter::sendMessage));
});
}
@@ -188,12 +188,12 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
.ifPresent(editor::sendMessage);
return;
}
boolean newIsPublic = !home.isPublic;
final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic);
if (editArgs != null && !editArgs.isBlank()) {
if (editArgs.equalsIgnoreCase("private")) {
newIsPublic = false;
newIsPublic.set(false);
} else if (editArgs.equalsIgnoreCase("public")) {
newIsPublic = true;
newIsPublic.set(true);
} else {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> privacy [private|public]")
@@ -201,57 +201,60 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return;
}
}
final String privacyKeyedString = newIsPublic ? "public" : "private";
if (newIsPublic == home.isPublic) {
final String privacyKeyedString = newIsPublic.get() ? "public" : "private";
if (newIsPublic.get() == home.isPublic) {
plugin.getLocales().getLocale(
"error_edit_home_privacy_already_" + privacyKeyedString)
.ifPresent(editor::sendMessage);
return;
}
// Perform checks if making the home public
if (newIsPublic && !otherOwner) {
// Check against maximum public homes
final List<Home> existingPublicHomes = plugin.getDatabase().getHomes(editor).join().stream()
.filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes,
plugin.getSettings().stackPermissionLimits);
if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes",
Integer.toString(maxPublicHomes))
.ifPresent(editor::sendMessage);
return;
// Get the homes of the editor
plugin.getDatabase().getHomes(editor).thenAccept(editorHomes -> {
// Perform checks if making the home public
if (newIsPublic.get() && !otherOwner) {
// Check against maximum public homes
final List<Home> existingPublicHomes = editorHomes.stream()
.filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes,
plugin.getSettings().stackPermissionLimits);
if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes",
Integer.toString(maxPublicHomes))
.ifPresent(editor::sendMessage);
return;
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC)) {
return;
}
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC)) {
return;
}
}
// Execute the update
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> {
if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
}
// Execute the update
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic).join();
if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
}
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC);
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC);
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage);
}
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage);
}
});
});
}
default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> [" + String.join("|", EDIT_HOME_COMPLETIONS) + "] [args]")
@@ -30,7 +30,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
switch (homes.size()) {
case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage);
case 1 -> plugin.getTeleportManager().timedTeleport(onlineUser, homes.get(0)).thenAccept(result ->
plugin.getTeleportManager().finishTeleport(onlineUser, result)).join();
plugin.getTeleportManager().finishTeleport(onlineUser, result));
default -> plugin.getCache().getHomeList(onlineUser, onlineUser,
plugin.getLocales(), homes, plugin.getSettings().listItemsPerPage, 1)
.ifPresent(onlineUser::sendMessage);
@@ -54,9 +54,8 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
final OnlineUser userToTeleport = target;
final boolean isExecutorTeleporting = userToTeleport.uuid.equals(onlineUser.uuid);
CompletableFuture.runAsync(() -> {
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
// Check the user is not still on /rtp cooldown
final Optional<UserData> userData = plugin.getDatabase().getUserData(onlineUser.uuid).join();
if (userData.isEmpty()) {
return;
}
@@ -6,12 +6,12 @@ import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class SetHomeCommand extends CommandBase {
@@ -62,52 +62,58 @@ public class SetHomeCommand extends CommandBase {
return;
}
// Check against economy if needed
boolean newSlotNeeded = false;
UserData userDataToUpdate = null;
if (plugin.getSettings().economy) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots, plugin.getSettings().stackPermissionLimits);
final Optional<UserData> fetchedData = plugin.getDatabase().getUserData(onlineUser.uuid).join();
if (fetchedData.isPresent()) {
newSlotNeeded = (currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots());
}
// Get their user data
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(fetchedData -> {
// Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null);
if (plugin.getSettings().economy) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots,
plugin.getSettings().stackPermissionLimits);
if (fetchedData.isPresent()) {
newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots()));
// If a new slot is needed, validate the user has enough funds to purchase one
if (newSlotNeeded) {
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT)) {
return;
}
userDataToUpdate = new UserData(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown());
} else {
if (currentHomes.size() == freeHomes) {
plugin.getLocales().getLocale("set_home_used_free_slots", Integer.toString(freeHomes))
.ifPresent(onlineUser::sendMessage);
// If a new slot is needed, validate the user has enough funds to purchase one
if (newSlotNeeded.get()) {
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT)) {
return;
}
userDataToUpdate.set(new UserData(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown()));
} else {
if (currentHomes.size() == freeHomes) {
plugin.getLocales().getLocale("set_home_used_free_slots", Integer.toString(freeHomes))
.ifPresent(onlineUser::sendMessage);
}
}
}
}
}
// Set the home in the saved position manager
final SavedPositionManager.SaveResult setResult = plugin.getSavedPositionManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition()).join();
// Set the home in the saved position manager
plugin.getSavedPositionManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition())
.thenAccept(setResult -> {
// Display feedback of the result of the set operation
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
// Display feedback of the result of the set operation
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded.get()) {
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate.get());
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> plugin.getLocales().getLocale("error_home_description_characters");
}).ifPresent(onlineUser::sendMessage);
});
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded) {
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate).join();
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> plugin.getLocales().getLocale("error_home_description_characters");
}).ifPresent(onlineUser::sendMessage);
});
}
}
@@ -19,31 +19,32 @@ public class SetSpawnCommand extends CommandBase {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
CompletableFuture.supplyAsync(() -> {
if (args.length > 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/setspawn")
.ifPresent(onlineUser::sendMessage);
return false;
}
final Position position = onlineUser.getPosition();
if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) {
final Optional<Warp> warp = plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join();
if (args.length > 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/setspawn")
.ifPresent(onlineUser::sendMessage);
return;
}
final Position position = onlineUser.getPosition();
if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) {
plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).thenApply(warp -> {
if (warp.isPresent()) {
return plugin.getSavedPositionManager().updateWarpPosition(warp.get(), position).join();
return plugin.getSavedPositionManager().updateWarpPosition(warp.get(), position);
} else {
return plugin.getSavedPositionManager().setWarp(new PositionMeta(plugin.getSettings().globalSpawnName,
plugin.getLocales().getRawLocale("spawn_warp_default_description")
.orElse("")), position).join().resultType().successful;
plugin.getLocales().getRawLocale("spawn_warp_default_description").orElse("")), position)
.thenApply(result -> result.resultType().successful);
}
} else {
plugin.setServerSpawn(position);
return true;
}
}).thenAccept(succeeded -> {
if (succeeded) {
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
});
}).thenAccept(result -> result.thenAccept(successful -> {
if (successful) {
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
}));
} else {
plugin.setServerSpawn(position);
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
}
}
@@ -6,8 +6,6 @@ import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public class SetWarpCommand extends CommandBase {
protected SetWarpCommand(@NotNull HuskHomes implementor) {
@@ -17,7 +15,7 @@ public class SetWarpCommand extends CommandBase {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
CompletableFuture.runAsync(() -> setWarp(onlineUser, args[0]));
setWarp(onlineUser, args[0]);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp <name>")
.ifPresent(onlineUser::sendMessage);
@@ -10,7 +10,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -22,23 +21,22 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
CompletableFuture.runAsync(() -> {
// Ensure a valid target was found
final Optional<TeleportTarget> teleportTarget = getTeleportTarget(args, onlineUser);
if (teleportTarget.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", "/tp <target> [destination]")
.ifPresent(onlineUser::sendMessage);
return;
}
// Ensure a valid target was found
final Optional<TeleportTarget> teleportTarget = getTeleportTarget(args, onlineUser);
if (teleportTarget.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", "/tp <target> [destination]")
.ifPresent(onlineUser::sendMessage);
return;
}
// Determine the player to teleport
final String targetPlayerToTeleport = ((teleportTarget.get() instanceof TargetPlayer) && args.length == 2)
? args[0] : ((teleportTarget.get() instanceof TargetPosition)
? args.length > 3 ? (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]) ? args[0] : onlineUser.username)
: onlineUser.username : onlineUser.username);
// Determine the player to teleport
final String targetPlayerToTeleport = ((teleportTarget.get() instanceof TargetPlayer) && args.length == 2)
? args[0] : ((teleportTarget.get() instanceof TargetPosition)
? args.length > 3 ? (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]) ? args[0] : onlineUser.username)
: onlineUser.username : onlineUser.username);
// Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).join();
// Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenRun(() -> {
final String playerToTeleport = plugin.getCache().players.stream()
.filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst()
.or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.username : null))
@@ -101,9 +99,6 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
.ifPresent(onlineUser::sendMessage);
}));
}
}).exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "An error occurred whilst executing a teleport command", throwable);
return null;
});
}
@@ -183,7 +178,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// Execute the console teleport
if (teleportTarget instanceof TargetPlayer targetPlayer) {
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username
+ " to " + targetPlayer.playerName);
+ " to " + targetPlayer.playerName);
plugin.getTeleportManager().teleportToPlayerByName(playerToTeleport, targetPlayer.playerName, false);
} else {
final TargetPosition targetPosition = (TargetPosition) teleportTarget;
@@ -193,7 +188,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.username);
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.username
+ " (" + teleportResult.name() + ")");
+ " (" + teleportResult.name() + ")");
}
plugin.getTeleportManager().finishTeleport(playerToTeleport, teleportResult);
});
@@ -25,12 +25,12 @@ public class TpIgnoreCommand extends CommandBase {
final boolean isIgnoringRequests = !plugin.getRequestManager().isIgnoringRequests(onlineUser);
plugin.getRequestManager().setIgnoringRequests(onlineUser, isIgnoringRequests);
// Update value on the database and send a message
plugin.getDatabase().getUserData(onlineUser.uuid).thenAcceptAsync(
userData -> userData.ifPresent(data -> plugin.getDatabase().updateUserData(new UserData(onlineUser,
data.homeSlots(), isIgnoringRequests, data.rtpCooldown())).join())).thenRun(
() -> plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"),
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale))));
// Update value on the database and send a message | todo: Clean this up
plugin.getDatabase().getUserData(onlineUser.uuid)
.thenAcceptAsync(userData -> userData.ifPresent(data -> plugin.getDatabase()
.updateUserData(new UserData(onlineUser, data.homeSlots(), isIgnoringRequests, data.rtpCooldown()))
.thenRun(() -> plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"),
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale))))));
}
}
@@ -54,21 +54,22 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: warp <player> <warp>");
return;
}
CompletableFuture.runAsync(() -> {
final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null);
if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]);
return;
}
final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null);
if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]);
return;
}
final Warp warp = plugin.getDatabase().getWarp(args[1]).join().orElse(null);
if (warp == null) {
plugin.getDatabase().getWarp(args[1]).thenAccept(optionalWarp -> {
if (optionalWarp.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Could not find warp '" + args[1] + "'");
return;
}
final Warp warp = optionalWarp.get();
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.meta.name);
plugin.getTeleportManager().teleport(playerToTeleport, warp)
plugin.getTeleportManager()
.teleport(playerToTeleport, warp)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(playerToTeleport, result));
});
}
@@ -63,11 +63,10 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
@Override
public void onConsoleExecute(@NotNull String[] args) {
CompletableFuture.runAsync(() -> {
final List<Warp> warps = plugin.getDatabase().getWarps().join();
StringJoiner rowJoiner = new StringJoiner(" ");
plugin.getDatabase().getWarps().thenAccept(warps -> {
plugin.getLoggingAdapter().log(Level.INFO, "List of " + warps.size() + " warps:");
StringJoiner rowJoiner = new StringJoiner(" ");
for (int i = 1; i <= warps.size(); i++) {
final String warp = warps.get(i - 1).meta.name;
rowJoiner.add(warp.length() < 16 ? warp + " ".repeat(16 - warp.length()) : warp);
@@ -36,72 +36,94 @@ public class EventListener {
*/
protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) {
// Handle the first player joining the server
CompletableFuture.runAsync(() -> {
if (plugin.getSettings().crossServer && firstUser) {
firstUser = false;
plugin.fetchServer(onlineUser).join();
}
}).thenRunAsync(() -> {
// Ensure the player is present on the database first
plugin.getDatabase().ensureUser(onlineUser).join();
}).thenRun(() -> {
// If the server is in proxy mode, check if the player is teleporting cross-server and handle
if (plugin.getSettings().crossServer) {
plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> teleport.ifPresent(activeTeleport -> {
// Handle cross-server respawn
if (activeTeleport.type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getPluginServer()))
.ifPresent(position -> onlineUser.teleport(position, plugin.getSettings().asynchronousTeleports));
onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleport(bedPosition.get(), plugin.getSettings().asynchronousTeleports);
}
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() ->
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)).join());
return;
}
cacheServer(onlineUser).thenRun(() -> plugin.getDatabase().ensureUser(onlineUser)
// Handle cross-server checks
.thenRun(() -> handleInboundTeleport(onlineUser).thenRun(() -> {
// Update the cached player list
plugin.getCache().updatePlayerListCache(plugin, onlineUser);
}).thenRun(() -> {
// Get this user's tp-ignore state and set locally
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
if (userData.isPresent()) {
final boolean ignoringRequests = userData.get().ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
// Teleport the player locally
onlineUser.teleport(activeTeleport.target, plugin.getSettings().asynchronousTeleports).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_world")
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(onlineUser::playSound);
// Send a reminder message if they are still ignoring requests
if (ignoringRequests) {
plugin.getLocales().getRawLocale("tpignore_on_notification",
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
}
}
}).thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null));
}));
}
}).thenRun(() -> {
// Update the cached player list
plugin.getCache().updatePlayerListCache(plugin, onlineUser);
}).thenRunAsync(() -> {
// Get this user's tp-ignore state and set locally
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
if (userData.isPresent()) {
final boolean ignoringRequests = userData.get().ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
}).thenRun(() -> {
// Cache this user's homes
plugin.getDatabase()
.getHomes(onlineUser)
.thenAccept(homes -> plugin.getCache().homes.put(onlineUser.uuid, homes.stream()
.map(home -> home.meta.name)
.collect(Collectors.toList())));
});
})));
}
// Send a reminder message if they are still ignoring requests
if (ignoringRequests) {
plugin.getLocales().getRawLocale("tpignore_on_notification",
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
}
/**
* Ensure the server data has been cached locally
*
* @param onlineUser user to handle the checks for
* @return a future returning void when done
*/
private CompletableFuture<Void> cacheServer(@NotNull OnlineUser onlineUser) {
if (plugin.getSettings().crossServer && firstUser) {
firstUser = false;
return plugin.fetchServer(onlineUser);
}
return CompletableFuture.completedFuture(null);
}
/**
* Handle inbound cross-server teleports
*
* @param onlineUser user to handle the checks for
* @return a future returning void when done
*/
private CompletableFuture<Void> handleInboundTeleport(@NotNull OnlineUser onlineUser) {
// If the server is in proxy mode, check if the player is teleporting cross-server and handle
if (plugin.getSettings().crossServer) {
return plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> {
if (teleport.isEmpty()) {
return;
}
}).join();
}).thenRun(() -> {
// Cache this user's homes
plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> plugin.getCache().homes.put(onlineUser.uuid,
homes.stream()
.map(home -> home.meta.name)
.collect(Collectors.toList()))).join();
});
// Handle cross-server respawn
if (teleport.get().type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getPluginServer()))
.ifPresent(position -> onlineUser.teleport(position, plugin.getSettings().asynchronousTeleports));
onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleport(bedPosition.get(), plugin.getSettings().asynchronousTeleports);
}
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() ->
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)));
return;
}
// Teleport the player locally
onlineUser.teleport(teleport.get().target, plugin.getSettings().asynchronousTeleports).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_world")
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(onlineUser::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(onlineUser::playSound);
}
}).thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null));
});
}
return CompletableFuture.completedFuture(null);
}
/**
@@ -174,8 +196,7 @@ public class EventListener {
plugin.getDatabase().getUserData(onlineUser.uuid)
.thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase()
.setLastPosition(data.user(), sourcePosition).join()))
.join();
.setLastPosition(data.user(), sourcePosition)));
}
/**
@@ -186,7 +207,7 @@ public class EventListener {
*/
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().setRespawnPosition(onlineUser, position).join();
plugin.getDatabase().setRespawnPosition(onlineUser, position);
}
}
@@ -82,14 +82,14 @@ public class SavedPositionManager {
validateMeta(homeMeta).map(resultType -> new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
if (optionalHome.isEmpty()) {
final Home home = new Home(position, homeMeta, homeOwner);
return eventDispatcher.dispatchHomeSaveEvent(home).thenApply(event -> {
return eventDispatcher.dispatchHomeSaveEvent(home).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
cache.homes.putIfAbsent(home.owner.uuid, new ArrayList<>());
cache.homes.get(home.owner.uuid).add(home.meta.name);
cache.privateHomeLists.remove(home.owner.username);
return database.saveHome(home).thenApply(value ->
return database.saveHome(home).thenApplyAsync(value ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(home))).join();
}).join();
}
@@ -108,12 +108,12 @@ public class SavedPositionManager {
public CompletableFuture<Boolean> deleteHome(@NotNull User homeOwner, @NotNull String homeName) {
return database.getHome(homeOwner, homeName).thenApplyAsync(optionalHome -> {
if (optionalHome.isPresent()) {
return eventDispatcher.dispatchHomeDeleteEvent(optionalHome.get()).thenApply(event -> {
return eventDispatcher.dispatchHomeDeleteEvent(optionalHome.get()).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
final Home home = event.getHome();
return database.deleteHome(home.uuid).thenApply(ignored -> {
return database.deleteHome(home.uuid).thenApplyAsync(ignored -> {
cache.homes.computeIfPresent(home.owner.uuid, (ownerUUID, homeNames) -> {
homeNames.remove(home.meta.name);
return homeNames;
@@ -147,7 +147,7 @@ public class SavedPositionManager {
return validateMeta(newHomeMeta).map(resultType ->
new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
home.meta = newHomeMeta;
return eventDispatcher.dispatchHomeSaveEvent(home).thenApply(event -> {
return eventDispatcher.dispatchHomeSaveEvent(home).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
@@ -160,7 +160,7 @@ public class SavedPositionManager {
if (home.isPublic && mapHook != null) {
mapHook.updateHome(home);
}
return database.saveHome(home).thenApply(value ->
return database.saveHome(home).thenApplyAsync(value ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(home))).join();
}).join();
});
@@ -184,7 +184,7 @@ public class SavedPositionManager {
if (home.isPublic && mapHook != null) {
mapHook.updateHome(home);
}
return database.saveHome(home).thenApply(ignored -> true).join();
return database.saveHome(home).thenApplyAsync(ignored -> true).join();
});
}
@@ -202,7 +202,7 @@ public class SavedPositionManager {
return false;
}
return database.saveHome(home).thenApply(ignored -> {
return database.saveHome(home).thenApplyAsync(ignored -> {
if (home.isPublic) {
cache.publicHomes.putIfAbsent(home.owner.username, new ArrayList<>());
cache.publicHomes.get(home.owner.username).add(home.meta.name);
@@ -237,7 +237,7 @@ public class SavedPositionManager {
validateMeta(warpMeta).map(resultType -> new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
if (optionalWarp.isEmpty()) {
final Warp warp = new Warp(position, warpMeta);
return eventDispatcher.dispatchWarpSaveEvent(warp).thenApply(event -> {
return eventDispatcher.dispatchWarpSaveEvent(warp).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
@@ -246,7 +246,7 @@ public class SavedPositionManager {
if (mapHook != null) {
mapHook.updateWarp(warp);
}
return database.saveWarp(warp).thenApply(ignored ->
return database.saveWarp(warp).thenApplyAsync(ignored ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(warp))).join();
}).join();
}
@@ -264,12 +264,12 @@ public class SavedPositionManager {
public CompletableFuture<Boolean> deleteWarp(@NotNull String warpName) {
return database.getWarp(warpName).thenApplyAsync(optionalWarp -> {
if (optionalWarp.isPresent()) {
return eventDispatcher.dispatchWarpDeleteEvent(optionalWarp.get()).thenApply(event -> {
return eventDispatcher.dispatchWarpDeleteEvent(optionalWarp.get()).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
final Warp warp = event.getWarp();
return database.deleteWarp(warp.uuid).thenApply(ignored -> {
return database.deleteWarp(warp.uuid).thenApplyAsync(ignored -> {
cache.warps.remove(warp.meta.name);
cache.warpLists.clear();
if (mapHook != null) {
@@ -299,7 +299,7 @@ public class SavedPositionManager {
return validateMeta(newWarpMeta).map(resultType ->
new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
warp.meta = newWarpMeta;
return eventDispatcher.dispatchWarpSaveEvent(warp).thenApply(event -> {
return eventDispatcher.dispatchWarpSaveEvent(warp).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
@@ -311,7 +311,7 @@ public class SavedPositionManager {
if (mapHook != null) {
mapHook.updateWarp(warp);
}
return database.saveWarp(warp).thenApply(value ->
return database.saveWarp(warp).thenApplyAsync(value ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(warp))).join();
}).join();
});
@@ -335,7 +335,7 @@ public class SavedPositionManager {
if (mapHook != null) {
mapHook.updateWarp(warp);
}
return database.saveWarp(warp).thenApply(ignored -> true).join();
return database.saveWarp(warp).thenApplyAsync(ignored -> true).join();
});
}
@@ -196,7 +196,7 @@ public class RequestManager {
// 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)
+ "_request_received", request.requesterName)
.ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.requesterName)
.ifPresent(recipient::sendMessage);
@@ -275,52 +275,54 @@ public class RequestManager {
request.status = accepted ? TeleportRequest.RequestStatus.ACCEPTED : TeleportRequest.RequestStatus.DECLINED;
// Send request response to the sender
CompletableFuture.runAsync(() -> {
final Optional<OnlineUser> localRequester = plugin.findPlayer(request.requesterName);
if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().crossServer) {
final Optional<OnlineUser> localRequester = plugin.findPlayer(request.requesterName);
if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().crossServer) {
// Ensure the sender is still online
plugin.getNetworkMessenger()
.findPlayer(recipient, request.requesterName)
.thenApplyAsync(networkedTarget -> {
if (networkedTarget.isEmpty()) {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
return false;
}
// Ensure the sender is still online
if (!plugin.getNetworkMessenger().findPlayer(recipient, request.requesterName).thenApply(networkedTarget -> {
if (networkedTarget.isEmpty()) {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
return false;
}
return plugin.getNetworkMessenger().sendMessage(recipient,
new Message(Message.MessageType.TELEPORT_REQUEST_RESPONSE,
recipient.username,
networkedTarget.get(),
MessagePayload.withTeleportRequest(request),
Message.RelayType.MESSAGE,
plugin.getSettings().clusterId))
.thenApply(reply -> true)
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> false).join();
})
.thenAccept(online -> {
if (!online) {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
}
});
} else {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
return;
}
return plugin.getNetworkMessenger().sendMessage(recipient,
new Message(Message.MessageType.TELEPORT_REQUEST_RESPONSE,
recipient.username,
networkedTarget.get(),
MessagePayload.withTeleportRequest(request),
Message.RelayType.MESSAGE,
plugin.getSettings().clusterId))
.thenApply(reply -> true)
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> false).join();
}).join()) {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
return;
}
// If the request is a tpa here request, teleport the recipient to the sender
if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) {
// Strict /tpahere requests will teleport to where the sender was when typing the command
if (plugin.getSettings().strictTpaHereRequests) {
plugin.getTeleportManager().timedTeleport(recipient, request.requesterPosition).thenAccept(
teleportResult -> plugin.getTeleportManager().finishTeleport(recipient, teleportResult));
} else {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
return;
plugin.getTeleportManager().teleportToPlayerByName(recipient, request.requesterName, true);
}
}
// If the request is a tpa here request, teleport the recipient to the sender
if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) {
// Strict /tpahere requests will teleport to where the sender was when typing the command
if (plugin.getSettings().strictTpaHereRequests) {
plugin.getTeleportManager().timedTeleport(recipient, request.requesterPosition).thenAccept(
teleportResult -> plugin.getTeleportManager().finishTeleport(recipient, teleportResult));
} else {
plugin.getTeleportManager().teleportToPlayerByName(recipient, request.requesterName, true);
}
}
});
}
/**