Adjust schema, fix commands and user data refactoring

This commit is contained in:
William committed 2022-08-09 18:46:12 +01:00
1 parent ec1c0b744f
commit ff2465ac85
12 files changed
+120 -105

No files matched your search

@@ -2,7 +2,6 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
@@ -33,16 +32,16 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso
if (RegexUtil.OWNER_NAME_PATTERN.matcher(homeName).matches()) {
final String ownerName = homeName.split("\\.")[0];
final String ownersHomeName = homeName.split("\\.")[1];
plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData
plugin.getDatabase().getUserDataByName(ownerName).thenAccept(optionalUserData -> optionalUserData
.ifPresentOrElse(userData -> {
if (!userData.uuid.equals(onlineUser.uuid)) {
if (!userData.getUserUuid().equals(onlineUser.uuid)) {
if (!onlineUser.hasPermission(Permission.COMMAND_DELETE_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(onlineUser::sendMessage);
return;
}
}
plugin.getSavedPositionManager().deleteHome(userData, ownersHomeName);
plugin.getSavedPositionManager().deleteHome(userData.user(), ownersHomeName);
},
() -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName, homeName)
.ifPresent(onlineUser::sendMessage)));
@@ -37,8 +37,8 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
if (RegexUtil.OWNER_NAME_PATTERN.matcher(homeName).matches()) {
final String ownerName = homeName.split("\\.")[0];
final String ownersHomeName = homeName.split("\\.")[1];
plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData
.ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(onlineUser, userData, ownersHomeName),
plugin.getDatabase().getUserDataByName(ownerName).thenAccept(optionalUserData -> optionalUserData
.ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(onlineUser, userData.user(), ownersHomeName),
() -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName, homeName)
.ifPresent(onlineUser::sendMessage)));
} else {
@@ -52,23 +52,29 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
return;
}
}
plugin.getDatabase().getUserByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(user -> {
if (!user.uuid.equals(onlineUser.uuid)) {
plugin.getLoggingAdapter().info("Getting home list for " + homeOwner);
plugin.getDatabase().getUserDataByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(userData -> {
plugin.getLoggingAdapter().info("Got user!");
if (!userData.getUserUuid().equals(onlineUser.uuid)) {
if (!onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage);
return;
}
}
plugin.getDatabase().getHomes(user).thenAccept(homes -> {
plugin.getLoggingAdapter().info("User has perms! Getting list...");
plugin.getDatabase().getHomes(userData.user()).thenAccept(homes -> {
plugin.getLoggingAdapter().info("Got home list!");
if (homes.isEmpty()) {
plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage);
return;
}
final PrivateHomeList homeList = new PrivateHomeList(homes, user, plugin);
plugin.getCache().positionLists.put(user.uuid, homeList);
plugin.getLoggingAdapter().info("Making list...");
final PrivateHomeList homeList = new PrivateHomeList(homes, userData.user(), plugin);
plugin.getCache().positionLists.put(userData.user().uuid, homeList);
plugin.getLoggingAdapter().info("Showing list...");
homeList.getDisplay(pageNumber).forEach(onlineUser::sendMessage);
});
}, () -> plugin.getLocales().getLocale("error_invalid_user").ifPresent(onlineUser::sendMessage)));
}, () -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(onlineUser::sendMessage)));
}
@@ -1,6 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.list.WarpList;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -16,11 +17,21 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
final String warpName = args[0];
plugin.getTeleportManager().teleportToWarp(onlineUser, warpName);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/warp [name]")
switch (args.length) {
case 0 -> plugin.getDatabase().getWarps().thenAccept(warps -> {
if (warps.isEmpty()) {
plugin.getLocales().getLocale("error_no_warps_set").ifPresent(onlineUser::sendMessage);
return;
}
final WarpList warpList = new WarpList(warps, plugin);
plugin.getCache().positionLists.put(onlineUser.uuid, warpList);
warpList.getDisplay(1).forEach(onlineUser::sendMessage);
});
case 1 -> {
final String warpName = args[0];
plugin.getTeleportManager().teleportToWarp(onlineUser, warpName);
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/warp [name]")
.ifPresent(onlineUser::sendMessage);
}
}
@@ -222,20 +222,20 @@ public abstract class Database {
public abstract CompletableFuture<Void> ensureUser(@NotNull User user);
/**
* Get a user by their username (<i>case-insensitive</i>)
* Get {@link UserData} for a user by their Minecraft username (<i>case-insensitive</i>)
*
* @param name Username of the {@link UserData} to get (<i>case-insensitive</i>)
* @return A future returning an optional with the {@link UserData} present if they exist
*/
public abstract CompletableFuture<Optional<UserData>> getUserByName(@NotNull String name);
public abstract CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name);
/**
* Get a player by their Minecraft account {@link UUID}
* Get {@link UserData} for a user by their Minecraft account {@link UUID}
*
* @param uuid Minecraft account {@link UUID} of the {@link UserData} to get
* @return A future returning an optional with the {@link UserData} present if they exist
*/
public abstract CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid);
public abstract CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid);
/**
@@ -2,7 +2,6 @@ package net.william278.huskhomes.database;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
@@ -145,7 +144,11 @@ public class MySqlDatabase extends Database {
statement.setString(8, position.server.name);
statement.executeUpdate();
return statement.getGeneratedKeys().getInt(1);
final ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet.next()) {
return resultSet.getInt(1);
}
throw new SQLException("Failed to insert position into database");
}
}
@@ -188,7 +191,11 @@ public class MySqlDatabase extends Database {
statement.setTimestamp(4, new Timestamp(Instant.ofEpochSecond(position.meta.timestamp).toEpochMilli()));
statement.executeUpdate();
return statement.getGeneratedKeys().getInt(1);
final ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet.next()) {
return resultSet.getInt(1);
}
throw new SQLException("Failed to insert saved position into database");
}
}
@@ -221,9 +228,9 @@ public class MySqlDatabase extends Database {
@Override
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) {
return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser ->
optionalUser.ifPresentOrElse(existingUser -> {
if (!existingUser.username.equals(onlineUser.username)) {
return CompletableFuture.runAsync(() -> getUserData(onlineUser.uuid).thenAccept(optionalUser ->
optionalUser.ifPresentOrElse(existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.username)) {
// Update a player's name if it has changed in the database
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -232,10 +239,10 @@ public class MySqlDatabase extends Database {
WHERE `uuid`=?"""))) {
statement.setString(1, onlineUser.username);
statement.setString(2, existingUser.uuid.toString());
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")");
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.username + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -259,34 +266,43 @@ public class MySqlDatabase extends Database {
}
@Override
public CompletableFuture<Optional<UserData>> getUserByName(@NotNull String name) {
public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
getLogger().info("Getting user data by name for " + name);
try (Connection connection = getConnection()) {
getLogger().info("Got connection");
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
FROM `%players_table%`
WHERE `username`=?"""))) {
statement.setString(1, name);
getLogger().info("Set str");
final ResultSet resultSet = statement.executeQuery();
getLogger().info("Got results");
if (resultSet.next()) {
getLogger().info("resultset paged to next");
return Optional.of(new UserData(
UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username"),
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
resultSet.getBoolean("ignoring_requests"),
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
} catch (Exception e) {
e.printStackTrace();
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid) {
public CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -299,8 +315,8 @@ public class MySqlDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username"),
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
resultSet.getBoolean("ignoring_requests"),
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
@@ -619,14 +635,14 @@ public class MySqlDatabase extends Database {
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, userData.homeSlots);
statement.setBoolean(2, userData.isIgnoringTeleports);
statement.setLong(3, userData.rtpCooldown);
statement.setString(4, userData.uuid.toString());
statement.setInt(1, userData.homeSlots());
statement.setBoolean(2, userData.ignoringTeleports());
statement.setLong(3, userData.rtpCooldown());
statement.setString(4, userData.getUserUuid().toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.username + " on the database", e);
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e);
}
});
}
@@ -705,7 +721,7 @@ public class MySqlDatabase extends Database {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `last_position`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = "%positions_table%".id
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
@@ -767,7 +783,7 @@ public class MySqlDatabase extends Database {
try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `offline_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = "%positions_table%".id
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
@@ -829,7 +845,7 @@ public class MySqlDatabase extends Database {
try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `respawn_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = "%positions_table%".id
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
@@ -1,7 +1,6 @@
package net.william278.huskhomes.database;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
@@ -204,9 +203,9 @@ public class SqLiteDatabase extends Database {
@Override
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) {
return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser ->
return CompletableFuture.runAsync(() -> getUserData(onlineUser.uuid).thenAccept(optionalUser ->
optionalUser.ifPresentOrElse(existingUser -> {
if (!existingUser.username.equals(onlineUser.username)) {
if (!existingUser.getUsername().equals(onlineUser.username)) {
// Update a player's name if it has changed in the database
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -215,10 +214,10 @@ public class SqLiteDatabase extends Database {
WHERE `uuid`=?"""))) {
statement.setString(1, onlineUser.username);
statement.setString(2, existingUser.uuid.toString());
statement.setString(2, existingUser.getUserUuid().toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")");
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.username + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -242,7 +241,7 @@ public class SqLiteDatabase extends Database {
}
@Override
public CompletableFuture<Optional<UserData>> getUserByName(@NotNull String name) {
public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -254,8 +253,8 @@ public class SqLiteDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username"),
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
resultSet.getBoolean("ignoring_requests"),
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
@@ -269,7 +268,7 @@ public class SqLiteDatabase extends Database {
}
@Override
public CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid) {
public CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -282,8 +281,8 @@ public class SqLiteDatabase extends Database {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new UserData(
UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username"),
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
resultSet.getInt("home_slots"),
resultSet.getBoolean("ignoring_requests"),
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
@@ -602,14 +601,14 @@ public class SqLiteDatabase extends Database {
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, userData.homeSlots);
statement.setBoolean(2, userData.isIgnoringTeleports);
statement.setLong(3, userData.rtpCooldown);
statement.setString(4, userData.uuid.toString());
statement.setInt(1, userData.homeSlots());
statement.setBoolean(2, userData.ignoringTeleports());
statement.setLong(3, userData.rtpCooldown());
statement.setString(4, userData.getUserUuid().toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.username + " on the database", e);
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e);
}
});
}
@@ -687,7 +686,7 @@ public class SqLiteDatabase extends Database {
try {
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
SELECT `last_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = "%positions_table%".id
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
@@ -749,7 +748,7 @@ public class SqLiteDatabase extends Database {
try {
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
SELECT `offline_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = "%positions_table%".id
INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
@@ -811,7 +810,7 @@ public class SqLiteDatabase extends Database {
try {
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
SELECT `respawn_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = "%positions_table%".id
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.uuid.toString());
@@ -15,7 +15,7 @@ public class EventListener {
@NotNull
protected final HuskHomes plugin;
public EventListener(@NotNull HuskHomes implementor) {
protected EventListener(@NotNull HuskHomes implementor) {
this.plugin = implementor;
}
@@ -24,9 +24,11 @@ public class EventListener {
*
* @param onlineUser the joining {@link OnlineUser}
*/
public void onPlayerJoin(@NotNull OnlineUser onlineUser) {
protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) {
plugin.getLoggingAdapter().info("Player " + onlineUser.username + " joined");
// Ensure the player is present on the database first
plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> {
plugin.getLoggingAdapter().info("Player " + onlineUser.username + " ensured");
// If the server is in proxy mode, check if the player is teleporting cross-server and handle
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
@@ -64,7 +66,7 @@ public class EventListener {
*
* @param onlineUser the leaving {@link OnlineUser}
*/
public void onPlayerLeave(@NotNull OnlineUser onlineUser) {
protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) {
// Remove this user's home cache
plugin.getCache().homes.remove(onlineUser.uuid);
@@ -87,7 +89,7 @@ public class EventListener {
*
* @param onlineUser the {@link OnlineUser} who died
*/
public void onPlayerDeath(@NotNull OnlineUser onlineUser) {
protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) {
//todo
}
@@ -96,14 +98,14 @@ public class EventListener {
*
* @param onlineUser the respawning {@link OnlineUser}
*/
public void onPlayerRespawn(@NotNull OnlineUser onlineUser) {
protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) {
//todo
}
/**
* Handle when the plugin is disabling (server is shutting down)
*/
public void handlePluginDisable() {
public final void handlePluginDisable() {
//todo
}
@@ -5,40 +5,17 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Extension of a {@link User} that contains persistently-stored additional user data
* (home slots, teleport ignoring status & rtp cooldown)
* Represents data about a player on the server
*/
public class UserData extends User {
public record UserData(@NotNull User user, int homeSlots, boolean ignoringTeleports, long rtpCooldown) {
/**
* The number of slots this user has consumed (bought) in total, used for economy checks
*/
public int homeSlots;
/**
* Whether this user is ignoring incoming /tpa and /tpahere requests
*/
public boolean isIgnoringTeleports;
/**
* A timestamp indicating when the user can use the /rtp command next
*/
public long rtpCooldown;
public UserData(@NotNull UUID uuid, @NotNull String username,
int homeSlots, boolean isIgnoringTeleports, long rtpCooldown) {
super(uuid, username);
this.homeSlots = homeSlots;
this.isIgnoringTeleports = isIgnoringTeleports;
this.rtpCooldown = rtpCooldown;
@NotNull
public UUID getUserUuid() {
return user.uuid;
}
public UserData(@NotNull User user,
int homeSlots, boolean isIgnoringTeleports, long rtpCooldown) {
super(user.uuid, user.username);
this.homeSlots = homeSlots;
this.isIgnoringTeleports = isIgnoringTeleports;
this.rtpCooldown = rtpCooldown;
public String getUsername() {
return user.username;
}
}