mirror of
https://github.com/darksaid98/HuskHomes.git
synced 2026-12-02 06:28:49 +00:00
SQLite, network messaging, caching, redis, more bukkit implementing
This commit is contained in:
1 parent
28a54b0b4a
commit
052eb57438
24 files changed
+1855
-38
No files matched your search
@@ -1,13 +1,14 @@
|
||||
package net.william278.huskhomes;
|
||||
|
||||
import net.william278.huskhomes.cache.Cache;
|
||||
import net.william278.huskhomes.config.Messages;
|
||||
import net.william278.huskhomes.config.Settings;
|
||||
import net.william278.huskhomes.data.Database;
|
||||
import net.william278.huskhomes.player.Player;
|
||||
import net.william278.huskhomes.position.Position;
|
||||
import net.william278.huskhomes.position.Server;
|
||||
import net.william278.huskhomes.util.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
@@ -27,7 +28,7 @@ public interface HuskHomes {
|
||||
*
|
||||
* @return a {@link Set} of currently online {@link Player}s
|
||||
*/
|
||||
Set<Player> getOnlinePlayers();
|
||||
List<Player> getOnlinePlayers();
|
||||
|
||||
/**
|
||||
* The plugin {@link Settings} loaded from file
|
||||
@@ -43,13 +44,6 @@ public interface HuskHomes {
|
||||
*/
|
||||
Messages getMessages();
|
||||
|
||||
/**
|
||||
* The {@link Server} the plugin is running on
|
||||
*
|
||||
* @return the {@link Server} object representing the implementing server
|
||||
*/
|
||||
Server getServerData();
|
||||
|
||||
/**
|
||||
* The {@link Database} that stores persistent plugin data
|
||||
*
|
||||
@@ -57,6 +51,38 @@ public interface HuskHomes {
|
||||
*/
|
||||
Database getDatabase();
|
||||
|
||||
/**
|
||||
* The {@link Cache} that holds cached data
|
||||
*
|
||||
* @return the plugin {@link Cache}
|
||||
*/
|
||||
Cache getCache();
|
||||
|
||||
/**
|
||||
* Returns true if the position is a valid location on the server
|
||||
*
|
||||
* @param position The {@link Position} to check
|
||||
* @return {@code true} if the position is a valid one on the server; {@code false} otherwise
|
||||
*/
|
||||
boolean isValidPositionOnServer(Position position);
|
||||
|
||||
/**
|
||||
* (Re)-load config and message data from files
|
||||
*/
|
||||
void loadConfigData();
|
||||
|
||||
/**
|
||||
* Get the HuskHomes plugin version
|
||||
*
|
||||
* @return the HuskHomes plugin version string
|
||||
*/
|
||||
String getPluginVersion();
|
||||
|
||||
/**
|
||||
* Get the platform type (e.g. Spigot, Paper etc)
|
||||
*
|
||||
* @return the type of server platform string
|
||||
*/
|
||||
String getPlatformType();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package net.william278.huskhomes.cache;
|
||||
|
||||
import net.william278.huskhomes.data.Database;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A cache used to hold persistently used data
|
||||
*/
|
||||
public class Cache {
|
||||
|
||||
/**
|
||||
* Cached home names - maps a {@link UUID} to a list of their homes
|
||||
*/
|
||||
public final HashMap<UUID, List<String>> homes;
|
||||
|
||||
/**
|
||||
* Cached home names - maps a username to a list of their public homes
|
||||
*/
|
||||
public final HashMap<String, List<String>> publicHomes;
|
||||
|
||||
/**
|
||||
* Cached warp names
|
||||
*/
|
||||
public final List<String> warps;
|
||||
|
||||
/**
|
||||
* Create a new cache
|
||||
*/
|
||||
public Cache() {
|
||||
this.homes = new HashMap<>();
|
||||
this.publicHomes = new HashMap<>();
|
||||
this.warps = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the cache, request basic data to load into memory
|
||||
*
|
||||
* @param database the database to load data from
|
||||
*/
|
||||
public void initialize(@NotNull Database database) {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
database.getPublicHomes().thenAccept(publicHomeList -> publicHomeList.forEach(home ->
|
||||
this.publicHomes.computeIfAbsent(home.owner.username, key -> new ArrayList<>()).add(home.meta.name)));
|
||||
database.getWarps().thenAccept(warpsList -> warpsList.forEach(warp ->
|
||||
this.warps.add(warp.meta.name)));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -384,4 +384,10 @@ public abstract class Database {
|
||||
*/
|
||||
public abstract CompletableFuture<Void> deleteWarp(@NotNull UUID uuid);
|
||||
|
||||
/**
|
||||
* Close any remaining connection to the database source
|
||||
*/
|
||||
public abstract void terminate();
|
||||
|
||||
|
||||
}
|
||||
@@ -418,11 +418,11 @@ public class MySqlDatabase extends Database {
|
||||
try (Connection connection = getConnection()) {
|
||||
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
|
||||
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
|
||||
FROM `%homes_table%`
|
||||
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `%homes_table%`.`uuid`=?;"""))) {
|
||||
FROM `%homes_table%`
|
||||
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `%homes_table%`.`uuid`=?;"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
@@ -880,4 +880,13 @@ public class MySqlDatabase extends Database {
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void terminate() {
|
||||
if (dataSource != null) {
|
||||
if (!dataSource.isClosed()) {
|
||||
dataSource.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
package net.william278.huskhomes.data;
|
||||
|
||||
import net.william278.huskhomes.config.Settings;
|
||||
import net.william278.huskhomes.player.Player;
|
||||
import net.william278.huskhomes.player.User;
|
||||
import net.william278.huskhomes.player.UserData;
|
||||
import net.william278.huskhomes.position.*;
|
||||
import net.william278.huskhomes.teleport.Teleport;
|
||||
import net.william278.huskhomes.util.Logger;
|
||||
import net.william278.huskhomes.util.ResourceReader;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.*;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.logging.Level;
|
||||
|
||||
/**
|
||||
* An SQLite implementation of the plugin {@link Database}
|
||||
*/
|
||||
@SuppressWarnings("DuplicatedCode")
|
||||
public class SqLiteDatabase extends Database {
|
||||
|
||||
/**
|
||||
* Path to the SQLite HuskHomesData.db file
|
||||
*/
|
||||
private final File databaseFile;
|
||||
|
||||
/**
|
||||
* The name of the database file
|
||||
*/
|
||||
private static final String DATABASE_FILE_NAME = "HuskHomesData.db";
|
||||
|
||||
/**
|
||||
* The persistent SQLite database connection
|
||||
*/
|
||||
private Connection connection;
|
||||
|
||||
|
||||
public SqLiteDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
|
||||
super(settings, logger, resourceReader);
|
||||
this.databaseFile = new File(resourceReader.getDataFolder(), DATABASE_FILE_NAME);
|
||||
}
|
||||
|
||||
private Connection getConnection() throws SQLException {
|
||||
if (connection == null) {
|
||||
setConnection();
|
||||
} else if (connection.isClosed()) {
|
||||
setConnection();
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
private void setConnection() {
|
||||
try {
|
||||
// Ensures the database file exists
|
||||
if (databaseFile.createNewFile()) {
|
||||
getLogger().log(Level.INFO, "Created the SQLite database file");
|
||||
}
|
||||
|
||||
// Establish the connection using the JDBC SQLite driver
|
||||
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
getLogger().log(Level.SEVERE, "An exception occurred creating the database file", e);
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> initialize() {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
setConnection();
|
||||
|
||||
// Prepare database schema; make tables if they don't exist
|
||||
try {
|
||||
// Load database schema CREATE statements from schema file
|
||||
final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql");
|
||||
try (Statement statement = getConnection().createStatement()) {
|
||||
for (String tableCreationStatement : databaseSchema) {
|
||||
statement.execute(tableCreationStatement);
|
||||
}
|
||||
}
|
||||
} catch (SQLException | IOException e) {
|
||||
getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
|
||||
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
|
||||
VALUES (?,?,?,?,?,?,?,?);"""),
|
||||
Statement.RETURN_GENERATED_KEYS)) {
|
||||
|
||||
statement.setDouble(1, position.x);
|
||||
statement.setDouble(2, position.y);
|
||||
statement.setDouble(3, position.z);
|
||||
statement.setFloat(4, position.yaw);
|
||||
statement.setFloat(5, position.pitch);
|
||||
statement.setString(6, position.world.name);
|
||||
statement.setString(7, position.world.uuid.toString());
|
||||
statement.setString(8, position.server.name);
|
||||
statement.executeUpdate();
|
||||
|
||||
return statement.getGeneratedKeys().getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int setPositionMeta(@NotNull PositionMeta meta, @NotNull Connection connection) throws SQLException {
|
||||
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%position_metadata_table%` (`name`, `description`, `timestamp`)
|
||||
VALUES (?,?,?);"""),
|
||||
Statement.RETURN_GENERATED_KEYS)) {
|
||||
|
||||
statement.setString(1, meta.name);
|
||||
statement.setString(2, meta.description);
|
||||
statement.setTimestamp(3, new Timestamp(Instant.ofEpochSecond(meta.timestamp).toEpochMilli()));
|
||||
statement.executeUpdate();
|
||||
|
||||
return statement.getGeneratedKeys().getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> ensureUser(@NotNull Player player) {
|
||||
return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser ->
|
||||
optionalUser.ifPresentOrElse(existingUser -> {
|
||||
if (!existingUser.username.equals(player.getName())) {
|
||||
// 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`=?"""))) {
|
||||
|
||||
statement.setString(1, player.getName());
|
||||
statement.setString(2, existingUser.uuid.toString());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username + " -> " + player.getName() + ")");
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
|
||||
}
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
// Insert new player data into the database
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%players_table%` (`uuid`,`username`)
|
||||
VALUES (?,?);"""))) {
|
||||
|
||||
statement.setString(1, player.getUuid().toString());
|
||||
statement.setString(2, player.getName());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e);
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<UserData>> getUserByName(@NotNull String name) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `uuid`, `username`
|
||||
FROM `%players_table%`
|
||||
WHERE `username`=?"""))) {
|
||||
statement.setString(1, name);
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new UserData(
|
||||
UUID.fromString(resultSet.getString("uuid")),
|
||||
resultSet.getString("username"),
|
||||
resultSet.getInt("home_slots"),
|
||||
resultSet.getBoolean("ignoring_requests"),
|
||||
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `uuid`, `username`
|
||||
FROM `%players_table%`
|
||||
WHERE `uuid`=?"""))) {
|
||||
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new UserData(
|
||||
UUID.fromString(resultSet.getString("uuid")),
|
||||
resultSet.getString("username"),
|
||||
resultSet.getInt("home_slots"),
|
||||
resultSet.getBoolean("ignoring_requests"),
|
||||
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<List<Home>> getHomes(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final List<Home> userHomes = new ArrayList<>();
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
|
||||
FROM `%homes_table%`
|
||||
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `owner_uuid`=?
|
||||
ORDER BY `name`;"""))) {
|
||||
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
userHomes.add(new Home(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("home_uuid")),
|
||||
user,
|
||||
resultSet.getBoolean("public")));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username);
|
||||
}
|
||||
return userHomes;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<List<Warp>> getWarps() {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final List<Warp> warps = new ArrayList<>();
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%warps_table%`
|
||||
INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
ORDER BY `name`;"""))) {
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
warps.add(new Warp(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("warp_uuid"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the database for warp data.");
|
||||
}
|
||||
return warps;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<List<Home>> getPublicHomes() {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
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`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
|
||||
FROM `%homes_table%`
|
||||
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `public`=true
|
||||
ORDER BY `name`;"""))) {
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
userHomes.add(new Home(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("home_uuid")),
|
||||
new User(UUID.fromString(resultSet.getString("owner_uuid")),
|
||||
resultSet.getString("owner_username")),
|
||||
resultSet.getBoolean("public")));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the database for public home data");
|
||||
}
|
||||
return userHomes;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
|
||||
FROM `%homes_table%`
|
||||
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `owner_uuid`=?
|
||||
AND `name`=?;"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
statement.setString(2, homeName);
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Home(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("home_uuid")),
|
||||
new User(UUID.fromString(resultSet.getString("owner_uuid")),
|
||||
resultSet.getString("owner_username")),
|
||||
resultSet.getBoolean("public")));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query a player's home", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Home>> getHome(@NotNull UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
|
||||
FROM `%homes_table%`
|
||||
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `%homes_table%`.`uuid`=?;"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Home(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("home_uuid")),
|
||||
new User(UUID.fromString(resultSet.getString("owner_uuid")),
|
||||
resultSet.getString("owner_username")),
|
||||
resultSet.getBoolean("public")));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query a player's home by UUID", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%warps_table%`
|
||||
INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `name`=?;"""))) {
|
||||
statement.setString(1, warpName);
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Warp(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("warp_uuid"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%warps_table%`
|
||||
INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id`
|
||||
WHERE `%warps_table%`.uuid=?;"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Warp(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")),
|
||||
new PositionMeta(resultSet.getString("name"),
|
||||
resultSet.getString("description"),
|
||||
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
|
||||
UUID.fromString(resultSet.getString("warp_uuid"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%teleports_table%`
|
||||
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
|
||||
WHERE `player_uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Teleport(user,
|
||||
new Position(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name")))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> updateUserData(@NotNull UserData userData) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
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.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.username + " on the database", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
if (teleport == null) {
|
||||
// Clear the user's current teleport
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%teleports_table%`
|
||||
WHERE `player_uuid`=?;"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e);
|
||||
}
|
||||
} else {
|
||||
// Set the user's teleport into the database
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`)
|
||||
VALUES (?,?);"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
statement.setInt(2, setPosition(teleport.target, getConnection()));
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id`
|
||||
WHERE `uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Position(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setLastPosition(@NotNull User user, @NotNull Position position) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `last_position`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setInt(1, setPosition(position, getConnection()));
|
||||
statement.setString(2, user.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
|
||||
WHERE `uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Position(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setOfflinePosition(@NotNull User user, @NotNull Position position) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `offline_position`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setInt(1, setPosition(position, getConnection()));
|
||||
statement.setString(2, user.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id`
|
||||
WHERE `uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Position(resultSet.getDouble("x"),
|
||||
resultSet.getDouble("y"),
|
||||
resultSet.getDouble("z"),
|
||||
resultSet.getFloat("yaw"),
|
||||
resultSet.getFloat("pitch"),
|
||||
new World(resultSet.getString("world_name"),
|
||||
UUID.fromString(resultSet.getString("world_uuid"))),
|
||||
new Server(resultSet.getString("server_name"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setRespawnPosition(@NotNull User user, @Nullable Position position) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
if (position == null) {
|
||||
// Clear the respawn position
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `respawn_position`=NULL
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
|
||||
}
|
||||
} else {
|
||||
// Set the respawn position
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `respawn_position`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setInt(1, setPosition(position, getConnection()));
|
||||
statement.setString(2, user.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setHome(@NotNull Home home) {
|
||||
return CompletableFuture.runAsync(() -> getHome(home.uuid)
|
||||
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%homes_table%`
|
||||
SET `position_id`=?, `metadata_id`=?, `public`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setInt(1, setPosition(home, getConnection()));
|
||||
statement.setInt(2, setPositionMeta(home.meta, getConnection()));
|
||||
statement.setBoolean(3, home.isPublic);
|
||||
statement.setString(4, home.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE,
|
||||
"Failed to update a home in the database for " + home.owner.username, e);
|
||||
}
|
||||
}, () -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%homes_table%` (`uuid`, `owner_uuid`, `position_id`, `metadata_id`, `public`)
|
||||
VALUES (?,?,?,?,?);"""))) {
|
||||
statement.setString(1, home.uuid.toString());
|
||||
statement.setString(2, home.owner.uuid.toString());
|
||||
statement.setInt(3, setPosition(home, getConnection()));
|
||||
statement.setInt(4, setPositionMeta(home.meta, getConnection()));
|
||||
statement.setBoolean(5, home.isPublic);
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE,
|
||||
"Failed to set a home to the database for " + home.owner.username, e);
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setWarp(@NotNull Warp warp) {
|
||||
return CompletableFuture.runAsync(() -> getWarp(warp.uuid)
|
||||
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%warps_table%`
|
||||
SET `position_id`=?, `metadata_id`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setInt(1, setPosition(warp, getConnection()));
|
||||
statement.setInt(2, setPositionMeta(warp.meta, getConnection()));
|
||||
statement.setString(3, warp.uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e);
|
||||
}
|
||||
}, () -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%warps_table%` (`uuid`, `position_id`, `metadata_id`)
|
||||
VALUES (?,?,?);"""))) {
|
||||
statement.setString(1, warp.uuid.toString());
|
||||
statement.setInt(2, setPosition(warp, getConnection()));
|
||||
statement.setInt(3, setPositionMeta(warp.meta, getConnection()));
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e);
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> deleteHome(@NotNull UUID uuid) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%homes_table%`
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> deleteWarp(@NotNull UUID uuid) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%warps_table%`
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void terminate() {
|
||||
try {
|
||||
if (connection != null) {
|
||||
if (!connection.isClosed()) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.WARNING, "Failed to properly close the SQLite connection");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,13 +6,15 @@ import net.william278.huskhomes.player.Player;
|
||||
import net.william278.huskhomes.player.User;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A handler for when events take place
|
||||
*/
|
||||
public class EventProcessor {
|
||||
|
||||
@NotNull
|
||||
private final HuskHomes implementor;
|
||||
protected final HuskHomes implementor;
|
||||
|
||||
public EventProcessor(@NotNull HuskHomes implementor) {
|
||||
this.implementor = implementor;
|
||||
@@ -26,6 +28,7 @@ public class EventProcessor {
|
||||
public void onPlayerJoin(@NotNull Player player) {
|
||||
// Ensure the player is present on the database first
|
||||
implementor.getDatabase().ensureUser(player).thenRun(() -> {
|
||||
|
||||
// If the server is in proxy mode, check if the player is teleporting cross-server
|
||||
if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
|
||||
implementor.getDatabase().getCurrentTeleport(new User(player))
|
||||
@@ -39,7 +42,17 @@ public class EventProcessor {
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
// Cache this user's homes
|
||||
implementor.getDatabase().getHomes(new User(player)).thenAccept(homes ->
|
||||
implementor.getCache().homes.put(player.getUuid(),
|
||||
homes.stream().map(home -> home.meta.name).collect(Collectors.toList())));
|
||||
});
|
||||
}
|
||||
|
||||
public void onPlayerLeave(@NotNull Player player) {
|
||||
// Remove this user's home cache
|
||||
implementor.getCache().homes.remove(player.getUuid());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package net.william278.huskhomes.messenger;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A message sent cross-proxy to a player
|
||||
*/
|
||||
public class Message {
|
||||
|
||||
/**
|
||||
* A unique ID representing this message
|
||||
*/
|
||||
@NotNull
|
||||
public UUID uuid;
|
||||
|
||||
/**
|
||||
* The type of the message
|
||||
*/
|
||||
@NotNull
|
||||
public MessageType type;
|
||||
|
||||
/**
|
||||
* The kind of message this is - {@link MessageKind#MESSAGE} or a {@link MessageKind#REPLY} to a message.
|
||||
*/
|
||||
@NotNull
|
||||
public MessageKind kind;
|
||||
|
||||
/**
|
||||
* Username of the target player the message is bound for
|
||||
*/
|
||||
@SerializedName("target_player")
|
||||
@NotNull
|
||||
public String targetPlayer;
|
||||
|
||||
/**
|
||||
* Username of the sender of the message
|
||||
*/
|
||||
@NotNull
|
||||
public String sender;
|
||||
|
||||
/**
|
||||
* ID of the cluster this message is for
|
||||
*/
|
||||
@SerializedName("cluster_id")
|
||||
public int clusterId;
|
||||
|
||||
/**
|
||||
* Data to send in the message
|
||||
*/
|
||||
@NotNull
|
||||
public String payload;
|
||||
|
||||
public Message(@NotNull MessageType type, @NotNull String sender, @NotNull String targetPlayer,
|
||||
@NotNull MessagePayload payload, @NotNull MessageKind messageKind, int clusterId) {
|
||||
this.type = type;
|
||||
this.sender = sender;
|
||||
this.targetPlayer = targetPlayer;
|
||||
this.payload = payload.toJson();
|
||||
this.kind = messageKind;
|
||||
this.clusterId = clusterId;
|
||||
this.uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
public String toJson() {
|
||||
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
|
||||
}
|
||||
|
||||
public static Message fromJson(String json) {
|
||||
return new GsonBuilder().setPrettyPrinting().create().fromJson(json, Message.class);
|
||||
}
|
||||
|
||||
public enum MessageType {
|
||||
TP_REQUEST
|
||||
}
|
||||
|
||||
public enum MessageKind {
|
||||
MESSAGE,
|
||||
REPLY
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other instanceof Message message) {
|
||||
return message.uuid.equals(this.uuid);
|
||||
}
|
||||
return super.equals(other);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.william278.huskhomes.messenger;
|
||||
|
||||
/**
|
||||
* Represents data that can be sent as a payload in a {@link Message}
|
||||
*/
|
||||
public interface MessagePayload {
|
||||
|
||||
String toJson();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package net.william278.huskhomes.messenger;
|
||||
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.config.Settings;
|
||||
import net.william278.huskhomes.player.Player;
|
||||
import net.william278.huskhomes.position.Server;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public abstract class NetworkMessenger {
|
||||
|
||||
/**
|
||||
* Name of the network message channel for HuskHomes messages
|
||||
*/
|
||||
public static final String NETWORK_MESSAGE_CHANNEL = "huskhomes:main";
|
||||
|
||||
/**
|
||||
* Map of message UUIDs to messages being processed
|
||||
*/
|
||||
protected HashMap<UUID, CompletableFuture<Message>> processingMessages;
|
||||
|
||||
/**
|
||||
* Future for processing {@link #getServerName(Player)} requests
|
||||
*/
|
||||
protected CompletableFuture<String> serverNameRequest;
|
||||
|
||||
/**
|
||||
* Future for processing {@link #getOnlinePlayerNames(Player)} requests
|
||||
*/
|
||||
protected CompletableFuture<String[]> onlinePlayerNamesRequest;
|
||||
|
||||
/**
|
||||
* Future for processing {@link #getOnlineServers(Player)} requests
|
||||
*/
|
||||
protected CompletableFuture<String[]> onlineServersRequest;
|
||||
|
||||
/**
|
||||
* ID of the HuskHomes network cluster this server is on
|
||||
*/
|
||||
protected int clusterId;
|
||||
|
||||
/**
|
||||
* Initialize the network messenger
|
||||
*
|
||||
* @param implementor Instance of the implementing plugin
|
||||
*/
|
||||
public void initialize(@NotNull HuskHomes implementor) {
|
||||
this.processingMessages = new HashMap<>();
|
||||
this.clusterId = implementor.getSettings().getIntegerValue(Settings.ConfigOption.CLUSTER_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a list of online player usernames from the proxy
|
||||
*
|
||||
* @param requester {@link Player} to send the request
|
||||
* @return Future returning a {@link List} of usernames of players on the proxy network
|
||||
*/
|
||||
public abstract CompletableFuture<String[]> getOnlinePlayerNames(@NotNull Player requester);
|
||||
|
||||
/**
|
||||
* Fetch the name of this server on the proxy network
|
||||
*
|
||||
* @param requester {@link Player} to send the request
|
||||
* @return Future returning the name of this server on the network
|
||||
*/
|
||||
public abstract CompletableFuture<String> getServerName(@NotNull Player requester);
|
||||
|
||||
/**
|
||||
* Fetch a list of online server names proxy
|
||||
*
|
||||
* @param requester {@link Player} to send the request
|
||||
* @return Future returning a {@link List} of online servers connected to the proxy network
|
||||
*/
|
||||
public abstract CompletableFuture<String[]> getOnlineServers(@NotNull Player requester);
|
||||
|
||||
/**
|
||||
* Send a {@link Player} to a target {@link Server} on the proxy network
|
||||
*
|
||||
* @param server The {@link Server} to send the {@link Player} to
|
||||
* @return A future, returning {@code true} if the player was sent.<p>
|
||||
* If the player could not be sent (i.e. the server was offline), this will return {@code false}
|
||||
*/
|
||||
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull Player player, @NotNull Server server);
|
||||
|
||||
/**
|
||||
* Send a network {@link Message} to a target player on the proxy
|
||||
*
|
||||
* @param message The {@link Message} to send
|
||||
* @return A future containing a reply to the {@link Message} that was sent
|
||||
*/
|
||||
public abstract CompletableFuture<Message> sendMessage(@NotNull Player sender, @NotNull Message message);
|
||||
|
||||
/**
|
||||
* Send a reply to a received {@link Message}
|
||||
*
|
||||
* @param reply The reply {@link Message} to send
|
||||
* @return A future completing when the message has been sent
|
||||
*/
|
||||
protected abstract CompletableFuture<Void> sendReply(@NotNull Player replier, @NotNull Message reply);
|
||||
|
||||
/**
|
||||
* Handle and action received network {@link Message}s
|
||||
*
|
||||
* @param receiver The online {@link Player} receiving the message
|
||||
* @param message The received {@link Message}
|
||||
*/
|
||||
protected final void handleMessage(@NotNull Player receiver, @NotNull Message message) {
|
||||
switch (message.kind) {
|
||||
// Handle a message and send reply
|
||||
case MESSAGE -> {
|
||||
// Handle different message types and apply changes for reply message
|
||||
switch (message.type) {
|
||||
case TP_REQUEST -> {
|
||||
message = message;
|
||||
}
|
||||
}
|
||||
|
||||
// Reply with the modified message
|
||||
message.targetPlayer = message.sender;
|
||||
message.sender = receiver.getName();
|
||||
sendReply(receiver, message);
|
||||
}
|
||||
// Handle a reply message
|
||||
case REPLY -> {
|
||||
if (processingMessages.containsKey(message.uuid)) {
|
||||
final Message finalMessage = message;
|
||||
processingMessages.get(message.uuid).completeAsync(() -> finalMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the network messenger
|
||||
*/
|
||||
public abstract void terminate();
|
||||
|
||||
}
|
||||
@@ -33,7 +33,7 @@ public interface Player {
|
||||
*
|
||||
* @return the player's current {@link Position}
|
||||
*/
|
||||
Position getPosition();
|
||||
CompletableFuture<Position> getPosition();
|
||||
|
||||
/**
|
||||
* Returns if the player has the permission node
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package net.william278.huskhomes.position;
|
||||
|
||||
import net.william278.huskhomes.player.Player;
|
||||
import net.william278.huskhomes.player.User;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package net.william278.huskhomes.redis;
|
||||
|
||||
import net.william278.huskhomes.config.Settings;
|
||||
import net.william278.huskhomes.messenger.Message;
|
||||
import net.william278.huskhomes.messenger.NetworkMessenger;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Handles Redis database pub/sub network messaging requests over Jedis
|
||||
*/
|
||||
public class RedisWorker {
|
||||
|
||||
@NotNull
|
||||
private final String redisHost;
|
||||
private final int redisPort;
|
||||
@Nullable
|
||||
private final String redisPassword;
|
||||
private final boolean redisSsl;
|
||||
public JedisPool jedisPool;
|
||||
|
||||
public RedisWorker(@NotNull Settings settings) {
|
||||
this.redisHost = settings.getStringValue(Settings.ConfigOption.REDIS_HOST);
|
||||
this.redisPort = settings.getIntegerValue(Settings.ConfigOption.REDIS_PORT);
|
||||
this.redisPassword = settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD).isEmpty() ? null : settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD);
|
||||
this.redisSsl = !redisHost.equalsIgnoreCase("localhost") && !redisHost.equalsIgnoreCase("127.0.0.1") && settings.getBooleanValue(Settings.ConfigOption.REDIS_USE_SSL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the JedisPool connection
|
||||
*/
|
||||
public void initialize() {
|
||||
if (redisPassword == null) {
|
||||
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisSsl);
|
||||
} else {
|
||||
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisPassword, redisSsl);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> sendMessage(@NotNull Message message) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try (Jedis jedis = jedisPool.getResource()) {
|
||||
jedis.publish(NetworkMessenger.NETWORK_MESSAGE_CHANNEL, message.toJson());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the JedisPool connection
|
||||
*/
|
||||
public void terminate() {
|
||||
if (jedisPool != null) {
|
||||
if (!jedisPool.isClosed()) {
|
||||
jedisPool.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package net.william278.huskhomes.teleport;
|
||||
|
||||
import net.william278.huskhomes.player.Player;
|
||||
import net.william278.huskhomes.player.User;
|
||||
import net.william278.huskhomes.position.Position;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package net.william278.huskhomes.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
@@ -15,4 +16,11 @@ public interface ResourceReader {
|
||||
*/
|
||||
InputStream getResource(String fileName);
|
||||
|
||||
/**
|
||||
* Gets the plugin data folder where plugin configuration and data are kept
|
||||
*
|
||||
* @return the plugin data directory
|
||||
*/
|
||||
File getDataFolder();
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user