Networking rework, further refactoring

This commit is contained in:
William278 committed 2023-03-02 22:51:50 +00:00
1 parent 1cebdac9b8
commit 4c90e5498c
88 files changed
+1116 -1364

No files matched your search

@@ -4,8 +4,8 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.TimedTeleport;
@@ -47,8 +47,8 @@ public class Cache {
final Database database = plugin.getDatabase();
plugin.runAsync(() -> {
database.getPublicHomes().forEach(home -> {
this.getPublicHomes().putIfAbsent(home.getOwner().username, new ArrayList<>());
this.getPublicHomes().get(home.getOwner().username).add(home.getMeta().getName());
this.getPublicHomes().putIfAbsent(home.getOwner().getUsername(), new ArrayList<>());
this.getPublicHomes().get(home.getOwner().getUsername()).add(home.getMeta().getName());
});
database.getWarps().forEach(warp -> this.getWarps().add(warp.getMeta().getName()));
});
@@ -61,10 +61,10 @@ public class Cache {
*/
public CompletableFuture<Set<String>> updatePlayerListCache(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) {
getPlayers().clear();
getPlayers().addAll(plugin.getOnlinePlayers()
getPlayers().addAll(plugin.getOnlineUsers()
.stream()
.filter(player -> !player.isVanished())
.map(onlineUser -> onlineUser.username)
.map(onlineUser -> onlineUser.getUsername())
.toList());
if (plugin.getSettings().isCrossServer()) {
@@ -119,18 +119,18 @@ public class Cache {
if (plugin.getEventDispatcher().dispatchViewHomeListEvent(homes, onlineUser, false).join().isCancelled()) {
return Optional.empty();
}
final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.username : "";
final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.getUsername() : "";
final PaginatedList homeList = PaginatedList.of(homes.stream().map(home ->
locales.getRawLocale("home_list_item",
Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().username + "." + home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().getUsername() + "." + home.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
.orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("home_list_page_title",
homeOwner.username, "%first_item_on_page_index%",
homeOwner.getUsername(), "%first_item_on_page_index%",
"%last_item_on_page_index%", "%total_items%").orElse(""))
.setCommand("/huskhomes:homelist" + homeListArguments).build());
this.getPrivateHomeLists().put(homeOwner.username, homeList);
this.getPrivateHomeLists().put(homeOwner.getUsername(), homeList);
return Optional.of(homeList.getNearestValidPage(page));
}
@@ -143,15 +143,15 @@ public class Cache {
final PaginatedList publicHomeList = PaginatedList.of(publicHomes.stream().map(home ->
locales.getRawLocale("public_home_list_item",
Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().username + "." + home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().username),
Locales.escapeMineDown(home.getOwner().getUsername() + "." + home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().getUsername()),
Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
.orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("public_home_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%",
"%total_items%").orElse(""))
.setCommand("/huskhomes:publichomelist").build());
getPublicHomeLists().put(onlineUser.uuid, publicHomeList);
getPublicHomeLists().put(onlineUser.getUuid(), publicHomeList);
return Optional.of(publicHomeList.getNearestValidPage(page));
}
@@ -170,7 +170,7 @@ public class Cache {
"%first_item_on_page_index%", "%last_item_on_page_index%",
"%total_items%").orElse(""))
.setCommand("/huskhomes:warplist").build());
getWarpLists().put(onlineUser.uuid, warpList);
getWarpLists().put(onlineUser.getUuid(), warpList);
return Optional.of(warpList.getNearestValidPage(page));
}
@@ -1,5 +1,9 @@
package net.william278.huskhomes;
import com.fatboyindustrial.gsonjavatime.Converters;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.kyori.adventure.key.Key;
import net.william278.desertwell.UpdateChecker;
import net.william278.desertwell.Version;
import net.william278.huskhomes.command.CommandBase;
@@ -12,9 +16,9 @@ import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Messenger;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.migrator.Migrator;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.request.RequestManager;
@@ -22,6 +26,7 @@ import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.TaskRunner;
import net.william278.huskhomes.util.Validator;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -53,7 +58,7 @@ public interface HuskHomes extends TaskRunner {
* @return a {@link Set} of currently online {@link OnlineUser}s
*/
@NotNull
List<OnlineUser> getOnlinePlayers();
List<OnlineUser> getOnlineUsers();
/**
* Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match
@@ -63,11 +68,11 @@ public interface HuskHomes extends TaskRunner {
*/
@NotNull
default Optional<OnlineUser> findOnlinePlayer(@NotNull String playerName) {
return getOnlinePlayers().stream()
.filter(user -> user.username.equalsIgnoreCase(playerName))
return getOnlineUsers().stream()
.filter(user -> user.getUsername().equalsIgnoreCase(playerName))
.findFirst()
.or(() -> getOnlinePlayers().stream()
.filter(user -> user.username.toLowerCase().startsWith(playerName.toLowerCase()))
.or(() -> getOnlineUsers().stream()
.filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase()))
.findFirst());
}
@@ -81,12 +86,12 @@ public interface HuskHomes extends TaskRunner {
*/
@NotNull
default CompletableFuture<Optional<String>> findPlayer(@NotNull OnlineUser requester, @NotNull String targetPlayerName) {
if (requester.username.equalsIgnoreCase(targetPlayerName)) {
return CompletableFuture.completedFuture(Optional.of(requester.username));
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().username));
return CompletableFuture.completedFuture(Optional.of(localPlayer.get().getUsername()));
}
if (getSettings().isCrossServer()) {
return getMessenger().findPlayer(requester, targetPlayerName);
@@ -151,12 +156,12 @@ public interface HuskHomes extends TaskRunner {
Manager getManager();
/**
* The {@link Messenger} that sends cross-network messages
* The {@link Broker} that sends cross-network messages
*
* @return the {@link Messenger} implementation
* @return the {@link Broker} implementation
*/
@NotNull
Messenger getMessenger();
Broker getMessenger();
/**
* The {@link RandomTeleportEngine} that manages random teleports
@@ -204,7 +209,7 @@ public interface HuskHomes extends TaskRunner {
default Optional<? extends Position> getSpawn() {
return getSettings().isCrossServer() && getSettings().isGlobalSpawn()
? getDatabase().getWarp(getSettings().getGlobalSpawnName())
: getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getServerName()));
: getLocalCachedSpawn().map(spawn -> spawn.getPosition(getServerName()));
}
/**
@@ -213,7 +218,7 @@ public interface HuskHomes extends TaskRunner {
* @return a {@link CompletableFuture} returning the latest {@link Version} if the current one is out-of-date
*/
default CompletableFuture<Optional<Version>> getLatestVersionIfOutdated() {
final UpdateChecker updateChecker = UpdateChecker.create(getPluginVersion(), SPIGOT_RESOURCE_ID);
final UpdateChecker updateChecker = UpdateChecker.create(getVersion(), SPIGOT_RESOURCE_ID);
return updateChecker.isUpToDate().thenApply(upToDate -> {
if (upToDate) {
return Optional.empty();
@@ -278,7 +283,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 Settings.EconomyAction action) {
default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull EconomyHook.EconomyAction 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();
@@ -299,7 +304,7 @@ 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 Settings.EconomyAction action) {
default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.EconomyAction action) {
if (!getSettings().isEconomy()) return;
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
@@ -328,7 +333,7 @@ public interface HuskHomes extends TaskRunner {
* @return The {@link Server} object
*/
@NotNull
Server getServerName();
String getServerName();
/**
* Returns a resource read from the plugin resources folder
@@ -361,7 +366,7 @@ public interface HuskHomes extends TaskRunner {
* @return the plugin {@link Version}
*/
@NotNull
Version getPluginVersion();
Version getVersion();
/**
* Returns a list of enabled commands
@@ -393,4 +398,29 @@ public interface HuskHomes extends TaskRunner {
*/
void registerMetrics(int metricsId);
/**
* Initialize plugin messaging channels
*/
void initializePluginChannels();
/**
* Create a resource key namespaced with the plugin id
*
* @param data the string ID elements to join
* @return the key
*/
@NotNull
default Key getKey(@NotNull String... data) {
if (data.length == 0) {
throw new IllegalArgumentException("Cannot create a key with no data");
}
@Subst("foo") final String joined = String.join("/", data);
return Key.key("husktowns", joined);
}
@NotNull
default Gson getGson() {
return Converters.registerOffsetDateTime(new GsonBuilder().excludeFieldsWithoutExposeAnnotation()).create();
}
}
@@ -3,9 +3,9 @@ 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.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
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;
@@ -109,7 +109,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0.2
*/
public boolean isUserWarmingUp(@NotNull User user) {
return plugin.getCache().isWarmingUp(user.uuid);
return plugin.getCache().isWarmingUp(user.getUuid());
}
/**
@@ -1,8 +1,8 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
@@ -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(Settings.EconomyAction.BACK_COMMAND)
.setEconomyActions(EconomyHook.EconomyAction.BACK_COMMAND)
.toTimedTeleport()
.thenApply(TimedTeleport::execute),
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage)));
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.intellij.lang.annotations.Pattern;
import org.intellij.lang.annotations.Subst;
@@ -1,8 +1,8 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.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;
@@ -39,7 +39,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse(homeIdentifier ->
plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName()).thenAccept(
optionalUserData -> optionalUserData.ifPresentOrElse(userData -> {
if (!userData.getUserUuid().equals(onlineUser.uuid)) {
if (!userData.getUserUuid().equals(onlineUser.getUuid())) {
if (!onlineUser.hasPermission(Permission.COMMAND_DELETE_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(onlineUser::sendMessage);
@@ -81,14 +81,14 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(deleter::sendMessage);
} else {
if (deleted) {
plugin.getLocales().getLocale("home_deleted_other", homeOwner.username, homeName).ifPresent(deleter::sendMessage);
plugin.getLocales().getLocale("home_deleted_other", homeOwner.getUsername(), homeName).ifPresent(deleter::sendMessage);
return;
}
if (homeName.equalsIgnoreCase("all")) {
deleteAllHomes(deleter, homeOwner, delHomeAllConfirm);
return;
}
plugin.getLocales().getLocale("error_home_invalid_other", homeOwner.username, homeName).ifPresent(deleter::sendMessage);
plugin.getLocales().getLocale("error_home_invalid_other", homeOwner.getUsername(), homeName).ifPresent(deleter::sendMessage);
}
});
}
@@ -126,7 +126,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
return Collections.emptyList();
}
return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes()
.getOrDefault(user.uuid, new ArrayList<>())
.getOrDefault(user.getUuid(), new ArrayList<>())
.stream()
.filter(s -> s.startsWith(args.length == 1 ? args[0] : ""))
.sorted()
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -3,8 +3,8 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
@@ -37,7 +37,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse(
homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName())
.thenAcceptAsync(optionalUserData -> optionalUserData.ifPresentOrElse(userData -> {
if (!userData.getUserUuid().equals(onlineUser.uuid)) {
if (!userData.getUserUuid().equals(onlineUser.getUuid())) {
if (!onlineUser.hasPermission(Permission.COMMAND_EDIT_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(onlineUser::sendMessage);
@@ -124,7 +124,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
oldHomeName, newHomeName);
} else {
yield plugin.getLocales().getLocale("edit_home_update_name_other",
home.getOwner().username, oldHomeName, newHomeName);
home.getOwner().getUsername(), oldHomeName, newHomeName);
}
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
@@ -149,7 +149,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
.getRawLocale("item_no_description").orElse("N/A") : newDescription);
} else {
yield plugin.getLocales().getLocale("edit_home_update_description_other",
home.getOwner().username,
home.getOwner().getUsername(),
home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
@@ -171,7 +171,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
home.getMeta().getName()).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other",
home.getOwner().username, home.getMeta().getName()).orElse(new MineDown("")));
home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown("")));
}
// Show the menu if the menu flag is set
@@ -226,7 +226,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC)) {
if (!plugin.validateEconomyCheck(editor, EconomyHook.EconomyAction.MAKE_HOME_PUBLIC)) {
return;
}
}
@@ -240,11 +240,11 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.getOwner().username, home.getMeta().getName()).orElse(new MineDown("")));
home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown("")));
}
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC);
plugin.performEconomyTransaction(editor, EconomyHook.EconomyAction.MAKE_HOME_PUBLIC);
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
@@ -293,7 +293,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
plugin.getLocales().getLocale("edit_home_menu_title", home.getMeta().getName())
.ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().username, home.getMeta().getName())
plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().getUsername(), home.getMeta().getName())
.ifPresent(this::add);
}
}
@@ -326,7 +326,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
String.format("%.2f", home.getYaw()), String.format("%.2f", home.getPitch()))
.ifPresent(this::add);
final String formattedName = home.getOwner().username + "." + home.getMeta().getName();
final String formattedName = home.getOwner().getUsername() + "." + home.getMeta().getName();
if (showTeleportButton) {
plugin.getLocales().getLocale("edit_home_menu_use_buttons",
formattedName)
@@ -351,7 +351,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return Collections.emptyList();
}
return switch (args.length) {
case 0, 1 -> plugin.getCache().getHomes().getOrDefault(user.uuid, new ArrayList<>())
case 0, 1 -> plugin.getCache().getHomes().getOrDefault(user.getUuid(), new ArrayList<>())
.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted()
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
@@ -1,8 +1,8 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
@@ -74,7 +74,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
.thenAccept(TimedTeleport::execute);
}, () -> {
if (otherHome) {
plugin.getLocales().getLocale("error_home_invalid_other", owner.username, homeName)
plugin.getLocales().getLocale("error_home_invalid_other", owner.getUsername(), homeName)
.ifPresent(teleporter::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid", homeName)
@@ -100,7 +100,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
identifier -> matchedHome.set(plugin.getDatabase().getUserDataByName(identifier.ownerName()).join()
.flatMap(user -> plugin.getDatabase().getHome(user.user(), identifier.homeName()).join())
.orElse(null)),
() -> matchedHome.set(plugin.getDatabase().getUserDataByName(playerToTeleport.username).join()
() -> matchedHome.set(plugin.getDatabase().getUserDataByName(playerToTeleport.getUsername()).join()
.flatMap(user -> plugin.getDatabase().getHome(user.user(), args[1]).join())
.orElse(null)));
@@ -110,8 +110,8 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
return;
}
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.getOwner().username + "." + home.getMeta().getName());
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to "
+ home.getOwner().getUsername() + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport)
.setTarget(home)
.toTeleport()
@@ -125,7 +125,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
return Collections.emptyList();
}
return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes()
.getOrDefault(user.uuid, new ArrayList<>())
.getOrDefault(user.getUuid(), new ArrayList<>())
.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted()
@@ -1,8 +1,8 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -22,11 +22,11 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> showHomeList(onlineUser, onlineUser.username, 1);
case 0 -> showHomeList(onlineUser, onlineUser.getUsername(), 1);
case 1 -> {
try {
int pageNumber = Integer.parseInt(args[0]);
showHomeList(onlineUser, onlineUser.username, pageNumber);
showHomeList(onlineUser, onlineUser.getUsername(), pageNumber);
} catch (NumberFormatException e) {
showHomeList(onlineUser, args[0], 1);
}
@@ -58,7 +58,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
return;
}
plugin.getDatabase().getUserDataByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(userData -> {
if (!userData.getUserUuid().equals(onlineUser.uuid)) {
if (!userData.getUserUuid().equals(onlineUser.getUuid())) {
if (!onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage);
return;
@@ -98,7 +98,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
final List<Home> homes = plugin.getDatabase().getHomes(userData.get().user()).join();
StringJoiner rowJoiner = new StringJoiner("\t");
plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().username + "'s "
plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().getUsername() + "'s "
+ homes.size() + " homes:");
for (int i = 0; i < homes.size(); i++) {
final String home = homes.get(i).getMeta().getName();
@@ -4,7 +4,7 @@ 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.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -25,7 +25,7 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
super("huskhomes", Permission.COMMAND_HUSKHOMES, implementor);
this.aboutMenu = AboutMenu.create("HuskHomes")
.withDescription("A powerful, intuitive and flexible teleportation suite")
.withVersion(implementor.getPluginVersion())
.withVersion(implementor.getVersion())
.addAttribution("Author",
AboutMenu.Credit.of("William278").withDescription("Click to visit website").withUrl("https://william278.net"))
.addAttribution("Contributors",
@@ -102,10 +102,10 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
newestVersion.ifPresentOrElse(
newVersion -> onlineUser.sendMessage(
new MineDown("[HuskHomes](#00fb9a bold) [| A new version of HuskHomes is available!"
+ " (v" + newVersion + " (Running: v" + plugin.getPluginVersion() + ")](#00fb9a)")),
+ " (v" + newVersion + " (Running: v" + plugin.getVersion() + ")](#00fb9a)")),
() -> onlineUser.sendMessage(
new MineDown("[HuskHomes](#00fb9a bold) [| HuskHomes is up-to-date."
+ " (Running: v" + plugin.getPluginVersion() + ")](#00fb9a)"))));
+ " (Running: v" + plugin.getVersion() + ")](#00fb9a)"))));
}
case "migrate" -> plugin.getLocales().getLocale("error_console_command_only")
.ifPresent(onlineUser::sendMessage);
@@ -143,10 +143,10 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
case "update" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion ->
newestVersion.ifPresentOrElse(newVersion -> plugin.getLoggingAdapter().log(Level.WARNING,
"An update is available for HuskHomes, v" + newVersion
+ " (Running v" + plugin.getPluginVersion() + ")"),
+ " (Running v" + plugin.getVersion() + ")"),
() -> plugin.getLoggingAdapter().log(Level.INFO,
"HuskHomes is up to date" +
" (Running v" + plugin.getPluginVersion() + ")")));
" (Running v" + plugin.getVersion() + ")")));
case "migrate" -> {
if (args.length < 2) {
plugin.getLoggingAdapter().log(Level.INFO,
@@ -1,8 +1,8 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
@@ -86,7 +86,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
.thenAccept(TimedTeleport::execute);
}, () -> {
if (otherHome) {
plugin.getLocales().getLocale("error_home_invalid_other", owner.username, homeName)
plugin.getLocales().getLocale("error_home_invalid_other", owner.getUsername(), homeName)
.ifPresent(teleporter::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid", homeName)
@@ -124,8 +124,8 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
return;
}
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.getOwner().username + "." + home.getMeta().getName());
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to "
+ home.getOwner().getUsername() + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport)
.setTarget(home)
.toTeleport()
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -42,8 +42,8 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
* @param pageNumber page number to display
*/
private void showPublicHomeList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().getPublicHomeLists().containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().getPublicHomeLists().get(onlineUser.uuid).getNearestValidPage(pageNumber));
if (plugin.getCache().getPublicHomeLists().containsKey(onlineUser.getUuid())) {
onlineUser.sendMessage(plugin.getCache().getPublicHomeLists().get(onlineUser.getUuid()).getNearestValidPage(pageNumber));
return;
}
@@ -68,7 +68,7 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
plugin.getLoggingAdapter().log(Level.INFO, "List of " + homes.size() + " public homes:");
for (int i = 0; i < homes.size(); i++) {
final String ownerUsername = homes.get(i).getOwner().username;
final String ownerUsername = homes.get(i).getOwner().getUsername();
final String homeName = homes.get(i).getMeta().getName();
final String home = ownerUsername + "." + homeName;
int spacingSize = (16 - ownerUsername.length()) + 17;
@@ -1,9 +1,9 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.hook.EconomyHook;
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;
@@ -49,13 +49,13 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
}
// Perform economy check if necessary
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.RANDOM_TELEPORT)) {
if (!plugin.validateEconomyCheck(onlineUser, EconomyHook.EconomyAction.RANDOM_TELEPORT)) {
return;
}
final OnlineUser userToTeleport = target;
final boolean isExecutorTeleporting = userToTeleport.equals(onlineUser);
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
plugin.getDatabase().getUserData(onlineUser.getUuid()).thenAccept(userData -> {
// Check the user is not still on /rtp cooldown
if (userData.isEmpty()) {
return;
@@ -83,7 +83,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(Settings.EconomyAction.RANDOM_TELEPORT).toTimedTeleport()
? builder.setEconomyActions(EconomyHook.EconomyAction.RANDOM_TELEPORT).toTimedTeleport()
: builder.toTeleport();
teleportFuture.thenAccept(teleport -> teleport.execute()
@@ -110,10 +110,10 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
return;
}
plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().username + "...");
plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().getUsername() + "...");
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().getWorld(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
if (position.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!");
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().getUsername() + " to a random position; randomization timed out!");
return;
}
Teleport.builder(plugin, foundUser.get())
@@ -121,9 +121,9 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful()) {
plugin.getLoggingAdapter().log(Level.INFO, "Teleported " + foundUser.get().username + " to a random position.");
plugin.getLoggingAdapter().log(Level.INFO, "Teleported " + foundUser.get().getUsername() + " to a random position.");
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport" + foundUser.get().username + " to a random position.");
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport" + foundUser.get().getUsername() + " to a random position.");
}
}));
});
@@ -1,9 +1,9 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
@@ -63,7 +63,7 @@ public class SetHomeCommand extends CommandBase {
}
// Get their user data
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(fetchedData -> {
plugin.getDatabase().getUserData(onlineUser.getUuid()).thenAccept(fetchedData -> {
// Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null);
@@ -71,7 +71,7 @@ public class SetHomeCommand extends CommandBase {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(),
plugin.getSettings().doStackPermissionLimits());
if (fetchedData.isPresent()) {
final Settings.EconomyAction action = Settings.EconomyAction.ADDITIONAL_HOME_SLOT;
final EconomyHook.EconomyAction action = EconomyHook.EconomyAction.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, Settings.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.performEconomyTransaction(onlineUser, EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate.get());
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
@@ -1,6 +1,6 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
@@ -26,7 +26,7 @@ public class TpAllCommand extends CommandBase {
// Determine players to teleport and teleport them
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenAccept(fetchedPlayers -> {
final List<String> players = fetchedPlayers.stream()
.filter(userName -> !userName.equalsIgnoreCase(onlineUser.username)).toList();
.filter(userName -> !userName.equalsIgnoreCase(onlineUser.getUsername())).toList();
if (players.isEmpty()) {
plugin.getLocales().getLocale("error_no_players_online").ifPresent(onlineUser::sendMessage);
return;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World;
@@ -34,19 +34,19 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// 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);
? args.length > 3 ? (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]) ? args[0] : onlineUser.getUsername())
: onlineUser.getUsername() : onlineUser.getUsername());
// Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenRun(() -> {
// Get the list of potential teleports, filtered against vanished players, but ensuring the executor is in the list
final Set<String> players = plugin.getCache().getPlayers();
players.add(onlineUser.username);
players.add(onlineUser.getUsername());
// Find the player to teleport
final String playerToTeleport = players.stream()
.filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst()
.or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.username : null))
.or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.getUsername() : null))
.or(() -> plugin.getCache().getPlayers().stream().filter(user -> user.toLowerCase().startsWith(targetPlayerToTeleport)).findFirst())
.orElse(null);
@@ -58,7 +58,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
}
// Ensure the user has permission to teleport the player to teleport
if (!playerToTeleport.equals(onlineUser.username)) {
if (!playerToTeleport.equals(onlineUser.getUsername())) {
if (!onlineUser.hasPermission(Permission.COMMAND_TP_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(onlineUser::sendMessage);
@@ -77,7 +77,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (result.successful()) {
result.getTeleporter()
.flatMap(teleporter -> plugin.getLocales().getLocale("teleporting_other_complete",
teleporter.username, targetPlayer.playerName))
teleporter.getUsername(), targetPlayer.playerName))
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("error_player_not_found", targetPlayer.playerName)
@@ -97,13 +97,13 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
.setTarget(targetPosition.position)
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (!result.successful() || playerToTeleport.equalsIgnoreCase(onlineUser.username) || result.getDestination().isEmpty()) {
if (!result.successful() || playerToTeleport.equalsIgnoreCase(onlineUser.getUsername()) || result.getDestination().isEmpty()) {
return;
}
final Position destination = result.getDestination().get();
result.getTeleporter()
.flatMap(teleporter -> plugin.getLocales()
.getLocale("teleporting_other_complete_position", teleporter.username,
.getLocale("teleporting_other_complete_position", teleporter.getUsername(),
Integer.toString((int) destination.getX()),
Integer.toString((int) destination.getY()),
Integer.toString((int) destination.getZ())))
@@ -188,7 +188,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// Execute the console teleport
final TeleportBuilder builder = Teleport.builder(plugin, playerToTeleport)
.setTeleporter(playerToTeleport.username);
.setTeleporter(playerToTeleport.getUsername());
if (teleportTarget instanceof TargetPlayer targetPlayer) {
builder.setTarget(targetPlayer.playerName);
} else {
@@ -196,9 +196,9 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
}
builder.toTeleport().thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful()) {
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.username);
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.getUsername());
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.username + " to " + teleportTarget);
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.getUsername() + " to " + teleportTarget);
}
}));
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -42,7 +42,7 @@ public class TpHereCommand extends CommandBase implements TabCompletable {
if (result.successful()) {
result.getTeleporter()
.flatMap(teleporter -> plugin.getLocales().getLocale("teleporting_other_complete",
teleporter.username, onlineUser.username))
teleporter.getUsername(), onlineUser.getUsername()))
.ifPresent(onlineUser::sendMessage);
}
}));
@@ -2,8 +2,8 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.UserData;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -26,7 +26,7 @@ public class TpIgnoreCommand extends CommandBase {
plugin.getRequestManager().setIgnoringRequests(onlineUser, isIgnoringRequests);
// Update value on the database and send a message | todo: Clean this up
plugin.getDatabase().getUserData(onlineUser.uuid)
plugin.getDatabase().getUserData(onlineUser.getUuid())
.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"),
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -34,7 +34,7 @@ public class TpaAllCommand extends CommandBase {
// Determine players to teleport and teleport them
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenAccept(playerList -> {
final List<String> players = plugin.getCache().getPlayers().stream()
.filter(userName -> !userName.equalsIgnoreCase(onlineUser.username)).toList();
.filter(userName -> !userName.equalsIgnoreCase(onlineUser.getUsername())).toList();
if (players.isEmpty()) {
plugin.getLocales().getLocale("error_no_players_online").ifPresent(onlineUser::sendMessage);
return;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -30,7 +30,7 @@ public class TpaCommand extends CommandBase implements TabCompletable {
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA)
.thenAccept(sent -> {
if (sent.isEmpty()) {
if (args[0].equalsIgnoreCase(onlineUser.username)) {
if (args[0].equalsIgnoreCase(onlineUser.getUsername())) {
plugin.getLocales().getLocale("error_teleport_request_self")
.ifPresent(onlineUser::sendMessage);
return;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.request.TeleportRequest;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -30,7 +30,7 @@ public class TpaHereCommand extends CommandBase implements TabCompletable {
.sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA_HERE)
.thenAccept(sent -> {
if (sent.isEmpty()) {
if (args[0].equalsIgnoreCase(onlineUser.username)) {
if (args[0].equalsIgnoreCase(onlineUser.getUsername())) {
plugin.getLocales().getLocale("error_teleport_request_self")
.ifPresent(onlineUser::sendMessage);
return;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
@@ -89,7 +89,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
}
final Warp warp = optionalWarp.get();
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.getMeta().getName());
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + warp.getMeta().getName());
Teleport.builder(plugin, playerToTeleport)
.setTarget(warp)
.toTimedTeleport()
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -40,8 +40,8 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
* @param pageNumber page number to display
*/
private void showWarpList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().getWarpLists().containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().getWarpLists().get(onlineUser.uuid).getNearestValidPage(pageNumber));
if (plugin.getCache().getWarpLists().containsKey(onlineUser.getUuid())) {
onlineUser.sendMessage(plugin.getCache().getWarpLists().get(onlineUser.getUuid()).getNearestValidPage(pageNumber));
return;
}
@@ -34,15 +34,12 @@ public class CachedSpawn {
/**
* Returns the {@link Position} of the spawn
*
* @param server The server the spawn is on
* @return The {@link Position} of the spawn
*/
public Optional<Position> getPosition(@NotNull Server server) {
try {
return Optional.of(new Position(x, y, z, yaw, pitch,
new World(worldName, UUID.fromString(worldUuid)), server));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
@NotNull
public Position getPosition(@NotNull String server) {
return new Position(x, y, z, yaw, pitch, new World(worldName, UUID.fromString(worldUuid)), server);
}
/**
@@ -3,6 +3,10 @@ package net.william278.huskhomes.config;
import net.william278.annotaml.YamlComment;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.network.Broker;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
@@ -38,7 +42,7 @@ public class Settings {
// Database settings
@YamlComment("Database connection settings")
@YamlKey("database.type")
private DatabaseType databaseType = DatabaseType.SQLITE;
private Database.DatabaseType databaseType = Database.DatabaseType.SQLITE;
@YamlKey("database.mysql.credentials.host")
private String mySqlHost = "localhost";
@@ -76,17 +80,17 @@ public class Settings {
@YamlKey("database.table_names")
private Map<String, String> tableNames = Map.of(
TableName.PLAYER_DATA.name().toLowerCase(), TableName.PLAYER_DATA.defaultName,
TableName.POSITION_DATA.name().toLowerCase(), TableName.POSITION_DATA.defaultName,
TableName.SAVED_POSITION_DATA.name().toLowerCase(), TableName.SAVED_POSITION_DATA.defaultName,
TableName.HOME_DATA.name().toLowerCase(), TableName.HOME_DATA.defaultName,
TableName.WARP_DATA.name().toLowerCase(), TableName.WARP_DATA.defaultName,
TableName.TELEPORT_DATA.name().toLowerCase(), TableName.TELEPORT_DATA.defaultName
Database.TableName.PLAYER_DATA.name().toLowerCase(), Database.TableName.PLAYER_DATA.getDefaultName(),
Database.TableName.POSITION_DATA.name().toLowerCase(), Database.TableName.POSITION_DATA.getDefaultName(),
Database.TableName.SAVED_POSITION_DATA.name().toLowerCase(), Database.TableName.SAVED_POSITION_DATA.getDefaultName(),
Database.TableName.HOME_DATA.name().toLowerCase(), Database.TableName.HOME_DATA.getDefaultName(),
Database.TableName.WARP_DATA.name().toLowerCase(), Database.TableName.WARP_DATA.getDefaultName(),
Database.TableName.TELEPORT_DATA.name().toLowerCase(), Database.TableName.TELEPORT_DATA.getDefaultName()
);
@NotNull
public String getTableName(@NotNull TableName tableName) {
return Optional.ofNullable(getTableNames().get(tableName.name().toLowerCase())).orElse(tableName.defaultName);
public String getTableName(@NotNull Database.TableName tableName) {
return Optional.ofNullable(getTableNames().get(tableName.name().toLowerCase())).orElse(tableName.getDefaultName());
}
@@ -160,7 +164,7 @@ public class Settings {
private boolean crossServer = false;
@YamlKey("cross_server.messenger_type")
private MessengerType messengerType = MessengerType.PLUGIN_MESSAGE;
private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE;
@YamlKey("cross_server.cluster_id")
private String clusterId = "";
@@ -222,13 +226,13 @@ public class Settings {
@YamlKey("economy.costs")
private Map<String, Double> economyCosts = Map.of(
EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost,
EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost,
EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyAction.RANDOM_TELEPORT.defaultCost,
EconomyAction.BACK_COMMAND.name().toLowerCase(), EconomyAction.BACK_COMMAND.defaultCost
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()
);
public Optional<Double> getEconomyCost(@NotNull EconomyAction action) {
public Optional<Double> getEconomyCost(@NotNull EconomyHook.EconomyAction action) {
if (!isEconomy()) {
return Optional.empty();
}
@@ -245,7 +249,7 @@ public class Settings {
private boolean doMapHook = false;
@YamlKey("map_hook.map_plugin")
private MappingPlugin mappingPlugin = MappingPlugin.DYNMAP;
private MapHook.MappingPlugin mappingPlugin = MapHook.MappingPlugin.DYNMAP;
@YamlKey("map_hook.show_public_homes")
private boolean publicHomesOnMap = true;
@@ -275,7 +279,7 @@ public class Settings {
return debugLogging;
}
public DatabaseType getDatabaseType() {
public Database.DatabaseType getDatabaseType() {
return databaseType;
}
@@ -399,8 +403,8 @@ public class Settings {
return crossServer;
}
public MessengerType getMessengerType() {
return messengerType;
public Broker.Type getBrokerType() {
return messageBrokerType;
}
public String getClusterId() {
@@ -431,7 +435,7 @@ public class Settings {
return redisPassword;
}
public boolean isRedisUseSsl() {
public boolean useRedisSsl() {
return redisUseSsl;
}
@@ -479,7 +483,7 @@ public class Settings {
return doMapHook;
}
public MappingPlugin getMappingPlugin() {
public MapHook.MappingPlugin getMappingPlugin() {
return mappingPlugin;
}
@@ -495,24 +499,6 @@ public class Settings {
return disabledCommands;
}
/**
* Represents the names of tables in the database
*/
public enum TableName {
PLAYER_DATA("huskhomes_users"),
POSITION_DATA("huskhomes_position_data"),
SAVED_POSITION_DATA("huskhomes_saved_positions"),
HOME_DATA("huskhomes_homes"),
WARP_DATA("huskhomes_warps"),
TELEPORT_DATA("huskhomes_teleports");
private final String defaultName;
TableName(@NotNull String defaultName) {
this.defaultName = defaultName;
}
}
/**
* Represents where a chat message should display
*/
@@ -537,68 +523,4 @@ public class Settings {
}
}
/**
* Identifies actions that incur an economic cost if economy is enabled
*/
public enum EconomyAction {
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"),
BACK_COMMAND(0.00, "economy_action_back_command");
private final double defaultCost;
@NotNull
public final String confirmationLocaleId;
EconomyAction(final double defaultCost, @NotNull String confirmationLocaleId) {
this.defaultCost = defaultCost;
this.confirmationLocaleId = confirmationLocaleId;
}
}
/**
* Identifies types of databases
*/
public enum DatabaseType {
MYSQL("MySQL"),
SQLITE("SQLite");
@NotNull
public final String displayName;
DatabaseType(@NotNull String displayName) {
this.displayName = displayName;
}
}
/**
* Identifies types of network messenger
*/
public enum MessengerType {
PLUGIN_MESSAGE("Plugin Messages"),
REDIS("Redis");
@NotNull
public final String displayName;
MessengerType(@NotNull String displayName) {
this.displayName = displayName;
}
}
/**
* Identifies types of supported Map plugins
*/
public enum MappingPlugin {
DYNMAP("Dynmap"),
BLUEMAP("BlueMap");
@NotNull
public final String displayName;
MappingPlugin(@NotNull String displayName) {
this.displayName = displayName;
}
}
}
@@ -1,10 +1,9 @@
package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.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.util.Logger;
@@ -154,12 +153,12 @@ public abstract class Database {
*/
protected Database(@NotNull HuskHomes implementor) {
this.plugin = implementor;
this.playerTableName = implementor.getSettings().getTableName(Settings.TableName.PLAYER_DATA);
this.positionsTableName = implementor.getSettings().getTableName(Settings.TableName.POSITION_DATA);
this.savedPositionsTableName = implementor.getSettings().getTableName(Settings.TableName.SAVED_POSITION_DATA);
this.homesTableName = implementor.getSettings().getTableName(Settings.TableName.HOME_DATA);
this.warpsTableName = implementor.getSettings().getTableName(Settings.TableName.WARP_DATA);
this.teleportsTableName = implementor.getSettings().getTableName(Settings.TableName.TELEPORT_DATA);
this.playerTableName = implementor.getSettings().getTableName(TableName.PLAYER_DATA);
this.positionsTableName = implementor.getSettings().getTableName(TableName.POSITION_DATA);
this.savedPositionsTableName = implementor.getSettings().getTableName(TableName.SAVED_POSITION_DATA);
this.homesTableName = implementor.getSettings().getTableName(TableName.HOME_DATA);
this.warpsTableName = implementor.getSettings().getTableName(TableName.WARP_DATA);
this.teleportsTableName = implementor.getSettings().getTableName(TableName.TELEPORT_DATA);
this.logger = implementor.getLoggingAdapter();
}
@@ -459,4 +458,41 @@ public abstract class Database {
public abstract void terminate();
/**
* Identifies types of databases
*/
public enum DatabaseType {
MYSQL("MySQL"),
SQLITE("SQLite");
@NotNull
public final String displayName;
DatabaseType(@NotNull String displayName) {
this.displayName = displayName;
}
}
/**
* Represents the names of tables in the database
*/
public enum TableName {
PLAYER_DATA("huskhomes_users"),
POSITION_DATA("huskhomes_position_data"),
SAVED_POSITION_DATA("huskhomes_saved_positions"),
HOME_DATA("huskhomes_homes"),
WARP_DATA("huskhomes_warps"),
TELEPORT_DATA("huskhomes_teleports");
private final String defaultName;
TableName(@NotNull String defaultName) {
this.defaultName = defaultName;
}
@NotNull
public String getDefaultName() {
return defaultName;
}
}
}
@@ -2,9 +2,9 @@ package net.william278.huskhomes.database;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.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.TeleportType;
@@ -242,8 +242,8 @@ public class MySqlDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.uuid).ifPresentOrElse(existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.username)) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
// Update a player's name if it has changed in the database
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -251,11 +251,11 @@ public class MySqlDatabase extends Database {
SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, onlineUser.username);
statement.setString(1, onlineUser.getUsername());
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.username + ")");
getLogger().log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.getUsername() + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -268,8 +268,8 @@ public class MySqlDatabase extends Database {
INSERT INTO `%players_table%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.uuid.toString());
statement.setString(2, onlineUser.username);
statement.setString(1, onlineUser.getUuid().toString());
statement.setString(2, onlineUser.getUsername());
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -342,7 +342,7 @@ public class MySqlDatabase extends Database {
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
@@ -364,7 +364,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username);
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
}
return userHomes;
}
@@ -453,7 +453,7 @@ public class MySqlDatabase extends Database {
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
AND `name`=?;"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
statement.setString(2, homeName);
final ResultSet resultSet = statement.executeQuery();
@@ -596,7 +596,7 @@ public class MySqlDatabase extends Database {
FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, onlineUser.uuid.toString());
statement.setString(1, onlineUser.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -617,7 +617,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e);
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
}
return Optional.empty();
}
@@ -652,7 +652,7 @@ public class MySqlDatabase extends Database {
FROM `%teleports_table%`
WHERE `%teleports_table%`.`player_uuid`=?
);"""))) {
deleteStatement.setString(1, user.uuid.toString());
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
}
@@ -661,7 +661,7 @@ public class MySqlDatabase extends Database {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition(teleport.target, connection));
statement.setInt(3, teleport.type.typeId);
@@ -669,7 +669,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
}
}
@@ -681,7 +681,7 @@ public class MySqlDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -696,7 +696,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
}
return Optional.empty();
}
@@ -709,7 +709,7 @@ public class MySqlDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
queryStatement.setString(1, user.getUuid().toString());
final ResultSet resultSet = queryStatement.executeQuery();
if (resultSet.next()) {
@@ -722,13 +722,13 @@ public class MySqlDatabase extends Database {
SET `last_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
updateStatement.setString(2, user.uuid.toString());
updateStatement.setString(2, user.getUuid().toString());
updateStatement.executeUpdate();
}
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
}
}
@@ -740,7 +740,7 @@ public class MySqlDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -755,7 +755,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
}
return Optional.empty();
}
@@ -767,7 +767,7 @@ public class MySqlDatabase extends Database {
SELECT `offline_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
queryStatement.setString(1, user.getUuid().toString());
final ResultSet resultSet = queryStatement.executeQuery();
if (resultSet.next()) {
@@ -780,13 +780,13 @@ public class MySqlDatabase extends Database {
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
updateStatement.setString(2, user.uuid.toString());
updateStatement.setString(2, user.getUuid().toString());
updateStatement.executeUpdate();
}
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
}
}
@@ -798,7 +798,7 @@ public class MySqlDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -813,7 +813,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
}
return Optional.empty();
}
@@ -825,7 +825,7 @@ public class MySqlDatabase extends Database {
SELECT `respawn_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
queryStatement.setString(1, user.getUuid().toString());
final ResultSet resultSet = queryStatement.executeQuery();
if (resultSet.next()) {
@@ -838,7 +838,7 @@ public class MySqlDatabase extends Database {
FROM `%players_table%`
WHERE `%players_table%`.`uuid`=?
);"""))) {
deleteStatement.setString(1, user.uuid.toString());
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
}
} else {
@@ -853,14 +853,14 @@ public class MySqlDatabase extends Database {
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
updateStatement.setString(2, user.uuid.toString());
updateStatement.setString(2, user.getUuid().toString());
updateStatement.executeUpdate();
}
}
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
}
}
@@ -891,7 +891,7 @@ public class MySqlDatabase extends Database {
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.getOwner().username, e);
"Failed to update a home in the database for " + home.getOwner().getUsername(), e);
}
}, () -> {
try (Connection connection = getConnection()) {
@@ -900,14 +900,14 @@ public class MySqlDatabase extends Database {
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
statement.setString(3, home.getOwner().uuid.toString());
statement.setString(3, home.getOwner().getUuid().toString());
statement.setBoolean(4, home.isPublic());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().username, e);
"Failed to set a home to the database for " + home.getOwner().getUsername(), e);
}
});
}
@@ -983,11 +983,11 @@ public class MySqlDatabase extends Database {
)
);"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
return statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e);
getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e);
}
return 0;
}
@@ -1,9 +1,9 @@
package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.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.TeleportType;
@@ -238,8 +238,8 @@ public class SqLiteDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.uuid).ifPresentOrElse(existingUser -> {
if (!existingUser.getUsername().equals(onlineUser.username)) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUser -> {
if (!existingUser.getUsername().equals(onlineUser.getUsername())) {
// Update a player's name if it has changed in the database
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -247,11 +247,11 @@ public class SqLiteDatabase extends Database {
SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, onlineUser.username);
statement.setString(1, onlineUser.getUsername());
statement.setString(2, existingUser.getUserUuid().toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.username + ")");
getLogger().log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.getUsername() + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -264,8 +264,8 @@ public class SqLiteDatabase extends Database {
INSERT INTO `%players_table%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.uuid.toString());
statement.setString(2, onlineUser.username);
statement.setString(1, onlineUser.getUuid().toString());
statement.setString(2, onlineUser.getUsername());
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -338,7 +338,7 @@ public class SqLiteDatabase extends Database {
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
@@ -360,7 +360,7 @@ public class SqLiteDatabase extends Database {
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username);
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
}
return userHomes;
}
@@ -449,7 +449,7 @@ public class SqLiteDatabase extends Database {
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
AND `name`=?;"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
statement.setString(2, homeName);
final ResultSet resultSet = statement.executeQuery();
@@ -592,7 +592,7 @@ public class SqLiteDatabase extends Database {
FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, onlineUser.uuid.toString());
statement.setString(1, onlineUser.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -613,7 +613,7 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e);
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
}
return Optional.empty();
}
@@ -646,11 +646,11 @@ public class SqLiteDatabase extends Database {
FROM `%teleports_table%`
WHERE `%teleports_table%`.`player_uuid`=?
);"""))) {
deleteStatement.setString(1, user.uuid.toString());
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
}
// Set the user's teleport into the database (if it's not null)
@@ -658,14 +658,14 @@ public class SqLiteDatabase extends Database {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition(teleport.target, connection));
statement.setInt(3, teleport.type.typeId);
statement.executeUpdate();
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.getUsername(), e);
}
}
}
@@ -677,7 +677,7 @@ public class SqLiteDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -691,7 +691,7 @@ public class SqLiteDatabase extends Database {
new Server(resultSet.getString("server_name"))));
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
}
return Optional.empty();
}
@@ -703,7 +703,7 @@ public class SqLiteDatabase extends Database {
SELECT `last_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
queryStatement.setString(1, user.getUuid().toString());
final ResultSet resultSet = queryStatement.executeQuery();
if (resultSet.next()) {
@@ -716,13 +716,13 @@ public class SqLiteDatabase extends Database {
SET `last_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
updateStatement.setString(2, user.uuid.toString());
updateStatement.setString(2, user.getUuid().toString());
updateStatement.executeUpdate();
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
}
}
@@ -734,7 +734,7 @@ public class SqLiteDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -749,7 +749,7 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
}
return Optional.empty();
}
@@ -760,7 +760,7 @@ public class SqLiteDatabase extends Database {
SELECT `offline_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
queryStatement.setString(1, user.getUuid().toString());
final ResultSet resultSet = queryStatement.executeQuery();
if (resultSet.next()) {
@@ -773,12 +773,12 @@ public class SqLiteDatabase extends Database {
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
updateStatement.setString(2, user.uuid.toString());
updateStatement.setString(2, user.getUuid().toString());
updateStatement.executeUpdate();
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
}
}
@@ -789,7 +789,7 @@ public class SqLiteDatabase extends Database {
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -803,7 +803,7 @@ public class SqLiteDatabase extends Database {
new Server(resultSet.getString("server_name"))));
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
}
return Optional.empty();
}
@@ -814,7 +814,7 @@ public class SqLiteDatabase extends Database {
SELECT `respawn_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
queryStatement.setString(1, user.getUuid().toString());
final ResultSet resultSet = queryStatement.executeQuery();
if (resultSet.next()) {
@@ -827,7 +827,7 @@ public class SqLiteDatabase extends Database {
FROM `%players_table%`
WHERE `%players_table%`.`uuid`=?
);"""))) {
deleteStatement.setString(1, user.uuid.toString());
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
}
} else {
@@ -842,14 +842,14 @@ public class SqLiteDatabase extends Database {
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
updateStatement.setString(2, user.uuid.toString());
updateStatement.setString(2, user.getUuid().toString());
updateStatement.executeUpdate();
}
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
}
}
@@ -880,7 +880,7 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.getOwner().username, e);
"Failed to update a home in the database for " + home.getOwner().getUsername(), e);
}
}, () -> {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -888,14 +888,14 @@ public class SqLiteDatabase extends Database {
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
statement.setString(3, home.getOwner().uuid.toString());
statement.setString(3, home.getOwner().getUuid().toString());
statement.setBoolean(4, home.isPublic());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().username, e);
"Failed to set a home to the database for " + home.getOwner().getUsername(), e);
}
});
}
@@ -968,10 +968,10 @@ public class SqLiteDatabase extends Database {
)
);"""))) {
statement.setString(1, user.uuid.toString());
statement.setString(1, user.getUuid().toString());
return statement.executeUpdate();
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e);
getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e);
}
return 0;
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.event;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
@@ -1,6 +1,6 @@
package net.william278.huskhomes.event;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
/**
@@ -1,6 +1,6 @@
package net.william278.huskhomes.event;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import org.jetbrains.annotations.NotNull;
@@ -1,6 +1,6 @@
package net.william278.huskhomes.event;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Warp;
import org.jetbrains.annotations.NotNull;
@@ -6,7 +6,7 @@ import de.bluecolored.bluemap.api.BlueMapWorld;
import de.bluecolored.bluemap.api.markers.MarkerSet;
import de.bluecolored.bluemap.api.markers.POIMarker;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.World;
@@ -74,9 +74,9 @@ public class BlueMapHook extends MapHook {
blueMapAPI -> getBlueMapWorld(blueMapAPI, home.getWorld())).ifPresent(blueMapWorld -> blueMapWorld.getMaps()
.forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().put(home.getOwner().uuid + ":" + home.getUuid(),
markerSet.getMarkers().put(home.getOwner().getUuid() + ":" + home.getUuid(),
POIMarker.toBuilder()
.label("/phome" + home.getOwner().username + "." + home.getMeta().getName())
.label("/phome" + home.getOwner().getUsername() + "." + home.getMeta().getName())
.position((int) home.getX(), (int) home.getY(), (int) home.getZ())
.icon(publicHomeMarkerIconPath, Vector2i.from(25, 25))
.maxDistance(5000)
@@ -92,7 +92,7 @@ public class BlueMapHook extends MapHook {
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, home.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().remove(home.getOwner().uuid + ":" + home.getUuid());
markerSet.getMarkers().remove(home.getOwner().getUuid() + ":" + home.getUuid());
return markerSet;
})));
return CompletableFuture.completedFuture(null);
@@ -104,7 +104,7 @@ public class BlueMapHook extends MapHook {
.forEach(blueMapWorld -> blueMapWorld.getMaps()
.forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().keySet().removeIf(key -> key.startsWith(user.uuid.toString()));
markerSet.getMarkers().keySet().removeIf(key -> key.startsWith(user.getUuid().toString()));
return markerSet;
}))));
@@ -1,7 +1,7 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
/**
@@ -37,4 +37,26 @@ public abstract class EconomyHook extends PluginHook {
*/
public abstract String formatCurrency(final double amount);
/**
* Identifies actions that incur an economic cost if economy is enabled
*/
public enum EconomyAction {
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"),
BACK_COMMAND(0.00, "economy_action_back_command");
private final double defaultCost;
@NotNull
public final String confirmationLocaleId;
EconomyAction(final double defaultCost, @NotNull String confirmationLocaleId) {
this.defaultCost = defaultCost;
this.confirmationLocaleId = confirmationLocaleId;
}
public double getDefaultCost() {
return defaultCost;
}
}
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
@@ -113,4 +113,18 @@ public abstract class MapHook extends PluginHook {
}
}
/**
* Identifies types of supported Map plugins
*/
public enum MappingPlugin {
DYNMAP("Dynmap"),
BLUEMAP("BlueMap");
@NotNull
public final String displayName;
MappingPlugin(@NotNull String displayName) {
this.displayName = displayName;
}
}
}
@@ -6,7 +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.player.UserData;
import net.william278.huskhomes.user.UserData;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@@ -2,7 +2,7 @@ package net.william278.huskhomes.listener;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
@@ -41,7 +41,7 @@ public class EventListener {
}
// Set their ignoring requests state
plugin.getDatabase().getUserData(onlineUser.uuid).ifPresent(userData -> {
plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> {
final boolean ignoringRequests = userData.ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
@@ -54,7 +54,7 @@ public class EventListener {
});
// Cache this user's homes
plugin.getCache().getHomes().put(onlineUser.uuid, plugin.getDatabase()
plugin.getCache().getHomes().put(onlineUser.getUuid(), plugin.getDatabase()
.getHomes(onlineUser).stream()
.map(Home::getName)
.toList());
@@ -72,7 +72,7 @@ public class EventListener {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn()
.flatMap(spawn -> spawn.getPosition(plugin.getServerName()))
.map(spawn -> spawn.getPosition(plugin.getServerName()))
.ifPresent(position -> onlineUser.teleportLocally(position,
plugin.getSettings().isAsynchronousTeleports()));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
@@ -100,10 +100,10 @@ public class EventListener {
*/
protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) {
// Remove this user's home cache
plugin.getCache().getHomes().remove(onlineUser.uuid);
plugin.getCache().getHomes().remove(onlineUser.getUuid());
// Update the cached player list using another online player if possible
plugin.getOnlinePlayers()
plugin.getOnlineUsers()
.stream()
.filter(onlinePlayer -> !onlinePlayer.equals(onlineUser))
.findAny()
@@ -168,7 +168,7 @@ public class EventListener {
return;
}
plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.uuid)
plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.getUuid())
.ifPresent(data -> plugin.getDatabase().setLastPosition(data.user(), sourcePosition)));
}
@@ -188,7 +188,7 @@ public class EventListener {
* Handle when the plugin is disabling (server is shutting down)
*/
public final void handlePluginDisable() {
plugin.getLoggingAdapter().log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getPluginVersion());
plugin.getLoggingAdapter().log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion());
}
}
@@ -2,7 +2,7 @@ package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
public class UsersManager {
@@ -0,0 +1,142 @@
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
*
* @param plugin the HuskTowns plugin instance
*/
protected Broker(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/**
* Handle an inbound {@link Message}
*
* @param receiver The user who received the message, if a receiver exists
* @param message The message
*/
protected void handle(@Nullable OnlineUser receiver, @NotNull Message message) {
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());
}
}
}
/**
* Initialize the message broker
*
* @throws RuntimeException if the broker fails to initialize
*/
public abstract void initialize() throws RuntimeException;
/**
* Send a message to the broker
*
* @param message the message to send
* @param sender the sender of the message
*/
protected abstract void send(@NotNull Message message, @NotNull OnlineUser sender);
/**
* Move an {@link OnlineUser} to a new server on the proxy network
*
* @param user the user to move
* @param server the server to move the user to
*/
public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server);
@NotNull
protected Map<UUID, CompletableFuture<Message>> getOutboundMessages() {
return outboundMessages;
}
/**
* Terminate the broker
*/
public abstract void close();
@NotNull
protected String getSubChannelId() {
final String version = plugin.getVersion().getMajor() + "." + plugin.getVersion().getMinor();
return plugin.getKey(plugin.getSettings().getClusterId(), version).asString();
}
@NotNull
protected String getServer() {
return plugin.getServerName();
}
/**
* 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;
}
}
}
@@ -0,0 +1,158 @@
package net.william278.huskhomes.network;
import com.google.gson.annotations.Expose;
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
* a builder to create a message.
*/
public class Message {
public static final String TARGET_ALL = "ALL";
@Expose
private UUID id;
@Expose
private Type type;
@Expose
private String target;
@Expose
private Payload payload;
@Expose
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;
this.target = target;
this.payload = payload;
this.id = UUID.randomUUID();
}
@SuppressWarnings("unused")
private Message() {
}
public static Builder builder() {
return new Builder();
}
public CompletableFuture<Message> 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
public Type getType() {
return type;
}
@NotNull
public String getTarget() {
return target;
}
@NotNull
public Payload getPayload() {
return payload;
}
@NotNull
public String getSender() {
return sender;
}
@NotNull
public String getSourceServer() {
return sourceServer;
}
@NotNull
public Direction getDirection() {
return direction;
}
@NotNull
public UUID getUuid() {
return id;
}
/**
* Builder for {@link Message}s
*/
public static class Builder {
private Type type;
private Payload payload = Payload.empty();
private String target;
private Builder() {
}
@NotNull
public Builder type(@NotNull Type type) {
this.type = type;
return this;
}
@NotNull
public Builder payload(@NotNull Payload payload) {
this.payload = payload;
return this;
}
@NotNull
public Builder target(@NotNull String target) {
this.target = target;
return this;
}
@NotNull
public Message build() {
return new Message(type, target, payload);
}
}
/**
* Different types of cross-server messages
*/
public enum Type {
TELEPORT_TO_POSITION_REQUEST,
POSITION_REQUEST,
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
}
}
@@ -1,215 +0,0 @@
package net.william278.huskhomes.network;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public abstract class Messenger implements AutoCloseable {
/**
* Name of the network message channel for HuskHomes messages
*/
public static final String NETWORK_MESSAGE_CHANNEL = "huskhomes:main";
/**
* Map of message UUIDs to messages being processed
*/
protected HashMap<UUID, CompletableFuture<Request>> processingMessages;
/**
* List of pending futures for processing {@link #getOnlinePlayerNames(OnlineUser)} requests
*/
protected List<CompletableFuture<String[]>> onlinePlayerNamesRequests;
/**
* List of pending futures for processing {@link #fetchOnlineServerList(OnlineUser)} requests
*/
protected List<CompletableFuture<String[]>> onlineServersRequests;
/**
* ID of the HuskHomes network cluster this server is on
*/
protected String clusterId;
/**
* The implementing HuskHomes plugin instance
*/
protected HuskHomes plugin;
/**
* The time-to-live of a message before it expires and the {@link CompletableFuture} is cancelled
*/
private final long MESSAGE_TIME_OUT = 5L;
/**
* Initialize the network messenger
*
* @param implementor Instance of the implementing plugin
*/
public void initialize(@NotNull HuskHomes implementor) {
this.processingMessages = new HashMap<>();
this.onlinePlayerNamesRequests = new ArrayList<>();
this.onlineServersRequests = new ArrayList<>();
this.clusterId = implementor.getSettings().getClusterId();
this.plugin = implementor;
}
/**
* Fetch a list of online player usernames from the proxy
*
* @param requester {@link OnlineUser} to send the request
* @return Future returning a {@link List} of usernames of players on the proxy network
*/
public abstract CompletableFuture<String[]> getOnlinePlayerNames(@NotNull OnlineUser requester);
/**
* Find a player on the proxy network by username to validate if they exist.
*
* @param requester {@link OnlineUser} to send the request
* @param playerName Approximate name of the player to find. If an exact match is not found,
* this will attempt to return the closest match
* @return Future returning an {@link Optional} of the player's canonical username if found;
* otherwise an empty {@link Optional}
*/
public final CompletableFuture<Optional<String>> findPlayer(@NotNull OnlineUser requester, @NotNull String playerName) {
return getOnlinePlayerNames(requester).thenApply(networkedPlayers ->
Arrays.stream(networkedPlayers)
.filter(user -> user.equalsIgnoreCase(playerName))
.findFirst()
.or(() -> Arrays.stream(networkedPlayers)
.filter(user -> user.toLowerCase().startsWith(playerName))
.findFirst()));
}
/**
* Fetch a list of online server names proxy
*
* @param requester {@link OnlineUser} to send the request
* @return Future returning a {@link List} of online servers connected to the proxy network
*/
public abstract CompletableFuture<String[]> fetchOnlineServerList(@NotNull OnlineUser requester);
/**
* Send a {@link OnlineUser} to a target {@link Server} on the proxy network
*
* @param server The {@link Server} to send the {@link OnlineUser} to
* @return A future, returning {@code true} if the player was sent.<p>
* If the player could not be sent (i.e. the server was offline), this will return {@code false}
*/
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server);
/**
* Send a network message
*
* @param sender {@link OnlineUser} sending the message
* @param request {@link Request} to send
* @return Future returning the {@link Request} sent, that will time out after
* @apiNote This method invokes {@link #dispatchMessage(OnlineUser, Request)}, applying a time-to-live timeOut
*/
protected final CompletableFuture<Optional<Request>> sendMessage(@NotNull OnlineUser sender, @NotNull Request request) {
return dispatchMessage(sender, request)
.orTimeout(MESSAGE_TIME_OUT, TimeUnit.SECONDS)
.exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Message dispatch after " + MESSAGE_TIME_OUT + " seconds", e);
return null;
})
.thenApply(result -> {
processingMessages.remove(request.getUuid());
return Optional.ofNullable(result);
});
}
/**
* Dispatch a {@link Request} via the appropriate handler
*
* @param sender The {@link OnlineUser} that sent the {@link Request}
* @param request The {@link Request} to dispatch
* @return A future containing a reply to the {@link Request} that was sent
*/
protected abstract CompletableFuture<Request> dispatchMessage(@NotNull OnlineUser sender, @NotNull Request request);
/**
* Send a reply to a received {@link Request}
*
* @param reply The reply {@link Request} to send
*/
protected abstract void sendReply(@NotNull OnlineUser replier, @NotNull Request reply);
/**
* Handle and action received network {@link Request}s
*
* @param receiver The online {@link OnlineUser} receiving the message
* @param request The received {@link Request}
*/
protected final void handleMessage(@NotNull OnlineUser receiver, @NotNull Request request) {
switch (request.getRelayType()) {
// Handle a message and send reply
case MESSAGE -> handleRequest(receiver, request);
// Handle a reply message
case REPLY -> {
if (processingMessages.containsKey(request.getUuid())) {
final Request finalRequest = request;
processingMessages.get(request.getUuid()).completeAsync(() -> finalRequest);
return;
}
plugin.getLoggingAdapter().log(Level.WARNING, "Received a reply to a message that was not sent by this server");
}
}
}
/**
* Handle different message types, executed needed operations and dispatches a reply message
* to the sender
*
* @param receiver The {@link OnlineUser} receiving the message
* @param request The received {@link Request}
*/
private void handleRequest(@NotNull OnlineUser receiver, @NotNull Request request) {
switch (request.getType()) {
case TELEPORT_TO_POSITION_REQUEST -> {
if (request.getPayload().position != null) {
Teleport.builder(plugin, receiver)
.setTarget(request.getPayload().position).toTeleport()
.thenAccept(teleport -> teleport.execute()
.thenAccept(result -> request.reply(receiver,
Payload.withTeleportResult(result.getState()), plugin)));
return;
}
request.reply(receiver, Payload.empty(), plugin);
}
case POSITION_REQUEST -> request.reply(receiver, Payload.withPosition(receiver.getPosition()), plugin);
case TELEPORT_REQUEST -> {
if (request.getPayload().teleportRequest != null) {
request.reply(receiver, plugin.getRequestManager()
.sendLocalTeleportRequest(request.getPayload().teleportRequest, receiver)
.map(Payload::withTeleportRequest)
.orElse(Payload.empty()), plugin);
return;
}
request.reply(receiver, Payload.empty(), plugin);
}
case TELEPORT_REQUEST_RESPONSE -> {
if (request.getPayload().teleportRequest != null) {
plugin.getRequestManager().handleLocalRequestResponse(receiver, request.getPayload().teleportRequest);
request.reply(receiver, plugin);
return;
}
request.reply(receiver, Payload.empty(), plugin);
}
}
}
/**
* Close the network messenger
*/
@Override
public abstract void close();
}
@@ -12,25 +12,16 @@ import org.jetbrains.annotations.Nullable;
*/
public class Payload {
/**
* A position field
*/
@Nullable
public Position position;
private Position position;
/**
* A teleport result field
*/
@Nullable
@SerializedName("teleport_result")
public TeleportResult resultState;
private TeleportResult resultState;
/**
* A teleport request field
*/
@Nullable
@SerializedName("teleport_request")
public TeleportRequest teleportRequest;
private TeleportRequest teleportRequest;
/**
* Returns an empty cross-server message payload
@@ -84,4 +75,27 @@ public class Payload {
private Payload() {
}
/**
* A position field
*/
@Nullable
public Position getPosition() {
return position;
}
/**
* A teleport result field
*/
@Nullable
public TeleportResult getResultState() {
return resultState;
}
/**
* A teleport request field
*/
@Nullable
public TeleportRequest getTeleportRequest() {
return teleportRequest;
}
}
@@ -0,0 +1,101 @@
package net.william278.huskhomes.network;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">Plugin Messaging channel</a> message
* broker implementation
*/
public class PluginMessageBroker extends Broker {
/**
* The name of BungeeCord's provided plugin channel.
*
* @implNote Technically, the effective identifier of this channel is {@code bungeecord:main}, but Spigot remaps
* {@code BungeeCord} automatically to the new one (<a href="https://wiki.vg/Plugin_channels#bungeecord:main">source</a>).
* Spigot's <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">official documentation</a>
* still instructs usage of {@code BungeeCord} as the name to use, however. It's all a bit inconsistent, so just in case
* it's best to leave it how it is for to maintain backwards compatibility.
*/
public static final String BUNGEE_CHANNEL_ID = "BungeeCord";
public PluginMessageBroker(@NotNull HuskHomes plugin) {
super(plugin);
}
@Override
public void initialize() throws RuntimeException {
plugin.initializePluginChannels();
}
@SuppressWarnings("UnstableApiUsage")
public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) {
if (!channel.equals(BUNGEE_CHANNEL_ID)) {
return;
}
final ByteArrayDataInput inputStream = ByteStreams.newDataInput(message);
final String subChannelId = inputStream.readUTF();
if (!subChannelId.equals(getSubChannelId())) {
return;
}
short messageLength = inputStream.readShort();
byte[] messageBody = new byte[messageLength];
inputStream.readFully(messageBody);
try (final DataInputStream messageReader = new DataInputStream(new ByteArrayInputStream(messageBody))) {
super.handle(user, plugin.getGson().fromJson(messageReader.readUTF(), Message.class));
} catch (IOException e) {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to fully read plugin message", e);
}
}
@Override
@SuppressWarnings("UnstableApiUsage")
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF("ForwardToPlayer");
messageWriter.writeUTF(message.getTarget());
messageWriter.writeUTF(getSubChannelId());
// Write the plugin message
try (final ByteArrayOutputStream messageByteStream = new ByteArrayOutputStream()) {
try (DataOutputStream messageDataStream = new DataOutputStream(messageByteStream)) {
messageDataStream.writeUTF(plugin.getGson().toJson(message));
messageWriter.writeShort(messageByteStream.toByteArray().length);
messageWriter.write(messageByteStream.toByteArray());
}
} catch (IOException e) {
plugin.getLoggingAdapter().log(Level.SEVERE, "Exception dispatching plugin message", e);
return;
}
sender.sendPluginMessage(BUNGEE_CHANNEL_ID, messageWriter.toByteArray());
}
@Override
@SuppressWarnings("UnstableApiUsage")
public void changeServer(@NotNull OnlineUser user, @NotNull String server) {
final ByteArrayDataOutput outputStream = ByteStreams.newDataOutput();
outputStream.writeUTF("Connect");
outputStream.writeUTF(server);
user.sendPluginMessage(BUNGEE_CHANNEL_ID, outputStream.toByteArray());
}
@Override
public void close() {
}
}
@@ -0,0 +1,77 @@
package net.william278.huskhomes.network;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
import java.util.logging.Level;
/**
* Redis message broker implementation
*/
public class RedisBroker extends PluginMessageBroker {
private JedisPool jedisPool;
public RedisBroker(@NotNull HuskHomes plugin) {
super(plugin);
}
@Override
public void initialize() throws RuntimeException {
super.initialize();
final String password = plugin.getSettings().getRedisPassword();
final String host = plugin.getSettings().getRedisHost();
final int port = plugin.getSettings().getRedisPort();
final boolean useSSL = plugin.getSettings().useRedisSsl();
this.jedisPool = password.isEmpty() ? new JedisPool(new JedisPoolConfig(), host, port, 0, useSSL)
: new JedisPool(new JedisPoolConfig(), host, port, 0, password, useSSL);
new Thread(getSubscriber(), plugin.getKey("redis_subscriber").toString()).start();
plugin.getLoggingAdapter().log(Level.INFO, "Initialized Redis connection pool");
}
@NotNull
private Runnable getSubscriber() {
return () -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(@NotNull String channel, @NotNull String encodedMessage) {
if (!channel.equals(getSubChannelId())) {
return;
}
final Message message = plugin.getGson().fromJson(encodedMessage, Message.class);
plugin.getOnlineUsers().stream()
.filter(online -> online.getUsername().equalsIgnoreCase(message.getTarget()))
.findFirst()
.ifPresent(receiver -> handle(receiver, message));
}
}, getSubChannelId());
}
};
}
@Override
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(getSubChannelId(), plugin.getGson().toJson(message));
}
}
@Override
public void close() {
super.close();
if (jedisPool != null) {
jedisPool.close();
}
}
}
@@ -1,185 +0,0 @@
package net.william278.huskhomes.network;
import com.google.gson.*;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* A message sent cross-proxy to a player
*/
public class Request {
/**
* A unique ID representing this message
*/
@NotNull
@Expose
private UUID uuid;
/**
* The type of the message
*/
@NotNull
@Expose
private MessageType type;
/**
* Represents the context under which this message is being relayed; an outbound {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to one.
*/
@SerializedName("relay_type")
@NotNull
@Expose
private RelayType relayType;
/**
* Username of the target player the message is bound for
*/
@SerializedName("target_player")
@NotNull
@Expose
private String targetPlayer;
/**
* ID of the cluster this message is for
*/
@SerializedName("cluster_id")
@NotNull
@Expose
private String clusterId;
/**
* Data to send in the message
*/
@NotNull
@Expose
private Payload payload;
/**
* Username of the sender of the message
*/
@NotNull
@Expose
private String sender;
protected Request(@NotNull MessageType type, @NotNull String targetPlayer, @NotNull Payload payload,
@NotNull Request.RelayType relayType) {
this.type = type;
this.targetPlayer = targetPlayer;
this.payload = payload;
this.relayType = relayType;
this.uuid = UUID.randomUUID();
}
@SuppressWarnings("unused")
private Request() {
}
@NotNull
public static RequestBuilder builder() {
return new RequestBuilder();
}
@NotNull
public String toJson() {
return new GsonBuilder().create().toJson(this);
}
@NotNull
public static Request fromJson(@NotNull String json) {
return new GsonBuilder().create().fromJson(json, Request.class);
}
/**
* Identifies the type of message or reply
*/
public enum MessageType {
TELEPORT_TO_POSITION_REQUEST,
POSITION_REQUEST,
TELEPORT_REQUEST,
TELEPORT_REQUEST_RESPONSE
}
/**
* Identifies the source of the message being relayed - a {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to a message.
*/
public enum RelayType {
/**
* An outbound message to/from a server
*/
MESSAGE,
/**
* A reply to an outbound message
*/
REPLY
}
@NotNull
public UUID getUuid() {
return uuid;
}
@NotNull
public MessageType getType() {
return type;
}
@NotNull
public RelayType getRelayType() {
return relayType;
}
@NotNull
public String getTargetPlayer() {
return targetPlayer;
}
@NotNull
public String getSender() {
return sender;
}
@NotNull
public String getClusterId() {
return clusterId;
}
@NotNull
public Payload getPayload() {
return payload;
}
public CompletableFuture<Optional<Request>> send(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) {
this.sender = sender.username;
this.clusterId = plugin.getSettings().getClusterId();
return plugin.getMessenger().sendMessage(sender, this);
}
public void reply(@NotNull OnlineUser sender, @NotNull Payload payload, @NotNull HuskHomes plugin) {
this.targetPlayer = this.sender;
this.sender = sender.username;
this.clusterId = plugin.getSettings().getClusterId();
this.payload = payload;
this.relayType = RelayType.REPLY;
plugin.getMessenger().sendReply(sender, this);
}
public void reply(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) {
this.reply(sender, this.payload, plugin);
}
@Override
public boolean equals(@NotNull Object other) {
if (other instanceof Request request) {
return request.uuid.equals(this.uuid);
}
return super.equals(other);
}
}
@@ -1,40 +0,0 @@
package net.william278.huskhomes.network;
import org.jetbrains.annotations.NotNull;
public class RequestBuilder {
private Request.MessageType type;
private String targetPlayer;
@NotNull
private Payload payload = Payload.empty();
protected RequestBuilder() {
}
@NotNull
public RequestBuilder withType(Request.MessageType type) {
this.type = type;
return this;
}
@NotNull
public RequestBuilder withTargetPlayer(String targetPlayer) {
this.targetPlayer = targetPlayer;
return this;
}
@NotNull
public RequestBuilder withPayload(Payload payload) {
this.payload = payload;
return this;
}
@NotNull
public Request build() {
return new Request(type, targetPlayer, payload, Request.RelayType.MESSAGE);
}
}
@@ -1,6 +1,6 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@@ -10,15 +10,15 @@ import java.util.UUID;
*/
public class Position extends Location {
private Server server;
private String server;
public Position(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server) {
@NotNull World world, @NotNull String server) {
super(x, y, z, yaw, pitch, world);
this.setServer(server);
}
public Position(@NotNull Location location, @NotNull Server server) {
public Position(@NotNull Location location, @NotNull String server) {
super(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), location.getWorld());
this.setServer(server);
}
@@ -61,7 +61,7 @@ public class Position extends Location {
final double y = parseCoordinate(args[1], relativeTo.getY());
final double z = parseCoordinate(args[2], relativeTo.getZ());
final World world = args.length > 3 ? new World(args[3], UUID.randomUUID()) : relativeTo.getWorld();
final Server server = args.length > 4 ? new Server(args[4]) : relativeTo.getServer();
final String server = args.length > 4 ? args[4] : relativeTo.getServer();
return Optional.of(new Position(x, y, z, relativeTo.getYaw(), relativeTo.getPitch(), world, server));
} catch (NumberFormatException ignored) {
return Optional.empty();
@@ -90,13 +90,14 @@ public class Position extends Location {
}
/**
* The {@link Server} the position is on
* The name of the server the position is on
*/
public Server getServer() {
@NotNull
public String getServer() {
return server;
}
public void setServer(Server server) {
public void setServer(@NotNull String server) {
this.server = server;
}
}
@@ -1,6 +1,6 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
@@ -1,64 +0,0 @@
package net.william278.huskhomes.redis;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.network.Request;
import net.william278.huskhomes.network.Messenger;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.concurrent.CompletableFuture;
/**
* Handles Redis database pub/sub network messaging requests over Jedis
*/
public class RedisWorker {
public String host;
public int port;
public String password;
public boolean ssl;
public JedisPool jedisPool;
public RedisWorker(@NotNull Settings settings) {
this.host = settings.getRedisHost();
this.port = settings.getRedisPort();
this.password = settings.getRedisPassword() != null ? settings.getRedisPassword() : "";
this.ssl = settings.isRedisUseSsl() && !(this.host.equalsIgnoreCase("localhost")
|| this.host.equalsIgnoreCase("127.0.0.1"));
}
/**
* Initialize the JedisPool connection
*/
public void initialize() {
if (password.isEmpty()) {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, ssl);
} else {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, password, ssl);
}
}
public CompletableFuture<Void> sendMessage(@NotNull Request request) {
return CompletableFuture.runAsync(() -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(Messenger.NETWORK_MESSAGE_CHANNEL, request.toJson());
}
});
}
/**
* Close the JedisPool connection
*/
public void terminate() {
if (jedisPool != null) {
if (!jedisPool.isClosed()) {
jedisPool.close();
}
}
}
}
@@ -3,8 +3,8 @@ package net.william278.huskhomes.request;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.network.Request;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
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;
@@ -45,9 +45,9 @@ public class RequestManager {
*/
public void setIgnoringRequests(@NotNull User user, boolean ignoring) {
if (ignoring) {
this.ignoringRequests.add(user.uuid);
this.ignoringRequests.add(user.getUuid());
} else {
this.ignoringRequests.remove(user.uuid);
this.ignoringRequests.remove(user.getUuid());
}
}
@@ -58,7 +58,7 @@ public class RequestManager {
* @return {@code true} if the user is ignoring tpa requests
*/
public boolean isIgnoringRequests(@NotNull User user) {
return this.ignoringRequests.contains(user.uuid);
return this.ignoringRequests.contains(user.getUuid());
}
/**
@@ -68,7 +68,7 @@ public class RequestManager {
* @param recipient the {@link User} recipient of the request
*/
public void addTeleportRequest(@NotNull TeleportRequest request, @NotNull User recipient) {
this.requests.computeIfAbsent(recipient.uuid, uuid -> new LinkedList<>()).addFirst(request);
this.requests.computeIfAbsent(recipient.getUuid(), uuid -> new LinkedList<>()).addFirst(request);
}
/**
@@ -78,7 +78,7 @@ public class RequestManager {
* @param recipient the {@link User} recipient of the request
*/
public void removeTeleportRequest(@NotNull String requesterName, @NotNull User recipient) {
this.requests.computeIfPresent(recipient.uuid, (uuid, requests) -> {
this.requests.computeIfPresent(recipient.getUuid(), (uuid, requests) -> {
requests.removeIf(teleportRequest -> teleportRequest.requesterName.equalsIgnoreCase(requesterName));
return requests.isEmpty() ? null : requests;
});
@@ -91,7 +91,7 @@ public class RequestManager {
* @return the last received request, if present
*/
public Optional<TeleportRequest> getLastTeleportRequest(@NotNull User recipient) {
return this.requests.getOrDefault(recipient.uuid, new LinkedList<>()).stream().findFirst();
return this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream().findFirst();
}
/**
@@ -106,11 +106,11 @@ public class RequestManager {
* @return the last unexpired teleport request received from the requester, if present
*/
public Optional<TeleportRequest> getTeleportRequest(@NotNull String requesterName, @NotNull User recipient) {
return this.requests.getOrDefault(recipient.uuid, new LinkedList<>()).stream()
return this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream()
.filter(request -> request.requesterName.equalsIgnoreCase(requesterName))
.filter(request -> !request.hasExpired())
.findFirst()
.or(() -> this.requests.getOrDefault(recipient.uuid, new LinkedList<>()).stream()
.or(() -> this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream()
.filter(request -> request.requesterName.equalsIgnoreCase(requesterName))
.findFirst());
}
@@ -133,7 +133,7 @@ public class RequestManager {
if (localTarget.get().equals(requester)) {
return CompletableFuture.completedFuture(Optional.empty());
}
request.recipientName = localTarget.get().username;
request.recipientName = localTarget.get().getUsername();
return CompletableFuture.completedFuture(sendLocalTeleportRequest(request, localTarget.get()));
}
@@ -154,7 +154,7 @@ public class RequestManager {
.build().send(requester, plugin)
.thenApply(reply -> {
if (reply.isPresent()) {
final TeleportRequest result = reply.get().getPayload().teleportRequest;
final TeleportRequest result = reply.get().getPayload().getTeleportRequest();
if (result == null || result.status == TeleportRequest.RequestStatus.IGNORED) {
return null;
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.request;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
@@ -53,7 +53,7 @@ public class TeleportRequest {
*/
protected TeleportRequest(@NotNull OnlineUser requester, @NotNull RequestType requestType,
final long expiryTime) {
this.requesterName = requester.username;
this.requesterName = requester.getUsername();
this.requesterPosition = requester.getPosition();
this.type = requestType;
this.status = RequestStatus.PENDING;
@@ -1,8 +1,8 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
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;
@@ -2,18 +2,18 @@ package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.network.Request;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
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.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
/**
* Represents a teleport in the process of being executed
@@ -55,10 +55,10 @@ public class Teleport {
public final TeleportType type;
/**
* {@link Settings.EconomyAction}s to be checked against the {@link #executor executor}'s balance
* {@link EconomyHook.EconomyAction}s to be checked against the {@link #executor executor}'s balance
*/
@NotNull
public final Set<Settings.EconomyAction> economyActions;
public final Set<EconomyHook.EconomyAction> economyActions;
/**
* Whether to update the {@link #teleporter teleporter}'s last position (i.e. their {@code /back} position)
@@ -69,7 +69,7 @@ public class Teleport {
* <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<Settings.EconomyAction> economyActions,
@NotNull TeleportType type, @NotNull Set<EconomyHook.EconomyAction> economyActions,
final boolean updateLastPosition, @NotNull HuskHomes plugin) {
this.teleporter = teleporter;
this.executor = executor;
@@ -112,7 +112,7 @@ public class Teleport {
}
// Check economy actions
for (Settings.EconomyAction economyAction : economyActions) {
for (EconomyHook.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
@@ -183,20 +183,9 @@ public class Teleport {
}
// If the target position is on another server, execute a cross-server teleport
final CompletableFuture<TeleportResult> teleportFuture = new CompletableFuture<>();
plugin.getDatabase().setCurrentTeleport(teleporter, this);
plugin.getMessenger()
.sendPlayer(teleporter, target.getServer())
.thenApply(completed -> completed
? TeleportResult.COMPLETED_CROSS_SERVER
: TeleportResult.FAILED_INVALID_SERVER)
.orTimeout(10, TimeUnit.SECONDS)
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Cross-server teleport timed out for " + teleporter.username);
plugin.getDatabase().setCurrentTeleport(teleporter, null);
return TeleportResult.FAILED_INVALID_SERVER;
});
return teleportFuture;
plugin.getMessenger().changeServer(teleporter, target.getServer());
return CompletableFuture.completedFuture(TeleportResult.COMPLETED_CROSS_SERVER);
}
/**
@@ -212,20 +201,13 @@ public class Teleport {
assert teleporter != null;
// Send a network message to a user on another server to teleport them to the target position
return Request.builder()
.withType(Request.MessageType.TELEPORT_TO_POSITION_REQUEST)
.withPayload(Payload.withPosition(target))
.withTargetPlayer(teleporter.username)
.build().send(executor, plugin)
.thenApply(result -> {
if (result.isPresent()) {
final Request reply = result.get();
if (reply.getPayload().resultState != null) {
return reply.getPayload().resultState;
}
}
return TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED;
});
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));
}
}
@@ -1,10 +1,10 @@
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.Request;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
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;
@@ -43,12 +43,12 @@ public class TeleportBuilder {
private CompletableFuture<Position> target;
/**
* List of {@link Settings.EconomyAction}s to check against.
* 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<Settings.EconomyAction> economyActions = new HashSet<>();
private final Set<EconomyHook.EconomyAction> economyActions = new HashSet<>();
/**
* The type of teleport. Defaults to {@link TeleportType#TELEPORT}
@@ -85,18 +85,7 @@ public class TeleportBuilder {
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTeleporter(@NotNull String teleporterUsername) {
this.teleporter = CompletableFuture.supplyAsync(() -> plugin
.findOnlinePlayer(teleporterUsername)
.map(onlineUser -> (User) onlineUser)
.or(() -> {
if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger()
.findPlayer(executor, teleporterUsername).join()
.map(username -> new User(UUID.randomUUID(), username));
}
return Optional.empty();
})
.orElse(null));
this.teleporter = teleporterUsername;
return this;
}
@@ -148,12 +137,12 @@ public class TeleportBuilder {
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link Settings.EconomyAction}s to check against
* @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<Settings.EconomyAction> economyActions) {
public TeleportBuilder setEconomyActions(@NotNull Set<EconomyHook.EconomyAction> economyActions) {
this.economyActions.addAll(economyActions);
return this;
}
@@ -161,12 +150,12 @@ public class TeleportBuilder {
/**
* Set the economy actions to check against during the teleport
*
* @param economyActions The {@link Settings.EconomyAction}s to check against
* @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 Settings.EconomyAction... economyActions) {
public TeleportBuilder setEconomyActions(@NotNull EconomyHook.EconomyAction... economyActions) {
this.economyActions.addAll(Arrays.asList(economyActions));
return this;
}
@@ -243,7 +232,7 @@ public class TeleportBuilder {
.withType(Request.MessageType.POSITION_REQUEST)
.withTargetPlayer(playerName)
.build().send(executor, plugin)
.thenApply(reply -> reply.map(message -> message.getPayload().position)).join();
.thenApply(reply -> reply.map(message -> message.getPayload().getPosition())).join();
});
}
return CompletableFuture.supplyAsync(Optional::empty);
@@ -1,7 +1,7 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
@@ -3,7 +3,8 @@ package net.william278.huskhomes.teleport;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -24,7 +25,7 @@ public class TimedTeleport extends Teleport {
private boolean cancelled = false;
protected TimedTeleport(@NotNull OnlineUser teleporter, @NotNull OnlineUser executor, @NotNull Position target,
@NotNull TeleportType type, int warmupTime, @NotNull Set<Settings.EconomyAction> economyActions,
@NotNull TeleportType type, int warmupTime, @NotNull Set<EconomyHook.EconomyAction> economyActions,
final boolean updateLastPosition, @NotNull HuskHomes plugin) {
super(teleporter, executor, target, type, economyActions, updateLastPosition, plugin);
this.plugin = plugin;
@@ -53,13 +54,13 @@ public class TimedTeleport extends Teleport {
}
// Check if the teleporter is already warming up to teleport
if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.uuid)) {
if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.getUuid())) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
// Check economy actions
for (Settings.EconomyAction economyAction : economyActions) {
for (EconomyHook.EconomyAction economyAction : economyActions) {
if (!plugin.validateEconomyCheck(executor, economyAction)) {
return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
@@ -98,7 +99,7 @@ public class TimedTeleport extends Teleport {
}
// Mark the player as warming up and display the message
plugin.getCache().getCurrentlyOnWarmup().add(teleporter.uuid);
plugin.getCache().getCurrentlyOnWarmup().add(teleporter.getUuid());
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft))
.ifPresent(teleporter::sendMessage);
@@ -118,7 +119,7 @@ public class TimedTeleport extends Teleport {
// Tick (decrement) the timed teleport timer and end it if done
if (tickWarmup()) {
plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.uuid);
plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.getUuid());
timedTeleportFuture.complete(null);
executor.shutdown();
}
@@ -1,4 +1,4 @@
package net.william278.huskhomes.player;
package net.william278.huskhomes.user;
import de.themoep.minedown.adventure.MineDown;
import de.themoep.minedown.adventure.MineDownParser;
@@ -11,8 +11,6 @@ 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.util.Permission;
import org.intellij.lang.annotations.Pattern;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
@@ -28,7 +26,6 @@ public abstract class OnlineUser extends User {
super(uuid, username);
}
/**
* Returns the current {@link Position} of this player
*
@@ -146,6 +143,13 @@ public abstract class OnlineUser extends User {
*/
public abstract CompletableFuture<TeleportResult> teleportLocally(@NotNull Location location, boolean asynchronous);
/**
* Send a plugin message to the user
* @param channel channel to send it on
* @param message byte array of message data
*/
public abstract void sendPluginMessage(@NotNull String channel, byte[] message);
/**
* Returns if a player is moving (i.e. they have momentum)
*
@@ -1,4 +1,4 @@
package net.william278.huskhomes.player;
package net.william278.huskhomes.user;
import org.jetbrains.annotations.NotNull;
@@ -10,10 +10,10 @@ import java.util.UUID;
public class User {
@NotNull
public final UUID uuid;
private final UUID uuid;
@NotNull
public final String username;
private final String username;
/**
* Get a user from a {@link UUID} and username
@@ -29,8 +29,18 @@ public class User {
@Override
public boolean equals(@NotNull Object obj) {
if (obj instanceof User user) {
return user.uuid.equals(uuid);
return user.getUuid().equals(getUuid());
}
return super.equals(obj);
}
@NotNull
public UUID getUuid() {
return uuid;
}
@NotNull
public String getUsername() {
return username;
}
}
@@ -1,4 +1,4 @@
package net.william278.huskhomes.player;
package net.william278.huskhomes.user;
import org.jetbrains.annotations.NotNull;
@@ -12,11 +12,11 @@ public record UserData(@NotNull User user, int homeSlots, boolean ignoringTelepo
@NotNull
public UUID getUserUuid() {
return user.uuid;
return user.getUuid();
}
public String getUsername() {
return user.username;
return user.getUsername();
}
}