Add ability to define cooldowns for actions (#437)

This commit is contained in:
William authored and GitHub committed 2023-06-16 17:39:54 +01:00
1 parent fb052340c0
commit fc8d3b0098
52 files changed
+1140 -619

No files matched your search

@@ -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<Optional<Instant>> 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<Optional<Position>> 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);
@@ -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);
}
}
@@ -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<Home> {
}
// 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<Home> {
// 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";
@@ -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<Home> {
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)
);
}
@@ -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)));
});
}
@@ -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<T extends SavedPosition> 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<T extends SavedPosition> 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<T extends SavedPosition> extends Comm
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, plugin, teleporter.getUsername());
e.displayMessage(executor, teleporter.getUsername());
}
}
@@ -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);
}
}
@@ -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)
@@ -54,7 +54,7 @@ public class TpAllCommand extends InGameCommand {
.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, plugin, args);
e.displayMessage(executor, args);
return;
}
@@ -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) {
@@ -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);
}
}
@@ -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);
}
}
@@ -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<Warp> {
return;
}
this.teleport(executor, optionalTeleporter.get(), warp, EconomyHook.Action.WARP_TELEPORT);
this.teleport(executor, optionalTeleporter.get(), warp, TransactionResolver.Action.WARP_TELEPORT);
}
}
@@ -195,7 +195,8 @@ public class Locales {
CHAT,
ACTION_BAR,
SUBTITLE,
TITLE
TITLE,
NONE
}
}
@@ -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<String, String> 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.<number> 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.<number> permission.")
@YamlKey("general.max_public_homes")
private int maxPublicHomes = 10;
@YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>) 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.<warp_name>) to use warps")
@YamlKey("general.permission_restrict_warps")
private boolean permissionRestrictWarps = false;
@YamlComment("Whether running /sethome <name> or /setwarp <name> 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<String, String> 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<String> 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<String, Integer> 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<String, Double> economyCosts = Arrays.stream(EconomyHook.Action.values())
private Map<String, Double> 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<String> 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<Double> getEconomyCost(@NotNull EconomyHook.Action action) {
public Optional<Double> 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"),
@@ -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 (<i>case-insensitive</i>)
*
* @param name Username of the {@link SavedUser} to get (<i>case-insensitive</i>)
* @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<SavedUser> 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<SavedUser> 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<Instant> 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<Warp> getWarps();
@@ -178,7 +204,7 @@ public abstract class Database {
* Get a list of publicly-set {@link Warp}s on <i>this {@link Server}</i>
*
* @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<Warp> 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<Home> getPublicHomes();
@@ -198,7 +224,7 @@ public abstract class Database {
* Get a list of publicly-set {@link Home}s on <i>this {@link Server}</i>
*
* @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<Home> 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<Home> 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<Home> 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<Home> 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<Warp> 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<Warp> 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<Warp> 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<Teleport> 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<Position> 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<Position> 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<Position> 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"),
@@ -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<SavedUser> 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<SavedUser> 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<Instant> 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<Home> getHomes(@NotNull User user) {
final List<Home> 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) {
@@ -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<SavedUser> 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<SavedUser> 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<Instant> 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<Home> getHomes(@NotNull User user) {
final List<Home> 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<Warp> getWarps() {
final List<Warp> 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<Home> getPublicHomes() {
final List<Home> 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<Home> 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<Home> 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<Warp> 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<Warp> 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<Teleport> 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<Position> 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);
}
@@ -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());
}
}
}
@@ -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<String> 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<String> 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<String> 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);
}
});
}
@@ -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));
}
@@ -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);
}
}
}
@@ -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()
@@ -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<EconomyHook.Action> economyActions;
protected final List<TransactionResolver.Action> 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<EconomyHook.Action> actions,
@NotNull Type type, boolean updateLastPosition, @NotNull List<TransactionResolver.Action> 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<OnlineUser> 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
@@ -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<EconomyHook.Action> economyActions = List.of();
private List<TransactionResolver.Action> 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;
}
@@ -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,
@@ -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<EconomyHook.Action> actions, @NotNull HuskHomes plugin) {
@NotNull List<TransactionResolver.Action> 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);
}
}
@@ -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
* <p>
* 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
}
}
@@ -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.
* <p>
* 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;
}
}
}
@@ -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
}