Refactor bootstrap procedure, use enum for command loading

This commit is contained in:
William committed 2022-08-09 14:18:48 +01:00
1 parent eff21a16d5
commit ec1c0b744f
42 files changed
+982 -718

No files matched your search

@@ -3,14 +3,15 @@ package net.william278.huskhomes;
import net.william278.huskhomes.cache.Cache;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.data.Database;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.messenger.NetworkMessenger;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.Version;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -28,20 +29,23 @@ public interface HuskHomes {
*
* @return the {@link Logger} implementation to use
*/
@NotNull
Logger getLoggingAdapter();
/**
* The {@link Set} of online {@link Player}s on this server
* The {@link Set} of online {@link OnlineUser}s on this server
*
* @return a {@link Set} of currently online {@link Player}s
* @return a {@link Set} of currently online {@link OnlineUser}s
*/
List<Player> getOnlinePlayers();
@NotNull
List<OnlineUser> getOnlinePlayers();
/**
* The plugin {@link Settings} loaded from file
*
* @return the plugin {@link Settings}
*/
@NotNull
Settings getSettings();
/**
@@ -49,6 +53,7 @@ public interface HuskHomes {
*
* @return The plugin {@link Locales}
*/
@NotNull
Locales getLocales();
/**
@@ -56,6 +61,7 @@ public interface HuskHomes {
*
* @return the {@link Database} implementation for accessing data
*/
@NotNull
Database getDatabase();
/**
@@ -63,6 +69,7 @@ public interface HuskHomes {
*
* @return the plugin {@link Cache}
*/
@NotNull
Cache getCache();
/**
@@ -70,6 +77,7 @@ public interface HuskHomes {
*
* @return the {@link TeleportManager} implementation
*/
@NotNull
TeleportManager getTeleportManager();
/**
@@ -77,6 +85,7 @@ public interface HuskHomes {
*
* @return the {@link SavedPositionManager} implementation
*/
@NotNull
SavedPositionManager getSavedPositionManager();
/**
@@ -92,7 +101,7 @@ public interface HuskHomes {
*
* @return The server
*/
CompletableFuture<Server> getServer(@NotNull Player requester);
CompletableFuture<Server> getServer(@NotNull OnlineUser requester);
/**
* Returns true if the position is a valid location on the server
@@ -103,22 +112,33 @@ public interface HuskHomes {
boolean isValidPositionOnServer(Position position);
/**
* (Re)-load config and message data from files
* Returns the plugin version
*
* @return the plugin {@link Version}
*/
void loadConfigData();
@NotNull
Version getPluginVersion();
/**
* Get the HuskHomes plugin version
* Returns the Minecraft version implementation
*
* @return the HuskHomes plugin version string
* @return the Minecraft {@link Version}
*/
String getPluginVersion();
@NotNull
Version getMinecraftVersion();
/**
* Get the platform type (e.g. Spigot, Paper etc)
*
* @return the type of server platform string
*/
@NotNull
String getPlatformType();
/**
* Reloads the {@link Settings} and {@link Locales} from their respective config files
*
* @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful
*/
CompletableFuture<Boolean> reload();
}
@@ -0,0 +1,12 @@
package net.william278.huskhomes;
import org.jetbrains.annotations.NotNull;
/**
* Indicates an exception occurred while initialising the HuskHomes plugin
*/
public class HuskHomesInitializationException extends RuntimeException {
public HuskHomesInitializationException(@NotNull String message) {
super(message);
}
}
@@ -2,9 +2,9 @@ package net.william278.huskhomes.cache;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.data.Database;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.list.ChatList;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
@@ -75,7 +75,7 @@ public class Cache {
*
* @param plugin the implementing plugin
*/
public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull Player requester) {
public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) {
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
assert plugin.getNetworkMessenger() != null;
CompletableFuture.runAsync(() -> plugin.getNetworkMessenger().
@@ -85,7 +85,7 @@ public class Cache {
}));
} else {
players.clear();
players.addAll(plugin.getOnlinePlayers().stream().map(Player::getName).toList());
players.addAll(plugin.getOnlinePlayers().stream().map(onlineUser -> onlineUser.username).toList());
}
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -13,11 +13,11 @@ public class BackCommand extends CommandBase {
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
plugin.getDatabase().getLastPosition(new User(player)).thenAccept(lastPosition ->
lastPosition.ifPresentOrElse(position -> plugin.getTeleportManager().teleport(player, position)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(player, result)),
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(player::sendMessage)));
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition ->
lastPosition.ifPresentOrElse(position -> plugin.getTeleportManager().teleport(onlineUser, position)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)),
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage)));
}
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -41,10 +41,10 @@ public abstract class CommandBase {
/**
* Fires when the command is executed
*
* @param player {@link Player} executing the command
* @param onlineUser {@link OnlineUser} executing the command
* @param args Command arguments
*/
public abstract void onExecute(@NotNull Player player, @NotNull String[] args);
public abstract void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args);
/**
* Returns the localised description string of this command
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
@@ -17,15 +17,15 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
final User user = new User(player);
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> {
case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> {
if (homes.size() == 1) {
homes.stream().findFirst().ifPresent(home -> plugin.getSavedPositionManager().deleteHome(user, home.meta.name));
homes.stream().findFirst().ifPresent(home -> plugin.getSavedPositionManager().deleteHome(onlineUser, home.meta.name));
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/delhome <name>")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
});
case 1 -> {
@@ -35,23 +35,23 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso
final String ownersHomeName = homeName.split("\\.")[1];
plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData
.ifPresentOrElse(userData -> {
if (!userData.uuid.equals(player.getUuid())) {
if (!player.hasPermission(Permission.COMMAND_DELETE_HOME_OTHER.node)) {
if (!userData.uuid.equals(onlineUser.uuid)) {
if (!onlineUser.hasPermission(Permission.COMMAND_DELETE_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
return;
}
}
plugin.getSavedPositionManager().deleteHome(userData, ownersHomeName);
},
() -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName, homeName)
.ifPresent(player::sendMessage)));
.ifPresent(onlineUser::sendMessage)));
} else {
plugin.getSavedPositionManager().deleteHome(user, homeName);
plugin.getSavedPositionManager().deleteHome(onlineUser, homeName);
}
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/delhome <name>")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
@@ -61,8 +61,8 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso
}
@Override
public List<String> onTabComplete(@NotNull Player player, @NotNull String[] args) {
return plugin.getCache().homes.get(player.getUuid()).stream()
public List<String> onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
return plugin.getCache().homes.get(onlineUser.uuid).stream()
.filter(s -> s.startsWith(args.length >= 1 ? args[0] : ""))
.sorted().collect(Collectors.toList());
}
@@ -1,10 +1,8 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -17,12 +15,12 @@ public class DelWarpCommand extends CommandBase implements TabCompletable, Conso
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
plugin.getSavedPositionManager().deleteWarp(args[0]);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/delwarp <name>")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
@@ -32,7 +30,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable, Conso
}
@Override
public List<String> onTabComplete(@NotNull Player player, @NotNull String[] args) {
public List<String> onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
return plugin.getCache().warps.stream()
.filter(s -> s.startsWith(args.length >= 1 ? args[0] : ""))
.sorted().collect(Collectors.toList());
@@ -2,8 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.list.PrivateHomeList;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
@@ -18,18 +17,18 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
final User user = new User(player);
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> {
case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> {
switch (homes.size()) {
case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(player::sendMessage);
case 1 -> plugin.getTeleportManager().teleport(player, homes.get(0)).thenAccept(result ->
plugin.getTeleportManager().finishTeleport(player, result));
case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage);
case 1 -> plugin.getTeleportManager().teleport(onlineUser, homes.get(0)).thenAccept(result ->
plugin.getTeleportManager().finishTeleport(onlineUser, result));
default -> {
final PrivateHomeList homeList = new PrivateHomeList(homes, user, plugin);
plugin.getCache().positionLists.put(user.uuid, homeList);
homeList.getDisplay(1).forEach(player::sendMessage);
final PrivateHomeList homeList = new PrivateHomeList(homes, onlineUser, plugin);
plugin.getCache().positionLists.put(onlineUser.uuid, homeList);
homeList.getDisplay(1).forEach(onlineUser::sendMessage);
}
}
});
@@ -39,15 +38,15 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
final String ownerName = homeName.split("\\.")[0];
final String ownersHomeName = homeName.split("\\.")[1];
plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData
.ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(player, userData, ownersHomeName),
.ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(onlineUser, userData, ownersHomeName),
() -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName, homeName)
.ifPresent(player::sendMessage)));
.ifPresent(onlineUser::sendMessage)));
} else {
plugin.getTeleportManager().teleportToHome(player, user, homeName);
plugin.getTeleportManager().teleportToHome(onlineUser, onlineUser, homeName);
}
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/home [name]")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
@@ -57,8 +56,8 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
}
@Override
public List<String> onTabComplete(@NotNull Player player, @NotNull String[] args) {
return plugin.getCache().homes.get(player.getUuid()).stream()
public List<String> onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
return plugin.getCache().homes.get(onlineUser.uuid).stream()
.filter(s -> s.startsWith(args.length >= 1 ? args[0] : ""))
.sorted().collect(Collectors.toList());
}
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.list.PrivateHomeList;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -13,62 +13,62 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> showHomeList(player, player.getName(), 1);
case 0 -> showHomeList(onlineUser, onlineUser.username, 1);
case 1 -> {
try {
int pageNumber = Integer.parseInt(args[0]);
showHomeList(player, player.getName(), pageNumber);
showHomeList(onlineUser, onlineUser.username, pageNumber);
} catch (NumberFormatException e) {
showHomeList(player, args[0], 1);
showHomeList(onlineUser, args[0], 1);
}
}
case 2 -> {
try {
int pageNumber = Integer.parseInt(args[1]);
showHomeList(player, args[0], pageNumber);
showHomeList(onlineUser, args[0], pageNumber);
} catch (NumberFormatException e) {
plugin.getLocales().getLocale("error_invalid_syntax", "/homelist [player] [page]")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/homelist [page]")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
/**
* Show a (cached) list of a {@link Player}'s homes
* Show a (cached) list of a {@link OnlineUser}'s homes
*
* @param player the user to display the homes to
* @param onlineUser the user to display the homes to
* @param homeOwner the user whose homes should be displayed
* @param pageNumber page number to display
*/
private void showHomeList(@NotNull Player player, @NotNull String homeOwner, int pageNumber) {
if (plugin.getCache().positionLists.containsKey(player.getUuid())) {
if (plugin.getCache().positionLists.get(player.getUuid()) instanceof PrivateHomeList privateHomeList) {
privateHomeList.getDisplay(pageNumber).forEach(player::sendMessage);
private void showHomeList(@NotNull OnlineUser onlineUser, @NotNull String homeOwner, int pageNumber) {
if (plugin.getCache().positionLists.containsKey(onlineUser.uuid)) {
if (plugin.getCache().positionLists.get(onlineUser.uuid) instanceof PrivateHomeList privateHomeList) {
privateHomeList.getDisplay(pageNumber).forEach(onlineUser::sendMessage);
return;
}
}
plugin.getDatabase().getUserByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(user -> {
if (!user.uuid.equals(player.getUuid())) {
if (!player.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage);
if (!user.uuid.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 -> {
if (homes.isEmpty()) {
plugin.getLocales().getLocale("error_no_homes_set").ifPresent(player::sendMessage);
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);
homeList.getDisplay(pageNumber).forEach(player::sendMessage);
homeList.getDisplay(pageNumber).forEach(onlineUser::sendMessage);
});
}, () -> plugin.getLocales().getLocale("error_invalid_user").ifPresent(player::sendMessage)));
}, () -> plugin.getLocales().getLocale("error_invalid_user").ifPresent(onlineUser::sendMessage)));
}
@@ -2,7 +2,7 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
@@ -15,28 +15,28 @@ public class SetHomeCommand extends CommandBase {
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
final User user = new User(player);
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> {
case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> {
if (homes.isEmpty()) {
setHome(player, user, "home");
setHome(onlineUser, onlineUser, "home");
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
});
case 1 -> setHome(player, user, args[0]);
case 1 -> setHome(onlineUser, onlineUser, args[0]);
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
private void setHome(@NotNull Player player, @NotNull User user, @NotNull String homeName) {
player.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setHome(new PositionMeta(homeName,
private void setHome(@NotNull OnlineUser onlineUser, @NotNull User user, @NotNull String homeName) {
onlineUser.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setHome(new PositionMeta(homeName,
plugin.getLocales().getRawLocale("home_default_description", user.username).orElse("")),
user, position).thenAccept(setResult ->
player.sendMessage(switch (setResult.resultType()) {
onlineUser.sendMessage(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.setPosition() != null;
yield plugin.getLocales().getLocale("set_home_success", setResult.setPosition().meta.name)
@@ -2,8 +2,7 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -15,24 +14,20 @@ public class SetWarpCommand extends CommandBase {
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
final User user = new User(player);
switch (args.length) {
case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> {
plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp <name>")
.ifPresent(player::sendMessage);
});
case 1 -> setWarp(player, args[0]);
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp <name>")
.ifPresent(player::sendMessage);
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
setWarp(onlineUser, args[0]);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp <name>")
.ifPresent(onlineUser::sendMessage);
}
}
private void setWarp(@NotNull Player player, @NotNull String warpName) {
player.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setWarp(new PositionMeta(warpName,
private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
onlineUser.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setWarp(new PositionMeta(warpName,
plugin.getLocales().getRawLocale("warp_default_description").orElse("")),
position).thenAccept(setResult ->
player.sendMessage(switch (setResult.resultType()) {
onlineUser.sendMessage(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.setPosition() != null;
yield plugin.getLocales().getLocale("set_warp_success", setResult.setPosition().meta.name)
@@ -1,6 +1,6 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -13,10 +13,10 @@ public interface TabCompletable {
/**
* What should be returned when the player attempts to TAB-complete the command
*
* @param player {@link Player} doing the TAB completion
* @param onlineUser {@link OnlineUser} doing the TAB completion
* @param args Current command arguments
* @return List of String arguments to offer TAB suggestions
*/
List<String> onTabComplete(@NotNull Player player, @NotNull String[] args);
List<String> onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args);
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -15,18 +15,18 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
final String warpName = args[0];
plugin.getTeleportManager().teleportToWarp(player, warpName);
plugin.getTeleportManager().teleportToWarp(onlineUser, warpName);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/warp [name]")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
@Override
public List<String> onTabComplete(@NotNull Player player, @NotNull String[] args) {
public List<String> onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
return plugin.getCache().warps.stream()
.filter(s -> s.startsWith(args.length >= 1 ? args[0] : ""))
.sorted().collect(Collectors.toList());
@@ -2,8 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.list.WarpList;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -14,45 +13,45 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> showWarpList(player, 1);
case 0 -> showWarpList(onlineUser, 1);
case 1 -> {
try {
int pageNumber = Integer.parseInt(args[0]);
showWarpList(player, pageNumber);
showWarpList(onlineUser, pageNumber);
} catch (NumberFormatException e) {
plugin.getLocales().getLocale("error_invalid_syntax", "/warplist [page]")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/warplist [page]")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
/**
* Show a (cached) list of server warps
*
* @param player the user to display warps to
* @param onlineUser the user to display warps to
* @param pageNumber page number to display
*/
private void showWarpList(@NotNull Player player, int pageNumber) {
if (plugin.getCache().positionLists.containsKey(player.getUuid())) {
if (plugin.getCache().positionLists.get(player.getUuid()) instanceof WarpList warpList) {
warpList.getDisplay(pageNumber).forEach(player::sendMessage);
private void showWarpList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().positionLists.containsKey(onlineUser.uuid)) {
if (plugin.getCache().positionLists.get(onlineUser.uuid) instanceof WarpList warpList) {
warpList.getDisplay(pageNumber).forEach(onlineUser::sendMessage);
return;
}
}
final User user = new User(player);
plugin.getDatabase().getWarps().thenAccept(warps -> {
if (warps.isEmpty()) {
plugin.getLocales().getLocale("error_no_warps_set").ifPresent(player::sendMessage);
plugin.getLocales().getLocale("error_no_warps_set").ifPresent(onlineUser::sendMessage);
return;
}
final WarpList warpList = new WarpList(warps, plugin);
plugin.getCache().positionLists.put(user.uuid, warpList);
warpList.getDisplay(pageNumber).forEach(player::sendMessage);
plugin.getCache().positionLists.put(onlineUser.uuid, warpList);
warpList.getDisplay(pageNumber).forEach(onlineUser::sendMessage);
});
}
@@ -114,7 +114,7 @@ public class Settings {
public enum ConfigOption {
LANGUAGE("language", OptionType.STRING, "en-gb"),
CHECK_FOR_UPDATES("check_for_updates", OptionType.BOOLEAN, true),
DEBUG_LOGGING("debug_logging", OptionType.BOOLEAN, false),
DATA_STORAGE_TYPE("data_storage_options.storage_type", OptionType.STRING, "SQLite"),
DATABASE_HOST("data_storage_options.mysql_credentials.host", OptionType.STRING, "localhost"),
DATABASE_PORT("data_storage_options.mysql_credentials.port", OptionType.INTEGER, 3306),
@@ -1,7 +1,6 @@
package net.william278.huskhomes.data;
package net.william278.huskhomes.database;
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.*;
@@ -172,7 +171,7 @@ public abstract class Database {
*
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> initialize();
public abstract boolean initialize();
/**
* <b>(Internal use only)</b> - Sets a position to the position table in the database
@@ -215,12 +214,12 @@ public abstract class Database {
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition, @NotNull Connection connection) throws SQLException;
/**
* Ensure a {@link Player} has a {@link UserData} entry in the database and that their username is up-to-date
* Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date
*
* @param player The {@link Player} to ensure
* @param user The {@link User} to ensure
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> ensureUser(@NotNull Player player);
public abstract CompletableFuture<Void> ensureUser(@NotNull User user);
/**
* Get a user by their username (<i>case-insensitive</i>)
@@ -1,8 +1,8 @@
package net.william278.huskhomes.data;
package net.william278.huskhomes.database;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
@@ -90,8 +90,8 @@ public class MySqlDatabase extends Database {
}
@Override
public CompletableFuture<Void> initialize() {
return CompletableFuture.runAsync(() -> {
public boolean initialize() {
try {
// Create jdbc driver connection url
final String jdbcUrl = "jdbc:mysql://" + mySqlHost + ":" + mySqlPort + "/" + mySqlDatabaseName + mySqlConnectionParameters;
dataSource = new HikariDataSource();
@@ -118,10 +118,14 @@ public class MySqlDatabase extends Database {
statement.execute(tableCreationStatement);
}
}
return true;
} catch (SQLException | IOException e) {
getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e);
}
});
} catch (Exception e) {
getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e);
}
return false;
}
@Override
@@ -202,10 +206,10 @@ public class MySqlDatabase extends Database {
updatePosition(positionId, position, connection);
try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
UPDATE `%saved_positions_table%`
SET `name`=?,
`description`=?
WHERE `id`=?;"""))) {
UPDATE `%saved_positions_table%`
SET `name`=?,
`description`=?
WHERE `id`=?;"""))) {
updateStatement.setString(1, position.meta.name);
updateStatement.setString(2, position.meta.description);
updateStatement.setInt(3, savedPositionId);
@@ -216,10 +220,10 @@ public class MySqlDatabase extends Database {
}
@Override
public CompletableFuture<Void> ensureUser(@NotNull Player player) {
return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser ->
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) {
return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser ->
optionalUser.ifPresentOrElse(existingUser -> {
if (!existingUser.username.equals(player.getName())) {
if (!existingUser.username.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("""
@@ -227,11 +231,11 @@ public class MySqlDatabase extends Database {
SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, player.getName());
statement.setString(1, onlineUser.username);
statement.setString(2, existingUser.uuid.toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username + " -> " + player.getName() + ")");
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -244,8 +248,8 @@ public class MySqlDatabase extends Database {
INSERT INTO `%players_table%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, player.getUuid().toString());
statement.setString(2, player.getName());
statement.setString(1, onlineUser.uuid.toString());
statement.setString(2, onlineUser.username);
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -1,7 +1,7 @@
package net.william278.huskhomes.data;
package net.william278.huskhomes.database;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.*;
@@ -87,9 +87,9 @@ public class SqLiteDatabase extends Database {
}
@Override
public CompletableFuture<Void> initialize() {
return CompletableFuture.runAsync(() -> {
// Setup the connection
public boolean initialize() {
try {
// Set up the connection
setConnection();
// Prepare database schema; make tables if they don't exist
@@ -101,10 +101,14 @@ public class SqLiteDatabase extends Database {
statement.execute(tableCreationStatement);
}
}
return true;
} catch (SQLException | IOException e) {
getLogger().log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e);
}
});
} catch (Exception e) {
getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e);
}
return false;
}
@Override
@@ -199,10 +203,10 @@ public class SqLiteDatabase extends Database {
}
@Override
public CompletableFuture<Void> ensureUser(@NotNull Player player) {
return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser ->
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) {
return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser ->
optionalUser.ifPresentOrElse(existingUser -> {
if (!existingUser.username.equals(player.getName())) {
if (!existingUser.username.equals(onlineUser.username)) {
// Update a player's name if it has changed in the database
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -210,11 +214,11 @@ public class SqLiteDatabase extends Database {
SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, player.getName());
statement.setString(1, onlineUser.username);
statement.setString(2, existingUser.uuid.toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username + " -> " + player.getName() + ")");
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -227,8 +231,8 @@ public class SqLiteDatabase extends Database {
INSERT INTO `%players_table%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, player.getUuid().toString());
statement.setString(2, player.getName());
statement.setString(1, onlineUser.uuid.toString());
statement.setString(2, onlineUser.username);
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -2,8 +2,7 @@ package net.william278.huskhomes.listener;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.stream.Collectors;
@@ -11,94 +10,101 @@ import java.util.stream.Collectors;
/**
* A handler for when events take place
*/
public class EventProcessor {
public class EventListener {
@NotNull
protected final HuskHomes plugin;
public EventProcessor(@NotNull HuskHomes implementor) {
public EventListener(@NotNull HuskHomes implementor) {
this.plugin = implementor;
}
/**
* Handle when a {@link Player} joins the server
* Handle when a {@link OnlineUser} joins the server
*
* @param player the joining {@link Player}
* @param onlineUser the joining {@link OnlineUser}
*/
public void onPlayerJoin(@NotNull Player player) {
public void onPlayerJoin(@NotNull OnlineUser onlineUser) {
// Ensure the player is present on the database first
plugin.getDatabase().ensureUser(player).thenRun(() -> {
plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> {
// 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)) {
plugin.getDatabase().getCurrentTeleport(new User(player))
plugin.getDatabase().getCurrentTeleport(onlineUser)
.thenAccept(teleport -> teleport.ifPresent(currentTeleport ->
// Teleport the player locally
player.teleport(currentTeleport.target).thenAccept(teleportResult -> {
onlineUser.teleport(currentTeleport.target).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
plugin.getLocales().getLocale("error_invalid_on_arrival")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
})));
// Update the player list
assert plugin.getNetworkMessenger() != null;
plugin.getCache().updatePlayerList(plugin, player);
plugin.getCache().updatePlayerList(plugin, onlineUser);
}
// Cache this user's homes
plugin.getDatabase().getHomes(new User(player)).thenAccept(homes ->
plugin.getCache().homes.put(player.getUuid(),
plugin.getDatabase().getHomes(onlineUser).thenAccept(homes ->
plugin.getCache().homes.put(onlineUser.uuid,
homes.stream().map(home -> home.meta.name).collect(Collectors.toList())));
// Ensure the server has been set
if (plugin.getOnlinePlayers().size() == 1) {
plugin.getServer(player);
plugin.getServer(onlineUser);
}
});
}
/**
* Handle when a {@link Player} leaves the server
* Handle when a {@link OnlineUser} leaves the server
*
* @param player the leaving {@link Player}
* @param onlineUser the leaving {@link OnlineUser}
*/
public void onPlayerLeave(@NotNull Player player) {
public void onPlayerLeave(@NotNull OnlineUser onlineUser) {
// Remove this user's home cache
plugin.getCache().homes.remove(player.getUuid());
plugin.getCache().homes.remove(onlineUser.uuid);
// Update the player list
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
assert plugin.getNetworkMessenger() != null;
plugin.getOnlinePlayers().stream().filter(
onlinePlayer -> !onlinePlayer.getUuid().equals(player.getUuid()))
onlinePlayer -> !onlinePlayer.uuid.equals(onlineUser.uuid))
.findAny().ifPresent(updater ->
plugin.getCache().updatePlayerList(plugin, updater));
}
// Set offline position
player.getPosition().thenAcceptAsync(position -> plugin.getDatabase().setOfflinePosition(
new User(player.getUuid(), player.getName()), position));
onlineUser.getPosition().thenAcceptAsync(position -> plugin.getDatabase()
.setOfflinePosition(onlineUser, position));
}
/**
* Handle when a {@link Player} dies
* Handle when a {@link OnlineUser} dies
*
* @param player the {@link Player} who died
* @param onlineUser the {@link OnlineUser} who died
*/
public void onPlayerDeath(@NotNull Player player) {
public void onPlayerDeath(@NotNull OnlineUser onlineUser) {
//todo
}
/**
* Handle when a {@link Player} respawns after dying
* Handle when a {@link OnlineUser} respawns after dying
*
* @param player the respawning {@link Player}
* @param onlineUser the respawning {@link OnlineUser}
*/
public void onPlayerRespawn(@NotNull Player player) {
public void onPlayerRespawn(@NotNull OnlineUser onlineUser) {
//todo
}
/**
* Handle when the plugin is disabling (server is shutting down)
*/
public void handlePluginDisable() {
//todo
}
}
@@ -2,8 +2,7 @@ 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.Position;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Server;
import org.jetbrains.annotations.NotNull;
@@ -25,17 +24,17 @@ public abstract class NetworkMessenger {
protected HashMap<UUID, CompletableFuture<Message>> processingMessages;
/**
* Future for processing {@link #getServerName(Player)} requests
* Future for processing {@link #getServerName(OnlineUser)} requests
*/
protected CompletableFuture<String> serverNameRequest;
/**
* Future for processing {@link #getOnlinePlayerNames(Player)} requests
* Future for processing {@link #getOnlinePlayerNames(OnlineUser)} requests
*/
protected CompletableFuture<String[]> onlinePlayerNamesRequest;
/**
* Future for processing {@link #getOnlineServers(Player)} requests
* Future for processing {@link #getOnlineServers(OnlineUser)} requests
*/
protected CompletableFuture<String[]> onlineServersRequest;
@@ -57,35 +56,35 @@ public abstract class NetworkMessenger {
/**
* Fetch a list of online player usernames from the proxy
*
* @param requester {@link Player} to send the request
* @param requester {@link OnlineUser} to send the request
* @return Future returning a {@link List} of usernames of players on the proxy network
*/
public abstract CompletableFuture<String[]> getOnlinePlayerNames(@NotNull Player requester);
public abstract CompletableFuture<String[]> getOnlinePlayerNames(@NotNull OnlineUser requester);
/**
* Fetch the name of this server on the proxy network
*
* @param requester {@link Player} to send the request
* @param requester {@link OnlineUser} to send the request
* @return Future returning the name of this server on the network
*/
public abstract CompletableFuture<String> getServerName(@NotNull Player requester);
public abstract CompletableFuture<String> getServerName(@NotNull OnlineUser requester);
/**
* Fetch a list of online server names proxy
*
* @param requester {@link Player} to send the request
* @param requester {@link OnlineUser} to send the request
* @return Future returning a {@link List} of online servers connected to the proxy network
*/
public abstract CompletableFuture<String[]> getOnlineServers(@NotNull Player requester);
public abstract CompletableFuture<String[]> getOnlineServers(@NotNull OnlineUser requester);
/**
* Send a {@link Player} to a target {@link Server} on the proxy network
* Send a {@link OnlineUser} to a target {@link Server} on the proxy network
*
* @param server The {@link Server} to send the {@link Player} to
* @param server The {@link Server} to send the {@link OnlineUser} to
* @return A future, returning {@code true} if the player was sent.<p>
* If the player could not be sent (i.e. the server was offline), this will return {@code false}
*/
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull Player player, @NotNull Server server);
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server);
/**
* Send a network {@link Message} to a target player on the proxy
@@ -93,7 +92,7 @@ public abstract class NetworkMessenger {
* @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);
public abstract CompletableFuture<Message> sendMessage(@NotNull OnlineUser sender, @NotNull Message message);
/**
* Send a reply to a received {@link Message}
@@ -101,15 +100,15 @@ public abstract class NetworkMessenger {
* @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);
protected abstract CompletableFuture<Void> sendReply(@NotNull OnlineUser replier, @NotNull Message reply);
/**
* Handle and action received network {@link Message}s
*
* @param receiver The online {@link Player} receiving the message
* @param receiver The online {@link OnlineUser} receiving the message
* @param message The received {@link Message}
*/
protected final void handleMessage(@NotNull Player receiver, @NotNull Message message) {
protected final void handleMessage(@NotNull OnlineUser receiver, @NotNull Message message) {
switch (message.kind) {
// Handle a message and send reply
case MESSAGE -> prepareReply(receiver, message).thenAccept(reply -> sendReply(receiver, message));
@@ -123,7 +122,7 @@ public abstract class NetworkMessenger {
}
}
private CompletableFuture<Message> prepareReply(@NotNull final Player receiver, @NotNull final Message message) {
private CompletableFuture<Message> prepareReply(@NotNull final OnlineUser receiver, @NotNull final Message message) {
return CompletableFuture.supplyAsync(() -> {
// Handle different message types and apply changes for reply message
switch (message.type) {
@@ -137,7 +136,7 @@ public abstract class NetworkMessenger {
// Prepare reply message
message.targetPlayer = message.sender;
message.sender = receiver.getName();
message.sender = receiver.username;
message.kind = Message.MessageKind.REPLY;
return message;
});
@@ -3,7 +3,6 @@ package net.william278.huskhomes.player;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.util.EconomyUnsupportedException;
import org.jetbrains.annotations.NotNull;
@@ -12,44 +11,35 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* A cross-platform representation of a player
* A cross-platform representation of a logged-in {@link User}
*/
public interface Player {
public abstract class OnlineUser extends User {
/**
* Return the player's name
*
* @return the player's name
*/
String getName();
public OnlineUser(@NotNull UUID uuid, @NotNull String username) {
super(uuid, username);
}
/**
* Return the player's {@link UUID}
*
* @return the player {@link UUID}
*/
UUID getUuid();
/**
* Returns the current {@link Position} of this player
*
* @return the player's current {@link Position}
*/
CompletableFuture<Position> getPosition();
public abstract CompletableFuture<Position> getPosition();
/**
* Returns the current local {@link Location} of this player
*
* @return the player's current {@link Location} on the server
*/
Location getLocation();
public abstract Location getLocation();
/**
* Returns the health of this player
*
* @return the player's health points
*/
double getHealth();
public abstract double getHealth();
/**
* Returns if the player has the permission node
@@ -57,35 +47,43 @@ public interface Player {
* @param node The permission node string
* @return {@code true} if the player has the node; {@code false} otherwise
*/
boolean hasPermission(@NotNull String node);
public abstract boolean hasPermission(@NotNull String node);
/**
* Dispatch a MineDown-formatted message to this player
* Dispatch a MineDown-formatted action bar message to this player
*
* @param mineDown the parsed {@link MineDown} to send
*/
void sendMessage(@NotNull MineDown mineDown);
public abstract void sendActionBar(@NotNull MineDown mineDown);
/**
* Dispatch a MineDown-formatted chat message to this player
*
* @param mineDown the parsed {@link MineDown} to send
*/
public abstract void sendMessage(@NotNull MineDown mineDown);
/**
* Teleport a player to the specified {@link Location}
*
* @param location the {@link Location} to teleport the player to
*/
CompletableFuture<TeleportResult> teleport(Location location);
public abstract CompletableFuture<TeleportResult> teleport(Location location);
/**
* Returns the maximum number of homes this player can set
*
* @return a {@link CompletableFuture} providing the max number of homes this player can set
*/
CompletableFuture<Integer> getMaxHomes();
public abstract CompletableFuture<Integer> getMaxHomes();
/**
* Returns the number of homes this player can set for free
*
* @return a {@link CompletableFuture} providing the max number of homes this player can set
*/
CompletableFuture<Integer> getFreeHomes();
public abstract CompletableFuture<Integer> getFreeHomes();
/**
* Get this player's economy balance
@@ -93,14 +91,14 @@ public interface Player {
* @return the player's economy balance
* @throws EconomyUnsupportedException if the economy integration is not enabled
*/
double getEconomyBalance() throws EconomyUnsupportedException;
public abstract double getEconomyBalance() throws EconomyUnsupportedException;
/**
* Deduct money from this player's economy balance
*
* @throws EconomyUnsupportedException if the economy integration is not enabled
*/
void deductEconomyBalance() throws EconomyUnsupportedException;
public abstract void deductEconomyBalance() throws EconomyUnsupportedException;
}
@@ -5,13 +5,14 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents persistently stored {@link User} data about a {@link Player}; uuid and username
* A {@link Player} may be retrieved from a user by the platform implementing classes
* Represents a user who has data saved in the database
*/
public class User {
@NotNull
public final UUID uuid;
@NotNull
public final String username;
/**
@@ -25,13 +26,4 @@ public class User {
this.username = username;
}
/**
* Get a user from an online {@link Player}
*
* @param player the online {@link Player}
*/
public User(Player player) {
this.uuid = player.getUuid();
this.username = player.getName();
}
}
@@ -1,7 +1,7 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.cache.Cache;
import net.william278.huskhomes.data.Database;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
@@ -4,7 +4,7 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.EmptyPayload;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
@@ -32,74 +32,74 @@ public abstract class TeleportManager {
}
/**
* Teleport a {@link Player} to another {@link User}'s {@link Home}
* Teleport a {@link OnlineUser} to another {@link User}'s {@link Home}
*
* @param player the {@link Player} to teleport
* @param onlineUser the {@link OnlineUser} to teleport
* @param homeOwner the {@link User} who owns the home
* @param homeName the name of the home
*/
public void teleportToHome(@NotNull Player player, @NotNull User homeOwner, @NotNull String homeName) {
public void teleportToHome(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull String homeName) {
plugin.getDatabase().getHome(homeOwner, homeName).thenAccept(optionalHome ->
optionalHome.ifPresentOrElse(home -> {
if (!homeOwner.uuid.equals(player.getUuid())) {
if (!home.isPublic && !player.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
if (!homeOwner.uuid.equals(onlineUser.uuid)) {
if (!home.isPublic && !onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) {
plugin.getLocales().getLocale("error_public_home_invalid", homeOwner.username, homeName)
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
return;
}
}
teleport(player, home).thenAccept(result -> finishTeleport(player, result));
teleport(onlineUser, home).thenAccept(result -> finishTeleport(onlineUser, result));
}, () -> {
if (homeOwner.uuid.equals(player.getUuid())) {
plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(player::sendMessage);
if (homeOwner.uuid.equals(onlineUser.uuid)) {
plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(onlineUser::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(player::sendMessage);
plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(onlineUser::sendMessage);
}
}));
}
/**
* Teleport a {@link Player} to a server {@link Warp}
* Teleport a {@link OnlineUser} to a server {@link Warp}
*
* @param player the {@link Player} to teleport
* @param onlineUser the {@link OnlineUser} to teleport
* @param warpName the name of the warp
*/
public void teleportToWarp(@NotNull Player player, @NotNull String warpName) {
public void teleportToWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
plugin.getDatabase().getWarp(warpName).thenAccept(optionalWarp ->
optionalWarp.ifPresentOrElse(warp -> //todo permission restricted warps
teleport(player, warp).thenAccept(result -> finishTeleport(player, result)), () ->
teleport(onlineUser, warp).thenAccept(result -> finishTeleport(onlineUser, result)), () ->
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(player::sendMessage)));
.ifPresent(onlineUser::sendMessage)));
}
/**
* Teleport a {@link Player} to another player by given input name
* Teleport a {@link OnlineUser} to another player by given input name
*
* @param player the {@link Player} to teleport
* @param onlineUser the {@link OnlineUser} to teleport
* @param targetPlayer the name of the target player
*/
public void teleportToPlayer(@NotNull Player player, @NotNull String targetPlayer) {
public void teleportToPlayer(@NotNull OnlineUser onlineUser, @NotNull String targetPlayer) {
MatcherUtil.matchPlayerName(targetPlayer, plugin).ifPresentOrElse(playerName ->
getPlayerPosition(player, playerName).thenAccept(optionalPosition ->
getPlayerPosition(onlineUser, playerName).thenAccept(optionalPosition ->
optionalPosition.ifPresentOrElse(targetPosition ->
teleport(player, targetPosition).thenAccept(result ->
finishTeleport(player, result)),
teleport(onlineUser, targetPosition).thenAccept(result ->
finishTeleport(onlineUser, result)),
() -> plugin.getLocales().getLocale("error_invalid_player").
ifPresent(player::sendMessage))),
() -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(player::sendMessage));
ifPresent(onlineUser::sendMessage))),
() -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(onlineUser::sendMessage));
}
/**
* Gets the position of a player by their username, including players on other servers
*
* @param requester the {@link Player} requesting their position
* @param requester the {@link OnlineUser} requesting their position
* @param playerName the username of the player being requested
* @return future optionally supplying the player's position, if the player could be found
*/
private CompletableFuture<Optional<Position>> getPlayerPosition(@NotNull Player requester, @NotNull String playerName) {
private CompletableFuture<Optional<Position>> getPlayerPosition(@NotNull OnlineUser requester, @NotNull String playerName) {
return CompletableFuture.supplyAsync(() -> {
final Optional<Player> localPlayer = plugin.getOnlinePlayers().stream().filter(player ->
player.getName().equalsIgnoreCase(playerName)).findFirst();
final Optional<OnlineUser> localPlayer = plugin.getOnlinePlayers().stream().filter(player ->
player.username.equalsIgnoreCase(playerName)).findFirst();
if (localPlayer.isPresent()) {
return localPlayer.get().getPosition().thenApply(Optional::of).join();
}
@@ -107,7 +107,7 @@ public abstract class TeleportManager {
assert plugin.getNetworkMessenger() != null;
return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.POSITION_REQUEST,
requester.getName(),
requester.username,
playerName,
new EmptyPayload(),
Message.MessageKind.MESSAGE,
@@ -119,16 +119,16 @@ public abstract class TeleportManager {
}
/**
* Teleport a {@link Player} to a specified {@link Position}. Respects timed teleport.
* Teleport a {@link OnlineUser} to a specified {@link Position}. Respects timed teleport.
*
* @param player the {@link Player} to teleport
* @param onlineUser the {@link OnlineUser} to teleport
* @param position the target {@link Position} to teleport to
*/
public CompletableFuture<TeleportResult> teleport(@NotNull Player player, @NotNull Position position) {
public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position) {
return CompletableFuture.supplyAsync(() -> {
final int teleportWarmupTime = plugin.getSettings().getIntegerValue(Settings.ConfigOption.TELEPORT_WARMUP_TIME);
if (!player.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) {
return processTimedTeleport(new TimedTeleport(player, position, teleportWarmupTime))
if (!onlineUser.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) {
return processTimedTeleport(new TimedTeleport(onlineUser, position, teleportWarmupTime))
.thenApply(teleport -> {
if (!teleport.cancelled) {
return teleport.getPlayer().teleport(teleport.getTargetPosition()).join();
@@ -137,58 +137,57 @@ public abstract class TeleportManager {
}
}).join();
} else {
return teleportNow(player, position).join();
return teleportNow(onlineUser, position).join();
}
});
}
/**
* Handles a completed {@link Player}'s {@link TeleportResult} with the appropriate message
* Handles a completed {@link OnlineUser}'s {@link TeleportResult} with the appropriate message
*
* @param player the {@link Player} who just completed a teleport
* @param onlineUser the {@link OnlineUser} who just completed a teleport
* @param teleportResult the {@link TeleportResult} to handle
*/
public void finishTeleport(@NotNull Player player, @NotNull TeleportResult teleportResult) {
public void finishTeleport(@NotNull OnlineUser onlineUser, @NotNull TeleportResult teleportResult) {
switch (teleportResult) {
case COMPLETED_LOCALLY -> plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
case FAILED_INVALID_WORLD -> plugin.getLocales().getLocale("error_invalid_on_arrival")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
case FAILED_UNSAFE -> {
//todo
}
case FAILED_ILLEGAL_COORDINATES -> plugin.getLocales().getLocale("error_illegal_target_coordinates")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
case FAILED_INVALID_SERVER -> plugin.getLocales().getLocale("error_invalid_server")
.ifPresent(player::sendMessage);
.ifPresent(onlineUser::sendMessage);
}
}
/**
* Executes a teleport now, teleporting a {@link Player} to a specified {@link Position}
* Executes a teleport now, teleporting a {@link OnlineUser} to a specified {@link Position}
*
* @param player the {@link Player} to teleport
* @param onlineUser the {@link OnlineUser} to teleport
* @param position the target {@link Position} to teleport to
*/
private CompletableFuture<TeleportResult> teleportNow(@NotNull Player player, @NotNull Position position) {
final User user = new User(player);
final Teleport teleport = new Teleport(user, position);
return CompletableFuture.supplyAsync(() -> player.getPosition().thenApply(preTeleportPosition -> plugin.getDatabase()
.setLastPosition(user, preTeleportPosition) // Update the player's last position
.thenApply(ignored -> plugin.getServer(player).thenApply(server -> {
private CompletableFuture<TeleportResult> teleportNow(@NotNull OnlineUser onlineUser, @NotNull Position position) {
final Teleport teleport = new Teleport(onlineUser, position);
return CompletableFuture.supplyAsync(() -> onlineUser.getPosition().thenApply(preTeleportPosition -> plugin.getDatabase()
.setLastPosition(onlineUser, preTeleportPosition) // Update the player's last position
.thenApply(ignored -> plugin.getServer(onlineUser).thenApply(server -> {
// Teleport player locally, or across server depending on need
if (position.server.equals(server)) {
return player.teleport(teleport.target).join();
return onlineUser.teleport(teleport.target).join();
} else {
return teleportCrossServer(player, teleport).join();
return teleportCrossServer(onlineUser, teleport).join();
}
}).join()).join()).join());
}
private CompletableFuture<TeleportResult> teleportCrossServer(Player player, Teleport teleport) {
private CompletableFuture<TeleportResult> teleportCrossServer(OnlineUser onlineUser, Teleport teleport) {
assert plugin.getNetworkMessenger() != null;
return CompletableFuture.supplyAsync(() -> plugin.getDatabase().setCurrentTeleport(teleport.player, teleport)
.thenApply(ignored -> plugin.getNetworkMessenger().sendPlayer(player, teleport.target.server)
.thenApply(ignored -> plugin.getNetworkMessenger().sendPlayer(onlineUser, teleport.target.server)
.thenApply(completed -> completed ? TeleportResult.COMPLETED_CROSS_SERVER :
TeleportResult.FAILED_INVALID_SERVER)
.join()).join());
@@ -1,6 +1,6 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
@@ -10,7 +10,7 @@ import org.jetbrains.annotations.NotNull;
*/
public class TimedTeleport {
private final Player player;
private final OnlineUser onlineUser;
private final Position targetPosition;
private final Location startLocation;
@@ -21,11 +21,11 @@ public class TimedTeleport {
public boolean cancelled = false;
protected TimedTeleport(@NotNull Player player, @NotNull Position targetPosition, int duration) {
this.player = player;
protected TimedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position targetPosition, int duration) {
this.onlineUser = onlineUser;
this.targetPosition = targetPosition;
this.startLocation = player.getLocation();
this.startHealth = player.getHealth();
this.startLocation = onlineUser.getLocation();
this.startHealth = onlineUser.getHealth();
this.duration = duration;
this.timeLeft = duration;
}
@@ -41,10 +41,10 @@ public class TimedTeleport {
/**
* Get the teleporting player
*
* @return the {@link Player} who is teleporting
* @return the {@link OnlineUser} who is teleporting
*/
public Player getPlayer() {
return player;
public OnlineUser getPlayer() {
return onlineUser;
}
/**
@@ -54,9 +54,9 @@ public class TimedTeleport {
*/
public boolean hasMoved() {
final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.x - player.getLocation().x) +
Math.abs(startLocation.y - player.getLocation().y) +
Math.abs(startLocation.z - player.getLocation().z);
double movementDistance = Math.abs(startLocation.x - onlineUser.getLocation().x) +
Math.abs(startLocation.y - onlineUser.getLocation().y) +
Math.abs(startLocation.z - onlineUser.getLocation().z);
return movementDistance > maxMovementDistance;
}
@@ -66,7 +66,7 @@ public class TimedTeleport {
* @return {@code true} if the player has taken damage
*/
public boolean hasTakenDamage() {
return player.getHealth() < startHealth;
return onlineUser.getHealth() < startHealth;
}
/**
@@ -1,20 +1,37 @@
package net.william278.huskhomes.util;
import de.themoep.minedown.MineDown;
import org.jetbrains.annotations.NotNull;
import java.util.logging.Level;
/**
* An abstract, cross-platform representation of a logger
*/
public interface Logger {
public abstract class Logger {
void log(Level level, String message, Exception e);
private boolean debug;
void log(Level level, String message);
public abstract void log(@NotNull Level level, @NotNull String message, @NotNull Exception e);
void info(String message);
public abstract void log(@NotNull Level level, @NotNull String message);
void severe(String message);
public abstract void log(@NotNull Level level, @NotNull MineDown mineDown);
void config(String message);
public abstract void info(@NotNull String message);
public abstract void severe(@NotNull String message);
public final void debug(@NotNull String message) {
if (debug) {
log(Level.INFO, "[DEBUG] " + message);
}
}
public abstract void config(@NotNull String message);
public final void showDebugLogs(boolean debug) {
this.debug = debug;
}
}
@@ -0,0 +1,57 @@
package net.william278.huskhomes.util;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
public class UpdateChecker {
private final static int SPIGOT_PROJECT_ID = 83767;
private final Logger logger;
private final Version currentVersion;
public UpdateChecker(@NotNull Version currentVersion, @NotNull Logger logger) {
this.currentVersion = currentVersion;
this.logger = logger;
}
public CompletableFuture<Version> fetchLatestVersion() {
return CompletableFuture.supplyAsync(() -> {
try {
final URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + SPIGOT_PROJECT_ID);
URLConnection urlConnection = url.openConnection();
return Version.pluginVersion(new BufferedReader(new InputStreamReader(urlConnection.getInputStream())).readLine());
} catch (Exception e) {
logger.log(Level.WARNING, "Failed to fetch the latest plugin version", e);
}
return new Version();
});
}
public boolean isUpdateAvailable(@NotNull Version latestVersion) {
return latestVersion.compareTo(currentVersion) > 0;
}
public Version getCurrentVersion() {
return currentVersion;
}
public CompletableFuture<Boolean> isUpToDate() {
return fetchLatestVersion().thenApply(this::isUpdateAvailable);
}
public void logToConsole() {
fetchLatestVersion().thenAccept(latestVersion -> {
if (isUpdateAvailable(latestVersion)) {
logger.log(Level.WARNING, "A new version of HuskHomes is available: v" + latestVersion);
} else {
logger.log(Level.INFO, "HuskHomes is up-to-date! (Running: v" + getCurrentVersion().toString() + ")");
}
});
}
}
@@ -0,0 +1,71 @@
package net.william278.huskhomes.util;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.regex.Pattern;
public class Version implements Comparable<Version> {
private final static String VERSION_SEPARATOR = ".";
private final static String MINECRAFT_META_SEPARATOR = "-";
private final static String PLUGIN_META_SEPARATOR = "+";
private int[] versions = new int[]{};
@NotNull
private String metadata = "";
@NotNull
private String metaSeparator = "";
protected Version() {
}
private Version(@NotNull String version, @NotNull String metaSeparator) {
this.parse(version, metaSeparator);
this.metaSeparator = metaSeparator;
}
@NotNull
public static Version pluginVersion(@NotNull String versionString) {
return new Version(versionString, PLUGIN_META_SEPARATOR);
}
@NotNull
public static Version minecraftVersion(@NotNull String versionString) {
return new Version(versionString, MINECRAFT_META_SEPARATOR);
}
private void parse(@NotNull String version, @NotNull String metaSeparator) {
int metaIndex = version.indexOf(metaSeparator);
if (metaIndex > 0) {
this.metadata = version.substring(metaIndex + 1);
version = version.substring(0, metaIndex);
}
String[] versions = version.split(Pattern.quote(VERSION_SEPARATOR));
this.versions = Arrays.stream(versions).mapToInt(Integer::parseInt).toArray();
}
@Override
public int compareTo(@NotNull Version other) {
int length = Math.max(this.versions.length, other.versions.length);
for (int i = 0; i < length; i++) {
int a = i < this.versions.length ? this.versions[i] : 0;
int b = i < other.versions.length ? other.versions[i] : 0;
if (a < b) return -1;
if (a > b) return 1;
}
return 0;
}
@Override
public String toString() {
final StringJoiner joiner = new StringJoiner(VERSION_SEPARATOR);
for (int version : this.versions) {
joiner.add(String.valueOf(version));
}
return joiner + ((!this.metadata.isEmpty()) ? (this.metaSeparator + this.metadata) : "");
}
}