More implementation, timed teleports, regex, etc

This commit is contained in:
William committed 2022-05-26 15:54:19 +01:00
1 parent 7ac52d747f
commit e335a48888
25 files changed
+803 -157

No files matched your search

@@ -1,14 +1,17 @@
package net.william278.huskhomes;
import net.william278.huskhomes.cache.Cache;
import net.william278.huskhomes.config.Messages;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.data.Database;
import net.william278.huskhomes.messenger.NetworkMessenger;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Set;
@@ -43,9 +46,9 @@ public interface HuskHomes {
/**
* The plugin messages loaded from file
*
* @return The plugin {@link Messages}
* @return The plugin {@link Locales}
*/
Messages getMessages();
Locales getLocales();
/**
* The {@link Database} that stores persistent plugin data
@@ -61,8 +64,24 @@ public interface HuskHomes {
*/
Cache getCache();
/**
* The {@link TeleportManager} that manages player teleports
*
* @return the {@link TeleportManager} implementation
*/
TeleportManager getTeleportManager();
/**
* The {@link NetworkMessenger} that sends cross-network messages
*
* @return the {@link NetworkMessenger} implementation
*/
@Nullable
NetworkMessenger getNetworkMessenger();
/**
* Get the {@link Server} this server is on
*
* @return The server
*/
CompletableFuture<Server> getServer(@NotNull Player requester);
@@ -1,6 +1,10 @@
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.messenger.NetworkMessenger;
import net.william278.huskhomes.player.Player;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
@@ -8,6 +12,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
/**
* A cache used to hold persistently used data
@@ -29,6 +34,11 @@ public class Cache {
*/
public final List<String> warps;
/**
* Cached player list
*/
public final List<String> players;
/**
* Create a new cache
*/
@@ -36,6 +46,7 @@ public class Cache {
this.homes = new HashMap<>();
this.publicHomes = new HashMap<>();
this.warps = new ArrayList<>();
this.players = new ArrayList<>();
}
/**
@@ -52,4 +63,23 @@ public class Cache {
});
}
/**
* Updates the cached list of online players
*
* @param plugin the implementing plugin
*/
public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull Player requester) {
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
assert plugin.getNetworkMessenger() != null;
CompletableFuture.runAsync(() -> plugin.getNetworkMessenger().
getOnlinePlayerNames(requester).thenAcceptAsync(returnedPlayerList -> {
players.clear();
players.addAll(List.of(returnedPlayerList));
}));
} else {
players.clear();
players.addAll(plugin.getOnlinePlayers().stream().map(Player::getName).toList());
}
}
}
@@ -2,6 +2,7 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -26,15 +27,15 @@ public abstract class CommandBase {
public final String[] aliases;
/**
* Instance of the proxy plugin implementor
* Instance of the implementing plugin
*/
public final HuskHomes implementor;
public final HuskHomes plugin;
public CommandBase(String command, String permission, HuskHomes implementingPlugin, String... aliases) {
public CommandBase(@NotNull String command, @NotNull String permission, @NotNull HuskHomes implementor, String... aliases) {
this.command = command;
this.permission = permission;
this.implementor = implementingPlugin;
this.plugin = implementor;
this.aliases = aliases;
}
@@ -44,15 +45,25 @@ public abstract class CommandBase {
* @param player {@link Player} executing the command
* @param args Command arguments
*/
public abstract void onExecute(Player player, String[] args);
public abstract void onExecute(@NotNull Player player, @NotNull String[] args);
/**
* What should be returned when the player attempts to TAB complete the command
* What should be returned when the player attempts to TAB-complete the command
*
* @param player {@link Player} doing the TAB completion
* @param args Current command arguments
* @return List of String arguments to offer TAB suggestions
*/
public abstract List<String> onTabComplete(Player player, String[] args);
public abstract List<String> onTabComplete(@NotNull Player player, @NotNull String[] args);
/**
* Returns the localised description string of this command
*
* @return the command description
*/
public String getDescription() {
return plugin.getLocales().getRawLocale(command + "_command_description")
.orElse("A HuskHomes command");
}
}
@@ -0,0 +1,9 @@
package net.william278.huskhomes.command;
import org.jetbrains.annotations.NotNull;
public interface ConsoleExecutable {
void onConsoleExecute(@NotNull String[] args);
}
@@ -0,0 +1,44 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
public class HomeCommand extends CommandBase {
private final static String PERMISSION = "huskhomes.command.home";
public HomeCommand(@NotNull HuskHomes implementor) {
super("home", PERMISSION, implementor);
}
@Override
public void onExecute(@NotNull Player player, @NotNull String[] args) {
if (args.length >= 1) {
//todo check if its a public home, process. Support sending a player
plugin.getTeleportManager().teleportToHome(player, new User(player), args[0]);
} else {
plugin.getDatabase().getHomes(new User(player)).thenAccept(homes -> {
switch (homes.size()) {
case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(player::sendMessage);
case 1 -> plugin.getTeleportManager().executeTeleport(player, homes.get(0)).thenAccept(result ->
plugin.getTeleportManager().finishTeleport(player, result));
default -> {
//todo show home list
}
}
});
}
}
@Override
public List<String> onTabComplete(@NotNull Player player, @NotNull String[] args) {
return plugin.getCache().homes.get(player.getUuid()).stream()
.filter(s -> s.startsWith(args.length >= 1 ? args[0] : ""))
.sorted().collect(Collectors.toList());
}
}
@@ -0,0 +1,97 @@
package net.william278.huskhomes.config;
import de.themoep.minedown.MineDown;
import dev.dejvokep.boostedyaml.YamlDocument;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Optional;
/**
* Loaded locales used by the plugin to display various locales
*/
public class Locales {
@NotNull
private final HashMap<String, String> rawLocales;
private Locales(YamlDocument localesConfig) {
this.rawLocales = new HashMap<>();
for (String localeId : localesConfig.getRoutesAsStrings(false)) {
rawLocales.put(localeId, localesConfig.getString(localeId));
}
}
/**
* Returns an unformatted locale loaded from the locales file
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the locale corresponding to the id, if it exists
*/
public Optional<String> getRawLocale(String localeId) {
if (rawLocales.containsKey(localeId)) {
return Optional.of(rawLocales.get(localeId));
}
return Optional.empty();
}
/**
* Returns an unformatted locale loaded from the locales file, with replacements applied
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists
*/
public Optional<String> getRawLocale(String localeId, String... replacements) {
return getRawLocale(localeId).map(locale -> applyReplacements(locale, replacements));
}
/**
* Returns a MineDown-formatted locale from the locales file
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists
*/
public Optional<MineDown> getLocale(String localeId) {
return getRawLocale(localeId).map(MineDown::new);
}
/**
* Returns a MineDown-formatted locale from the locales file, with replacements applied
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists
*/
public Optional<MineDown> getLocale(String localeId, String... replacements) {
return getRawLocale(localeId, replacements).map(MineDown::new);
}
/**
* Apply placeholder replacements to a raw locale
*
* @param rawLocale The raw, unparsed locale
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return the raw locale, with inserted placeholders
*/
private String applyReplacements(String rawLocale, String... replacements) {
int replacementIndexer = 1;
for (String replacement : replacements) {
String replacementString = "%" + replacementIndexer + "%";
rawLocale = rawLocale.replace(replacementString, replacement);
replacementIndexer = replacementIndexer + 1;
}
return rawLocale;
}
/**
* Load the locales from a BoostedYaml {@link YamlDocument} locales file
*
* @param localesConfig The loaded {@link YamlDocument} locales.yml file
* @return the loaded {@link Locales}
*/
public static Locales load(YamlDocument localesConfig) {
return new Locales(localesConfig);
}
}
@@ -1,97 +0,0 @@
package net.william278.huskhomes.config;
import de.themoep.minedown.MineDown;
import dev.dejvokep.boostedyaml.YamlDocument;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Optional;
/**
* Loaded locales used by the plugin to display various messages
*/
public class Messages {
@NotNull
private final HashMap<String, String> rawMessages;
private Messages(YamlDocument messagesConfig) {
this.rawMessages = new HashMap<>();
for (String messageId : messagesConfig.getRoutesAsStrings(false)) {
rawMessages.put(messageId, messagesConfig.getString(messageId));
}
}
/**
* Returns an unformatted message loaded from the messages file
*
* @param messageId String identifier of the message, corresponding to a key in the file
* @return An {@link Optional} containing the message corresponding to the id, if it exists
*/
public Optional<String> getRawMessage(String messageId) {
if (rawMessages.containsKey(messageId)) {
return Optional.of(rawMessages.get(messageId));
}
return Optional.empty();
}
/**
* Returns an unformatted message loaded from the messages file, with replacements applied
*
* @param messageId String identifier of the message, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied message corresponding to the id, if it exists
*/
public Optional<String> getRawMessage(String messageId, String... replacements) {
return getRawMessage(messageId).map(message -> applyReplacements(message, replacements));
}
/**
* Returns a MineDown-formatted message from the messages file
*
* @param messageId String identifier of the message, corresponding to a key in the file
* @return An {@link Optional} containing the formatted message corresponding to the id, if it exists
*/
public Optional<MineDown> getMessage(String messageId) {
return getRawMessage(messageId).map(MineDown::new);
}
/**
* Returns a MineDown-formatted message from the messages file, with replacements applied
*
* @param messageId String identifier of the message, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied, formatted message corresponding to the id, if it exists
*/
public Optional<MineDown> getMessage(String messageId, String... replacements) {
return getRawMessage(messageId, replacements).map(MineDown::new);
}
/**
* Apply placeholder replacements to a raw message
*
* @param rawMessage The raw, unparsed message
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return the raw message, with inserted placeholders
*/
private String applyReplacements(String rawMessage, String... replacements) {
int replacementIndexer = 1;
for (String replacement : replacements) {
String replacementString = "%" + replacementIndexer + "%";
rawMessage = rawMessage.replace(replacementString, replacement);
replacementIndexer = replacementIndexer + 1;
}
return rawMessage;
}
/**
* Load the messages from a BoostedYaml {@link YamlDocument} messages file
*
* @param messagesConfig The loaded {@link YamlDocument} messages.yml file
* @return the loaded {@link Messages}
*/
public static Messages load(YamlDocument messagesConfig) {
return new Messages(messagesConfig);
}
}
@@ -29,18 +29,22 @@ public class EventProcessor {
// 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 the server is in proxy mode, check if the player is teleporting cross-server and handle
if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
implementor.getDatabase().getCurrentTeleport(new User(player))
.thenAccept(teleport -> teleport.ifPresent(currentTeleport ->
player.teleport(currentTeleport.target).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
//todo error handling if the teleport was not successful on arrival
return;
implementor.getLocales().getLocale("error_invalid_on_arrival")
.ifPresent(player::sendMessage);
} else {
//todo display teleport complete ^-^
implementor.getLocales().getLocale("teleporting_complete")
.ifPresent(player::sendMessage);
}
})));
// Update the player list
assert implementor.getNetworkMessenger() != null;
implementor.getCache().updatePlayerList(implementor, player);
}
// Cache this user's homes
@@ -50,9 +54,23 @@ public class EventProcessor {
});
}
/**
* Handle when a {@link Player} leaves the server
*
* @param player the leaving {@link Player}
*/
public void onPlayerLeave(@NotNull Player player) {
// Remove this user's home cache
implementor.getCache().homes.remove(player.getUuid());
// Update the player list
if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
assert implementor.getNetworkMessenger() != null;
implementor.getOnlinePlayers().stream().filter(
onlinePlayer -> !onlinePlayer.getUuid().equals(player.getUuid()))
.findAny().ifPresent(updater ->
implementor.getCache().updatePlayerList(implementor, updater));
}
}
}
@@ -0,0 +1,10 @@
package net.william278.huskhomes.messenger;
import com.google.gson.GsonBuilder;
public class EmptyPayload implements MessageSerializable {
@Override
public String toJson() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
}
@@ -55,7 +55,7 @@ public class Message {
public String payload;
public Message(@NotNull MessageType type, @NotNull String sender, @NotNull String targetPlayer,
@NotNull MessagePayload payload, @NotNull MessageKind messageKind, int clusterId) {
@NotNull MessageSerializable payload, @NotNull MessageKind messageKind, int clusterId) {
this.type = type;
this.sender = sender;
this.targetPlayer = targetPlayer;
@@ -74,7 +74,9 @@ public class Message {
}
public enum MessageType {
TP_REQUEST
TP_REQUEST,
POSITION_REQUEST
}
public enum MessageKind {
@@ -3,7 +3,7 @@ package net.william278.huskhomes.messenger;
/**
* Represents data that can be sent as a payload in a {@link Message}
*/
public interface MessagePayload {
public interface MessageSerializable {
String toJson();
@@ -3,6 +3,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.position.Server;
import org.jetbrains.annotations.NotNull;
@@ -111,19 +112,7 @@ public abstract class NetworkMessenger {
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);
}
case MESSAGE -> prepareReply(receiver, message).thenAccept(reply -> sendReply(receiver, message));
// Handle a reply message
case REPLY -> {
if (processingMessages.containsKey(message.uuid)) {
@@ -134,6 +123,26 @@ public abstract class NetworkMessenger {
}
}
private CompletableFuture<Message> prepareReply(@NotNull final Player receiver, @NotNull final Message message) {
return CompletableFuture.supplyAsync(() -> {
// Handle different message types and apply changes for reply message
switch (message.type) {
case TP_REQUEST -> {
}
case POSITION_REQUEST -> {
message.payload = receiver.getPosition().join().toJson();
}
}
// Prepare reply message
message.targetPlayer = message.sender;
message.sender = receiver.getName();
message.kind = Message.MessageKind.REPLY;
return message;
});
}
/**
* Close the network messenger
*/
@@ -35,6 +35,20 @@ public interface Player {
*/
CompletableFuture<Position> getPosition();
/**
* Returns the current local {@link Location} of this player
*
* @return the player's current {@link Location} on the server
*/
Location getLocation();
/**
* Returns the health of this player
*
* @return the player's health points
*/
double getHealth();
/**
* Returns if the player has the permission node
*
@@ -35,7 +35,6 @@ public class Location {
/**
* The {@link World} the location is on
*/
@NotNull
public World world;
public Location(double x, double y, double z, float yaw, float pitch,
@@ -48,4 +47,7 @@ public class Location {
this.world = world;
}
public Location() {
}
}
@@ -1,16 +1,24 @@
package net.william278.huskhomes.position;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import net.william278.huskhomes.messenger.MessageSerializable;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.UUID;
/**
* Represents a position - a location somewhere on the proxy network or server
*/
public class Position extends Location {
public class Position extends Location implements MessageSerializable {
/**
* The {@link Server} the position is on
*/
@NotNull
public Server server;
public Position(double x, double y, double z, float yaw, float pitch,
@@ -19,4 +27,81 @@ public class Position extends Location {
this.server = server;
}
public Position() {
}
public String toJson() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
public static Position fromJson(String json) {
return new GsonBuilder().setPrettyPrinting()
.registerTypeAdapter(World.class, new TypeAdapter<World>() {
@Override
public void write(JsonWriter jsonWriter, World world) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("name");
jsonWriter.value(world.name);
jsonWriter.name("uuid");
jsonWriter.value(world.uuid.toString());
jsonWriter.endObject();
}
@Override
public World read(JsonReader jsonReader) throws IOException {
final World readWorld = new World();
jsonReader.beginObject();
String fieldName = null;
while (jsonReader.hasNext()) {
JsonToken token = jsonReader.peek();
if (token.equals(JsonToken.NAME)) {
fieldName = jsonReader.nextName();
}
if (fieldName != null) {
if (fieldName.equals("name")) {
jsonReader.peek();
readWorld.name = jsonReader.nextString();
}
if (fieldName.equals("uuid")) {
jsonReader.peek();
readWorld.uuid = UUID.fromString(jsonReader.nextString());
}
}
}
jsonReader.endObject();
return readWorld;
}
})
.registerTypeAdapter(Server.class, new TypeAdapter<Server>() {
@Override
public void write(JsonWriter jsonWriter, Server world) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("name");
jsonWriter.value(world.name);
jsonWriter.endObject();
}
@Override
public Server read(JsonReader jsonReader) throws IOException {
final Server readServer = new Server();
jsonReader.beginObject();
String fieldName = null;
while (jsonReader.hasNext()) {
JsonToken token = jsonReader.peek();
if (token.equals(JsonToken.NAME)) {
fieldName = jsonReader.nextName();
}
if (fieldName != null) {
if (fieldName.equals("name")) {
jsonReader.peek();
readServer.name = jsonReader.nextString();
}
}
}
jsonReader.endObject();
return readServer;
}
})
.create().fromJson(json, Position.class);
}
}
@@ -10,13 +10,15 @@ public class Server {
/**
* Proxy-defined name of this server
*/
@NotNull
public String name;
public Server(@NotNull String name) {
this.name = name;
}
public Server() {
}
@Override
public boolean equals(Object other) {
if (other instanceof Server server) {
@@ -25,4 +27,5 @@ public class Server {
}
return super.equals(other);
}
}
@@ -12,13 +12,11 @@ public class World {
/**
* The name of this world, as defined by the world directory name
*/
@NotNull
public String name;
/**
* UUID of this world, as defined by the {@code uid.dat} file in the world directory
*/
@NotNull
public UUID uuid;
public World(@NotNull String name, @NotNull UUID uuid) {
@@ -26,4 +24,7 @@ public class World {
this.uuid = uuid;
}
public World() {
}
}
@@ -1,26 +1,137 @@
package net.william278.huskhomes.teleport;
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.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.util.MatcherUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Cross-platform teleportation manager
*/
public class TeleportManager {
public abstract class TeleportManager {
/**
* Instance of the implementing plugin
*/
@NotNull
private final HuskHomes plugin;
protected final HuskHomes plugin;
public TeleportManager(@NotNull HuskHomes plugin) {
this.plugin = plugin;
private static final String WARMUP_BYPASS_PERMISSION = "huskhomes.bypass.teleport_warmup";
public TeleportManager(@NotNull HuskHomes implementor) {
this.plugin = implementor;
}
/**
* Teleport a {@link Player} to another {@link User}'s {@link Home}
*
* @param player the {@link Player} 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) {
plugin.getDatabase().getHome(homeOwner, homeName).thenAccept(optionalHome ->
optionalHome.ifPresentOrElse(home ->
executeTeleport(player, home).thenAccept(result -> finishTeleport(player, result)), () -> {
if (homeOwner.uuid.equals(player.getUuid())) {
plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(player::sendMessage);
} else {
plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(player::sendMessage);
}
}));
}
/**
* Teleport a {@link Player} to a server {@link Warp}
*
* @param player the {@link Player} to teleport
* @param warpName the name of the warp
*/
public void teleportToWarp(@NotNull Player player, @NotNull String warpName) {
plugin.getDatabase().getWarp(warpName).thenAccept(optionalWarp ->
optionalWarp.ifPresentOrElse(warp ->
executeTeleport(player, warp).thenAccept(result -> finishTeleport(player, result)), () ->
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(player::sendMessage)));
}
/**
* Teleport a {@link Player} to another player by given input name
*
* @param player the {@link Player} to teleport
* @param targetPlayer the name of the target player
*/
public void teleportToPlayer(@NotNull Player player, @NotNull String targetPlayer) {
MatcherUtil.matchPlayerName(targetPlayer, plugin).ifPresentOrElse(playerName ->
getPlayerPosition(player, playerName).thenAccept(optionalPosition ->
optionalPosition.ifPresentOrElse(targetPosition ->
executeTeleport(player, targetPosition).thenAccept(result ->
finishTeleport(player, result)),
() -> plugin.getLocales().getLocale("error_invalid_player").
ifPresent(player::sendMessage))),
() -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(player::sendMessage));
}
private CompletableFuture<Optional<Position>> getPlayerPosition(@NotNull Player requester, @NotNull String playerName) {
final Optional<Player> localPlayer = plugin.getOnlinePlayers().stream().filter(player ->
player.getName().equalsIgnoreCase(playerName)).findFirst();
if (localPlayer.isPresent()) {
return localPlayer.get().getPosition().thenApply(Optional::of);
}
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
assert plugin.getNetworkMessenger() != null;
return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.POSITION_REQUEST,
requester.getName(),
playerName,
new EmptyPayload(),
Message.MessageKind.MESSAGE,
plugin.getSettings().getIntegerValue(Settings.ConfigOption.CLUSTER_ID)))
.thenApplyAsync(reply -> Optional.of(Position.fromJson(reply.payload)));
}
return CompletableFuture.supplyAsync(Optional::empty);
}
public CompletableFuture<TeleportResult> executeTeleport(@NotNull Player player, @NotNull Position position) {
final int teleportWarmupTime = plugin.getSettings().getIntegerValue(Settings.ConfigOption.TELEPORT_WARMUP_TIME);
CompletableFuture<TeleportResult> completableTeleport;
if (!player.hasPermission(WARMUP_BYPASS_PERMISSION) && teleportWarmupTime > 0) {
completableTeleport = processTimedTeleport(new TimedTeleport(player, position, teleportWarmupTime))
.thenApplyAsync(teleport -> teleport.getPlayer().teleport(teleport.getTargetPosition()).join());
} else {
completableTeleport = player.teleport(position);
}
return completableTeleport;
}
public void finishTeleport(@NotNull Player player, @NotNull TeleportResult teleportResult) {
switch (teleportResult) {
case COMPLETED_LOCALLY -> {
plugin.getLocales().getLocale("teleporting_complete").ifPresent(player::sendMessage);
}
case FAILED_INVALID_WORLD -> {
plugin.getLocales().getLocale("error_invalid_on_arrival").ifPresent(player::sendMessage);
}
case FAILED_UNSAFE -> {
//todo
}
case FAILED_ILLEGAL_COORDINATES -> {
plugin.getLocales().getLocale("error_illegal_target_coordinates").ifPresent(player::sendMessage);
}
case FAILED_INVALID_SERVER -> {
//todo
}
}
}
/**
@@ -35,16 +146,55 @@ public class TeleportManager {
if (position.server.equals(server)) {
return player.teleport(teleport.target).join();
} else {
return teleportCrossServer(teleport).join();
return teleportCrossServer(player, teleport).join();
}
});
}
private CompletableFuture<TeleportResult> teleportCrossServer(Teleport teleport) {
return CompletableFuture.supplyAsync(() -> {
//todo
return TeleportResult.COMPLETED_CROSS_SERVER;
});
private CompletableFuture<TeleportResult> teleportCrossServer(Player player, Teleport teleport) {
assert plugin.getNetworkMessenger() != null;
return CompletableFuture.supplyAsync(() -> plugin.getDatabase().setCurrentTeleport(teleport.player, teleport)
.thenApplyAsync(ignored -> plugin.getNetworkMessenger().sendPlayer(player, teleport.target.server)
.thenApplyAsync(completed -> completed ? TeleportResult.COMPLETED_CROSS_SERVER :
TeleportResult.FAILED_INVALID_SERVER)
.join()).join());
}
/**
* Process a timed teleport, ticking it
*
* @param teleport the {@link TimedTeleport} being ticked
* @param timedTeleportCompletableFuture a future tracking the {@link TimedTeleport}'s completion
* @return {@code true} if the implementor should cancel the timedTeleport
*/
protected final boolean tickTimedTeleport(@NotNull final TimedTeleport teleport,
@NotNull final CompletableFuture<TimedTeleport> timedTeleportCompletableFuture) {
if (teleport.isDone()) {
timedTeleportCompletableFuture.completeAsync(() -> teleport);
return true;
}
// Cancel the timed teleport if the player takes damage
if (teleport.hasTakenDamage()) {
plugin.getLocales().getLocale("teleporting_cancelled_damage").ifPresent(locale ->
teleport.getPlayer().sendMessage(locale));
timedTeleportCompletableFuture.cancel(true);
return true;
}
// Cancel the timed teleport if the player moves
if (teleport.hasMoved()) {
plugin.getLocales().getLocale("teleporting_cancelled_movement").ifPresent(locale ->
teleport.getPlayer().sendMessage(locale));
timedTeleportCompletableFuture.cancel(true);
return true;
}
// Decrement the countdown timer
teleport.countDown();
return false;
}
public abstract CompletableFuture<TimedTeleport> processTimedTeleport(TimedTeleport teleport);
}
@@ -0,0 +1,79 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
/**
* Represents a {@link Teleport} due to occur
*/
public class TimedTeleport {
private final Player player;
private final Position targetPosition;
private final Location startLocation;
private final double startHealth;
private final int duration;
private int timeLeft;
protected TimedTeleport(@NotNull Player player, @NotNull Position targetPosition, int duration) {
this.player = player;
this.targetPosition = targetPosition;
this.startLocation = player.getLocation();
this.startHealth = player.getHealth();
this.duration = duration;
this.timeLeft = duration;
}
public final boolean isDone() {
return timeLeft <= duration;
}
public final void countDown() {
timeLeft--;
}
/**
* Get the teleporting player
*
* @return the {@link Player} who is teleporting
*/
public Player getPlayer() {
return player;
}
/**
* Returns if the player has moved since the timed teleport started
*
* @return {@code true} if the player has moved; {@code false} otherwise
*/
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);
return movementDistance > maxMovementDistance;
}
/**
* Returns if the player has taken damage since the timed teleport started
*
* @return {@code true} if the player has taken damage
*/
public boolean hasTakenDamage() {
return player.getHealth() < startHealth;
}
/**
* Returns the target {@link Position} of this timed teleport
*
* @return the target {@link Position}
*/
public Position getTargetPosition() {
return targetPosition;
}
}
@@ -0,0 +1,35 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.Optional;
/**
* Utility for matching a username based on an input name
*/
public final class MatcherUtil {
/**
* Match a player's username from a user-supplied input name
*
* @param inputName the user input name
* @param plugin the implementing plugin
* @return an optional, containing a matched username if one was found
*/
public static Optional<String> matchPlayerName(@NotNull String inputName, @NotNull HuskHomes plugin) {
// Return an exact match if there is one present
final Optional<String> exactPlayer = plugin.getCache().players.stream().filter(username ->
username.equalsIgnoreCase(inputName)).findFirst();
if (exactPlayer.isPresent()) {
return exactPlayer;
}
// Return most likely match, if present
return plugin.getCache().players.stream().filter(username -> username.toLowerCase()
.startsWith(inputName.toLowerCase())).min(Comparator.comparingInt(username ->
username.length() - inputName.toLowerCase().length()));
}
}
@@ -0,0 +1,28 @@
package net.william278.huskhomes.util;
import java.util.regex.Pattern;
import net.william278.huskhomes.position.PositionMeta;
/**
* Provides a number of utility regular expressions for checking home name patterns
*/
public final class RegexUtil {
/**
* Pattern for checking home and warp {@link PositionMeta} description fields
*/
public static final Pattern DESCRIPTION_PATTERN = Pattern.compile("[a-zA-Z\\d\\-_\\s]+");
/**
* Pattern for checking home and warp {@link PositionMeta} name fields
*/
public static final Pattern NAME_PATTERN = Pattern.compile("[A-Za-z\\d_\\-]+");
/**
* Pattern for checking public home input fields
* e.g. {@code ownerName.homeName}
*/
public static final Pattern OWNER_NAME_PATTERN = Pattern.compile("\\w+\\.[A-Za-z\\d_\\-]+");
}