From fc8d3b0098f5758ff5e0044f32e3d2268b4f8055 Mon Sep 17 00:00:00 2001 From: William Date: Fri, 16 Jun 2023 17:39:54 +0100 Subject: [PATCH] Add ability to define cooldowns for actions (#437) --- .../william278/huskhomes/user/BukkitUser.java | 4 +- .../huskhomes/api/BaseHuskHomesAPI.java | 61 +- .../huskhomes/command/BackCommand.java | 6 +- .../huskhomes/command/EditHomeCommand.java | 6 +- .../huskhomes/command/HomeCommand.java | 4 +- .../huskhomes/command/RtpCommand.java | 30 +- .../command/SavedPositionCommand.java | 8 +- .../huskhomes/command/SpawnCommand.java | 6 +- .../command/TeleportRequestCommand.java | 6 +- .../huskhomes/command/TpAllCommand.java | 2 +- .../huskhomes/command/TpCommand.java | 4 +- .../huskhomes/command/TpHereCommand.java | 2 +- .../huskhomes/command/TpOfflineCommand.java | 2 +- .../huskhomes/command/WarpCommand.java | 4 +- .../william278/huskhomes/config/Locales.java | 3 +- .../william278/huskhomes/config/Settings.java | 119 +++- .../huskhomes/database/Database.java | 63 +- .../huskhomes/database/MySqlDatabase.java | 77 ++- .../huskhomes/database/SqLiteDatabase.java | 560 +++++++++--------- .../huskhomes/hook/EconomyHook.java | 79 ++- .../huskhomes/listener/EventListener.java | 72 +-- .../huskhomes/manager/HomesManager.java | 8 +- .../huskhomes/manager/RequestsManager.java | 12 +- .../william278/huskhomes/network/Broker.java | 2 +- .../huskhomes/teleport/Teleport.java | 40 +- .../huskhomes/teleport/TeleportBuilder.java | 26 +- .../teleport/TeleportationException.java | 14 +- .../huskhomes/teleport/TimedTeleport.java | 12 +- .../william278/huskhomes/user/SavedUser.java | 37 +- .../huskhomes/util/TransactionResolver.java | 168 +++++- .../huskhomes/util/ValidationException.java | 2 +- .../main/resources/database/mysql_schema.sql | 15 +- .../main/resources/database/sqlite_schema.sql | 14 +- common/src/main/resources/locales/bg-bg.yml | 2 +- common/src/main/resources/locales/de-de.yml | 2 +- common/src/main/resources/locales/en-gb.yml | 2 +- common/src/main/resources/locales/es-es.yml | 2 +- common/src/main/resources/locales/it-it.yml | 2 +- common/src/main/resources/locales/ja-jp.yml | 88 +-- common/src/main/resources/locales/pl-pl.yml | 2 +- common/src/main/resources/locales/tr-tr.yml | 2 +- common/src/main/resources/locales/uk-ua.yml | 2 +- common/src/main/resources/locales/zh-cn.yml | 2 +- common/src/main/resources/locales/zh-tw.yml | 2 +- docs/Commands.md | 18 +- docs/Config-Files.md | 78 ++- docs/Cooldowns.md | 46 ++ docs/Economy-Hook.md | 35 +- docs/Home.md | 1 + docs/_Sidebar.md | 1 + .../william278/huskhomes/user/FabricUser.java | 2 +- gradle.properties | 2 +- 52 files changed, 1140 insertions(+), 619 deletions(-) create mode 100644 docs/Cooldowns.md diff --git a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java index a5ba00d4..c1ae4fde 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java +++ b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java @@ -108,13 +108,13 @@ public class BukkitUser extends OnlineUser { // Ensure the world exists final Optional resolvedLocation = BukkitAdapter.adaptLocation(location); if (resolvedLocation.isEmpty() || resolvedLocation.get().getWorld() == null) { - throw new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND); + throw new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND, plugin); } // Ensure the coordinates are within the world limits final org.bukkit.Location bukkitLocation = resolvedLocation.get(); if (!bukkitLocation.getWorld().getWorldBorder().isInside(resolvedLocation.get())) { - throw new TeleportationException(TeleportationException.Type.ILLEGAL_TARGET_COORDINATES); + throw new TeleportationException(TeleportationException.Type.ILLEGAL_TARGET_COORDINATES, plugin); } // Run on the appropriate thread scheduler for this platform diff --git a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index 3119a067..b5399b85 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -32,8 +32,11 @@ import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; +import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -84,6 +87,58 @@ public abstract class BaseHuskHomesAPI { return plugin.supplyAsync(() -> plugin.getDatabase().getUserDataByName(username)); } + /** + * Get the timestamp of when a user's cooldown for performing an {@link TransactionResolver.Action action} expires + * + * @param user The {@link User} to get data for. + * @param action The {@link TransactionResolver.Action} to get the cooldown for + * @return An {@link Optional} containing the {@link Instant} the cooldown expires, if there is one + * @since 4.4 + */ + public final CompletableFuture> getCooldown(@NotNull User user, @NotNull TransactionResolver.Action action) { + return plugin.supplyAsync(() -> plugin.getDatabase().getCooldown(action, user)); + } + + /** + * Set a cooldown for a user performing an {@link TransactionResolver.Action action} + * + * @param user The {@link User} to set data for. + * @param action The {@link TransactionResolver.Action} to set the cooldown for + * @param expiry The {@link Instant} the cooldown expires + * @throws IllegalArgumentException if the expiry is in the past + * @since 4.4 + */ + public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action, @NotNull Instant expiry) throws IllegalArgumentException { + if (Instant.now().isAfter(expiry)) { + throw new IllegalArgumentException("Cooldown expiry time must be in the future"); + } + plugin.runAsync(() -> plugin.getDatabase().setCooldown(action, user, expiry)); + } + + /** + * Set a cooldown for a user performing an {@link TransactionResolver.Action action} + * + * @param user The {@link User} to set data for. + * @param action The {@link TransactionResolver.Action} to set the cooldown for + * @param duration The {@link Duration} the cooldown lasts for + * @throws IllegalArgumentException if the duration is negative + * @since 4.4 + */ + public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action, @NotNull Duration duration) throws IllegalArgumentException { + this.setCooldown(user, action, Instant.now().plus(duration)); + } + + /** + * Remove a cooldown for a user performing an {@link TransactionResolver.Action action} + * + * @param user The {@link User} to remove the cooldown for + * @param action The {@link TransactionResolver.Action} to remove the cooldown for + * @since 4.4 + */ + public final void removeCooldown(@NotNull User user, @NotNull TransactionResolver.Action action) { + plugin.runAsync(() -> plugin.getDatabase().removeCooldown(action, user)); + } + /** * Returns the last position, as used in the {@code /back} command, for this user * @@ -94,11 +149,11 @@ public abstract class BaseHuskHomesAPI { public CompletableFuture> getUserLastPosition(@NotNull User user) { return plugin.supplyAsync(() -> plugin.getDatabase().getLastPosition(user)); } - + /** * Set the last {@link Position}, as used in the {@code /back} command, for this user * - * @param user The {@link User} to set the last position for + * @param user The {@link User} to set the last position for * @param position The {@link Position} to set as the user's last position * @since 4.2.1 */ @@ -687,7 +742,7 @@ public abstract class BaseHuskHomesAPI { builder.toTeleport().execute(); } } catch (TeleportationException e) { - e.displayMessage(user, plugin, rtpArgs); + e.displayMessage(user, rtpArgs); } }).exceptionally(e -> { throw new IllegalStateException("Random teleport engine threw an exception", e); diff --git a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java index ffe7bd42..c29fa099 100644 --- a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java @@ -20,11 +20,11 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -54,12 +54,12 @@ public class BackCommand extends InGameCommand { Teleport.builder(plugin) .teleporter(executor) .target(lastPosition.get()) - .economyActions(EconomyHook.Action.BACK_COMMAND) + .actions(TransactionResolver.Action.BACK_COMMAND) .type(Teleport.Type.BACK) .toTimedTeleport() .execute(); } catch (TeleportationException e) { - e.displayMessage(executor, plugin, args); + e.displayMessage(executor, args); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java index 22c23f32..60235b39 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -21,10 +21,10 @@ package net.william278.huskhomes.command; import de.themoep.minedown.adventure.MineDown; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; @@ -171,7 +171,7 @@ public class EditHomeCommand extends SavedPositionCommand { } // Check against economy - if (executor instanceof OnlineUser user && !plugin.canPerformTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC)) { + if (executor instanceof OnlineUser user && !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) { return; } @@ -191,7 +191,7 @@ public class EditHomeCommand extends SavedPositionCommand { // Perform transaction if (executor instanceof OnlineUser user) { - plugin.performTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC); + plugin.performTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC); } final String privacy = home.isPublic() ? "public" : "private"; diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java index ecceafc4..041d064a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -20,11 +20,11 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.teleport.Teleportable; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -56,7 +56,7 @@ public abstract class HomeCommand extends SavedPositionCommand { this.teleport( executor, optionalTeleporter.get(), home, (executor instanceof OnlineUser user && home.getOwner().equals(user) - ? EconomyHook.Action.HOME_TELEPORT : EconomyHook.Action.PUBLIC_HOME_TELEPORT) + ? TransactionResolver.Action.HOME_TELEPORT : TransactionResolver.Action.PUBLIC_HOME_TELEPORT) ); } diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index 814794dd..3da5f311 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -20,19 +20,16 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.SavedUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.Optional; @@ -43,8 +40,7 @@ public class RtpCommand extends Command implements UserListTabProvider { super("rtp", List.of(), "[player] [world]", plugin); addAdditionalPermissions(Map.of( "other", true, - "world", true, - "bypass_cooldown", true + "world", true )); } @@ -100,7 +96,7 @@ public class RtpCommand extends Command implements UserListTabProvider { } // Check they have sufficient funds - if (!plugin.canPerformTransaction(teleporter, EconomyHook.Action.RANDOM_TELEPORT)) { + if (!plugin.validateTransaction(teleporter, TransactionResolver.Action.RANDOM_TELEPORT)) { return Optional.empty(); } @@ -127,18 +123,6 @@ public class RtpCommand extends Command implements UserListTabProvider { return Optional.empty(); } - // Check they are not on random teleport cooldown - final SavedUser user = plugin.getSavedUser(teleporter) - .orElseThrow(() -> new IllegalStateException("No user data found for " + teleporter.getUsername())); - final Instant currentTime = Instant.now(); - if (executor.equals(teleporter) && !currentTime.isAfter(user.getRtpCooldown()) && - !executor.hasPermission(getPermission("bypass_cooldown"))) { - plugin.getLocales().getLocale("error_rtp_cooldown", Long.toString( - currentTime.until(user.getRtpCooldown(), ChronoUnit.MINUTES) + 1) - ).ifPresent(executor::sendMessage); - return Optional.empty(); - } - return Optional.of(world); } @@ -167,6 +151,7 @@ public class RtpCommand extends Command implements UserListTabProvider { // Build and execute the teleport final TeleportBuilder builder = Teleport.builder(plugin) .teleporter(teleporter) + .actions(TransactionResolver.Action.RANDOM_TELEPORT) .target(position.get()); try { if (executor.equals(teleporter)) { @@ -175,13 +160,8 @@ public class RtpCommand extends Command implements UserListTabProvider { builder.toTeleport().execute(); } } catch (TeleportationException e) { - e.displayMessage(executor, plugin, args); - return; + e.displayMessage(executor, args); } - - // Update their RTP cooldown - plugin.editUserData(teleporter, (SavedUser saved) -> saved.setRtpCooldown(Instant.now() - .plus(plugin.getSettings().getRtpCooldownLength(), ChronoUnit.MINUTES))); }); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index 3edb3f4c..35ef518a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -20,7 +20,6 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.SavedPosition; import net.william278.huskhomes.position.Warp; @@ -31,6 +30,7 @@ import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -158,7 +158,7 @@ public abstract class SavedPositionCommand extends Comm } protected void teleport(@NotNull CommandUser executor, @NotNull Teleportable teleporter, @NotNull T position, - @NotNull EconomyHook.Action... economyActions) { + @NotNull TransactionResolver.Action... actions) { if (!teleporter.equals(executor) && !executor.hasPermission(getPermission("other"))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); @@ -167,7 +167,7 @@ public abstract class SavedPositionCommand extends Comm final TeleportBuilder builder = Teleport.builder(plugin) .teleporter(teleporter) - .economyActions(economyActions) + .actions(actions) .target(position); try { if (executor.equals(teleporter)) { @@ -176,7 +176,7 @@ public abstract class SavedPositionCommand extends Comm builder.toTeleport().execute(); } } catch (TeleportationException e) { - e.displayMessage(executor, plugin, teleporter.getUsername()); + e.displayMessage(executor, teleporter.getUsername()); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java index 3db24bd2..a44da280 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java @@ -20,13 +20,13 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.teleport.Teleportable; import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -69,7 +69,7 @@ public class SpawnCommand extends Command { final TeleportBuilder builder = Teleport.builder(plugin) .teleporter(teleporter) - .economyActions(EconomyHook.Action.SPAWN_TELEPORT) + .actions(TransactionResolver.Action.SPAWN_TELEPORT) .target(spawn); try { if (teleporter.equals(executor)) { @@ -78,7 +78,7 @@ public class SpawnCommand extends Command { builder.toTeleport().execute(); } } catch (TeleportationException e) { - e.displayMessage(executor, plugin, args); + e.displayMessage(executor, args); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java b/common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java index bef5a644..53ab499b 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java @@ -20,10 +20,10 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.manager.RequestsManager; import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -63,7 +63,7 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab } // Validate economy check - if (!plugin.canPerformTransaction(onlineUser, EconomyHook.Action.SEND_TELEPORT_REQUEST)) { + if (!plugin.validateTransaction(onlineUser, TransactionResolver.Action.SEND_TELEPORT_REQUEST)) { return; } @@ -75,7 +75,7 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab return; } - plugin.performTransaction(onlineUser, EconomyHook.Action.SEND_TELEPORT_REQUEST); + plugin.performTransaction(onlineUser, TransactionResolver.Action.SEND_TELEPORT_REQUEST); plugin.getLocales() .getLocale((requestType == TeleportRequest.Type.TPA ? "tpa" : "tpahere") + "_request_sent", target) diff --git a/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java index 815204be..971d1144 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java @@ -54,7 +54,7 @@ public class TpAllCommand extends InGameCommand { .toTeleport().execute(); } } catch (TeleportationException e) { - e.displayMessage(executor, plugin, args); + e.displayMessage(executor, args); return; } diff --git a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java index 7ac90cef..6a4b76c8 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -94,11 +94,11 @@ public class TpCommand extends Command implements TabProvider { } builder.toTeleport().execute(); } catch (TeleportationException e) { - e.displayMessage(executor, plugin, args); + e.displayMessage(executor, args); return; } - // Display teleport completion message + // Display a teleport completion message final String teleporterName = teleportable instanceof OnlineUser user ? user.getUsername() : ((Username) teleportable).name(); if (target instanceof Position position) { diff --git a/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java index 6fb66d75..9cbaa958 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java @@ -54,7 +54,7 @@ public class TpHereCommand extends InGameCommand implements UserListTabProvider plugin.getLocales().getLocale("teleporting_other_complete", optionalTarget.get(), executor.getUsername()); } catch (TeleportationException e) { - e.displayMessage(executor, plugin, args); + e.displayMessage(executor, args); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java index 38bbe1fd..ab3dae9a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java @@ -75,7 +75,7 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid .target(position.get()) .toTeleport().execute(); } catch (TeleportationException e) { - e.displayMessage(user, plugin, args); + e.displayMessage(user, args); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index f2c07e3f..2ce4141b 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -20,10 +20,10 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.teleport.Teleportable; import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -62,6 +62,6 @@ public class WarpCommand extends SavedPositionCommand { return; } - this.teleport(executor, optionalTeleporter.get(), warp, EconomyHook.Action.WARP_TELEPORT); + this.teleport(executor, optionalTeleporter.get(), warp, TransactionResolver.Action.WARP_TELEPORT); } } diff --git a/common/src/main/java/net/william278/huskhomes/config/Locales.java b/common/src/main/java/net/william278/huskhomes/config/Locales.java index 56e13eb9..c3666594 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Locales.java +++ b/common/src/main/java/net/william278/huskhomes/config/Locales.java @@ -195,7 +195,8 @@ public class Locales { CHAT, ACTION_BAR, SUBTITLE, - TITLE + TITLE, + NONE } } diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index 5e93a47e..50e35462 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -24,9 +24,9 @@ import net.william278.annotaml.YamlFile; import net.william278.annotaml.YamlKey; import net.william278.huskhomes.command.Command; import net.william278.huskhomes.database.Database; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.position.World; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -40,24 +40,26 @@ import java.util.stream.Collectors; ┃ HuskHomes Config ┃ ┃ Developed by William278 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ - ┣╸ Information: https://william278.net/project/huskhomes - ┗╸ Documentation: https://william278.net/docs/huskhomes""", - - versionField = "config_version", versionNumber = 11) + ┣╸ Information: https://william278.net/project/huskhomes/ + ┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/ + ┗╸ Documentation: https://william278.net/docs/huskhomes/""") public class Settings { // Top-level settings + @YamlComment("Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations") @YamlKey("language") private String language = "en-gb"; + @YamlComment("Whether to automatically check for plugin updates on startup") @YamlKey("check_for_updates") private boolean checkForUpdates = true; // Database settings - @YamlComment("Database connection settings") + @YamlComment("Type of database to use (MYSQL, SQLITE)") @YamlKey("database.type") private Database.Type databaseType = Database.Type.SQLITE; + @YamlComment("Specify credentials here if you are using MYSQL as your database type") @YamlKey("database.mysql.credentials.host") private String mySqlHost = "localhost"; @@ -76,7 +78,7 @@ public class Settings { @YamlKey("database.mysql.credentials.parameters") private String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"; - @YamlComment("MySQL connection pool properties") + @YamlComment("MYSQL database Hikari connection pool properties. Don't modify this unless you know what you're doing!") @YamlKey("database.mysql.connection_pool.size") private int mySqlConnectionPoolSize = 12; @@ -92,9 +94,11 @@ public class Settings { @YamlKey("database.mysql.connection_pool.timeout") private long mySqlConnectionPoolTimeout = 20000; + @YamlComment("Names of tables to use on your database. Don't modify this unless you know what you're doing!") @YamlKey("database.table_names") private Map tableNames = Map.of( Database.Table.PLAYER_DATA.name().toLowerCase(), Database.Table.PLAYER_DATA.getDefaultName(), + Database.Table.PLAYER_COOLDOWNS_DATA.name().toLowerCase(), Database.Table.PLAYER_COOLDOWNS_DATA.getDefaultName(), Database.Table.POSITION_DATA.name().toLowerCase(), Database.Table.POSITION_DATA.getDefaultName(), Database.Table.SAVED_POSITION_DATA.name().toLowerCase(), Database.Table.SAVED_POSITION_DATA.getDefaultName(), Database.Table.HOME_DATA.name().toLowerCase(), Database.Table.HOME_DATA.getDefaultName(), @@ -102,64 +106,77 @@ public class Settings { Database.Table.TELEPORT_DATA.name().toLowerCase(), Database.Table.TELEPORT_DATA.getDefaultName() ); - @NotNull - public String getTableName(@NotNull Database.Table table) { - return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getDefaultName()); - } - // General settings - @YamlComment("General plugin settings") + @YamlComment("The maximum homes a user can create. Override with the huskhomes.max_homes. permission.") @YamlKey("general.max_homes") private int maxHomes = 10; + @YamlComment("The maximum public homes a user can create. Override with the huskhomes.max_public_homes. permission.") @YamlKey("general.max_public_homes") private int maxPublicHomes = 10; + @YamlComment("Whether permission limits (i.e. huskhomes.max_homes.) should stack if the user inherits multiple nodes.") @YamlKey("general.stack_permission_limits") private boolean stackPermissionLimits = false; + @YamlComment("Whether users require a permission (huskhomes.command.warp.) to use warps") @YamlKey("general.permission_restrict_warps") private boolean permissionRestrictWarps = false; + @YamlComment("Whether running /sethome or /setwarp when a home/warp already exists should overwrite it.") @YamlKey("general.overwrite_existing_homes_warps") private boolean overwriteExistingHomesWarps = true; + @YamlComment("How long a player has to stand still and not take damage for when teleporting (in seconds) ") @YamlKey("general.teleport_warmup_time") private int teleportWarmupTime = 5; + @YamlComment("Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE)") @YamlKey("general.teleport_warmup_display") private Locales.DisplaySlot teleportWarmupDisplay = Locales.DisplaySlot.ACTION_BAR; + @YamlComment("How long before received teleport requests expire (in seconds)") @YamlKey("general.teleport_request_expiry_time") private int teleportRequestExpiryTime = 60; + + @YamlComment("Whether /tpahere should use the location of the sender when sent. Docs: https://william278.net/docs/huskhomes/strict-tpahere/") @YamlKey("general.strict_tpa_here_requests") private boolean strictTpaHereRequests = true; + @YamlComment("Whether home or warp names should be case insensitive (i.e. allow /home HomeOne and /home homeone)") @YamlKey("general.case_insensitive_names") private boolean caseInsensitiveNames = false; + @YamlComment("Whether home or warp names should allow UTF-8 characters (i.e. allow /home 你好)") @YamlKey("general.allow_unicode_names") private boolean allowUnicodeNames = false; + @YamlComment("Whether home or warp descriptions should allow UTF-8 characters") @YamlKey("general.allow_unicode_descriptions") private boolean allowUnicodeDescriptions = true; + @YamlComment("Whether /back should work to teleport the user to where they died") @YamlKey("general.back_command_return_by_death") private boolean backCommandReturnByDeath = true; + @YamlComment("Whether /back should work with other plugins that use the PlayerTeleportEvent (this can cause conflicts)") @YamlKey("general.back_command_save_teleport_event") private boolean backCommandSaveOnTeleportEvent = false; + @YamlComment("How many items should be displayed per-page in chat menu lists") @YamlKey("general.list_items_per_page") private int listItemsPerPage = 12; + @YamlComment("Whether teleportation should be carried out asynchronously (ensuring chunks load before teleporting)") @YamlKey("general.asynchronous_teleports") private boolean asynchronousTeleports = true; + @YamlComment("Whether to play sound effects") @YamlKey("general.play_sound_effects") private boolean playSoundEffects = true; + @YamlComment("Which sound effects to play for various actions") @YamlKey("general.sound_effects") private Map soundEffects = Map.of( SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect, @@ -168,30 +185,37 @@ public class Settings { SoundEffectAction.TELEPORT_REQUEST_RECEIVED.name().toLowerCase(), SoundEffectAction.TELEPORT_REQUEST_RECEIVED.defaultSoundEffect ); + @YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)") @YamlKey("general.brigadier_tab_completion") private boolean brigadierTabCompletion = true; // Cross-server settings - @YamlComment("Enable teleporting across proxied servers. Requires MySQL") + @YamlComment("Enable teleporting across your proxy network. Requires database type to be MYSQL") @YamlKey("cross_server.enabled") private boolean crossServer = false; + @YamlComment("The type of message broker to use for cross-server communication. Options: PLUGIN_MESSAGE, REDIS") @YamlKey("cross_server.messenger_type") private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE; + @YamlComment("Specify a common ID for grouping servers running HuskHomes on your proxy. Don't modify this unless you know what you're doing!") @YamlKey("cross_server.cluster_id") private String clusterId = ""; + @YamlComment("Define a single global /spawn for your network via a warp. Docs: https://william278.net/docs/huskhomes/global-spawn/") @YamlKey("cross_server.global_spawn.enabled") private boolean globalSpawn = false; + @YamlComment("The name of the warp to use as the global spawn.") @YamlKey("cross_server.global_spawn.warp_name") private String globalSpawnName = "Spawn"; + @YamlComment("Whether player respawn positions should work cross-server. Docs: https://william278.net/docs/huskhomes/global-respawning/") @YamlKey("cross_server.global_respawning") private boolean globalRespawning = false; + @YamlComment("Specify credentials here if you are using REDIS as your messenger_type. Docs: https://william278.net/docs/huskhomes/redis-support/") @YamlKey("cross_server.redis_credentials.host") private String redisHost = "localhost"; @@ -206,28 +230,44 @@ public class Settings { // Rtp command settings - @YamlComment("Random teleport (/rtp) command settings") - @YamlKey("rtp.cooldown_length") - private int rtpCooldownLength = 10; - + @YamlComment("Radius around the spawn point in which players cannot be random teleported to") @YamlKey("rtp.radius") private int rtpRadius = 5000; + @YamlComment("Radius of the spawn area in which players cannot be random teleported to") @YamlKey("rtp.spawn_radius") private int rtpSpawnRadius = 500; + @YamlComment("Mean of the normal distribution used to calculate the distance from the center of the world") @YamlKey("rtp.distribution_mean") private float rtpDistributionMean = 0.75f; + @YamlComment("Standard deviation of the normal distribution used to calculate the distance from the center of the world") @YamlKey("rtp.distribution_deviation") private float rtpDistributionStandardDeviation = 2f; + @YamlComment("List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether.") @YamlKey("rtp.restricted_worlds") private List rtpRestrictedWorlds = List.of("world_nether", "world_the_end"); + // Cooldown settings + @YamlComment("Whether to apply a cooldown between performing certain actions") + @YamlKey("cooldowns.enabled") + private boolean cooldowns = true; + + @YamlComment("Set a cooldown between performing actions (in seconds). Docs: https://william278.net/docs/huskhomes/cooldowns/") + @YamlKey("cooldowns.cooldown_times") + private Map cooldownTimes = Arrays.stream(TransactionResolver.Action.values()) + .filter(action -> action.getDefaultCooldown() > 0) + .collect(Collectors.toMap( + action -> action.name().toLowerCase(Locale.ENGLISH), + TransactionResolver.Action::getDefaultCooldown) + ); + + // Economy settings - @YamlComment("Charge for certain actions (requires Vault)") + @YamlComment("Enable economy plugin integration (requires Vault)") @YamlKey("economy.enabled") private boolean economy = false; @@ -235,35 +275,39 @@ public class Settings { @YamlKey("economy.redis_economy_name") private String redisEconomyName = "vault"; + @YamlComment("Specify how many homes players can set for free, before they need to pay for more slots") @YamlKey("economy.free_home_slots") private int freeHomeSlots = 5; - @YamlComment("Require money to perform certain actions. Check https://william278.net/docs/huskhomes/economy-hook for available actions") + @YamlComment("Charge money for perform certain actions. Docs: https://william278.net/docs/huskhomes/economy-hook/") @YamlKey("economy.costs") - private Map economyCosts = Arrays.stream(EconomyHook.Action.values()) + private Map economyCosts = Arrays.stream(TransactionResolver.Action.values()) .filter(action -> action.getDefaultCost() > 0) .collect(Collectors.toMap( action -> action.name().toLowerCase(Locale.ENGLISH), - EconomyHook.Action::getDefaultCost) + TransactionResolver.Action::getDefaultCost) ); // Mapping plugins - @YamlComment("Display public homes/warps on your web map (supports Dynmap and BlueMap)") + @YamlComment("Display public homes/warps on your Dynmap, BlueMap or Pl3xMap. Docs: https://william278.net/docs/huskhomes/map-hooks") @YamlKey("map_hook.enabled") private boolean doMapHook = true; + @YamlComment("Show public homes on the web map") @YamlKey("map_hook.show_public_homes") private boolean publicHomesOnMap = true; + @YamlComment("Show warps on the web map") @YamlKey("map_hook.show_warps") private boolean warpsOnMap = true; // Disabled commands - @YamlComment("Disabled commands (e.g. ['/home', '/warp'] to disable /home and /warp)") + @YamlComment("List of commands to disable (e.g. ['/home', '/warp'] to disable /home and /warp)") @YamlKey("disabled_commands") private List disabledCommands = Collections.emptyList(); + @SuppressWarnings("unused") private Settings() { } @@ -328,6 +372,11 @@ public class Settings { return tableNames; } + @NotNull + public String getTableName(@NotNull Database.Table table) { + return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getDefaultName()); + } + public int getMaxHomes() { return maxHomes; } @@ -443,9 +492,6 @@ public class Settings { return redisUseSsl; } - public int getRtpCooldownLength() { - return rtpCooldownLength; - } public int getRtpRadius() { return rtpRadius; @@ -471,6 +517,21 @@ public class Settings { .anyMatch(name -> name.equalsIgnoreCase(filteredName)); } + public boolean doCooldowns() { + return cooldowns; + } + + public long getCooldown(@NotNull TransactionResolver.Action action) { + if (!doCooldowns()) { + return 0; + } + final Integer cooldown = cooldownTimes.get(action.name().toLowerCase(Locale.ENGLISH)); + if (cooldown != null && cooldown > 0) { + return cooldown; + } + return 0; + } + public boolean doEconomy() { return economy; } @@ -483,7 +544,7 @@ public class Settings { return freeHomeSlots; } - public Optional getEconomyCost(@NotNull EconomyHook.Action action) { + public Optional getEconomyCost(@NotNull TransactionResolver.Action action) { if (!doEconomy()) { return Optional.empty(); } @@ -519,7 +580,7 @@ public class Settings { } /** - * Represents the sound effect to play when an action happens + * Represents actions that have a sound effect associated with performing them */ public enum SoundEffectAction { TELEPORTATION_COMPLETE("entity.enderman.teleport"), diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index 310246d1..ce22c9d6 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -29,6 +29,7 @@ import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,6 +37,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; +import java.time.Instant; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -75,6 +77,7 @@ public abstract class Database { return sql .replaceAll("%positions_table%", plugin.getSettings().getTableName(Table.POSITION_DATA)) .replaceAll("%players_table%", plugin.getSettings().getTableName(Table.PLAYER_DATA)) + .replaceAll("%cooldowns_table%", plugin.getSettings().getTableName(Table.PLAYER_COOLDOWNS_DATA)) .replaceAll("%teleports_table%", plugin.getSettings().getTableName(Table.TELEPORT_DATA)) .replaceAll("%saved_positions_table%", plugin.getSettings().getTableName(Table.SAVED_POSITION_DATA)) .replaceAll("%homes_table%", plugin.getSettings().getTableName(Table.HOME_DATA)) @@ -146,7 +149,7 @@ public abstract class Database { * Get {@link SavedUser} for a user by their Minecraft username (case-insensitive) * * @param name Username of the {@link SavedUser} to get (case-insensitive) - * @return A future returning an optional with the {@link SavedUser} present if they exist + * @return An optional with the {@link SavedUser} present if they exist */ public abstract Optional getUserDataByName(@NotNull String name); @@ -154,10 +157,33 @@ public abstract class Database { * Get {@link SavedUser} for a user by their Minecraft account {@link UUID} * * @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get - * @return A future returning an optional with the {@link SavedUser} present if they exist + * @return An optional with the {@link SavedUser} present if they exist */ public abstract Optional getUserData(@NotNull UUID uuid); + /** + * Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action} + * + * @return An optional containing the {@link Instant} the cooldown expires at, or empty if the {@link User} has no cooldown + */ + public abstract Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user); + + /** + * Set the cooldown of a {@link User} for a specific {@link TransactionResolver.Action} + * + * @param action The {@link TransactionResolver.Action} to set the cooldown for + * @param user The {@link User} to set the cooldown for + * @param cooldownExpiry The {@link Instant} the cooldown expires at + */ + public abstract void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry); + + /** + * Remove the cooldown of a {@link User} for a specific {@link TransactionResolver.Action} + * + * @param action The {@link TransactionResolver.Action} to remove the cooldown for + * @param user The {@link User} to remove the cooldown for + */ + public abstract void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user); /** * Get a list of {@link Home}s set by a {@link User} @@ -170,7 +196,7 @@ public abstract class Database { /** * Get a list of all {@link Warp}s that have been set * - * @return A future returning a list containing all {@link Warp}s + * @return A list containing all {@link Warp}s */ public abstract List getWarps(); @@ -178,7 +204,7 @@ public abstract class Database { * Get a list of publicly-set {@link Warp}s on this {@link Server} * * @param plugin The plugin instance - * @return A future returning a list containing all {@link Warp}s set on this server + * @return A list containing all {@link Warp}s set on this server */ @NotNull public final List getLocalWarps(@NotNull HuskHomes plugin) { @@ -190,7 +216,7 @@ public abstract class Database { /** * Get a list of all publicly-set {@link Home}s * - * @return A future returning a list containing all publicly-set {@link Home}s + * @return A list containing all publicly-set {@link Home}s */ public abstract List getPublicHomes(); @@ -198,7 +224,7 @@ public abstract class Database { * Get a list of publicly-set {@link Home}s on this {@link Server} * * @param plugin The plugin instance - * @return A future returning a list containing all publicly-set {@link Home}s on this server + * @return A list containing all publicly-set {@link Home}s on this server */ @NotNull public final List getLocalPublicHomes(@NotNull HuskHomes plugin) { @@ -212,7 +238,7 @@ public abstract class Database { * * @param user The {@link User} who set the home * @param homeName The name of the home to get - * @return A future returning an optional with the {@link Home} present if it exists + * @return An optional with the {@link Home} present if it exists * @apiNote Whether the name lookup query is case-insensitive is determined by the {@code general.case_insensitive_names} setting */ public final Optional getHome(@NotNull User user, @NotNull String homeName) { @@ -225,7 +251,7 @@ public abstract class Database { * @param user The {@link User} who set the home * @param homeName The name of the home to get * @param caseInsensitive Whether the name lookup query should be case-insensitive - * @return A future returning an optional with the {@link Home} present if it exists + * @return An optional with the {@link Home} present if it exists */ public abstract Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive); @@ -233,7 +259,7 @@ public abstract class Database { * Get a {@link Home} by its unique id * * @param uuid the {@link UUID} of the home to get - * @return A future returning an optional with the {@link Home} present if it exists + * @return An optional with the {@link Home} present if it exists */ public abstract Optional getHome(@NotNull UUID uuid); @@ -241,7 +267,7 @@ public abstract class Database { * Get a {@link Warp} with the given name * * @param warpName The name of the warp to get - * @return A future returning an optional with the {@link Warp} present if it exists + * @return An optional with the {@link Warp} present if it exists * @apiNote Whether the name lookup query is case-insensitive is determined by the {@code general.case_insensitive_names} setting */ public final Optional getWarp(@NotNull String warpName) { @@ -253,7 +279,7 @@ public abstract class Database { * * @param warpName The name of the warp to get * @param caseInsensitive Whether the search should be case-insensitive - * @return A future returning an optional with the {@link Warp} present if it exists + * @return An optional with the {@link Warp} present if it exists */ public abstract Optional getWarp(@NotNull String warpName, boolean caseInsensitive); @@ -261,7 +287,7 @@ public abstract class Database { * Get a {@link Warp} by its unique id * * @param uuid the {@link UUID} of the warp to get - * @return A future returning an optional with the {@link Warp} present if it exists + * @return An optional with the {@link Warp} present if it exists */ public abstract Optional getWarp(@NotNull UUID uuid); @@ -269,7 +295,7 @@ public abstract class Database { * Get the current {@link Teleport} being executed by the specified {@link OnlineUser} * * @param onlineUser The {@link OnlineUser} to check - * @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server + * @return An optional with the {@link Teleport} present if they are teleporting cross-server */ public abstract Optional getCurrentTeleport(@NotNull OnlineUser onlineUser); @@ -302,7 +328,7 @@ public abstract class Database { * Get the last teleport {@link Position} of a specified {@link User} * * @param user The {@link User} to check - * @return A future returning an optional with the {@link Position} present if it has been set + * @return An optional with the {@link Position} present if it has been set */ public abstract Optional getLastPosition(@NotNull User user); @@ -318,7 +344,7 @@ public abstract class Database { * Get the offline {@link Position} of a specified {@link User} * * @param user The {@link User} to check - * @return A future returning an optional with the {@link Position} present if it has been set + * @return An optional with the {@link Position} present if it has been set */ public abstract Optional getOfflinePosition(@NotNull User user); @@ -334,7 +360,7 @@ public abstract class Database { * Get the respawn {@link Position} of a specified {@link User} * * @param user The {@link User} to check - * @return A future returning an optional with the {@link Position} present if it has been set + * @return An optional with the {@link Position} present if it has been set */ public abstract Optional getRespawnPosition(@NotNull User user); @@ -372,7 +398,7 @@ public abstract class Database { * Deletes all {@link Home}s of a {@link User} from the home table on the database. * * @param user The {@link User} to delete all homes of - * @return A future returning an integer; the number of deleted homes + * @return An integer; the number of deleted homes */ public abstract int deleteAllHomes(@NotNull User user); @@ -386,7 +412,7 @@ public abstract class Database { /** * Deletes all {@link Warp}s set on the database table * - * @return A future returning an integer; the number of deleted warps + * @return An integer; the number of deleted warps */ public abstract int deleteAllWarps(); @@ -420,6 +446,7 @@ public abstract class Database { */ public enum Table { PLAYER_DATA("huskhomes_users"), + PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"), POSITION_DATA("huskhomes_position_data"), SAVED_POSITION_DATA("huskhomes_saved_positions"), HOME_DATA("huskhomes_homes"), diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index 7c5de930..3db9dbae 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -27,11 +27,13 @@ import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.sql.*; +import java.time.Instant; import java.util.*; import java.util.logging.Level; @@ -258,7 +260,7 @@ public class MySqlDatabase extends Database { public Optional getUserDataByName(@NotNull String name) { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, FROM `%players_table%` WHERE `username`=?"""))) { statement.setString(1, name); @@ -269,8 +271,8 @@ public class MySqlDatabase extends Database { User.of(UUID.fromString(resultSet.getString("uuid")), resultSet.getString("username")), resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); + resultSet.getBoolean("ignoring_requests") + )); } } } catch (SQLException e) { @@ -283,7 +285,7 @@ public class MySqlDatabase extends Database { public Optional getUserData(@NotNull UUID uuid) { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` FROM `%players_table%` WHERE `uuid`=?"""))) { @@ -295,8 +297,8 @@ public class MySqlDatabase extends Database { User.of(UUID.fromString(resultSet.getString("uuid")), resultSet.getString("username")), resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); + resultSet.getBoolean("ignoring_requests") + )); } } } catch (SQLException e) { @@ -305,6 +307,62 @@ public class MySqlDatabase extends Database { return Optional.empty(); } + @Override + public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `type`, `start_timestamp`, `end_timestamp` + FROM `%cooldowns_table%` + WHERE `player_uuid`=? AND `type`=? + ORDER BY `start_timestamp` DESC + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(resultSet.getTimestamp("end_timestamp").toInstant()); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a player's cooldown from the database", e); + } + return Optional.empty(); + } + + @Override + public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) + VALUES (?,?,?,?);"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + statement.setTimestamp(3, Timestamp.from(Instant.now())); + statement.setTimestamp(4, Timestamp.from(cooldownExpiry)); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to set a player's cooldown in the database", e); + } + } + + @Override + public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%cooldowns_table%` + WHERE `player_uuid`=? AND `type`=?;"""))) { + + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to remove a player's cooldown from the database", e); + } + } + @Override public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); @@ -598,7 +656,7 @@ public class MySqlDatabase extends Database { } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); } catch (TeleportationException e) { - e.displayMessage(onlineUser, plugin); + e.displayMessage(onlineUser); } return Optional.empty(); } @@ -608,13 +666,12 @@ public class MySqlDatabase extends Database { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" UPDATE `%players_table%` - SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? + SET `home_slots`=?, `ignoring_requests`=? WHERE `uuid`=?"""))) { statement.setInt(1, savedUser.getHomeSlots()); statement.setBoolean(2, savedUser.isIgnoringTeleports()); - statement.setTimestamp(3, Timestamp.from(savedUser.getRtpCooldown())); - statement.setString(4, savedUser.getUserUuid().toString()); + statement.setString(3, savedUser.getUserUuid().toString()); statement.executeUpdate(); } } catch (SQLException e) { diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index c21eae59..9c4adc45 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -26,6 +26,7 @@ import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.sqlite.SQLiteConfig; @@ -33,10 +34,8 @@ import org.sqlite.SQLiteConfig; import java.io.File; import java.io.IOException; import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; +import java.time.Instant; +import java.util.*; import java.util.logging.Level; /** @@ -232,16 +231,14 @@ public class SqLiteDatabase extends Database { 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(""" - UPDATE `%players_table%` - SET `username`=? - WHERE `uuid`=?"""))) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `username`=? + WHERE `uuid`=?"""))) { - statement.setString(1, onlineUser.getUsername()); - statement.setString(2, existingUser.getUserUuid().toString()); - statement.executeUpdate(); - } + statement.setString(1, onlineUser.getUsername()); + statement.setString(2, existingUser.getUserUuid().toString()); + statement.executeUpdate(); plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.getUsername() + ")"); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); @@ -250,15 +247,14 @@ public class SqLiteDatabase extends Database { }, () -> { // Insert new player data into the database - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%players_table%` (`uuid`,`username`) - VALUES (?,?);"""))) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + INSERT INTO `%players_table%` (`uuid`,`username`) + VALUES (?,?);"""))) { + + statement.setString(1, onlineUser.getUuid().toString()); + statement.setString(2, onlineUser.getUsername()); + statement.executeUpdate(); - statement.setString(1, onlineUser.getUuid().toString()); - statement.setString(2, onlineUser.getUsername()); - statement.executeUpdate(); - } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to insert a player into the database", e); } @@ -267,22 +263,20 @@ public class SqLiteDatabase extends Database { @Override public Optional getUserDataByName(@NotNull String name) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` - FROM `%players_table%` - WHERE `username`=?"""))) { - statement.setString(1, name); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` + FROM `%players_table%` + WHERE `username`=?"""))) { + statement.setString(1, name); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new SavedUser( - User.of(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username")), - resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new SavedUser( + User.of(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests") + )); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to fetch a player by name from the database", e); @@ -292,23 +286,21 @@ public class SqLiteDatabase extends Database { @Override public Optional getUserData(@NotNull UUID uuid) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` - FROM `%players_table%` - WHERE `uuid`=?"""))) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` + FROM `%players_table%` + WHERE `uuid`=?"""))) { - statement.setString(1, uuid.toString()); + statement.setString(1, uuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new SavedUser( - User.of(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username")), - resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new SavedUser( + User.of(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests") + )); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); @@ -316,40 +308,87 @@ public class SqLiteDatabase extends Database { return Optional.empty(); } + @Override + public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `type`, `start_timestamp`, `end_timestamp` + FROM `%cooldowns_table%` + WHERE `player_uuid`=? AND `type`=? + ORDER BY `start_timestamp` DESC + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(resultSet.getTimestamp("end_timestamp").toInstant()); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a player's cooldown from the database", e); + } + return Optional.empty(); + } + + @Override + public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%cooldowns_table%` + WHERE `player_uuid`=? AND `type`=?;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + statement.executeUpdate(); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to remove a player's cooldown from the database", e); + } + } + + @Override + public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) + VALUES (?,?,?,?);"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + statement.setTimestamp(3, Timestamp.from(Instant.now())); + statement.setTimestamp(4, Timestamp.from(cooldownExpiry)); + statement.executeUpdate(); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to set a player's cooldown in the database", e); + } + } + @Override public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - ORDER BY `name`;"""))) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + ORDER BY `name`;"""))) { + statement.setString(1, user.getUuid().toString()); - statement.setString(1, user.getUuid().toString()); - - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - userHomes.add(Home.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - user, - resultSet.getBoolean("public"))); - } + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); } + } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); } @@ -359,30 +398,28 @@ public class SqLiteDatabase extends Database { @Override public List getWarps() { final List warps = new ArrayList<>(); - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - ORDER BY `name`;"""))) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + ORDER BY `name`;"""))) { - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - warps.add(Warp.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + warps.add(Warp.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query the database for warp data."); @@ -393,36 +430,35 @@ public class SqLiteDatabase extends Database { @Override public List getPublicHomes() { final List userHomes = new ArrayList<>(); - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `public`=true - ORDER BY `name`;"""))) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `public`=true + ORDER BY `name`;"""))) { - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - userHomes.add(Home.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - User.of(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + User.of(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); } + } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query the database for public home data"); } @@ -431,38 +467,36 @@ public class SqLiteDatabase extends Database { @Override public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { - statement.setString(1, user.getUuid().toString()); - statement.setBoolean(2, caseInsensitive); - statement.setString(3, homeName); - statement.setString(4, homeName); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setBoolean(2, caseInsensitive); + statement.setString(3, homeName); + statement.setString(4, homeName); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(Home.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - user, - resultSet.getBoolean("public"))); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query a player's home", e); @@ -472,35 +506,33 @@ public class SqLiteDatabase extends Database { @Override public Optional getHome(@NotNull UUID uuid) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `%homes_table%`.`uuid`=?;"""))) { - statement.setString(1, uuid.toString()); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `%homes_table%`.`uuid`=?;"""))) { + statement.setString(1, uuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(Home.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - User.of(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + User.of(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query a player's home by uuid", e); @@ -510,33 +542,31 @@ public class SqLiteDatabase extends Database { @Override public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { - statement.setBoolean(1, caseInsensitive); - statement.setString(2, warpName); - statement.setString(3, warpName); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { + statement.setBoolean(1, caseInsensitive); + statement.setString(2, warpName); + statement.setString(3, warpName); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(Warp.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Warp.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query a server warp", e); @@ -546,31 +576,29 @@ public class SqLiteDatabase extends Database { @Override public Optional getWarp(@NotNull UUID uuid) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `%warps_table%`.uuid=?;"""))) { - statement.setString(1, uuid.toString()); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + WHERE `%warps_table%`.uuid=?;"""))) { + statement.setString(1, uuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(Warp.from(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - World.from(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - resultSet.getString("server_name"), - PositionMeta.from(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Warp.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query a server warp", e); @@ -580,7 +608,6 @@ public class SqLiteDatabase extends Database { @Override public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` FROM `%teleports_table%` @@ -605,11 +632,10 @@ public class SqLiteDatabase extends Database { .updateLastPosition(false) .toTeleport()); } - } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); } catch (TeleportationException e) { - e.displayMessage(onlineUser, plugin); + e.displayMessage(onlineUser); } return Optional.empty(); } @@ -618,13 +644,12 @@ public class SqLiteDatabase extends Database { public void updateUserData(@NotNull SavedUser savedUser) { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" UPDATE `%players_table%` - SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? + SET `home_slots`=?, `ignoring_requests`=? WHERE `uuid`=?"""))) { statement.setInt(1, savedUser.getHomeSlots()); statement.setBoolean(2, savedUser.isIgnoringTeleports()); - statement.setTimestamp(3, Timestamp.from(savedUser.getRtpCooldown())); - statement.setString(4, savedUser.getUserUuid().toString()); + statement.setString(3, savedUser.getUserUuid().toString()); statement.executeUpdate(); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); @@ -634,17 +659,15 @@ public class SqLiteDatabase extends Database { @Override public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { // Clear the user's current teleport - try { - try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `id`=( - SELECT `destination_id` - FROM `%teleports_table%` - WHERE `%teleports_table%`.`player_uuid`=? - );"""))) { - deleteStatement.setString(1, user.getUuid().toString()); - deleteStatement.executeUpdate(); - } + try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `destination_id` + FROM `%teleports_table%` + WHERE `%teleports_table%`.`player_uuid`=? + );"""))) { + deleteStatement.setString(1, user.getUuid().toString()); + deleteStatement.executeUpdate(); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); } @@ -657,9 +680,7 @@ public class SqLiteDatabase extends Database { statement.setString(1, user.getUuid().toString()); statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); statement.setInt(3, teleport.getType().getTypeId()); - statement.executeUpdate(); - } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to set the current teleport of " + user.getUsername(), e); } @@ -694,7 +715,6 @@ public class SqLiteDatabase extends Database { @Override public void setLastPosition(@NotNull User user, @NotNull Position position) { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" SELECT `last_position` FROM `%players_table%` INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` @@ -716,7 +736,6 @@ public class SqLiteDatabase extends Database { updateStatement.executeUpdate(); } } - } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); } @@ -724,7 +743,6 @@ public class SqLiteDatabase extends Database { @Override public Optional getOfflinePosition(@NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` FROM `%players_table%` @@ -900,16 +918,14 @@ public class SqLiteDatabase extends Database { public void saveWarp(@NotNull Warp warp) { getWarp(warp.getUuid()) .ifPresentOrElse(presentWarp -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%warps_table%` - WHERE `uuid`=?;"""))) { - statement.setString(1, warp.getUuid().toString()); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `saved_position_id` FROM `%warps_table%` + WHERE `uuid`=?;"""))) { + statement.setString(1, warp.getUuid().toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - updateSavedPosition(resultSet.getInt("saved_position_id"), warp, connection); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + updateSavedPosition(resultSet.getInt("saved_position_id"), warp, connection); } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update a warp in the database", e); @@ -942,9 +958,7 @@ public class SqLiteDatabase extends Database { ) );"""))) { statement.setString(1, uuid.toString()); - statement.executeUpdate(); - } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete a home from the database", e); } diff --git a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java index 525e72af..1003dfaf 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java @@ -22,6 +22,7 @@ package net.william278.huskhomes.hook; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.Locale; @@ -31,8 +32,6 @@ import java.util.Locale; */ public abstract class EconomyHook extends Hook { - public static final String BYPASS_PERMISSION = "huskhomes.bypass_economy_checks"; - protected EconomyHook(@NotNull HuskHomes plugin, @NotNull String hookName) { super(plugin, hookName); } @@ -69,7 +68,7 @@ public abstract class EconomyHook extends Hook { * @param plugin the plugin instance * @param action the action that was performed */ - public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull Action action) { + public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull TransactionResolver.Action action) { plugin.getSettings().getEconomyCost(action) .flatMap(cost -> plugin.getLocales().getLocale( "economy_transaction_complete", @@ -82,31 +81,37 @@ public abstract class EconomyHook extends Hook { } /** - * Identifies actions that have a price associated with performing them + * Send the player a message notifying them that they have been charged + * for performing an action + * + * @param user the user to notify + * @param plugin the plugin instance + * @param action the action that was performed + * @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead, + * using the new {@link TransactionResolver.Action} enum */ + @Deprecated(since = "4.4", forRemoval = true) + public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull Action action) { + this.notifyDeducted(user, plugin, action.getTransactionAction()); + } + + /** + * Economy actions for which a player can be charged + * + * @deprecated Use the new {@link TransactionResolver.Action} enum instead + */ + @Deprecated(since = "4.4", forRemoval = true) public enum Action { - - /* - * Home and public home slots - */ - ADDITIONAL_HOME_SLOT(100.00), - MAKE_HOME_PUBLIC(50.00), - BACK_COMMAND(0.00), - - /* - * Teleportation actions - */ - RANDOM_TELEPORT(25.00), - HOME_TELEPORT(0.00), - PUBLIC_HOME_TELEPORT(0.00), - WARP_TELEPORT(0.00), - SPAWN_TELEPORT(0.00), - - /* - * Teleport request actions - */ - SEND_TELEPORT_REQUEST(0.00), - ACCEPT_TELEPORT_REQUEST(0.00); + ADDITIONAL_HOME_SLOT(100d), + MAKE_HOME_PUBLIC(50d), + BACK_COMMAND, + RANDOM_TELEPORT(25d), + HOME_TELEPORT, + PUBLIC_HOME_TELEPORT, + WARP_TELEPORT, + SPAWN_TELEPORT, + SEND_TELEPORT_REQUEST, + ACCEPT_TELEPORT_REQUEST; private final double defaultCost; @@ -114,9 +119,31 @@ public abstract class EconomyHook extends Hook { this.defaultCost = defaultCost; } + Action() { + this(0d); + } + + /** + * Create an action with a default cost + * + * @return the default cost + * @deprecated Use the new {@link TransactionResolver.Action#getDefaultCost()} instead + */ + @Deprecated(since = "4.4", forRemoval = true) public double getDefaultCost() { return defaultCost; } + /** + * Translate this legacy Action to the new {@link TransactionResolver.Action} + * + * @return the equivalent {@link TransactionResolver.Action} + */ + @NotNull + public TransactionResolver.Action getTransactionAction() { + return TransactionResolver.Action.valueOf(this.name()); + } + } + } diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 34068c90..0f216074 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -90,6 +90,38 @@ public class EventListener { }); } + /** + * Handle when a {@link OnlineUser} leaves the server + * + * @param onlineUser the leaving {@link OnlineUser} + */ + protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) { + plugin.runAsync(() -> { + // Set offline position + plugin.getDatabase().setOfflinePosition(onlineUser, onlineUser.getPosition()); + + // Remove this user's home cache + plugin.getManager().homes().removeUserHomes(onlineUser); + + // Update global lists + if (plugin.getSettings().doCrossServer()) { + final List localPlayerList = plugin.getLocalPlayerList().stream() + .filter(player -> !player.equals(onlineUser.getUsername())) + .toList(); + + if (plugin.getSettings().getBrokerType() == Broker.Type.REDIS) { + this.synchronizeGlobalPlayerList(onlineUser, localPlayerList); + return; + } + + plugin.getOnlineUsers().stream() + .filter(user -> !user.equals(onlineUser)) + .findAny() + .ifPresent(player -> this.synchronizeGlobalPlayerList(player, localPlayerList)); + } + }); + } + /** * Handle inbound cross-server teleports * @@ -105,7 +137,7 @@ public class EventListener { try { teleporter.teleportLocally((Position) teleport.getTarget(), plugin.getSettings().doAsynchronousTeleports()); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); } plugin.getDatabase().clearCurrentTeleport(teleporter); teleport.displayTeleportingComplete(teleporter); @@ -130,14 +162,14 @@ public class EventListener { .updateLastPosition(false) .toTeleport().execute(); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); } }, 40L); } else { try { teleporter.teleportLocally(spawn, plugin.getSettings().doAsynchronousTeleports()); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); } } teleporter.sendTranslatableMessage("block.minecraft.spawn.not_valid"); @@ -146,43 +178,13 @@ public class EventListener { try { teleporter.teleportLocally(bedPosition.get(), plugin.getSettings().doAsynchronousTeleports()); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); } } plugin.getDatabase().clearCurrentTeleport(teleporter); plugin.getDatabase().setRespawnPosition(teleporter, bedPosition.orElse(null)); } - /** - * Handle when a {@link OnlineUser} leaves the server - * - * @param onlineUser the leaving {@link OnlineUser} - */ - protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) { - // Set offline position - plugin.getDatabase().setOfflinePosition(onlineUser, onlineUser.getPosition()); - - // Remove this user's home cache - plugin.getManager().homes().removeUserHomes(onlineUser); - - // Update global lists - if (plugin.getSettings().doCrossServer()) { - final List localPlayerList = plugin.getLocalPlayerList().stream() - .filter(player -> !player.equals(onlineUser.getUsername())) - .toList(); - - if (plugin.getSettings().getBrokerType() == Broker.Type.REDIS) { - this.synchronizeGlobalPlayerList(onlineUser, localPlayerList); - return; - } - - plugin.getOnlineUsers().stream() - .filter(user -> !user.equals(onlineUser)) - .findAny() - .ifPresent(player -> this.synchronizeGlobalPlayerList(player, localPlayerList)); - } - } - // Synchronize the global player list private void synchronizeGlobalPlayerList(@NotNull OnlineUser user, @NotNull List localPlayerList) { // Send this server's player list to all servers @@ -258,7 +260,7 @@ public class EventListener { try { builder.toTeleport().execute(); } catch (TeleportationException e) { - e.displayMessage(onlineUser, plugin); + e.displayMessage(onlineUser); } }); } diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index 878ca092..6a5feabf 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -21,7 +21,6 @@ package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.command.ListCommand; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; import net.william278.huskhomes.position.Home; @@ -30,6 +29,7 @@ import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -178,10 +178,10 @@ public class HomesManager { } // Perform transaction and increase user slot size - if (!plugin.canPerformTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT)) { - throw new ValidationException(ValidationException.Type.NOT_ENOUGH_MONEY); + if (!plugin.validateTransaction(online, TransactionResolver.Action.ADDITIONAL_HOME_SLOT)) { + throw new ValidationException(ValidationException.Type.TRANSACTION_FAILED); } - plugin.performTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT); + plugin.performTransaction(online, TransactionResolver.Action.ADDITIONAL_HOME_SLOT); plugin.editUserData(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1)); } diff --git a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index 3f20bdf4..e187fcbc 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -21,7 +21,6 @@ package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; import net.william278.huskhomes.teleport.Teleport; @@ -31,6 +30,7 @@ import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.time.Instant; @@ -257,7 +257,7 @@ public class RequestsManager { } // Validate the economy check - if (accepted && !plugin.canPerformTransaction(recipient, EconomyHook.Action.ACCEPT_TELEPORT_REQUEST)) { + if (accepted && !plugin.validateTransaction(recipient, TransactionResolver.Action.ACCEPT_TELEPORT_REQUEST)) { return; } @@ -308,7 +308,7 @@ public class RequestsManager { // If the request is a tpa here request, teleport the recipient to the sender if (accepted && request.getType() == TeleportRequest.Type.TPA_HERE) { final TeleportBuilder builder = Teleport.builder(plugin) - .economyActions(EconomyHook.Action.ACCEPT_TELEPORT_REQUEST) + .actions(TransactionResolver.Action.ACCEPT_TELEPORT_REQUEST) .teleporter(recipient); // Strict /tpahere requests will teleport to where the sender was when typing the command @@ -321,7 +321,7 @@ public class RequestsManager { try { builder.toTimedTeleport().execute(); } catch (TeleportationException e) { - e.displayMessage(recipient, plugin); + e.displayMessage(recipient); } } })); @@ -352,11 +352,11 @@ public class RequestsManager { Teleport.builder(plugin) .teleporter(requester) .target(request.getRecipientName()) - .economyActions(EconomyHook.Action.ACCEPT_TELEPORT_REQUEST) + .actions(TransactionResolver.Action.ACCEPT_TELEPORT_REQUEST) .toTimedTeleport() .execute(); } catch (TeleportationException e) { - e.displayMessage(requester, plugin); + e.displayMessage(requester); } } } diff --git a/common/src/main/java/net/william278/huskhomes/network/Broker.java b/common/src/main/java/net/william278/huskhomes/network/Broker.java index 5e47f2bd..16b0d2a1 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Broker.java +++ b/common/src/main/java/net/william278/huskhomes/network/Broker.java @@ -63,7 +63,7 @@ public abstract class Broker { .toTeleport() .execute(); } catch (TeleportationException e) { - e.displayMessage(plugin.getConsole(), plugin); + e.displayMessage(plugin.getConsole()); } }); case TELEPORT_TO_NETWORKED_POSITION -> Message.builder() diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java index 9afbee9b..333b46d0 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -24,11 +24,11 @@ import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.command.BackCommand; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.event.ITeleportEvent; -import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.Arrays; @@ -47,19 +47,19 @@ public class Teleport { protected final Teleportable teleporter; protected final Target target; protected final Type type; - protected final List economyActions; + protected final List actions; private final boolean async; protected final boolean updateLastPosition; protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target, - @NotNull Type type, boolean updateLastPosition, @NotNull List actions, + @NotNull Type type, boolean updateLastPosition, @NotNull List actions, @NotNull HuskHomes plugin) { this.plugin = plugin; this.executor = executor; this.teleporter = teleporter; this.target = target; this.type = type; - this.economyActions = actions; + this.actions = actions; this.async = plugin.getSettings().doAsynchronousTeleports(); this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class) .map(command -> @@ -78,17 +78,17 @@ public class Teleport { final Optional localTeleporter = resolveLocalTeleporter(); // Validate economy actions - validateEconomyActions(); + validateTransactions(); // Teleport a user on another server if (localTeleporter.isEmpty()) { final Username teleporter = (Username) this.teleporter; if (!plugin.getSettings().doCrossServer()) { - throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND); + throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin); } fireEvent((event) -> { - executeEconomyActions(); + performTransactions(); if (target instanceof Username username) { Message.builder() .type(Message.Type.TELEPORT_TO_NETWORKED_USER) @@ -114,7 +114,7 @@ public class Teleport { ? Optional.of(executor) : username.findLocally(plugin); if (localTarget.isPresent()) { fireEvent((event) -> { - executeEconomyActions(); + performTransactions(); if (updateLastPosition) { plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition()); } @@ -122,7 +122,7 @@ public class Teleport { try { teleporter.teleportLocally(localTarget.get().getPosition(), async); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); return; } this.displayTeleportingComplete(teleporter); @@ -132,7 +132,7 @@ public class Teleport { if (plugin.getSettings().doCrossServer()) { fireEvent((event) -> { - executeEconomyActions(); + performTransactions(); Message.builder() .type(Message.Type.TELEPORT_TO_NETWORKED_POSITION) .target(username.name()) @@ -141,11 +141,11 @@ public class Teleport { return; } - throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND); + throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND, plugin); } fireEvent((event) -> { - executeEconomyActions(); + performTransactions(); if (updateLastPosition) { plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition()); } @@ -155,7 +155,7 @@ public class Teleport { try { teleporter.teleportLocally(target, async); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); return; } this.displayTeleportingComplete(teleporter); @@ -188,17 +188,17 @@ public class Teleport { } // Check economy actions - protected void validateEconomyActions() throws TeleportationException { - if (economyActions.stream() - .map(action -> plugin.canPerformTransaction(executor, action)) + protected void validateTransactions() throws TeleportationException { + if (actions.stream() + .map(action -> plugin.validateTransaction(executor, action)) .anyMatch(result -> !result)) { - throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED); + throw new TeleportationException(TeleportationException.Type.TRANSACTION_FAILED, plugin); } } - // Perform transactions on economy actions - private void executeEconomyActions() { - economyActions.forEach(action -> plugin.performTransaction(executor, action)); + // Perform economy and cooldown transactions + private void performTransactions() { + actions.forEach(action -> plugin.performTransaction(executor, action)); } @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java index 6237d5af..d3ba24a8 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java @@ -22,8 +22,10 @@ package net.william278.huskhomes.teleport; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; +import java.util.Arrays; import java.util.List; /** @@ -36,7 +38,7 @@ public class TeleportBuilder { private Target target; private boolean updateLastPosition = true; private Teleport.Type type = Teleport.Type.TELEPORT; - private List economyActions = List.of(); + private List actions = List.of(); protected TeleportBuilder(@NotNull HuskHomes plugin) { this.plugin = plugin; @@ -45,7 +47,7 @@ public class TeleportBuilder { @NotNull public Teleport toTeleport() throws TeleportationException { this.validateTeleport(); - return new Teleport(executor, teleporter, target, type, updateLastPosition, economyActions, plugin); + return new Teleport(executor, teleporter, target, type, updateLastPosition, actions, plugin); } @NotNull @@ -55,23 +57,23 @@ public class TeleportBuilder { throw new IllegalStateException("Teleporter must be an OnlineUser for timed teleportation"); } return new TimedTeleport(executor, onlineTeleporter, target, type, - plugin.getSettings().getTeleportWarmupTime(), updateLastPosition, economyActions, plugin); + plugin.getSettings().getTeleportWarmupTime(), updateLastPosition, actions, plugin); } private void validateTeleport() throws TeleportationException { if (teleporter == null) { - throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND); + throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin); } if (executor == null) { if (teleporter instanceof OnlineUser onlineUser) { executor = onlineUser; } else { - executor = ((Username) teleporter).findLocally(plugin) - .orElseThrow(() -> new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND)); + executor = ((Username) teleporter).findLocally(plugin).orElseThrow( + () -> new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin)); } } if (target == null) { - throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND); + throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND, plugin); } } @@ -111,9 +113,17 @@ public class TeleportBuilder { return this; } + @SuppressWarnings("removal") @NotNull + @Deprecated(since = "4.4", forRemoval = true) public TeleportBuilder economyActions(@NotNull EconomyHook.Action... economyActions) { - this.economyActions = List.of(economyActions); + this.actions = Arrays.stream(economyActions).map(EconomyHook.Action::getTransactionAction).toList(); + return this; + } + + @NotNull + public TeleportBuilder actions(@NotNull TransactionResolver.Action... actions) { + this.actions = List.of(actions); return this; } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java index dcf3cab3..9d29e566 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java @@ -25,14 +25,16 @@ import org.jetbrains.annotations.NotNull; public class TeleportationException extends IllegalStateException { + private final HuskHomes plugin; private final Type type; - public TeleportationException(@NotNull Type type) { - super("Error executing teleport: " + type.name()); - this.type = type; + public TeleportationException(@NotNull Type cause, @NotNull HuskHomes plugin) { + super("Error executing teleport: " + cause.name()); + this.type = cause; + this.plugin = plugin; } - public void displayMessage(@NotNull CommandUser user, @NotNull HuskHomes plugin, @NotNull String... args) { + public void displayMessage(@NotNull CommandUser user, @NotNull String... args) { switch (type) { case TELEPORTER_NOT_FOUND, TARGET_NOT_FOUND -> plugin.getLocales() .getLocale("error_player_not_found", args) @@ -62,13 +64,13 @@ public class TeleportationException extends IllegalStateException { } /** - * The types of teleportation errors + * Represents different causes of {@link TeleportationException}s */ public enum Type { TELEPORTER_NOT_FOUND, TARGET_NOT_FOUND, ALREADY_WARMING_UP, - ECONOMY_ACTION_FAILED, + TRANSACTION_FAILED, WARMUP_ALREADY_MOVING, WORLD_NOT_FOUND, ILLEGAL_TARGET_COORDINATES, diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index d102e75e..bd0c201b 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -22,10 +22,10 @@ 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.hook.EconomyHook; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.util.Task; +import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -47,7 +47,7 @@ public class TimedTeleport extends Teleport implements Runnable { protected TimedTeleport(@NotNull OnlineUser executor, @NotNull OnlineUser teleporter, @NotNull Target target, @NotNull Type type, int warmupTime, boolean updateLastPosition, - @NotNull List actions, @NotNull HuskHomes plugin) { + @NotNull List actions, @NotNull HuskHomes plugin) { super(teleporter, executor, target, type, updateLastPosition, actions, plugin); this.startLocation = teleporter.getPosition(); this.startHealth = teleporter.getHealth(); @@ -65,15 +65,15 @@ public class TimedTeleport extends Teleport implements Runnable { // Check if the teleporter is already warming up to teleport if (plugin.isWarmingUp(teleporter.getUuid())) { - throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP); + throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP, plugin); } // Validate economy actions - validateEconomyActions(); + validateTransactions(); // Check if they are moving at the start of the teleport if (teleporter.isMoving()) { - throw new TeleportationException(TeleportationException.Type.WARMUP_ALREADY_MOVING); + throw new TeleportationException(TeleportationException.Type.WARMUP_ALREADY_MOVING, plugin); } // Process the warmup and execute the teleport @@ -107,7 +107,7 @@ public class TimedTeleport extends Teleport implements Runnable { try { super.execute(); } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); + e.displayMessage(teleporter); } } diff --git a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java index d480393b..264ee0db 100644 --- a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java @@ -21,7 +21,9 @@ package net.william278.huskhomes.user; import org.jetbrains.annotations.NotNull; +import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.UUID; /** @@ -30,16 +32,31 @@ import java.util.UUID; public class SavedUser { private final User user; - private int homeSlots; private boolean ignoringTeleports; - private Instant rtpCooldown; - public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) { + /** + * Create a new SavedUser object + * + * @param user The user to create the object for + * @param homeSlots The number of home slots the user has + * @param ignoringTeleports Whether the user is ignoring teleports or not + */ + public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports) { this.user = user; this.homeSlots = homeSlots; this.ignoringTeleports = ignoringTeleports; - this.rtpCooldown = rtpCooldown; + } + + /** + * @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object + *

+ * User RTP cooldowns are no longer stored in {@link SavedUser} objects, + * please use the new API methods for getting/setting cooldowns + */ + @Deprecated(since = "4.4", forRemoval = true) + public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) { + this(user, homeSlots, ignoringTeleports); } @NotNull @@ -73,13 +90,21 @@ public class SavedUser { this.ignoringTeleports = ignoringTeleports; } + /** + * @deprecated Use the new API methods for setting and getting cooldowns + */ @NotNull + @Deprecated(since = "4.4", forRemoval = true) public Instant getRtpCooldown() { - return rtpCooldown; + return Instant.now().minus(Duration.of(5, ChronoUnit.SECONDS)); } + /** + * @deprecated Use the new API methods for setting and getting cooldowns + */ + @Deprecated(since = "4.4", forRemoval = true) public void setRtpCooldown(@NotNull Instant rtpCooldown) { - this.rtpCooldown = rtpCooldown; + // Do nothing } } diff --git a/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java b/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java index 0bf22104..eda722f9 100644 --- a/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java +++ b/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java @@ -24,24 +24,36 @@ import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.user.OnlineUser; import org.jetbrains.annotations.NotNull; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; +import java.util.StringJoiner; +import java.util.logging.Level; /** - * Utility class for resolving and performing economy transactions through an {@link EconomyHook} + * Class for validating and performing economy and cooldown transactions involving {@link Action}s */ public interface TransactionResolver { /** - * Perform an economy check on the {@link OnlineUser}; returning {@code true} if it passes the check + * Validates whether an {@link OnlineUser} can perform an {@link Action}, in terms of whether they have sufficient + * funds and are not on cooldown. This method will also send the user a message if they cannot perform the action. + *

+ * This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise + * {@code false}. * * @param player the {@link OnlineUser player} to perform the check on - * @param action the {@link EconomyHook.Action action} to perform - * @return {@code true} if the action passes the check, {@code false} if the user has insufficient funds + * @param action the {@link Action action} to perform + * @return {@code true} if the action can be performed, {@code false} otherwise */ - default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) { - return getPlugin().getSettings().getEconomyCost(action) - .map(Math::abs) - .flatMap(c -> player.hasPermission(EconomyHook.BYPASS_PERMISSION) ? Optional.empty() : Optional.of(c)) + default boolean validateTransaction(@NotNull OnlineUser player, @NotNull Action action) { + return hasFunds(player, action) && isNotOnCooldown(player, action); + } + + // Validates if the user has funds to perform an action + private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) { + return getPlugin().getSettings().getEconomyCost(action).map(Math::abs) + .flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) ? Optional.empty() : Optional.of(c)) .map(c -> getEconomyHook() .map(hook -> { if (hook.getPlayerBalance(player) < c) { @@ -55,20 +67,87 @@ public interface TransactionResolver { .orElse(true); } + // Validates if the user is on cooldown for an action + private boolean isNotOnCooldown(@NotNull OnlineUser player, @NotNull Action action) { + final long configCooldown = getPlugin().getSettings().getCooldown(action); + if (configCooldown <= 0 || player.hasPermission(Action.BYPASS_COOLDOWNS_PERMISSION)) { + return true; + } + return getPlugin().getDatabase().getCooldown(action, player) + .map(cooldownEnds -> { + if (cooldownEnds.isAfter(Instant.now())) { + getPlugin().getLocales().getLocale("error_on_cooldown", + formatDuration(Duration.between(Instant.now(), cooldownEnds).abs())) + .ifPresent(player::sendMessage); + return false; + } + getPlugin().getDatabase().removeCooldown(action, player); + return true; + }) + .orElse(true); + } + + // Formats a Duration object into a human-readable days/hours/minutes/seconds string (e.g. "1d 2h 3m 4s") + @NotNull + private String formatDuration(@NotNull Duration duration) { + final long days = duration.toDays(); + final long hours = duration.minusDays(days).toHours(); + final long minutes = duration.minusDays(days).minusHours(hours).toMinutes(); + final long seconds = duration.minusDays(days).minusHours(hours).minusMinutes(minutes).getSeconds(); + final StringJoiner formattedDuration = new StringJoiner(" "); + if (days > 0) { + formattedDuration.add(days + "d"); + } + if (hours > 0) { + formattedDuration.add(hours + "h"); + } + if (minutes > 0) { + formattedDuration.add(minutes + "m"); + } + if (seconds > 0) { + formattedDuration.add(seconds + "s"); + } + return formattedDuration.toString(); + } + /** * Execute an economy transaction if needed, updating the player's balance * * @param player the {@link OnlineUser player} to deduct the cost from if needed - * @param action the {@link EconomyHook.Action action} to deduct the cost from if needed + * @param action the {@link Action action} to deduct the cost from if needed */ - default void performTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) { - getPlugin().getSettings().getEconomyCost(action) - .map(Math::abs) - .flatMap(c -> player.hasPermission(EconomyHook.BYPASS_PERMISSION) ? Optional.empty() : Optional.of(c)) - .ifPresent(cost -> getEconomyHook().ifPresent(hook -> { + default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) { + getEconomyHook().ifPresent(hook -> getPlugin().getSettings() + .getEconomyCost(action).map(Math::abs) + .flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) ? Optional.empty() : Optional.of(c)) + .ifPresent(cost -> { hook.changePlayerBalance(player, -cost); hook.notifyDeducted(player, getPlugin(), action); })); + + final long configCooldown = getPlugin().getSettings().getCooldown(action); + getPlugin().log(Level.INFO, "Setting cooldown for " + player.getUsername() + " to " + configCooldown + " seconds"); + if (configCooldown > 0 && !player.hasPermission(Action.BYPASS_COOLDOWNS_PERMISSION)) { + getPlugin().getDatabase().setCooldown(action, player, Instant.now().plusSeconds(configCooldown)); + } + } + + /** + * @deprecated use {@link #validateTransaction(OnlineUser, Action)} instead + */ + @SuppressWarnings("removal") + @Deprecated(since = "4.4", forRemoval = true) + default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) { + return this.validateTransaction(player, action.getTransactionAction()); + } + + /** + * @deprecated use {@link #performTransaction(OnlineUser, Action)} instead + */ + @SuppressWarnings("removal") + @Deprecated(since = "4.4", forRemoval = true) + default void performTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) { + this.performTransaction(player, action.getTransactionAction()); } /** @@ -84,4 +163,65 @@ public interface TransactionResolver { @NotNull HuskHomes getPlugin(); + /** + * Represents actions that can be the subject of a transaction + */ + enum Action { + + /* + * Home and public home slots + */ + ADDITIONAL_HOME_SLOT(100d, 0), + MAKE_HOME_PUBLIC(50d, 0), + BACK_COMMAND, + + /* + * Teleportation actions + */ + RANDOM_TELEPORT(25d, 600), + HOME_TELEPORT, + PUBLIC_HOME_TELEPORT, + WARP_TELEPORT, + SPAWN_TELEPORT, + + /* + * Teleport request actions + */ + SEND_TELEPORT_REQUEST, + ACCEPT_TELEPORT_REQUEST; + + public static final String BYPASS_ECONOMY_PERMISSION = "huskhomes.bypass_economy_checks"; + public static final String BYPASS_COOLDOWNS_PERMISSION = "huskhomes.bypass_cooldowns"; + + private final double defaultCost; + private final int defaultCooldown; + + Action(double defaultCost, int defaultCooldown) { + this.defaultCost = defaultCost; + this.defaultCooldown = defaultCooldown; + } + + Action() { + this(0d, 0); + } + + /** + * Create an action with a default cost + * + * @return the default cost + */ + public double getDefaultCost() { + return defaultCost; + } + + /** + * Get the default cooldown for this action (in seconds) + * + * @return the default cooldown in seconds + */ + public int getDefaultCooldown() { + return defaultCooldown; + } + + } } diff --git a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java index b777470f..006b8dac 100644 --- a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java +++ b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java @@ -91,7 +91,7 @@ public class ValidationException extends IllegalArgumentException { REACHED_MAX_HOMES, NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_PUBLIC_HOMES, - NOT_ENOUGH_MONEY, + TRANSACTION_FAILED, DESCRIPTION_INVALID } diff --git a/common/src/main/resources/database/mysql_schema.sql b/common/src/main/resources/database/mysql_schema.sql index 318ef181..35f8b40a 100644 --- a/common/src/main/resources/database/mysql_schema.sql +++ b/common/src/main/resources/database/mysql_schema.sql @@ -31,7 +31,6 @@ CREATE TABLE IF NOT EXISTS `%players_table%` `respawn_position` integer DEFAULT NULL, `home_slots` integer NOT NULL DEFAULT 0, `ignoring_requests` boolean NOT NULL DEFAULT FALSE, - `rtp_cooldown` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`uuid`), FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, @@ -40,6 +39,20 @@ CREATE TABLE IF NOT EXISTS `%players_table%` ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; +# Create the cooldowns table if it does not exist +CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +( + `id` integer NOT NULL AUTO_INCREMENT, + `player_uuid` char(36) NOT NULL UNIQUE, + `type` integer NOT NULL, + `start_timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_timestamp` datetime NOT NULL, + + PRIMARY KEY (`id`), + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE +) CHARACTER SET utf8 + COLLATE utf8_unicode_ci; + # Create the current cross-server teleports table if it does not exist CREATE TABLE IF NOT EXISTS `%teleports_table%` ( diff --git a/common/src/main/resources/database/sqlite_schema.sql b/common/src/main/resources/database/sqlite_schema.sql index 9f5d5567..cc2356a4 100644 --- a/common/src/main/resources/database/sqlite_schema.sql +++ b/common/src/main/resources/database/sqlite_schema.sql @@ -24,7 +24,6 @@ CREATE TABLE IF NOT EXISTS `%players_table%` `respawn_position` integer DEFAULT NULL, `home_slots` integer NOT NULL DEFAULT 0, `ignoring_requests` boolean NOT NULL DEFAULT FALSE, - `rtp_cooldown` datetime NOT NULL DEFAULT 0, PRIMARY KEY (`uuid`), FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, @@ -32,6 +31,19 @@ CREATE TABLE IF NOT EXISTS `%players_table%` FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION ); +/* Create the cooldowns table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +( + `id` integer NOT NULL, + `player_uuid` char(36) NOT NULL UNIQUE, + `type` integer NOT NULL, + `start_timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_timestamp` datetime NOT NULL, + + PRIMARY KEY (`id`), + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE +); + /* Create the current cross-server teleports table if it does not exist */ CREATE TABLE IF NOT EXISTS `%teleports_table%` ( diff --git a/common/src/main/resources/locales/bg-bg.yml b/common/src/main/resources/locales/bg-bg.yml index 10099b7d..15541e90 100644 --- a/common/src/main/resources/locales/bg-bg.yml +++ b/common/src/main/resources/locales/bg-bg.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending te error_teleport_request_self: '[Error:](#ff3300) [You cannot send a teleport request to yourself.](#ff7e5e)' error_player_not_found: '[Грешка:](#ff3300) [Не можахме да открием играча %1%.](#ff7e5e)' error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)' -error_rtp_cooldown: '[Грешка:](#ff3300) [Трябва да изчакате %1% минута(и) преди да се телепортирате на случаен принцип отново.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Грешка:](#ff3300) [Тази команда е изключена!](#ff7e5e)' error_console_command_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' error_rtp_randomization_timeout: '[Грешка:](#ff3300) [Провалихме се да намерим безопасна локация на случаен принцип, до която да Ви телепортираме.](#ff7e5e)' diff --git a/common/src/main/resources/locales/de-de.yml b/common/src/main/resources/locales/de-de.yml index 50c79831..f884cdc0 100644 --- a/common/src/main/resources/locales/de-de.yml +++ b/common/src/main/resources/locales/de-de.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Fehler:](#ff3300) [Du hast keine ausstehende T error_teleport_request_self: '[Fehler:](#ff3300) [Du kannst dir selbst keine Teleportanfrage stellen.](#ff7e5e)' error_player_not_found: '[Fehler:](#ff3300) [Der Spieler %1% konnte nicht gefunden werden.](#ff7e5e)' error_rtp_restricted_world: '[Fehler:](#ff3300) [Du kannst dich in dieser Welt nicht zufällig teleportieren.](#ff7e5e)' -error_rtp_cooldown: '[Fehler:](#ff3300) [Du musst %1% Minute(n) warten, bevor du dich wieder zufällig teleportieren kannst.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Fehler:](#ff3300) [Dieser Befehl ist deaktiviert!](#ff7e5e)' error_console_command_only: '[Fehler:](#ff3300) [Dieser Befehl kann nur von der Serverkonsole aus ausgeführt werden.](#ff7e5e)' error_rtp_randomization_timeout: '[Fehler:](#ff3300) [Es ist nicht gelungen, einen sicheren zufälligen Ort zu finden um dich zu teleportieren.](#ff7e5e)' diff --git a/common/src/main/resources/locales/en-gb.yml b/common/src/main/resources/locales/en-gb.yml index e3add392..be642a0e 100644 --- a/common/src/main/resources/locales/en-gb.yml +++ b/common/src/main/resources/locales/en-gb.yml @@ -144,7 +144,7 @@ error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending te error_teleport_request_self: '[Error:](#ff3300) [You cannot send a teleport request to yourself.](#ff7e5e)' error_player_not_found: '[Error:](#ff3300) [Could not find the player %1%.](#ff7e5e)' error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)' -error_rtp_cooldown: '[Error:](#ff3300) [You must wait %1% minute(s) before randomly teleporting again.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Error:](#ff3300) [That command is disabled!](#ff7e5e)' error_console_command_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' error_rtp_randomization_timeout: '[Error:](#ff3300) [Failed to find a safe random location to teleport you.](#ff7e5e)' diff --git a/common/src/main/resources/locales/es-es.yml b/common/src/main/resources/locales/es-es.yml index 56d0e98e..12811abf 100644 --- a/common/src/main/resources/locales/es-es.yml +++ b/common/src/main/resources/locales/es-es.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Error:](#ff3300) [No tienes una solicitud de t error_teleport_request_self: '[Error:](#ff3300) [No puedes enviar una solicitud de teletransporte a ti mismo.](#ff7e5e)' error_player_not_found: '[Error:](#ff3300) [No se ha podido encontrar el jugador %1%.](#ff7e5e)' error_rtp_restricted_world: '[Error:](#ff3300) [No puedes teletransportarte al azar en este mundo.](#ff7e5e)' -error_rtp_cooldown: '[Error:](#ff3300) [Debes esperar %1% minutos antes de volver a teletransportarse de nuevo.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Error:](#ff3300) [Ese comando está desactivado.](#ff7e5e)' error_console_command_only: '[Error:](#ff3300) [Ese comando sólo se puede ejecutar desde la consola del servidor.](#ff7e5e)' error_rtp_randomization_timeout: '[Error:](#ff3300) [No se ha podido encontrar una ubicación aleatoria segura para teletransportarte...](#ff7e5e)' diff --git a/common/src/main/resources/locales/it-it.yml b/common/src/main/resources/locales/it-it.yml index ebcc31ed..1c2f3437 100644 --- a/common/src/main/resources/locales/it-it.yml +++ b/common/src/main/resources/locales/it-it.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Errore:](#ff3300) [Non hai richieste di teletr error_teleport_request_self: '[Errore:](#ff3300) [Non puoi teletrasportarti da te stesso!](#ff7e5e)' error_player_not_found: '[Errore:](#ff3300) [Non trovo il giocatore: %1%.](#ff7e5e)' error_rtp_restricted_world: '[Errore:](#ff3300) [Non puoi teletrasportarti randomicamente in questo mondo.](#ff7e5e)' -error_rtp_cooldown: '[Errore:](#ff3300) [Devi aspettare %1% minuti prima di utilizzare nuovamente l’’/rtp.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Errore:](#ff3300) [Questo comando è disabilitato!](#ff7e5e)' error_console_command_only: '[Errore:](#ff3300) [Quel comando può essere eseguito solo da console.](#ff7e5e)' error_rtp_randomization_timeout: '[Errore:](#ff3300) [Non sono riuscito a trovare una posizione sicura, riprova.](#ff7e5e)' diff --git a/common/src/main/resources/locales/ja-jp.yml b/common/src/main/resources/locales/ja-jp.yml index 4c29913d..5c934662 100644 --- a/common/src/main/resources/locales/ja-jp.yml +++ b/common/src/main/resources/locales/ja-jp.yml @@ -68,10 +68,10 @@ public_home_list_item: '[[%1%]](show_text=�fb9a&%1%\n&7☻ %3%\n&7ℹ %4% run warp_list_item: '[[%1%]](show_text=�fb9a&%1%\n&7ℹ %3% run_command=/huskhomes:warp %2%)' command_list_item: '[/%1%](#00fb9a show_text=&7Click to suggest command suggest_command=/%1%) [%2%](gray show_text=�fb9a&/%1%\n&7%3%)' list_item_divider: ' [•](gray) ' -list_footer: \n%1%[ページ](#00fb9a) [%2%](#00fb9a)/[%3%](#00fb9a)%4% %5% +list_footer: '\n%1%[ページ](#00fb9a) [%2%](#00fb9a)/[%3%](#00fb9a)%4% %5%' list_previous_page_button: '[◀](white show_text=&7前のページを表示 run_command=%2% %1%) ' list_next_page_button: ' [▶](white show_text=&7次のページを表示 run_command=%2% %1%)' -list_page_jumpers: (%1%) +list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7%1% ページ目を表示 run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' @@ -83,26 +83,26 @@ set_home_used_free_slots: '[ℹ %1% のフリーホームの枠をすべて使 set_home_success: '[新しいホーム ](#00fb9a) [%1%](#00fb9a bold) [ の設定に成功しました](#00fb9a)' set_warp_success: '[新しいワープ ](#00fb9a) [%1%](#00fb9a bold) [ の設定に成功しました](#00fb9a)' set_spawn_success: '[スポーン位置を現在地に更新しました。](#00fb9a)' -spawn_warp_default_description: サーバーの /spawn 座標にてレポートする -item_no_description: (説明文はありません) +spawn_warp_default_description: 'サーバーの /spawn 座標にてレポートする' +item_no_description: '(説明文はありません)' delete_all_homes_confirm: '[警告:](#ff3300) [本当に全ホームを消去してよろしいですか?](#ff7e5e)\n[一度実行すると復元はできません。](gray)\n[→](gray) [[Confirm]](#ff3300 show_text=&#ff3300&クリックすると消去が確定します。この操作は元に戻せません。 run_command=/delhome all confirm)' delete_all_warps_confirm: '[警告:](#ff3300) [本当に全サーバーを消去してよろしいですか?](#ff7e5e)\n[一度実行すると復元はできません。](gray)\n[→](gray) [[Confirm]](#ff3300 show_text=&#ff3300&クリックすると消去が確定します。この操作は元に戻せません。 run_command=/delwarp all confirm)' delete_all_homes_success: '[消去が完了しました](#00fb9a) [%1%](#00fb9a bold) [ のホーム。](#00fb9a)' delete_all_warps_success: '[消去が完了しました](#00fb9a) [%1%](#00fb9a bold) [ のサーバーワープ。](#00fb9a)' economy_transaction_complete: '[ℹ %1% が残高から引き落とされました。(%2%)](gray)' -economy_action_additional_home_slot: ホームスロットを追加購入する -economy_action_make_home_public: ホームを一般公開する -economy_action_back_command: /back コマンドを使用する -economy_action_random_teleport: /rtp コマンドを使用する -economy_action_home_teleport: ホームにテレポートしました -economy_action_public_home_teleport: 公開ホームにテレポートしました -economy_action_warp_teleport: ワープにテレポートしました -economy_action_spawn_teleport: スポーンにテレポートしました -economy_action_send_teleport_request: テレポートリクエストを送信する -economy_action_accept_teleport_request: テレポートリクエストを承諾する +economy_action_additional_home_slot: 'ホームスロットを追加購入する' +economy_action_make_home_public: 'ホームを一般公開する' +economy_action_back_command: '/back コマンドを使用する' +economy_action_random_teleport: '/rtp コマンドを使用する' +economy_action_home_teleport: 'ホームにテレポートしました' +economy_action_public_home_teleport: '公開ホームにテレポートしました' +economy_action_warp_teleport: 'ワープにテレポートしました' +economy_action_spawn_teleport: 'スポーンにテレポートしました' +economy_action_send_teleport_request: 'テレポートリクエストを送信する' +economy_action_accept_teleport_request: 'テレポートリクエストを承諾する' return_by_death_notification: '[死んだ座標に移動しますか?](gray) [[⏪ テレポート…]](#00fb9a show_text=�fb9a&クリックしてテレポートする\n&7死ん座標に戻る run_command=/huskhomes:back)' -map_hook_public_homes_marker_set_name: 一般公開ホーム一覧 -map_hook_warps_marker_set_name: ワープ一覧 +map_hook_public_homes_marker_set_name: '一般公開ホーム一覧' +map_hook_warps_marker_set_name: 'ワープ一覧' up_to_date: '[HuskHomes](#00fb9a bold) [| HuskHomesの最新バージョンを実行しています(v%1%).](#00fb9a)' update_available: '[HuskHomes](#ff7e5e bold) [| HuskHomesの最新バージョンが更新されています: v%1% (running: v%2%).](#ff7e5e)' importer_list_title: '[HuskHomes](#00fb9a bold) [| 利用可能なデータインポーター:](#00fb9a)\n' @@ -144,7 +144,7 @@ error_invalid_teleport_request: '[エラー:](#ff3300) [%1%からのテレポー error_teleport_request_self: '[エラー:](#ff3300) [自分自身にテレポートリクエストを送ることはできません。](#ff7e5e)' error_player_not_found: '[エラー:](#ff3300) [プレイヤー %1% が見つかりませんでした。](#ff7e5e)' error_rtp_restricted_world: '[エラー:](#ff3300) [このワールドでは、ランダムテレポートはできません。](#ff7e5e)' -error_rtp_cooldown: '[エラー:](#ff3300) [再びランダムテレポートを行うには、 %1% 分間待つ必要があります。](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[エラー:](#ff3300) [そのコマンドは無効です!](#ff7e5e)' error_console_command_only: '[エラー:](#ff3300) [そのコマンドはサーバーコンソールからしか実行できません。](#ff7e5e)' error_rtp_randomization_timeout: '[エラー:](#ff3300) [テレポートする安全なランダムな座標を見つけるのに失敗しました。](#ff7e5e)' @@ -155,30 +155,30 @@ error_home_invalid_other: '[エラー:](#ff3300) [%1% は "%2%" という名前 error_edit_home_maximum_public_homes: '[エラー:](#ff3300) [最大で %1% のホームしか公開できません。](#ff7e5e)' error_illegal_target_coordinates: '[エラー:](#ff3300) [ゲームワールドの限界値を超えているため、テレポートをキャンセルしました。](#ff7e5e)' error_no_players_online: '[エラー:](#ff3300) [テレポートできるプレーヤーがオンラインではありません。](#ff7e5e)' -home_command_description: ホームの一つにテレポートする -sethome_command_description: 与えられた名前で新しいホームをセットする -delhome_command_description: 以前に設定したホームを消去する -edithome_command_description: ホームを1つ編集する -warp_command_description: ワープにテレポートする -setwarp_command_description: 指定された名前の新しいワープを設定する -delwarp_command_description: ワープを消去する -editwarp_command_description: ワープを編集する -back_command_description: 以前いた座標、若しくは死んだ座標にテレポートする -homelist_command_description: ホーム一覧を表示する -warplist_command_description: ワープ一覧を表示する -phomelist_command_description: 公開ホーム一覧を表示する -phome_command_description: 公開ホームにテレポートする -tp_command_description: 他のプレイヤーや座標にテレポートする -tphere_command_description: 他のプレイヤーを自分のところにテレポートさせる -tpa_command_description: 他のプレイヤーへのテレポートをリクエストする -tpahere_command_description: 他のプレイヤーに自分のところへのテレポートを依頼する -tpaccept_command_description: テレポートリクエストを承諾する -tpdecline_command_description: テレポートリクエストを拒否する -tpignore_command_description: テレポートリクエストの受信を無視する -tpoffline_command_description: プレイヤーが最後にオンラインになった座標にテレポートする -rtp_command_description: ランダムな野生にテレポートする -spawn_command_description: スポーンにテレポートする -setspawn_command_description: スポーン地点を設定する -tpaall_command_description: 全員が自分のところにテレポートするように要求する -tpall_command_description: 全員を自分のところまでテレポートさせる -huskhomes_command_description: プラグイン情報の表示と設定のリロード +home_command_description: 'ホームの一つにテレポートする' +sethome_command_description: '与えられた名前で新しいホームをセットする' +delhome_command_description: '以前に設定したホームを消去する' +edithome_command_description: 'ホームを1つ編集する' +warp_command_description: 'ワープにテレポートする' +setwarp_command_description: '指定された名前の新しいワープを設定する' +delwarp_command_description: 'ワープを消去する' +editwarp_command_description: 'ワープを編集する' +back_command_description: '以前いた座標、若しくは死んだ座標にテレポートする' +homelist_command_description: 'ホーム一覧を表示する' +warplist_command_description: 'ワープ一覧を表示する' +phomelist_command_description: '公開ホーム一覧を表示する' +phome_command_description: '公開ホームにテレポートする' +tp_command_description: '他のプレイヤーや座標にテレポートする' +tphere_command_description: '他のプレイヤーを自分のところにテレポートさせる' +tpa_command_description: '他のプレイヤーへのテレポートをリクエストする' +tpahere_command_description: '他のプレイヤーに自分のところへのテレポートを依頼する' +tpaccept_command_description: 'テレポートリクエストを承諾する' +tpdecline_command_description: 'テレポートリクエストを拒否する' +tpignore_command_description: 'テレポートリクエストの受信を無視する' +tpoffline_command_description: 'プレイヤーが最後にオンラインになった座標にテレポートする' +rtp_command_description: 'ランダムな野生にテレポートする' +spawn_command_description: 'スポーンにテレポートする' +setspawn_command_description: 'スポーン地点を設定する' +tpaall_command_description: '全員が自分のところにテレポートするように要求する' +tpall_command_description: '全員を自分のところまでテレポートさせる' +huskhomes_command_description: 'プラグイン情報の表示と設定のリロード' diff --git a/common/src/main/resources/locales/pl-pl.yml b/common/src/main/resources/locales/pl-pl.yml index f81fd78a..8948a736 100644 --- a/common/src/main/resources/locales/pl-pl.yml +++ b/common/src/main/resources/locales/pl-pl.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending te error_teleport_request_self: '[Error:](#ff3300) [You cannot send a teleport request to yourself.](#ff7e5e)' error_player_not_found: '[Błąd:](#ff3300) [Nie odnalazłem gracza %1%.](#ff7e5e)' error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)' -error_rtp_cooldown: '[Błąd:](#ff3300) [Odczekaj %1% minut przed kolejną teleportacją.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Błąd:](#ff3300) [To polecenie jest wyłączone!](#ff7e5e)' error_console_command_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' error_rtp_randomization_timeout: '[Błąd:](#ff3300) [Nie mogę znaleśc bezpiecznej lokalizacji dla Ciebie.](#ff7e5e)' diff --git a/common/src/main/resources/locales/tr-tr.yml b/common/src/main/resources/locales/tr-tr.yml index e4258e27..376520e4 100644 --- a/common/src/main/resources/locales/tr-tr.yml +++ b/common/src/main/resources/locales/tr-tr.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Hata:](#ff3300) [%1% tarafından bekleyen bir error_teleport_request_self: '[Hata:](#ff3300) [Kendinize ışınlanma isteği gönderemezsiniz.](#ff7e5e)' error_player_not_found: '[Hata:](#ff3300) [%1% adlı oyuncu bulunamadı.](#ff7e5e)' error_rtp_restricted_world: '[Hata:](#ff3300) [Bu dünyada rastgele ışınlanamazsınız.](#ff7e5e)' -error_rtp_cooldown: '[Hata:](#ff3300) [Yeniden rastgele ışınlanmadan önce %1% dakika beklemelisiniz.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Hata:](#ff3300) [Bu komut devre dışı!](#ff7e5e)' error_console_command_only: '[Hata:](#ff3300) [Bu komut yalnızca sunucu konsolundan çalıştırılabilir.](#ff7e5e)' error_rtp_randomization_timeout: '[Hata:](#ff3300) [Sizi ışınlamak için güvenli bir rasgele konum bulunamadı.](#ff7e5e)' diff --git a/common/src/main/resources/locales/uk-ua.yml b/common/src/main/resources/locales/uk-ua.yml index 569d9dc5..466051a6 100644 --- a/common/src/main/resources/locales/uk-ua.yml +++ b/common/src/main/resources/locales/uk-ua.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending te error_teleport_request_self: '[Error:](#ff3300) [You cannot send a teleport request to yourself.](#ff7e5e)' error_player_not_found: '[Помилка:](#ff3300) [Не вдалося знайти гравця %1%.](#ff7e5e)' error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)' -error_rtp_cooldown: '[Помилка:](#ff3300) [Зачекайте %1% щоб знову випадково телепортуватися.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[Помилка:](#ff3300) [Ця команда вимкнена!](#ff7e5e)' error_console_command_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' error_rtp_randomization_timeout: '[Помилка:](#ff3300) [Не вдалося знайти випадкове безпечне місце, щоб вас телепортувати.](#ff7e5e)' diff --git a/common/src/main/resources/locales/zh-cn.yml b/common/src/main/resources/locales/zh-cn.yml index 25c5e09c..2ed2dc69 100644 --- a/common/src/main/resources/locales/zh-cn.yml +++ b/common/src/main/resources/locales/zh-cn.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[错误:](#ff3300) [您目前没有来自 %1% error_teleport_request_self: '[错误:](#ff3300) [您不能向自己发送传送请求.](#ff7e5e)' error_player_not_found: '[错误:](#ff3300) [没有找到玩家 %1%.](#ff7e5e)' error_rtp_restricted_world: '[错误:](#ff3300) [您不能在这个世界随机传送.](#ff7e5e)' -error_rtp_cooldown: '[错误:](#ff3300) [您必须等待 %1% 分钟才能再次随机传送.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[错误:](#ff3300) [该命令已禁用!](#ff7e5e)' error_console_command_only: '[错误:](#ff3300) [该命令只能从服务器控制台运行.](#ff7e5e)' error_rtp_randomization_timeout: '[错误:](#ff3300) [找不到安全的随机位置传送您.](#ff7e5e)' diff --git a/common/src/main/resources/locales/zh-tw.yml b/common/src/main/resources/locales/zh-tw.yml index e942228e..7dfe2e29 100644 --- a/common/src/main/resources/locales/zh-tw.yml +++ b/common/src/main/resources/locales/zh-tw.yml @@ -145,7 +145,7 @@ error_invalid_teleport_request: '[錯誤:](#ff3300) [您目前沒有來自 %1% error_teleport_request_self: '[錯誤:](#ff3300) [您不能向自己發送傳送請求.](#ff7e5e)' error_player_not_found: '[錯誤:](#ff3300) [沒有找到玩家 %1%.](#ff7e5e)' error_rtp_restricted_world: '[錯誤:](#ff3300) [您不能在這個世界隨機傳送.](#ff7e5e)' -error_rtp_cooldown: '[錯誤:](#ff3300) [您必須等待 %1% 分鐘才能再次隨機傳送.](#ff7e5e)' +error_on_cooldown: '[Error:](#ff3300) [You must wait %1% before doing that again.](#ff7e5e)' error_command_disabled: '[錯誤:](#ff3300) [該指令已禁用!](#ff7e5e)' error_console_command_only: '[錯誤:](#ff3300) [該指令只能從伺服器控制台運行.](#ff7e5e)' error_rtp_randomization_timeout: '[錯誤:](#ff3300) [找不到安全的隨機位置傳送您.](#ff7e5e)' diff --git a/docs/Commands.md b/docs/Commands.md index 5956a263..b804a80d 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -109,19 +109,17 @@ These permissions allow you to make a home public/private (toggling its privacy)

-Cooldown, warmup and economy bypasses +Bypass teleport warmup, cooldowns & economy checks -These permissions let you bypass teleportation warmup checks, rtp cooldown checks and economy checks +These permissions let you bypass teleportation warmup checks, cooldown, and economy checks -| Description | Permission | Default | -|--------------------------------------------|-----------------------------------------|:-------:| -| Bypass timed teleportation warmups† | `huskhomes.bypass_teleport_warmup` | Not set | -| Bypass economy checks | `huskhomes.bypass_economy_checks` | Not set | -| Bypass the cooldown on `/rtp`‡ | `huskhomes.command.rtp.bypass_cooldown` | ❌ | +| Description | Permission | Default | +|--------------------------------------------|------------------------------------|:-------:| +| Bypass timed teleportation warmups† | `huskhomes.bypass_teleport_warmup` | Not set | +| Bypass [cooldown checks](cooldowns) | `huskhomes.bypass_cooldowns` | Not set | +| Bypass [economy checks](economy-hook) | `huskhomes.bypass_economy_checks` | Not set | -†This is not effective when the teleport warmup time is set `<= 0` in the config file. - -‡This is not effective when the /rtp cooldown time is set `<= 0` in the config file. +†This is not effective when the teleport warmup time is set to `<= 0` in the config file.
diff --git a/docs/Config-Files.md b/docs/Config-Files.md index 21c88d6c..65b826cc 100644 --- a/docs/Config-Files.md +++ b/docs/Config-Files.md @@ -16,15 +16,19 @@ This page contains the configuration structure for HuskHomes. # ┃ HuskHomes Config ┃ # ┃ Developed by William278 ┃ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -# ┣╸ Information: https://william278.net/project/huskhomes -# ┗╸ Documentation: https://william278.net/docs/huskhomes +# ┣╸ Information: https://william278.net/project/huskhomes/ +# ┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/ +# ┗╸ Documentation: https://william278.net/docs/huskhomes/ +# Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations language: en-gb +# Whether to automatically check for plugin updates on startup check_for_updates: true database: - # Database connection settings + # Type of database to use (MYSQL, SQLITE) type: SQLITE mysql: credentials: + # Specify credentials here if you are using MYSQL as your database type host: localhost port: 3306 database: HuskHomes @@ -32,85 +36,123 @@ database: password: pa55w0rd parameters: ?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8 connection_pool: - # MySQL connection pool properties + # MYSQL database Hikari connection pool properties. Don't modify this unless you know what you're doing! size: 12 idle: 12 lifetime: 1800000 keepalive: 30000 timeout: 20000 + # Names of tables to use on your database. Don't modify this unless you know what you're doing! table_names: - home_data: huskhomes_homes + position_data: huskhomes_position_data warp_data: huskhomes_warps + saved_position_data: huskhomes_saved_positions + player_cooldowns_data: huskhomes_user_cooldowns + home_data: huskhomes_homes teleport_data: huskhomes_teleports player_data: huskhomes_users - saved_position_data: huskhomes_saved_positions - position_data: huskhomes_position_data general: - # General plugin settings + # The maximum homes a user can create. Override with the huskhomes.max_homes. permission. max_homes: 10 + # The maximum public homes a user can create. Override with the huskhomes.max_public_homes. permission. max_public_homes: 10 + # Whether permission limits (i.e. huskhomes.max_homes.) should stack if the user inherits multiple nodes. stack_permission_limits: false + # Whether users require a permission (huskhomes.command.warp.) to use warps permission_restrict_warps: false + # Whether running /sethome or /setwarp when a home/warp already exists should overwrite it. overwrite_existing_homes_warps: true + # How long a player has to stand still and not take damage for when teleporting (in seconds) teleport_warmup_time: 5 + # Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE) teleport_warmup_display: ACTION_BAR + # How long before received teleport requests expire (in seconds) teleport_request_expiry_time: 60 + # Whether /tpahere should use the location of the sender when sent. Docs: https://william278.net/docs/huskhomes/strict-tpahere/ strict_tpa_here_requests: true + # Whether home or warp names should be case insensitive (i.e. allow /home HomeOne and /home homeone) case_insensitive_names: false + # Whether home or warp names should allow UTF-8 characters (i.e. allow /home 你好) allow_unicode_names: false + # Whether home or warp descriptions should allow UTF-8 characters allow_unicode_descriptions: true + # Whether /back should work to teleport the user to where they died back_command_return_by_death: true + # Whether /back should work with other plugins that use the PlayerTeleportEvent (this can cause conflicts) back_command_save_teleport_event: false + # How many items should be displayed per-page in chat menu lists list_items_per_page: 12 + # Whether teleportation should be carried out asynchronously (ensuring chunks load before teleporting) asynchronous_teleports: true + # Whether to play sound effects play_sound_effects: true + # Which sound effects to play for various actions sound_effects: - teleportation_complete: entity.enderman.teleport - teleport_request_received: entity.experience_orb.pickup teleportation_cancelled: entity.item.break teleportation_warmup: block.note_block.banjo + teleportation_complete: entity.enderman.teleport + teleport_request_received: entity.experience_orb.pickup + # Whether to provide modern, rich TAB suggestions for commands (if available) brigadier_tab_completion: true cross_server: - # Enable teleporting across proxied servers. Requires MySQL + # Enable teleporting across your proxy network. Requires database type to be MYSQL enabled: false + # The type of message broker to use for cross-server communication. Options: PLUGIN_MESSAGE, REDIS messenger_type: PLUGIN_MESSAGE + # Specify a common ID for grouping servers running HuskHomes on your proxy. Don't modify this unless you know what you're doing! cluster_id: '' global_spawn: + # Define a single global /spawn for your network via a warp. Docs: https://william278.net/docs/huskhomes/global-spawn/ enabled: false + # The name of the warp to use as the global spawn. warp_name: Spawn + # Whether player respawn positions should work cross-server. Docs: https://william278.net/docs/huskhomes/global-respawning/ global_respawning: false redis_credentials: + # Specify credentials here if you are using REDIS as your messenger_type. Docs: https://william278.net/docs/huskhomes/redis-support/ host: localhost port: 6379 password: '' use_ssl: false rtp: - # Random teleport (/rtp) command settings - cooldown_length: 10 + # Radius around the spawn point in which players cannot be random teleported to radius: 5000 + # Radius of the spawn area in which players cannot be random teleported to spawn_radius: 500 + # Mean of the normal distribution used to calculate the distance from the center of the world distribution_mean: 0.75 + # Standard deviation of the normal distribution used to calculate the distance from the center of the world distribution_deviation: 2.0 + # List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether. restricted_worlds: - world_nether - world_the_end +cooldowns: + # Whether to apply a cooldown between performing certain actions + enabled: true + # Set a cooldown between performing actions (in seconds). Docs: https://william278.net/docs/huskhomes/cooldowns/ + cooldown_times: + random_teleport: 600 economy: - # Charge for certain actions (requires Vault) + # Enable economy plugin integration (requires Vault) enabled: false # Use this currency for payments (works only with RedisEconomy), defaults to Vault currency redis_economy_name: vault + # Specify how many homes players can set for free, before they need to pay for more slots free_home_slots: 5 - # Require money to perform certain actions. Check https://william278.net/docs/huskhomes/economy-hook for available actions + # Charge money for perform certain actions. Docs: https://william278.net/docs/huskhomes/economy-hook/ costs: - additional_home_slot: 100.0 make_home_public: 50.0 + additional_home_slot: 100.0 random_teleport: 25.0 map_hook: - # Display public homes/warps on your web map (supports Dynmap and BlueMap) + # Display public homes/warps on your Dynmap, BlueMap or Pl3xMap. Docs: https://william278.net/docs/huskhomes/map-hooks enabled: true + # Show public homes on the web map show_public_homes: true + # Show warps on the web map show_warps: true -# Disabled commands (e.g. ['/home', '/warp'] to disable /home and /warp) +# List of commands to disable (e.g. ['/home', '/warp'] to disable /home and /warp) disabled_commands: [] ```
diff --git a/docs/Cooldowns.md b/docs/Cooldowns.md new file mode 100644 index 00000000..40d75b6b --- /dev/null +++ b/docs/Cooldowns.md @@ -0,0 +1,46 @@ +HuskHomes supports enforcing a cooldown against certain actions. Players must wait a certain amount of time between performing the action, otherwise the action will not be allowed. The cooldown will be enforced just before the action is performed, and the player will be notified of the remaining cooldown time if they attempt to perform the action before the cooldown has expired. + +## Configuring cooldowns +Cooldowns can be configured in the `cooldowns` section of [`config.yml`](config-files). To enable cooldowns, set `enabled` to `true` and define `cooldown_times` for actions you want to apply cooldowns to. The cooldown time is an integer value, defined in seconds. + +### Bypassing cooldowns +Players with the `huskhomes.bypass_cooldowns` [permission node](commands) bypass cooldowns and can perform them immediately. + +### Table of actions +| Action | Description | +|---------------------------|-------------------------------------------------------------| +| `additional_home_slot` | When a user wants to buy another home slot | +| `make_home_public` | When a user wants to make their home public | +| `random_teleport` | When a user executes /rtp | +| `back_command` | When a user executes /back to return to their last position | +| `home_teleport` | When a user executes /home to teleport to a home | +| `public_home_teleport` | When a user uses /phome to teleport to a public home | +| `warp_teleport` | When a user uses /warp to teleport to a warp | +| `spawn_teleport` | When a user uses /spawn to teleport to spawn | +| `send_teleport_request` | When a user sends a teleport request | +| `accept_teleport_request` | When a user accepts an incoming teleport request | + +### Example config +Cooldowns are defined under `cooldown_times` in the `cooldowns` section of [`config.yml`](config-files). By default, only a cooldown for `random_teleport` is defined. Add the other actions to this section of the file and associate a cooldown with them to enable them. + +
+Defining cooldowns (config.yml) + +```yaml +cooldowns: + # Whether to apply a cooldown between performing certain actions + enabled: true + # Set a cooldown between performing actions (in seconds). Docs: https://william278.net/docs/huskhomes/cooldowns/ + costs: + additional_home_slot: 0 + make_home_public: 0 + random_teleport: 600 + back_command: 0 + home_teleport: 0 + public_home_teleport: 0 + warp_teleport: 0 + spawn_teleport: 0 + send_teleport_request: 0 + accept_teleport_request: 0 +``` +
\ No newline at end of file diff --git a/docs/Economy-Hook.md b/docs/Economy-Hook.md index 99063a4a..f39d18dd 100644 --- a/docs/Economy-Hook.md +++ b/docs/Economy-Hook.md @@ -18,7 +18,7 @@ To enable the Economy Hook on Sponge server, you require a mod installed for man ### Bypassing economy checks -Players with the `huskhomes.bypass.economy` [permission node](commands) bypass economy checks and can perform economy actions without paying. +Players with the `huskhomes.bypass_economy_checks` [permission node](commands) bypass economy checks and can perform economy actions without paying. ## Home slots With the economy hook enabled, players will need to pay for home slots beyond their initial "free" allotment. @@ -31,7 +31,7 @@ You can configure the number of 'free home slots' a user gets using the `free_ho You can set the economy cost for the following actions in the `costs` section of the `config.yml` file. Note that this section by default only has the `additional_home_slot`, `make_home_public` and `random_teleport` actions defined. Add the other actions to this section of the file and associate a price with them to enable them. ### Table of actions -| Economy Action | Description | Default Cost | +| Action | Description | Default Cost | |---------------------------|-------------------------------------------------------------|-------------:| | `additional_home_slot` | When a user wants to buy another home slot | `$100.00` | | `make_home_public` | When a user wants to make their home public | `$50.00` | @@ -46,21 +46,28 @@ You can set the economy cost for the following actions in the `costs` section of ### Example config +> **Warning:** You must specify a decimal monetary value in the config.yml. (i.e. `100.00` is valid, but `100` is not.) + +Economy costs are defined under `costs` in the `economy` section of [`config.yml`](config-files). +
Defining economy costs (config.yml) ```yaml -# Require money to perform certain actions. Check https://william278.net/docs/huskhomes/economy-hook for available actions -costs: - additional_home_slot: 100.0 - make_home_public: 50.0 - random_teleport: 25.0 - back_command: 0.0 - home_teleport: 0.0 - public_home_teleport: 0.0 - warp_teleport: 0.0 - spawn_teleport: 0.0 - send_teleport_request: 0.0 - accept_teleport_request: 0.0 +economy: + # Enable economy plugin integration (requires Vault) + enabled: true + # Charge money for perform certain actions. Docs: https://william278.net/docs/huskhomes/economy-hook/ + costs: + additional_home_slot: 100.0 + make_home_public: 50.0 + random_teleport: 25.0 + back_command: 0.0 + home_teleport: 0.0 + public_home_teleport: 0.0 + warp_teleport: 0.0 + spawn_teleport: 0.0 + send_teleport_request: 0.0 + accept_teleport_request: 0.0 ```
\ No newline at end of file diff --git a/docs/Home.md b/docs/Home.md index 27428548..c2943c18 100644 --- a/docs/Home.md +++ b/docs/Home.md @@ -14,6 +14,7 @@ Welcome to the plugin documentation for HuskHomes v4.x+, the powerful and intuit * 📝 [[Translations]] * 🟩 [[Plan Hook]] * 🗺️ [[Map Hooks]] +* ⏰ [[Cooldowns]] * 💵 [[Economy Hook]] * ⚠️ [[Strict Tpahere]] * 🚫 [[Restricted Warps]] diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md index 0f283754..8b458121 100644 --- a/docs/_Sidebar.md +++ b/docs/_Sidebar.md @@ -11,6 +11,7 @@ * 📝 [[Translations]] * 🟩 [[Plan Hook]] * 🗺️ [[Map Hooks]] +* ⏰ [[Cooldowns]] * 💵 [[Economy Hook]] * ⚠️ [[Strict Tpahere]] * 🚫 [[Restricted Warps]] diff --git a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java index 175a13c6..668f2419 100644 --- a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java +++ b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -133,7 +133,7 @@ public class FabricUser extends OnlineUser { player.teleport( server.getWorld(server.getWorldRegistryKeys().stream() .filter(key -> key.getValue().equals(worldId)).findFirst() - .orElseThrow(() -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND)) + .orElseThrow(() -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND, plugin)) ), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch() diff --git a/gradle.properties b/gradle.properties index 08c6a8ac..b627703b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ javaVersion=16 org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.daemon=true -plugin_version=4.3.3 +plugin_version=4.4 plugin_archive=huskhomes plugin_description=The powerful and intuitive homes, warps, and teleports plugin/mod