More refactor work, encapsulate classes

This commit is contained in:
William278 committed 2023-03-02 15:00:02 +00:00
1 parent 3e1ec09487
commit 1cebdac9b8
51 files changed
+756 -621

No files matched your search

@@ -163,8 +163,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
this.eventDispatcher = new BukkitEventDispatcher(this); this.eventDispatcher = new BukkitEventDispatcher(this);
// Initialize the cache // Initialize the cache
cache = new Cache(eventDispatcher); this.cache = new Cache(this);
cache.initialize(database);
// Prepare the home and warp position manager // Prepare the home and warp position manager
this.manager = new Manager(this); this.manager = new Manager(this);
@@ -445,7 +444,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
final int y = snapshot.getHighestBlockYAt(x, z); final int y = snapshot.getHighestBlockYAt(x, z);
final Material blockType = snapshot.getBlockType(chunkX, y, chunkZ); final Material blockType = snapshot.getBlockType(chunkX, y, chunkZ);
if (!isBlockUnsafe(blockType.getKey().toString())) { if (!isBlockUnsafe(blockType.getKey().toString())) {
return new Location((location.x + dX) + 0.5d, y + 1.25d, (location.z + dZ) + 0.5d, location.world); return new Location((location.getX() + dX) + 0.5d, y + 1.25d, (location.getZ() + dZ) + 0.5d, location.getWorld());
} }
} }
} }
@@ -18,7 +18,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
/** /**
* Hook to display warps and public homes on Dynmap * Hook to display warps and public homes on Dynmap
@@ -35,7 +34,8 @@ public class DynMapHook extends MapHook {
@Override @Override
protected CompletableFuture<Void> initializeMap() { protected CompletableFuture<Void> initializeMap() {
return CompletableFuture.runAsync(() -> { final CompletableFuture<Void> initializedFuture = new CompletableFuture<>();
plugin.runAsync(() -> {
final MarkerAPI markerAPI = dynmapAPI.getMarkerAPI(); final MarkerAPI markerAPI = dynmapAPI.getMarkerAPI();
if (plugin.getSettings().isPublicHomesOnMap()) { if (plugin.getSettings().isPublicHomesOnMap()) {
markerAPI.getMarkerIcons().stream() markerAPI.getMarkerIcons().stream()
@@ -57,10 +57,9 @@ public class DynMapHook extends MapHook {
markerAPI.createMarkerSet(WARPS_MARKER_SET_ID, markerAPI.createMarkerSet(WARPS_MARKER_SET_ID,
"Warps", dynmapAPI.getMarkerAPI().getMarkerIcons(), false); "Warps", dynmapAPI.getMarkerAPI().getMarkerIcons(), false);
} }
}).exceptionally(throwable -> { initializedFuture.complete(null);
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to initialize Dynmap integration", throwable);
return null;
}); });
return initializedFuture;
} }
@Override @Override
@@ -70,13 +69,13 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> updatedFuture = new CompletableFuture<>(); final CompletableFuture<Void> updatedFuture = new CompletableFuture<>();
removeHome(home).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { removeHome(home).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).createMarker( dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).createMarker(
home.owner.uuid + ":" + home.uuid, home.meta.name, home.world.name, home.getOwner().uuid + ":" + home.getUuid(), home.getMeta().getName(), home.getWorld().getName(),
home.x, home.y, home.z, dynmapAPI.getMarkerAPI().getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME), false) home.getX(), home.getY(), home.getZ(), dynmapAPI.getMarkerAPI().getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(home.meta.name) .setDescription(MarkerInformationPopup.create(home.getMeta().getName())
.setThumbnailMarker(PUBLIC_HOME_MARKER_IMAGE_NAME) .setThumbnailMarker(PUBLIC_HOME_MARKER_IMAGE_NAME)
.addField("Owner", home.owner.username) .addField("Owner", home.getOwner().username)
.addField("Description", plugin.getLocales().formatDescription(home.meta.description)) .addField("Description", plugin.getLocales().formatDescription(home.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommandType.PUBLIC_HOME_COMMAND.commandBase.command + " " + home.meta.name) .addField("Command", "/" + BukkitCommandType.PUBLIC_HOME_COMMAND.commandBase.command + " " + home.getMeta().getName())
.toHtml()); .toHtml());
updatedFuture.complete(null); updatedFuture.complete(null);
})); }));
@@ -90,7 +89,7 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> removedFuture = new CompletableFuture<>(); final CompletableFuture<Void> removedFuture = new CompletableFuture<>();
Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).getMarkers().stream() dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).getMarkers().stream()
.filter(marker -> marker.getMarkerID().equals(home.owner.uuid + ":" + home.uuid)) .filter(marker -> marker.getMarkerID().equals(home.getOwner().uuid + ":" + home.getUuid()))
.findFirst() .findFirst()
.ifPresent(Marker::deleteMarker); .ifPresent(Marker::deleteMarker);
removedFuture.complete(null); removedFuture.complete(null);
@@ -117,12 +116,12 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> updatedFuture = new CompletableFuture<>(); final CompletableFuture<Void> updatedFuture = new CompletableFuture<>();
removeWarp(warp).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { removeWarp(warp).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).createMarker( dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).createMarker(
warp.uuid.toString(), warp.meta.name, warp.world.name, warp.getUuid().toString(), warp.getMeta().getName(), warp.getWorld().getName(),
warp.x, warp.y, warp.z, dynmapAPI.getMarkerAPI().getMarkerIcon(WARP_MARKER_IMAGE_NAME), false) warp.getX(), warp.getY(), warp.getZ(), dynmapAPI.getMarkerAPI().getMarkerIcon(WARP_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(warp.meta.name) .setDescription(MarkerInformationPopup.create(warp.getMeta().getName())
.setThumbnailMarker(WARP_MARKER_IMAGE_NAME) .setThumbnailMarker(WARP_MARKER_IMAGE_NAME)
.addField("Description", plugin.getLocales().formatDescription(warp.meta.description)) .addField("Description", plugin.getLocales().formatDescription(warp.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommandType.WARP_COMMAND.commandBase.command + " " + warp.meta.name) .addField("Command", "/" + BukkitCommandType.WARP_COMMAND.commandBase.command + " " + warp.getMeta().getName())
.toHtml()); .toHtml());
updatedFuture.complete(null); updatedFuture.complete(null);
})); }));
@@ -136,7 +135,7 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> removedFuture = new CompletableFuture<>(); final CompletableFuture<Void> removedFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { CompletableFuture.runAsync(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).getMarkers().stream() dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).getMarkers().stream()
.filter(marker -> marker.getMarkerID().equals(warp.uuid.toString())) .filter(marker -> marker.getMarkerID().equals(warp.getUuid().toString()))
.findFirst() .findFirst()
.ifPresent(Marker::deleteMarker); .ifPresent(Marker::deleteMarker);
removedFuture.complete(null); removedFuture.complete(null);
@@ -74,9 +74,9 @@ public class BukkitEventListener extends EventListener implements Listener {
BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> { BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> {
final OnlineUser onlineUser = BukkitPlayer.adapt(event.getPlayer()); final OnlineUser onlineUser = BukkitPlayer.adapt(event.getPlayer());
super.handlePlayerUpdateSpawnPoint(onlineUser, new Position( super.handlePlayerUpdateSpawnPoint(onlineUser, new Position(
adaptedLocation.x, adaptedLocation.y, adaptedLocation.z, adaptedLocation.getX(), adaptedLocation.getY(), adaptedLocation.getZ(),
adaptedLocation.yaw, adaptedLocation.pitch, adaptedLocation.getYaw(), adaptedLocation.getPitch(),
adaptedLocation.world, plugin.getServerName())); adaptedLocation.getWorld(), plugin.getServerName()));
}); });
} }
@@ -78,18 +78,18 @@ public class PluginMessenger extends Messenger implements PluginMessageListener
return fetchOnlineServerList(onlineUser).thenApply(onlineServers -> { return fetchOnlineServerList(onlineUser).thenApply(onlineServers -> {
// Ensure the server is online // Ensure the server is online
final Optional<String> targetServer = Arrays.stream(onlineServers) final Optional<String> targetServer = Arrays.stream(onlineServers)
.filter(serverName -> serverName.equals(server.name)) .filter(serverName -> serverName.equals(server.getName()))
.findFirst(); .findFirst();
if (targetServer.isEmpty()) { if (targetServer.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, plugin.getLoggingAdapter().log(Level.WARNING,
"Failed to send " + dispatcher.username + " to " + server.name + "; server offline?"); "Failed to send " + dispatcher.username + " to " + server.getName() + "; server offline?");
return false; return false;
} }
// Send player to target server // Send player to target server
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput(); final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF("Connect"); messageWriter.writeUTF("Connect");
messageWriter.writeUTF(server.name); messageWriter.writeUTF(server.getName());
dispatcher.sendPluginMessage(BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray()); dispatcher.sendPluginMessage(BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray());
return true; return true;
}); });
@@ -19,15 +19,15 @@ public final class BukkitAdapter {
* @return the adapted {@link Location} * @return the adapted {@link Location}
*/ */
public static Optional<org.bukkit.Location> adaptLocation(@NotNull Location location) { public static Optional<org.bukkit.Location> adaptLocation(@NotNull Location location) {
org.bukkit.World world = Bukkit.getWorld(location.world.name); org.bukkit.World world = Bukkit.getWorld(location.getWorld().getName());
if (world == null) { if (world == null) {
world = Bukkit.getWorld(location.world.uuid); world = Bukkit.getWorld(location.getWorld().getUuid());
} }
if (world == null) { if (world == null) {
return Optional.empty(); return Optional.empty();
} }
return Optional.of(new org.bukkit.Location(world, location.x, location.y, location.z, return Optional.of(new org.bukkit.Location(world, location.getX(), location.getY(), location.getZ(),
location.yaw, location.pitch)); location.getYaw(), location.getPitch()));
} }
/** /**
@@ -4,7 +4,6 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.command.CommandBase; import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User; import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
@@ -23,79 +22,35 @@ import java.util.stream.Collectors;
*/ */
public class Cache { public class Cache {
/** private final HuskHomes plugin;
* Cached home names - maps a {@link UUID} to a list of their homes private final Map<UUID, List<String>> homes = new HashMap<>();
*/ private final Map<String, List<String>> publicHomes = new HashMap<>();
public final HashMap<UUID, List<String>> homes; private final List<String> warps = new ArrayList<>();
private final Set<String> players = new HashSet<>();
/** private final Map<String, PaginatedList> privateHomeLists = new HashMap<>();
* Cached home names - maps a username to a list of their public homes private final Map<UUID, PaginatedList> publicHomeLists = new HashMap<>();
*/ private final Map<UUID, PaginatedList> warpLists = new HashMap<>();
public final HashMap<String, List<String>> publicHomes; private final Set<UUID> currentlyOnWarmup = new HashSet<>();
/**
* Cached warp names
*/
public final List<String> warps;
/**
* Cached player list
*/
public final Set<String> players;
/**
* Cached lists of private homes for pagination, mapped to the username of the home owner
*/
public final HashMap<String, PaginatedList> privateHomeLists;
/**
* Cached lists of public homes for pagination
*/
public final HashMap<UUID, PaginatedList> publicHomeLists;
/**
* Cached lists of warps for pagination
*/
public final HashMap<UUID, PaginatedList> warpLists;
/**
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
*/
public final HashSet<UUID> currentlyOnWarmup;
/**
* Plugin event dispatcher
*/
private final EventDispatcher eventDispatcher;
/** /**
* Create a new cache * Create a new cache
*/ */
public Cache(@NotNull EventDispatcher eventDispatcher) { public Cache(@NotNull HuskHomes plugin) {
this.homes = new HashMap<>(); this.plugin = plugin;
this.publicHomes = new HashMap<>(); this.initialize();
this.warps = new ArrayList<>();
this.players = new HashSet<>();
this.privateHomeLists = new HashMap<>();
this.publicHomeLists = new HashMap<>();
this.warpLists = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.eventDispatcher = eventDispatcher;
} }
/** /**
* Initialize the cache, request basic data to load into memory * Initialize the cache with public home and warp names
*
* @param database the database to load data from
*/ */
public void initialize(@NotNull Database database) { public void initialize() {
CompletableFuture.runAsync(() -> { final Database database = plugin.getDatabase();
database.getPublicHomes().thenAccept(publicHomeList -> publicHomeList.forEach(home -> { plugin.runAsync(() -> {
this.publicHomes.putIfAbsent(home.owner.username, new ArrayList<>()); database.getPublicHomes().forEach(home -> {
this.publicHomes.get(home.owner.username).add(home.meta.name); this.getPublicHomes().putIfAbsent(home.getOwner().username, new ArrayList<>());
})); this.getPublicHomes().get(home.getOwner().username).add(home.getMeta().getName());
database.getWarps().thenAccept(warpsList -> warpsList.forEach(warp -> });
this.warps.add(warp.meta.name))); database.getWarps().forEach(warp -> this.getWarps().add(warp.getMeta().getName()));
}); });
} }
@@ -105,8 +60,8 @@ public class Cache {
* @param plugin the implementing plugin * @param plugin the implementing plugin
*/ */
public CompletableFuture<Set<String>> updatePlayerListCache(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) { public CompletableFuture<Set<String>> updatePlayerListCache(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) {
players.clear(); getPlayers().clear();
players.addAll(plugin.getOnlinePlayers() getPlayers().addAll(plugin.getOnlinePlayers()
.stream() .stream()
.filter(player -> !player.isVanished()) .filter(player -> !player.isVanished())
.map(onlineUser -> onlineUser.username) .map(onlineUser -> onlineUser.username)
@@ -116,11 +71,11 @@ public class Cache {
return plugin.getMessenger() return plugin.getMessenger()
.getOnlinePlayerNames(requester) .getOnlinePlayerNames(requester)
.thenApply(networkedPlayers -> { .thenApply(networkedPlayers -> {
players.addAll(Set.of(networkedPlayers)); getPlayers().addAll(Set.of(networkedPlayers));
return players; return getPlayers();
}); });
} }
return CompletableFuture.completedFuture(players); return CompletableFuture.completedFuture(getPlayers());
} }
/** /**
@@ -131,7 +86,7 @@ public class Cache {
* @since 3.1 * @since 3.1
*/ */
public boolean isWarmingUp(@NotNull UUID userUuid) { public boolean isWarmingUp(@NotNull UUID userUuid) {
return this.currentlyOnWarmup.contains(userUuid); return this.getCurrentlyOnWarmup().contains(userUuid);
} }
@NotNull @NotNull
@@ -161,61 +116,61 @@ public class Cache {
@NotNull @NotNull
public Optional<MineDown> getHomeList(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull Locales locales, public Optional<MineDown> getHomeList(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull Locales locales,
@NotNull List<Home> homes, final int itemsPerPage, final int page) { @NotNull List<Home> homes, final int itemsPerPage, final int page) {
if (eventDispatcher.dispatchViewHomeListEvent(homes, onlineUser, false).join().isCancelled()) { if (plugin.getEventDispatcher().dispatchViewHomeListEvent(homes, onlineUser, false).join().isCancelled()) {
return Optional.empty(); return Optional.empty();
} }
final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.username : ""; final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.username : "";
final PaginatedList homeList = PaginatedList.of(homes.stream().map(home -> final PaginatedList homeList = PaginatedList.of(homes.stream().map(home ->
locales.getRawLocale("home_list_item", locales.getRawLocale("home_list_item",
Locales.escapeMineDown(home.meta.name), Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.owner.username + "." + home.meta.name), Locales.escapeMineDown(home.getOwner().username + "." + home.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(home.meta.description))) Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
.orElse(home.meta.name)).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage) .orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("home_list_page_title", .setHeaderFormat(locales.getRawLocale("home_list_page_title",
homeOwner.username, "%first_item_on_page_index%", homeOwner.username, "%first_item_on_page_index%",
"%last_item_on_page_index%", "%total_items%").orElse("")) "%last_item_on_page_index%", "%total_items%").orElse(""))
.setCommand("/huskhomes:homelist" + homeListArguments).build()); .setCommand("/huskhomes:homelist" + homeListArguments).build());
this.privateHomeLists.put(homeOwner.username, homeList); this.getPrivateHomeLists().put(homeOwner.username, homeList);
return Optional.of(homeList.getNearestValidPage(page)); return Optional.of(homeList.getNearestValidPage(page));
} }
@NotNull @NotNull
public Optional<MineDown> getPublicHomeList(@NotNull OnlineUser onlineUser, @NotNull Locales locales, public Optional<MineDown> getPublicHomeList(@NotNull OnlineUser onlineUser, @NotNull Locales locales,
@NotNull List<Home> publicHomes, final int itemsPerPage, final int page) { @NotNull List<Home> publicHomes, final int itemsPerPage, final int page) {
if (eventDispatcher.dispatchViewHomeListEvent(publicHomes, onlineUser, true).join().isCancelled()) { if (plugin.getEventDispatcher().dispatchViewHomeListEvent(publicHomes, onlineUser, true).join().isCancelled()) {
return Optional.empty(); return Optional.empty();
} }
final PaginatedList publicHomeList = PaginatedList.of(publicHomes.stream().map(home -> final PaginatedList publicHomeList = PaginatedList.of(publicHomes.stream().map(home ->
locales.getRawLocale("public_home_list_item", locales.getRawLocale("public_home_list_item",
Locales.escapeMineDown(home.meta.name), Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.owner.username + "." + home.meta.name), Locales.escapeMineDown(home.getOwner().username + "." + home.getMeta().getName()),
Locales.escapeMineDown(home.owner.username), Locales.escapeMineDown(home.getOwner().username),
Locales.escapeMineDown(locales.formatDescription(home.meta.description))) Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
.orElse(home.meta.name)).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage) .orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("public_home_list_page_title", .setHeaderFormat(locales.getRawLocale("public_home_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%", "%first_item_on_page_index%", "%last_item_on_page_index%",
"%total_items%").orElse("")) "%total_items%").orElse(""))
.setCommand("/huskhomes:publichomelist").build()); .setCommand("/huskhomes:publichomelist").build());
publicHomeLists.put(onlineUser.uuid, publicHomeList); getPublicHomeLists().put(onlineUser.uuid, publicHomeList);
return Optional.of(publicHomeList.getNearestValidPage(page)); return Optional.of(publicHomeList.getNearestValidPage(page));
} }
@NotNull @NotNull
public Optional<MineDown> getWarpList(@NotNull OnlineUser onlineUser, @NotNull Locales locales, public Optional<MineDown> getWarpList(@NotNull OnlineUser onlineUser, @NotNull Locales locales,
@NotNull List<Warp> warps, final int itemsPerPage, final int page) { @NotNull List<Warp> warps, final int itemsPerPage, final int page) {
if (eventDispatcher.dispatchViewWarpListEvent(warps, onlineUser).join().isCancelled()) { if (plugin.getEventDispatcher().dispatchViewWarpListEvent(warps, onlineUser).join().isCancelled()) {
return Optional.empty(); return Optional.empty();
} }
final PaginatedList warpList = PaginatedList.of(warps.stream() final PaginatedList warpList = PaginatedList.of(warps.stream()
.map(warp -> locales.getRawLocale("warp_list_item", .map(warp -> locales.getRawLocale("warp_list_item",
Locales.escapeMineDown(warp.meta.name), Locales.escapeMineDown(warp.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(warp.meta.description))) Locales.escapeMineDown(locales.formatDescription(warp.getMeta().getDescription())))
.orElse(warp.meta.name)).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage) .orElse(warp.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("warp_list_page_title", .setHeaderFormat(locales.getRawLocale("warp_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%", "%first_item_on_page_index%", "%last_item_on_page_index%",
"%total_items%").orElse("")) "%total_items%").orElse(""))
.setCommand("/huskhomes:warplist").build()); .setCommand("/huskhomes:warplist").build());
warpLists.put(onlineUser.uuid, warpList); getWarpLists().put(onlineUser.uuid, warpList);
return Optional.of(warpList.getNearestValidPage(page)); return Optional.of(warpList.getNearestValidPage(page));
} }
@@ -238,4 +193,59 @@ public class Cache {
.getNearestValidPage(page); .getNearestValidPage(page);
} }
/**
* Cached home names - maps a {@link UUID} to a list of their homes
*/
public Map<UUID, List<String>> getHomes() {
return homes;
}
/**
* Cached home names - maps a username to a list of their public homes
*/
public Map<String, List<String>> getPublicHomes() {
return publicHomes;
}
/**
* Cached warp names
*/
public List<String> getWarps() {
return warps;
}
/**
* Cached player list
*/
public Set<String> getPlayers() {
return players;
}
/**
* Cached lists of private homes for pagination, mapped to the username of the home owner
*/
public Map<String, PaginatedList> getPrivateHomeLists() {
return privateHomeLists;
}
/**
* Cached lists of public homes for pagination
*/
public Map<UUID, PaginatedList> getPublicHomeLists() {
return publicHomeLists;
}
/**
* Cached lists of warps for pagination
*/
public Map<UUID, PaginatedList> getWarpLists() {
return warpLists;
}
/**
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
*/
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
} }
@@ -5,7 +5,7 @@ import org.jetbrains.annotations.NotNull;
public class ValidationException extends IllegalArgumentException { public class ValidationException extends IllegalArgumentException {
public ValidationException(@NotNull ValidationError error) { public ValidationException(@NotNull ValidationError error) {
super("Error validating position: " + error.toString()); super("Error validating position: " + error.name());
} }
public enum ValidationError { public enum ValidationError {
@@ -143,7 +143,7 @@ public abstract class BaseHuskHomesAPI {
*/ */
public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) { public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) {
return getUserHomes(user).thenApply(homes -> homes.stream() return getUserHomes(user).thenApply(homes -> homes.stream()
.filter(home -> home.isPublic) .filter(home -> home.isPublic())
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
@@ -320,7 +320,7 @@ public abstract class BaseHuskHomesAPI {
final boolean timedTeleport, final boolean timedTeleport,
@NotNull String... rtpArgs) { @NotNull String... rtpArgs) {
return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine() return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().world, rtpArgs) .getRandomPosition(user.getPosition().getWorld(), rtpArgs)
.map(position -> { .map(position -> {
final TeleportBuilder builder = Teleport.builder(plugin, user) final TeleportBuilder builder = Teleport.builder(plugin, user)
.setTarget(position); .setTarget(position);
@@ -125,7 +125,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
if (user == null) { if (user == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return args.length > 1 ? Collections.emptyList() : plugin.getCache().homes return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes()
.getOrDefault(user.uuid, new ArrayList<>()) .getOrDefault(user.uuid, new ArrayList<>())
.stream() .stream()
.filter(s -> s.startsWith(args.length == 1 ? args[0] : "")) .filter(s -> s.startsWith(args.length == 1 ? args[0] : ""))
@@ -73,7 +73,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length > 1 ? Collections.emptyList() : plugin.getCache().warps return args.length > 1 ? Collections.emptyList() : plugin.getCache().getWarps()
.stream() .stream()
.filter(s -> s.startsWith(args.length == 1 ? args[0] : "")) .filter(s -> s.startsWith(args.length == 1 ? args[0] : ""))
.sorted() .sorted()
@@ -85,7 +85,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
private void editHome(@NotNull Home home, @NotNull OnlineUser editor, private void editHome(@NotNull Home home, @NotNull OnlineUser editor,
@Nullable String editOperation, @Nullable String editArgs) { @Nullable String editOperation, @Nullable String editArgs) {
final AtomicBoolean showMenuFlag = new AtomicBoolean(false); final AtomicBoolean showMenuFlag = new AtomicBoolean(false);
final boolean otherOwner = !editor.equals(home.owner); final boolean otherOwner = !editor.equals(home.getOwner());
if (editOperation == null) { if (editOperation == null) {
getHomeEditorWindow(home, true, otherOwner, getHomeEditorWindow(home, true, otherOwner,
@@ -114,17 +114,17 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return; return;
} }
final String oldHomeName = home.meta.name; final String oldHomeName = home.getMeta().getName();
final String newHomeName = editArgs; final String newHomeName = editArgs;
plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.meta.description)) plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.getMeta().getDescription()))
.thenAccept(renameResult -> (switch (renameResult.resultType()) { .thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS -> { case SUCCESS -> {
if (home.owner.equals(editor)) { if (home.getOwner().equals(editor)) {
yield plugin.getLocales().getLocale("edit_home_update_name", yield plugin.getLocales().getLocale("edit_home_update_name",
oldHomeName, newHomeName); oldHomeName, newHomeName);
} else { } else {
yield plugin.getLocales().getLocale("edit_home_update_name_other", yield plugin.getLocales().getLocale("edit_home_update_name_other",
home.owner.username, oldHomeName, newHomeName); home.getOwner().username, oldHomeName, newHomeName);
} }
} }
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken"); case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
@@ -134,23 +134,23 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "description" -> { case "description" -> {
final String oldHomeDescription = home.meta.description; final String oldHomeDescription = home.getMeta().getDescription();
final String newDescription = editArgs != null ? editArgs : ""; final String newDescription = editArgs != null ? editArgs : "";
plugin.getManager().updateHomeMeta(home, new PositionMeta(home.meta.name, newDescription)) plugin.getManager().updateHomeMeta(home, new PositionMeta(home.getMeta().getName(), newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) { .thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> { case SUCCESS -> {
if (home.owner.equals(editor)) { if (home.getOwner().equals(editor)) {
yield plugin.getLocales().getLocale("edit_home_update_description", yield plugin.getLocales().getLocale("edit_home_update_description",
home.meta.name, home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales() oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription, .getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
newDescription.isBlank() ? plugin.getLocales() newDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : newDescription); .getRawLocale("item_no_description").orElse("N/A") : newDescription);
} else { } else {
yield plugin.getLocales().getLocale("edit_home_update_description_other", yield plugin.getLocales().getLocale("edit_home_update_description_other",
home.owner.username, home.getOwner().username,
home.meta.name, home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales() oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription, .getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
newDescription.isBlank() ? plugin.getLocales() newDescription.isBlank() ? plugin.getLocales()
@@ -166,12 +166,12 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
} }
case "relocate" -> case "relocate" ->
plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> {
if (home.owner.equals(editor)) { if (home.getOwner().equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location",
home.meta.name).orElse(new MineDown(""))); home.getMeta().getName()).orElse(new MineDown("")));
} else { } else {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other", editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other",
home.owner.username, home.meta.name).orElse(new MineDown(""))); home.getOwner().username, home.getMeta().getName()).orElse(new MineDown("")));
} }
// Show the menu if the menu flag is set // Show the menu if the menu flag is set
@@ -188,7 +188,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
.ifPresent(editor::sendMessage); .ifPresent(editor::sendMessage);
return; return;
} }
final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic); final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic());
if (editArgs != null && !editArgs.isBlank()) { if (editArgs != null && !editArgs.isBlank()) {
if (editArgs.equalsIgnoreCase("private")) { if (editArgs.equalsIgnoreCase("private")) {
newIsPublic.set(false); newIsPublic.set(false);
@@ -202,7 +202,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
} }
} }
final String privacyKeyedString = newIsPublic.get() ? "public" : "private"; final String privacyKeyedString = newIsPublic.get() ? "public" : "private";
if (newIsPublic.get() == home.isPublic) { if (newIsPublic.get() == home.isPublic()) {
plugin.getLocales().getLocale( plugin.getLocales().getLocale(
"error_edit_home_privacy_already_" + privacyKeyedString) "error_edit_home_privacy_already_" + privacyKeyedString)
.ifPresent(editor::sendMessage); .ifPresent(editor::sendMessage);
@@ -233,14 +233,14 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
// Execute the update // Execute the update
plugin.getManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> { plugin.getManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> {
if (home.owner.equals(editor)) { if (home.getOwner().equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale( editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success", "edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown(""))); home.getMeta().getName()).orElse(new MineDown("")));
} else { } else {
editor.sendMessage(plugin.getLocales().getLocale( editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other", "edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown(""))); home.getOwner().username, home.getMeta().getName()).orElse(new MineDown("")));
} }
// Perform necessary economy transaction // Perform necessary economy transaction
@@ -290,43 +290,43 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return new ArrayList<>() {{ return new ArrayList<>() {{
if (showTitle) { if (showTitle) {
if (!otherViewer) { if (!otherViewer) {
plugin.getLocales().getLocale("edit_home_menu_title", home.meta.name) plugin.getLocales().getLocale("edit_home_menu_title", home.getMeta().getName())
.ifPresent(this::add); .ifPresent(this::add);
} else { } else {
plugin.getLocales().getLocale("edit_home_menu_title_other", home.owner.username, home.meta.name) plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().username, home.getMeta().getName())
.ifPresent(this::add); .ifPresent(this::add);
} }
} }
plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic ? "private" : "public"), plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic() ? "private" : "public"),
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm") DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(home.meta.creationTime.atZone(ZoneId.systemDefault())), .format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
home.uuid.toString().split(Pattern.quote("-"))[0], home.getUuid().toString().split(Pattern.quote("-"))[0],
home.uuid.toString()) home.getUuid().toString())
.ifPresent(this::add); .ifPresent(this::add);
if (home.meta.description.length() > 0) { if (home.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_home_menu_description", plugin.getLocales().getLocale("edit_home_menu_description",
home.meta.description.length() > 50 home.getMeta().getDescription().length() > 50
? home.meta.description.substring(0, 49).trim() + "…" : home.meta.description, ? home.getMeta().getDescription().substring(0, 49).trim() + "…" : home.getMeta().getDescription(),
plugin.getLocales().formatDescription(home.meta.description)) plugin.getLocales().formatDescription(home.getMeta().getDescription()))
.ifPresent(this::add); .ifPresent(this::add);
} }
if (!plugin.getSettings().isCrossServer()) { if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.world.name) plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(this::add); .ifPresent(this::add);
} else { } else {
plugin.getLocales().getLocale("edit_home_menu_world_server", home.world.name, home.server.name) plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer().getName())
.ifPresent(this::add); .ifPresent(this::add);
} }
plugin.getLocales().getLocale("edit_home_menu_coordinates", plugin.getLocales().getLocale("edit_home_menu_coordinates",
String.format("%.1f", home.x), String.format("%.1f", home.y), String.format("%.1f", home.z), String.format("%.1f", home.getX()), String.format("%.1f", home.getY()), String.format("%.1f", home.getZ()),
String.format("%.2f", home.yaw), String.format("%.2f", home.pitch)) String.format("%.2f", home.getYaw()), String.format("%.2f", home.getPitch()))
.ifPresent(this::add); .ifPresent(this::add);
final String formattedName = home.owner.username + "." + home.meta.name; final String formattedName = home.getOwner().username + "." + home.getMeta().getName();
if (showTeleportButton) { if (showTeleportButton) {
plugin.getLocales().getLocale("edit_home_menu_use_buttons", plugin.getLocales().getLocale("edit_home_menu_use_buttons",
formattedName) formattedName)
@@ -336,7 +336,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", escapedName, plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", escapedName,
showPrivacyToggleButton ? plugin.getLocales() showPrivacyToggleButton ? plugin.getLocales()
.getRawLocale("edit_home_menu_privacy_button_" .getRawLocale("edit_home_menu_privacy_button_"
+ (home.isPublic ? "private" : "public"), escapedName) + (home.isPublic() ? "private" : "public"), escapedName)
.orElse("") : "") .orElse("") : "")
.map(MineDown::new).ifPresent(this::add); .map(MineDown::new).ifPresent(this::add);
plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons",
@@ -351,7 +351,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return Collections.emptyList(); return Collections.emptyList();
} }
return switch (args.length) { return switch (args.length) {
case 0, 1 -> plugin.getCache().homes.getOrDefault(user.uuid, new ArrayList<>()) case 0, 1 -> plugin.getCache().getHomes().getOrDefault(user.uuid, new ArrayList<>())
.stream() .stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted() .sorted()
@@ -83,9 +83,9 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
return; return;
} }
final String oldWarpName = warp.meta.name; final String oldWarpName = warp.getMeta().getName();
final String newWarpName = editArgs; final String newWarpName = editArgs;
plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.meta.description)) plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.getMeta().getDescription()))
.thenAccept(renameResult -> (switch (renameResult.resultType()) { .thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS -> case SUCCESS ->
plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName); plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName);
@@ -96,13 +96,13 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "description" -> { case "description" -> {
final String oldWarpDescription = warp.meta.description; final String oldWarpDescription = warp.getMeta().getDescription();
final String newDescription = editArgs != null ? editArgs : ""; final String newDescription = editArgs != null ? editArgs : "";
plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.meta.name, newDescription)) plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.getMeta().getName(), newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) { .thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description", case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description",
warp.meta.name, warp.getMeta().getName(),
oldWarpDescription.isBlank() ? plugin.getLocales() oldWarpDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldWarpDescription, .getRawLocale("item_no_description").orElse("N/A") : oldWarpDescription,
newDescription.isBlank() ? plugin.getLocales() newDescription.isBlank() ? plugin.getLocales()
@@ -117,7 +117,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
case "relocate" -> case "relocate" ->
plugin.getManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> { plugin.getManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> {
editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location", editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location",
warp.meta.name).orElse(new MineDown(""))); warp.getMeta().getName()).orElse(new MineDown("")));
// Show the menu if the menu flag is set // Show the menu if the menu flag is set
if (showMenuFlag.get()) { if (showMenuFlag.get()) {
@@ -156,43 +156,43 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
final boolean showTeleportButton) { final boolean showTeleportButton) {
return new ArrayList<>() {{ return new ArrayList<>() {{
if (showTitle) { if (showTitle) {
plugin.getLocales().getLocale("edit_warp_menu_title", warp.meta.name) plugin.getLocales().getLocale("edit_warp_menu_title", warp.getMeta().getName())
.ifPresent(this::add); .ifPresent(this::add);
} }
plugin.getLocales().getLocale("edit_warp_menu_metadata", plugin.getLocales().getLocale("edit_warp_menu_metadata",
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm") DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(warp.meta.creationTime.atZone(ZoneId.systemDefault())), .format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
warp.uuid.toString().split(Pattern.quote("-"))[0], warp.getUuid().toString().split(Pattern.quote("-"))[0],
warp.uuid.toString()) warp.getUuid().toString())
.ifPresent(this::add); .ifPresent(this::add);
if (warp.meta.description.length() > 0) { if (warp.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_warp_menu_description", plugin.getLocales().getLocale("edit_warp_menu_description",
warp.meta.description.length() > 50 warp.getMeta().getDescription().length() > 50
? warp.meta.description.substring(0, 49).trim() + "…" : warp.meta.description, ? warp.getMeta().getDescription().substring(0, 49).trim() + "…" : warp.getMeta().getDescription(),
plugin.getLocales().formatDescription(warp.meta.description)) plugin.getLocales().formatDescription(warp.getMeta().getDescription()))
.ifPresent(this::add); .ifPresent(this::add);
} }
if (!plugin.getSettings().isCrossServer()) { if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world", warp.world.name).ifPresent(this::add); plugin.getLocales().getLocale("edit_warp_menu_world", warp.getWorld().getName()).ifPresent(this::add);
} else { } else {
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.world.name, warp.server.name).ifPresent(this::add); plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer().getName()).ifPresent(this::add);
} }
plugin.getLocales().getLocale("edit_warp_menu_coordinates", plugin.getLocales().getLocale("edit_warp_menu_coordinates",
String.format("%.1f", warp.x), String.format("%.1f", warp.y), String.format("%.1f", warp.z), String.format("%.1f", warp.getX()), String.format("%.1f", warp.getY()), String.format("%.1f", warp.getZ()),
String.format("%.2f", warp.yaw), String.format("%.2f", warp.pitch)) String.format("%.2f", warp.getYaw()), String.format("%.2f", warp.getPitch()))
.ifPresent(this::add); .ifPresent(this::add);
if (showTeleportButton) { if (showTeleportButton) {
plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.meta.name) plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getMeta().getName())
.ifPresent(this::add); .ifPresent(this::add);
} }
plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.meta.name) plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getMeta().getName())
.ifPresent(this::add); .ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.meta.name) plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getMeta().getName())
.ifPresent(this::add); .ifPresent(this::add);
}}; }};
} }
@@ -200,7 +200,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return switch (args.length) { return switch (args.length) {
case 0, 1 -> plugin.getCache().warps case 0, 1 -> plugin.getCache().getWarps()
.stream() .stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted() .sorted()
@@ -111,7 +111,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
} }
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.owner.username + "." + home.meta.name); + home.getOwner().username + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport) Teleport.builder(plugin, playerToTeleport)
.setTarget(home) .setTarget(home)
.toTeleport() .toTeleport()
@@ -124,7 +124,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
if (user == null) { if (user == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return args.length > 1 ? Collections.emptyList() : plugin.getCache().homes return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes()
.getOrDefault(user.uuid, new ArrayList<>()) .getOrDefault(user.uuid, new ArrayList<>())
.stream() .stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
@@ -53,8 +53,8 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
* @param pageNumber page number to display * @param pageNumber page number to display
*/ */
private void showHomeList(@NotNull OnlineUser onlineUser, @NotNull String homeOwner, int pageNumber) { private void showHomeList(@NotNull OnlineUser onlineUser, @NotNull String homeOwner, int pageNumber) {
if (plugin.getCache().privateHomeLists.containsKey(homeOwner)) { if (plugin.getCache().getPrivateHomeLists().containsKey(homeOwner)) {
onlineUser.sendMessage(plugin.getCache().privateHomeLists.get(homeOwner).getNearestValidPage(pageNumber)); onlineUser.sendMessage(plugin.getCache().getPrivateHomeLists().get(homeOwner).getNearestValidPage(pageNumber));
return; return;
} }
plugin.getDatabase().getUserDataByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(userData -> { plugin.getDatabase().getUserDataByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(userData -> {
@@ -101,7 +101,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().username + "'s " plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().username + "'s "
+ homes.size() + " homes:"); + homes.size() + " homes:");
for (int i = 0; i < homes.size(); i++) { for (int i = 0; i < homes.size(); i++) {
final String home = homes.get(i).meta.name; final String home = homes.get(i).getMeta().getName();
rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home); rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home);
if ((i + 1) % 3 == 0) { if ((i + 1) % 3 == 0) {
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString());
@@ -125,7 +125,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
} }
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.owner.username + "." + home.meta.name); + home.getOwner().username + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport) Teleport.builder(plugin, playerToTeleport)
.setTarget(home) .setTarget(home)
.toTeleport() .toTeleport()
@@ -137,7 +137,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
// Return every public home name as username.home_name from the cache // Return every public home name as username.home_name from the cache
final List<String> publicHomes = new ArrayList<>(); final List<String> publicHomes = new ArrayList<>();
plugin.getCache().publicHomes.forEach((ownerName, homeNames) -> plugin.getCache().getPublicHomes().forEach((ownerName, homeNames) ->
homeNames.forEach(homeName -> publicHomes.add(ownerName + "." + homeName))); homeNames.forEach(homeName -> publicHomes.add(ownerName + "." + homeName)));
return args.length > 1 ? Collections.emptyList() : publicHomes return args.length > 1 ? Collections.emptyList() : publicHomes
.stream() .stream()
@@ -42,8 +42,8 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
* @param pageNumber page number to display * @param pageNumber page number to display
*/ */
private void showPublicHomeList(@NotNull OnlineUser onlineUser, int pageNumber) { private void showPublicHomeList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().publicHomeLists.containsKey(onlineUser.uuid)) { if (plugin.getCache().getPublicHomeLists().containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().publicHomeLists.get(onlineUser.uuid).getNearestValidPage(pageNumber)); onlineUser.sendMessage(plugin.getCache().getPublicHomeLists().get(onlineUser.uuid).getNearestValidPage(pageNumber));
return; return;
} }
@@ -68,8 +68,8 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
plugin.getLoggingAdapter().log(Level.INFO, "List of " + homes.size() + " public homes:"); plugin.getLoggingAdapter().log(Level.INFO, "List of " + homes.size() + " public homes:");
for (int i = 0; i < homes.size(); i++) { for (int i = 0; i < homes.size(); i++) {
final String ownerUsername = homes.get(i).owner.username; final String ownerUsername = homes.get(i).getOwner().username;
final String homeName = homes.get(i).meta.name; final String homeName = homes.get(i).getMeta().getName();
final String home = ownerUsername + "." + homeName; final String home = ownerUsername + "." + homeName;
int spacingSize = (16 - ownerUsername.length()) + 17; int spacingSize = (16 - ownerUsername.length()) + 17;
rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home); rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home);
@@ -42,7 +42,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
final Position userPosition = target.getPosition(); final Position userPosition = target.getPosition();
final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args; final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args;
if (plugin.getSettings().getRtpRestrictedWorlds().stream() if (plugin.getSettings().getRtpRestrictedWorlds().stream()
.anyMatch(worldName -> worldName.equals(userPosition.world.name))) { .anyMatch(worldName -> worldName.equals(userPosition.getWorld().getName()))) {
plugin.getLocales().getLocale("error_rtp_restricted_world") plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
return; return;
@@ -73,7 +73,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
plugin.getLocales().getLocale("teleporting_random_generation") plugin.getLocales().getLocale("teleporting_random_generation")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
final Optional<Position> position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments); final Optional<Position> position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().getWorld(), rtpArguments);
if (position.isEmpty()) { if (position.isEmpty()) {
plugin.getLocales().getLocale("error_rtp_randomization_timeout") plugin.getLocales().getLocale("error_rtp_randomization_timeout")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
@@ -111,7 +111,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
} }
plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().username + "..."); plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().username + "...");
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().world, ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> { plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().getWorld(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
if (position.isEmpty()) { if (position.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!"); plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!");
return; return;
@@ -40,14 +40,14 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// Find the online user to teleport // Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenRun(() -> { plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenRun(() -> {
// Get the list of potential teleports, filtered against vanished players, but ensuring the executor is in the list // Get the list of potential teleports, filtered against vanished players, but ensuring the executor is in the list
final Set<String> players = plugin.getCache().players; final Set<String> players = plugin.getCache().getPlayers();
players.add(onlineUser.username); players.add(onlineUser.username);
// Find the player to teleport // Find the player to teleport
final String playerToTeleport = players.stream() final String playerToTeleport = players.stream()
.filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst() .filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst()
.or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.username : null)) .or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.username : null))
.or(() -> plugin.getCache().players.stream().filter(user -> user.toLowerCase().startsWith(targetPlayerToTeleport)).findFirst()) .or(() -> plugin.getCache().getPlayers().stream().filter(user -> user.toLowerCase().startsWith(targetPlayerToTeleport)).findFirst())
.orElse(null); .orElse(null);
// Ensure the player to teleport exists // Ensure the player to teleport exists
@@ -104,9 +104,9 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
result.getTeleporter() result.getTeleporter()
.flatMap(teleporter -> plugin.getLocales() .flatMap(teleporter -> plugin.getLocales()
.getLocale("teleporting_other_complete_position", teleporter.username, .getLocale("teleporting_other_complete_position", teleporter.username,
Integer.toString((int) destination.x), Integer.toString((int) destination.getX()),
Integer.toString((int) destination.y), Integer.toString((int) destination.getY()),
Integer.toString((int) destination.z))) Integer.toString((int) destination.getZ())))
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
})); }));
} }
@@ -211,11 +211,11 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
final ArrayList<String> completions = new ArrayList<>(); final ArrayList<String> completions = new ArrayList<>();
completions.addAll(serveCoordinateCompletions completions.addAll(serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~", ? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) user.getPosition().x), Integer.toString((int) user.getPosition().getX()),
((int) user.getPosition().x + " " + (int) user.getPosition().y), ((int) user.getPosition().getX() + " " + (int) user.getPosition().getY()),
((int) user.getPosition().x + " " + (int) user.getPosition().y + " " + (int) user.getPosition().z)) ((int) user.getPosition().getX() + " " + (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()))
: Collections.emptyList()); : Collections.emptyList());
completions.addAll(plugin.getCache().players); completions.addAll(plugin.getCache().getPlayers());
return completions.stream() return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()); .sorted().collect(Collectors.toList());
@@ -226,16 +226,16 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (user == null) { if (user == null) {
return completions; return completions;
} }
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().y))); completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getY())));
completions.addAll(List.of("~ ~", (int) user.getPosition().y + " " + (int) user.getPosition().z)); completions.addAll(List.of("~ ~", (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()));
} else { } else {
completions.addAll(serveCoordinateCompletions completions.addAll(serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~", ? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) user.getPosition().x), Integer.toString((int) user.getPosition().getX()),
((int) user.getPosition().x + " " + (int) user.getPosition().y), ((int) user.getPosition().getX() + " " + (int) user.getPosition().getY()),
((int) user.getPosition().x + " " + (int) user.getPosition().y + " " + (int) user.getPosition().z)) ((int) user.getPosition().getX() + " " + (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()))
: Collections.emptyList()); : Collections.emptyList());
completions.addAll(plugin.getCache().players); completions.addAll(plugin.getCache().getPlayers());
} }
return completions.stream() return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase())) .filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase()))
@@ -247,13 +247,13 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (!serveCoordinateCompletions) { if (!serveCoordinateCompletions) {
return completions; return completions;
} }
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().z))); completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getZ())));
} else if (isCoordinate(args[1])) { } else if (isCoordinate(args[1])) {
if (!serveCoordinateCompletions) { if (!serveCoordinateCompletions) {
return completions; return completions;
} }
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().y))); completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getY())));
completions.addAll(List.of("~ ~", (int) user.getPosition().y + " " + (int) user.getPosition().z)); completions.addAll(List.of("~ ~", (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()));
} }
return completions.stream() return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase())) .filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase()))
@@ -265,7 +265,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (!serveCoordinateCompletions) { if (!serveCoordinateCompletions) {
return completions; return completions;
} }
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().z))); completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getZ())));
} }
return completions.stream() return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase())) .filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase()))
@@ -53,7 +53,7 @@ public class TpHereCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream() return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList(); .sorted().collect(Collectors.toList()) : Collections.emptyList();
} }
@@ -54,7 +54,7 @@ public class TpOfflineCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream() return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList(); .sorted().collect(Collectors.toList()) : Collections.emptyList();
} }
@@ -42,7 +42,7 @@ public class TpRespondCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream() return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList(); .sorted().collect(Collectors.toList()) : Collections.emptyList();
} }
@@ -33,7 +33,7 @@ public class TpaAllCommand extends CommandBase {
// Determine players to teleport and teleport them // Determine players to teleport and teleport them
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenAccept(playerList -> { plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenAccept(playerList -> {
final List<String> players = plugin.getCache().players.stream() final List<String> players = plugin.getCache().getPlayers().stream()
.filter(userName -> !userName.equalsIgnoreCase(onlineUser.username)).toList(); .filter(userName -> !userName.equalsIgnoreCase(onlineUser.username)).toList();
if (players.isEmpty()) { if (players.isEmpty()) {
plugin.getLocales().getLocale("error_no_players_online").ifPresent(onlineUser::sendMessage); plugin.getLocales().getLocale("error_no_players_online").ifPresent(onlineUser::sendMessage);
@@ -52,7 +52,7 @@ public class TpaCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream() return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList(); .sorted().collect(Collectors.toList()) : Collections.emptyList();
} }
@@ -52,7 +52,7 @@ public class TpaHereCommand extends CommandBase implements TabCompletable {
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream() return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList(); .sorted().collect(Collectors.toList()) : Collections.emptyList();
} }
@@ -63,7 +63,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return plugin.getCache().warps.stream() return plugin.getCache().getWarps().stream()
.filter(s -> user == null || Warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), user, s)) .filter(s -> user == null || Warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), user, s))
.filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : ""))
.sorted() .sorted()
@@ -89,7 +89,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
} }
final Warp warp = optionalWarp.get(); final Warp warp = optionalWarp.get();
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.meta.name); plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.getMeta().getName());
Teleport.builder(plugin, playerToTeleport) Teleport.builder(plugin, playerToTeleport)
.setTarget(warp) .setTarget(warp)
.toTimedTeleport() .toTimedTeleport()
@@ -40,8 +40,8 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
* @param pageNumber page number to display * @param pageNumber page number to display
*/ */
private void showWarpList(@NotNull OnlineUser onlineUser, int pageNumber) { private void showWarpList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().warpLists.containsKey(onlineUser.uuid)) { if (plugin.getCache().getWarpLists().containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().warpLists.get(onlineUser.uuid).getNearestValidPage(pageNumber)); onlineUser.sendMessage(plugin.getCache().getWarpLists().get(onlineUser.uuid).getNearestValidPage(pageNumber));
return; return;
} }
@@ -51,13 +51,13 @@ public class CachedSpawn {
* @param location The {@link Location} of the spawn * @param location The {@link Location} of the spawn
*/ */
public CachedSpawn(@NotNull Location location) { public CachedSpawn(@NotNull Location location) {
this.x = location.x; this.x = location.getX();
this.y = location.y; this.y = location.getY();
this.z = location.z; this.z = location.getZ();
this.yaw = location.yaw; this.yaw = location.getYaw();
this.pitch = location.pitch; this.pitch = location.getPitch();
this.worldName = location.world.name; this.worldName = location.getWorld().getName();
this.worldUuid = location.world.uuid.toString(); this.worldUuid = location.getWorld().getUuid().toString();
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@@ -268,11 +268,11 @@ public abstract class Database {
try { try {
final Server server = plugin.getServerName(); final Server server = plugin.getServerName();
return getWarps().stream() return getWarps().stream()
.filter(warp -> warp.server.equals(server)) .filter(warp -> warp.getServer().equals(server))
.collect(Collectors.toList()); .collect(Collectors.toList());
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
return getWarps().stream() return getWarps().stream()
.filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.world))) .filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.getWorld())))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }
@@ -295,11 +295,11 @@ public abstract class Database {
try { try {
final Server server = plugin.getServerName(); final Server server = plugin.getServerName();
return getPublicHomes().stream() return getPublicHomes().stream()
.filter(home -> home.server.equals(server)) .filter(home -> home.getServer().equals(server))
.collect(Collectors.toList()); .collect(Collectors.toList());
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
return plugin.getDatabase().getPublicHomes().stream() return plugin.getDatabase().getPublicHomes().stream()
.filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.world))) .filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.getWorld())))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }
@@ -145,14 +145,14 @@ public class MySqlDatabase extends Database {
VALUES (?,?,?,?,?,?,?,?);"""), VALUES (?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.x); statement.setDouble(1, position.getX());
statement.setDouble(2, position.y); statement.setDouble(2, position.getY());
statement.setDouble(3, position.z); statement.setDouble(3, position.getZ());
statement.setFloat(4, position.yaw); statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.pitch); statement.setFloat(5, position.getPitch());
statement.setString(6, position.world.name); statement.setString(6, position.getWorld().getName());
statement.setString(7, position.world.uuid.toString()); statement.setString(7, position.getWorld().getUuid().toString());
statement.setString(8, position.server.name); statement.setString(8, position.getServer().getName());
statement.executeUpdate(); statement.executeUpdate();
final ResultSet resultSet = statement.getGeneratedKeys(); final ResultSet resultSet = statement.getGeneratedKeys();
@@ -176,14 +176,14 @@ public class MySqlDatabase extends Database {
`world_name`=?, `world_name`=?,
`server_name`=? `server_name`=?
WHERE `id`=?"""))) { WHERE `id`=?"""))) {
statement.setDouble(1, position.x); statement.setDouble(1, position.getX());
statement.setDouble(2, position.y); statement.setDouble(2, position.getY());
statement.setDouble(3, position.z); statement.setDouble(3, position.getZ());
statement.setFloat(4, position.yaw); statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.pitch); statement.setFloat(5, position.getPitch());
statement.setString(6, position.world.uuid.toString()); statement.setString(6, position.getWorld().getUuid().toString());
statement.setString(7, position.world.name); statement.setString(7, position.getWorld().getName());
statement.setString(8, position.server.name); statement.setString(8, position.getServer().getName());
statement.setDouble(9, positionId); statement.setDouble(9, positionId);
statement.executeUpdate(); statement.executeUpdate();
} }
@@ -197,10 +197,10 @@ public class MySqlDatabase extends Database {
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection)); statement.setInt(1, setPosition(position, connection));
statement.setString(2, position.meta.name); statement.setString(2, position.getMeta().getName());
statement.setString(3, position.meta.description); statement.setString(3, position.getMeta().getDescription());
statement.setString(4, position.meta.getSerializedTags()); statement.setString(4, position.getMeta().getSerializedTags());
statement.setTimestamp(5, Timestamp.from(position.meta.creationTime)); statement.setTimestamp(5, Timestamp.from(position.getMeta().getCreationTime()));
statement.executeUpdate(); statement.executeUpdate();
final ResultSet resultSet = statement.getGeneratedKeys(); final ResultSet resultSet = statement.getGeneratedKeys();
@@ -230,9 +230,9 @@ public class MySqlDatabase extends Database {
`description`=?, `description`=?,
`tags`=? `tags`=?
WHERE `id`=?;"""))) { WHERE `id`=?;"""))) {
updateStatement.setString(1, position.meta.name); updateStatement.setString(1, position.getMeta().getName());
updateStatement.setString(2, position.meta.description); updateStatement.setString(2, position.getMeta().getDescription());
updateStatement.setString(3, position.meta.getSerializedTags()); updateStatement.setString(3, position.getMeta().getSerializedTags());
updateStatement.setInt(4, savedPositionId); updateStatement.setInt(4, savedPositionId);
updateStatement.executeUpdate(); updateStatement.executeUpdate();
} }
@@ -866,13 +866,13 @@ public class MySqlDatabase extends Database {
@Override @Override
public void saveHome(@NotNull Home home) { public void saveHome(@NotNull Home home) {
getHome(home.uuid).ifPresentOrElse(presentHome -> { getHome(home.getUuid()).ifPresentOrElse(presentHome -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
// Update the home's saved position, including metadata // Update the home's saved position, including metadata
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%homes_table%` SELECT `saved_position_id` FROM `%homes_table%`
WHERE `uuid`=?;"""))) { WHERE `uuid`=?;"""))) {
statement.setString(1, home.uuid.toString()); statement.setString(1, home.getUuid().toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@@ -885,41 +885,41 @@ public class MySqlDatabase extends Database {
UPDATE `%homes_table%` UPDATE `%homes_table%`
SET `public`=? SET `public`=?
WHERE `uuid`=?;"""))) { WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic); statement.setBoolean(1, home.isPublic());
statement.setString(2, home.uuid.toString()); statement.setString(2, home.getUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.owner.username, e); "Failed to update a home in the database for " + home.getOwner().username, e);
} }
}, () -> { }, () -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) { VALUES (?,?,?,?);"""))) {
statement.setString(1, home.uuid.toString()); statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection)); statement.setInt(2, setSavedPosition(home, connection));
statement.setString(3, home.owner.uuid.toString()); statement.setString(3, home.getOwner().uuid.toString());
statement.setBoolean(4, home.isPublic); statement.setBoolean(4, home.isPublic());
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e); "Failed to set a home to the database for " + home.getOwner().username, e);
} }
}); });
} }
@Override @Override
public void saveWarp(@NotNull Warp warp) { public void saveWarp(@NotNull Warp warp) {
getWarp(warp.uuid).ifPresentOrElse(presentWarp -> { getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%` SELECT `saved_position_id` FROM `%warps_table%`
WHERE `uuid`=?;"""))) { WHERE `uuid`=?;"""))) {
statement.setString(1, warp.uuid.toString()); statement.setString(1, warp.getUuid().toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@@ -934,7 +934,7 @@ public class MySqlDatabase extends Database {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) { VALUES (?,?);"""))) {
statement.setString(1, warp.uuid.toString()); statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection)); statement.setInt(2, setSavedPosition(warp, connection));
statement.executeUpdate(); statement.executeUpdate();
@@ -137,14 +137,14 @@ public class SqLiteDatabase extends Database {
VALUES (?,?,?,?,?,?,?,?);"""), VALUES (?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.x); statement.setDouble(1, position.getX());
statement.setDouble(2, position.y); statement.setDouble(2, position.getY());
statement.setDouble(3, position.z); statement.setDouble(3, position.getZ());
statement.setFloat(4, position.yaw); statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.pitch); statement.setFloat(5, position.getPitch());
statement.setString(6, position.world.name); statement.setString(6, position.getWorld().getName());
statement.setString(7, position.world.uuid.toString()); statement.setString(7, position.getWorld().getUuid().toString());
statement.setString(8, position.server.name); statement.setString(8, position.getServer().getName());
statement.executeUpdate(); statement.executeUpdate();
// Return the ID of the newly inserted row // Return the ID of the newly inserted row
@@ -170,14 +170,14 @@ public class SqLiteDatabase extends Database {
`world_name`=?, `world_name`=?,
`server_name`=? `server_name`=?
WHERE `id`=?"""))) { WHERE `id`=?"""))) {
statement.setDouble(1, position.x); statement.setDouble(1, position.getX());
statement.setDouble(2, position.y); statement.setDouble(2, position.getY());
statement.setDouble(3, position.z); statement.setDouble(3, position.getZ());
statement.setFloat(4, position.yaw); statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.pitch); statement.setFloat(5, position.getPitch());
statement.setString(6, position.world.uuid.toString()); statement.setString(6, position.getWorld().getUuid().toString());
statement.setString(7, position.world.name); statement.setString(7, position.getWorld().getName());
statement.setString(8, position.server.name); statement.setString(8, position.getServer().getName());
statement.setDouble(9, positionId); statement.setDouble(9, positionId);
statement.executeUpdate(); statement.executeUpdate();
} }
@@ -191,10 +191,10 @@ public class SqLiteDatabase extends Database {
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection)); statement.setInt(1, setPosition(position, connection));
statement.setString(2, position.meta.name); statement.setString(2, position.getMeta().getName());
statement.setString(3, position.meta.description); statement.setString(3, position.getMeta().getDescription());
statement.setString(4, position.meta.getSerializedTags()); statement.setString(4, position.getMeta().getSerializedTags());
statement.setTimestamp(5, Timestamp.from(position.meta.creationTime)); statement.setTimestamp(5, Timestamp.from(position.getMeta().getCreationTime()));
statement.executeUpdate(); statement.executeUpdate();
// Return the ID of the newly inserted row // Return the ID of the newly inserted row
@@ -226,9 +226,9 @@ public class SqLiteDatabase extends Database {
`description`=?, `description`=?,
`tags`=? `tags`=?
WHERE `id`=?;"""))) { WHERE `id`=?;"""))) {
updateStatement.setString(1, position.meta.name); updateStatement.setString(1, position.getMeta().getName());
updateStatement.setString(2, position.meta.description); updateStatement.setString(2, position.getMeta().getDescription());
updateStatement.setString(3, position.meta.getSerializedTags()); updateStatement.setString(3, position.getMeta().getSerializedTags());
updateStatement.setInt(4, savedPositionId); updateStatement.setInt(4, savedPositionId);
updateStatement.executeUpdate(); updateStatement.executeUpdate();
} }
@@ -855,13 +855,13 @@ public class SqLiteDatabase extends Database {
@Override @Override
public void saveHome(@NotNull Home home) { public void saveHome(@NotNull Home home) {
getHome(home.uuid).ifPresentOrElse(presentHome -> { getHome(home.getUuid()).ifPresentOrElse(presentHome -> {
try { try {
// Update the home's saved position, including metadata // Update the home's saved position, including metadata
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%homes_table%` SELECT `saved_position_id` FROM `%homes_table%`
WHERE `uuid`=?;"""))) { WHERE `uuid`=?;"""))) {
statement.setString(1, home.uuid.toString()); statement.setString(1, home.getUuid().toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@@ -874,41 +874,41 @@ public class SqLiteDatabase extends Database {
UPDATE `%homes_table%` UPDATE `%homes_table%`
SET `public`=? SET `public`=?
WHERE `uuid`=?;"""))) { WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic); statement.setBoolean(1, home.isPublic());
statement.setString(2, home.uuid.toString()); statement.setString(2, home.getUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.owner.username, e); "Failed to update a home in the database for " + home.getOwner().username, e);
} }
}, () -> { }, () -> {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) { VALUES (?,?,?,?);"""))) {
statement.setString(1, home.uuid.toString()); statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection)); statement.setInt(2, setSavedPosition(home, connection));
statement.setString(3, home.owner.uuid.toString()); statement.setString(3, home.getOwner().uuid.toString());
statement.setBoolean(4, home.isPublic); statement.setBoolean(4, home.isPublic());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
getLogger().log(Level.SEVERE, getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e); "Failed to set a home to the database for " + home.getOwner().username, e);
} }
}); });
} }
@Override @Override
public void saveWarp(@NotNull Warp warp) { public void saveWarp(@NotNull Warp warp) {
getWarp(warp.uuid) getWarp(warp.getUuid())
.ifPresentOrElse(presentWarp -> { .ifPresentOrElse(presentWarp -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%` SELECT `saved_position_id` FROM `%warps_table%`
WHERE `uuid`=?;"""))) { WHERE `uuid`=?;"""))) {
statement.setString(1, warp.uuid.toString()); statement.setString(1, warp.getUuid().toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@@ -922,7 +922,7 @@ public class SqLiteDatabase extends Database {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) { VALUES (?,?);"""))) {
statement.setString(1, warp.uuid.toString()); statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection)); statement.setInt(2, setSavedPosition(warp, connection));
statement.executeUpdate(); statement.executeUpdate();
@@ -35,9 +35,9 @@ public class BlueMapHook extends MapHook {
@Override @Override
protected CompletableFuture<Void> initializeMap() { protected CompletableFuture<Void> initializeMap() {
final CompletableFuture<Void> initializedFuture = new CompletableFuture<>(); final CompletableFuture<Void> initializedFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> BlueMapAPI.onEnable(blueMapAPI -> { plugin.runAsync(() -> BlueMapAPI.onEnable(blueMapAPI -> {
// Create marker sets // Create marker sets
plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.uuid) plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.getUuid())
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(map -> { .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(map -> {
if (plugin.getSettings().isPublicHomesOnMap()) { if (plugin.getSettings().isPublicHomesOnMap()) {
map.getMarkerSets().put(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, map.getMarkerSets().put(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID,
@@ -71,13 +71,13 @@ public class BlueMapHook extends MapHook {
if (!isValidPosition(home)) return CompletableFuture.completedFuture(null); if (!isValidPosition(home)) return CompletableFuture.completedFuture(null);
return removeHome(home).thenRun(() -> BlueMapAPI.getInstance().flatMap( return removeHome(home).thenRun(() -> BlueMapAPI.getInstance().flatMap(
blueMapAPI -> getBlueMapWorld(blueMapAPI, home.world)).ifPresent(blueMapWorld -> blueMapWorld.getMaps() blueMapAPI -> getBlueMapWorld(blueMapAPI, home.getWorld())).ifPresent(blueMapWorld -> blueMapWorld.getMaps()
.forEach(blueMapMap -> blueMapMap.getMarkerSets() .forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> { .computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().put(home.owner.uuid + ":" + home.uuid, markerSet.getMarkers().put(home.getOwner().uuid + ":" + home.getUuid(),
POIMarker.toBuilder() POIMarker.toBuilder()
.label("/phome" + home.owner.username + "." + home.meta.name) .label("/phome" + home.getOwner().username + "." + home.getMeta().getName())
.position((int) home.x, (int) home.y, (int) home.z) .position((int) home.getX(), (int) home.getY(), (int) home.getZ())
.icon(publicHomeMarkerIconPath, Vector2i.from(25, 25)) .icon(publicHomeMarkerIconPath, Vector2i.from(25, 25))
.maxDistance(5000) .maxDistance(5000)
.build()); .build());
@@ -89,10 +89,10 @@ public class BlueMapHook extends MapHook {
public CompletableFuture<Void> removeHome(@NotNull Home home) { public CompletableFuture<Void> removeHome(@NotNull Home home) {
if (!isValidPosition(home)) return CompletableFuture.completedFuture(null); if (!isValidPosition(home)) return CompletableFuture.completedFuture(null);
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, home.world)) BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, home.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets() .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> { .computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().remove(home.owner.uuid + ":" + home.uuid); markerSet.getMarkers().remove(home.getOwner().uuid + ":" + home.getUuid());
return markerSet; return markerSet;
}))); })));
return CompletableFuture.completedFuture(null); return CompletableFuture.completedFuture(null);
@@ -115,13 +115,13 @@ public class BlueMapHook extends MapHook {
public CompletableFuture<Void> updateWarp(@NotNull Warp warp) { public CompletableFuture<Void> updateWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null); if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null);
return removeWarp(warp).thenRun(() -> BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.world)) return removeWarp(warp).thenRun(() -> BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets() .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> { .computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().put(warp.uuid.toString(), markerSet.getMarkers().put(warp.getUuid().toString(),
POIMarker.toBuilder() POIMarker.toBuilder()
.label("/warp " + warp.meta.name) .label("/warp " + warp.getMeta().getName())
.position((int) warp.x, (int) warp.y, (int) warp.z) .position((int) warp.getX(), (int) warp.getY(), (int) warp.getZ())
.icon(warpMarkerIconPath, Vector2i.from(25, 25)) .icon(warpMarkerIconPath, Vector2i.from(25, 25))
.maxDistance(10000) .maxDistance(10000)
.build()); .build());
@@ -133,10 +133,10 @@ public class BlueMapHook extends MapHook {
public CompletableFuture<Void> removeWarp(@NotNull Warp warp) { public CompletableFuture<Void> removeWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null); if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null);
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.world)) BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets() .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> { .computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().remove(warp.uuid.toString()); markerSet.getMarkers().remove(warp.getUuid().toString());
return markerSet; return markerSet;
}))); })));
return CompletableFuture.completedFuture(null); return CompletableFuture.completedFuture(null);
@@ -163,10 +163,10 @@ public class BlueMapHook extends MapHook {
*/ */
@NotNull @NotNull
private Optional<BlueMapWorld> getBlueMapWorld(@NotNull BlueMapAPI blueMapAPI, @NotNull World world) { private Optional<BlueMapWorld> getBlueMapWorld(@NotNull BlueMapAPI blueMapAPI, @NotNull World world) {
if (world.uuid.equals(new UUID(0, 0))) { if (world.getUuid().equals(new UUID(0, 0))) {
return blueMapAPI.getWorld(world.name); return blueMapAPI.getWorld(world.getName());
} else { } else {
return blueMapAPI.getWorld(world.uuid); return blueMapAPI.getWorld(world.getUuid());
} }
} }
} }
@@ -5,6 +5,7 @@ import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition; import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -104,11 +105,11 @@ public abstract class MapHook extends PluginHook {
if (position instanceof Home && !plugin.getSettings().isPublicHomesOnMap()) return false; if (position instanceof Home && !plugin.getSettings().isPublicHomesOnMap()) return false;
try { try {
return position.server.equals(plugin.getServerName()); return position.getServer().equals(plugin.getServerName());
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
return plugin.getWorlds().stream() return plugin.getWorlds().stream()
.map(world -> world.uuid) .map(World::getUuid)
.anyMatch(uuid -> uuid.equals(position.world.uuid)); .anyMatch(uuid -> uuid.equals(position.getWorld().getUuid()));
} }
} }
@@ -78,7 +78,7 @@ public class PlanDataExtension implements DataExtension {
public long getPublicHomeCount(@NotNull UUID uuid) { public long getPublicHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid) return database.getUserData(uuid)
.map(userData -> database.getHomes(userData.user()) .map(userData -> database.getHomes(userData.user())
.stream().filter(home -> home.isPublic).count()) .stream().filter(home -> home.isPublic()).count())
.orElse(0L); .orElse(0L);
} }
@@ -121,9 +121,9 @@ public class PlanDataExtension implements DataExtension {
public String getOfflinePosition(@NotNull UUID uuid) { public String getOfflinePosition(@NotNull UUID uuid) {
return database.getUserData(uuid) return database.getUserData(uuid)
.map(userData -> database.getOfflinePosition(userData.user()) .map(userData -> database.getOfflinePosition(userData.user())
.map(position -> "x: " + (int) position.x + ", y: " + (int) position.y + ", z: " + (int) position.z .map(position -> "x: " + (int) position.getX() + ", y: " + (int) position.getY() + ", z: " + (int) position.getZ()
+ " (" + position.world.name + + " (" + position.getWorld().getName() +
((crossServer) ? "/" + position.server.name + ")" : ")")) ((crossServer) ? "/" + position.getServer().getName() + ")" : ")"))
.orElse(UNKNOWN_STRING)) .orElse(UNKNOWN_STRING))
.orElse(UNKNOWN_STRING); .orElse(UNKNOWN_STRING);
} }
@@ -3,6 +3,7 @@ package net.william278.huskhomes.listener;
import de.themoep.minedown.adventure.MineDown; import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType; import net.william278.huskhomes.teleport.TeleportType;
@@ -10,9 +11,7 @@ import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors;
/** /**
* A handler for when events take place * A handler for when events take place
@@ -32,77 +31,66 @@ public class EventListener {
* @param onlineUser the joining {@link OnlineUser} * @param onlineUser the joining {@link OnlineUser}
*/ */
protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) { protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) {
// Handle the first player joining the server plugin.runAsync(() -> {
plugin.getDatabase().ensureUser(onlineUser) // Ensure the user is in the database
// Handle cross-server checks plugin.getDatabase().ensureUser(onlineUser);
.thenRun(() -> handleInboundTeleport(onlineUser).thenRun(() -> {
// Update the cached player list
plugin.getCache().updatePlayerListCache(plugin, onlineUser);
}).thenRun(() -> {
// Get this user's tp-ignore state and set locally
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
if (userData.isPresent()) {
final boolean ignoringRequests = userData.get().ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
// Send a reminder message if they are still ignoring requests // Handle any inbound teleports
if (ignoringRequests) { if (plugin.getSettings().isCrossServer()) {
plugin.getLocales().getRawLocale("tpignore_on_notification", this.handleInboundTeleport(onlineUser);
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse("")) }
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
} // Set their ignoring requests state
} plugin.getDatabase().getUserData(onlineUser.uuid).ifPresent(userData -> {
}).thenRun(() -> { final boolean ignoringRequests = userData.ignoringTeleports();
// Cache this user's homes plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
plugin.getDatabase()
.getHomes(onlineUser) // Send a reminder message if they are still ignoring requests
.thenAccept(homes -> plugin.getCache().homes.put(onlineUser.uuid, homes.stream() if (ignoringRequests) {
.map(home -> home.meta.name) plugin.getLocales().getRawLocale("tpignore_on_notification", plugin.getLocales()
.collect(Collectors.toList()))); .getRawLocale("tpignore_toggle_button")
}); .orElse("")).ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
})); }
});
// Cache this user's homes
plugin.getCache().getHomes().put(onlineUser.uuid, plugin.getDatabase()
.getHomes(onlineUser).stream()
.map(Home::getName)
.toList());
});
} }
/** /**
* Handle inbound cross-server teleports * Handle inbound cross-server teleports
* *
* @param onlineUser user to handle the checks for * @param onlineUser user to handle the checks for
* @return a future returning void when done
*/ */
private CompletableFuture<Void> handleInboundTeleport(@NotNull OnlineUser onlineUser) { private void handleInboundTeleport(@NotNull OnlineUser onlineUser) {
// If the server is in proxy mode, check if the player is teleporting cross-server and handle plugin.getDatabase().getCurrentTeleport(onlineUser).ifPresent(teleport -> {
if (plugin.getSettings().isCrossServer()) { if (teleport.type == TeleportType.RESPAWN) {
return plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> { final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (teleport.isEmpty()) { if (bedPosition.isEmpty()) {
return; plugin.getLocalCachedSpawn()
.flatMap(spawn -> spawn.getPosition(plugin.getServerName()))
.ifPresent(position -> onlineUser.teleportLocally(position,
plugin.getSettings().isAsynchronousTeleports()));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().isAsynchronousTeleports());
} }
plugin.getDatabase().setCurrentTeleport(onlineUser, null);
// Handle cross-server respawn plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null));
if (teleport.get().type == TeleportType.RESPAWN) { return;
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition(); }
if (bedPosition.isEmpty()) { teleport.execute()
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getServerName())) .thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
.ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().isAsynchronousTeleports())); .exceptionally(throwable -> {
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid"); plugin.getLoggingAdapter().log(Level.SEVERE,
} else { "An error occurred while teleporting an inbound player", throwable);
onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().isAsynchronousTeleports()); return null;
} });
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() -> });
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)));
return;
}
// Teleport the player locally
teleport.get().execute()
.thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE,
"An error occurred while teleporting an inbound player", throwable);
return null;
});
});
}
return CompletableFuture.completedFuture(null);
} }
/** /**
@@ -112,7 +100,7 @@ public class EventListener {
*/ */
protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) { protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) {
// Remove this user's home cache // Remove this user's home cache
plugin.getCache().homes.remove(onlineUser.uuid); plugin.getCache().getHomes().remove(onlineUser.uuid);
// Update the cached player list using another online player if possible // Update the cached player list using another online player if possible
plugin.getOnlinePlayers() plugin.getOnlinePlayers()
@@ -134,7 +122,7 @@ public class EventListener {
protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) { protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) {
// Set the player's last position to where they died // Set the player's last position to where they died
if (plugin.getSettings().isBackCommandReturnByDeath() if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition()); plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
} }
} }
@@ -145,26 +133,28 @@ public class EventListener {
* @param onlineUser the respawning {@link OnlineUser} * @param onlineUser the respawning {@link OnlineUser}
*/ */
protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) { protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) {
// Display the return by death via /back notification plugin.runAsync(() -> {
if (plugin.getSettings().isBackCommandReturnByDeath() // Display the return by death via /back notification
&& onlineUser.hasPermission(Permission.COMMAND_BACK.node) if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { && onlineUser.hasPermission(Permission.COMMAND_BACK.node)
plugin.getLocales().getLocale("return_by_death_notification") && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
.ifPresent(onlineUser::sendMessage); plugin.getLocales().getLocale("return_by_death_notification")
} .ifPresent(onlineUser::sendMessage);
}
// Respawn the player cross-server if needed // Respawn the player cross-server if needed
if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) { if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> { plugin.getDatabase().getRespawnPosition(onlineUser).ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getServerName())) { if (!respawnPosition.getServer().equals(plugin.getServerName())) {
Teleport.builder(plugin, onlineUser) Teleport.builder(plugin, onlineUser)
.setType(TeleportType.RESPAWN) .setType(TeleportType.RESPAWN)
.setTarget(respawnPosition) .setTarget(respawnPosition)
.toTeleport() .toTeleport()
.thenAccept(Teleport::execute); .thenAccept(Teleport::execute);
} }
})); });
} }
});
} }
/** /**
@@ -174,11 +164,12 @@ public class EventListener {
* @param sourcePosition the source {@link Position} they came from * @param sourcePosition the source {@link Position} they came from
*/ */
protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) { protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) {
if (!plugin.getSettings().isBackCommandSaveOnTeleportEvent()) return; if (!plugin.getSettings().isBackCommandSaveOnTeleportEvent()) {
return;
}
plugin.getDatabase().getUserData(onlineUser.uuid) plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.uuid)
.thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase() .ifPresent(data -> plugin.getDatabase().setLastPosition(data.user(), sourcePosition)));
.setLastPosition(data.user(), sourcePosition)));
} }
/** /**
@@ -29,13 +29,13 @@ public class HomesManager {
final Home home = existingHome final Home home = existingHome
.map(existing -> { .map(existing -> {
existing.x = position.x; existing.setX(position.getX());
existing.y = position.y; existing.setY(position.getY());
existing.z = position.z; existing.setZ(position.getZ());
existing.world = position.world; existing.setWorld(position.getWorld());
existing.server = position.server; existing.setServer(position.getServer());
existing.yaw = position.yaw; existing.setYaw(position.getYaw());
existing.pitch = position.pitch; existing.setPitch(position.getPitch());
return existing; return existing;
}) })
.orElse(new Home(position, new PositionMeta(name, ""), owner)); .orElse(new Home(position, new PositionMeta(name, ""), owner));
@@ -47,7 +47,7 @@ public class HomesManager {
if (home.isEmpty()) { if (home.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
} }
plugin.getDatabase().deleteHome(home.get().uuid); plugin.getDatabase().deleteHome(home.get().getUuid());
} }
public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException { public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
@@ -65,7 +65,7 @@ public class HomesManager {
} }
final Home home = optionalHome.get(); final Home home = optionalHome.get();
home.meta.name = newName; home.getMeta().setName(newName);
plugin.getDatabase().saveHome(home); plugin.getDatabase().saveHome(home);
} }
@@ -80,7 +80,7 @@ public class HomesManager {
} }
final Home home = optionalHome.get(); final Home home = optionalHome.get();
home.meta.description = description; home.getMeta().setDescription(description);
plugin.getDatabase().saveHome(home); plugin.getDatabase().saveHome(home);
} }
@@ -91,7 +91,7 @@ public class HomesManager {
} }
final Home home = optionalHome.get(); final Home home = optionalHome.get();
home.isPublic = isPublic; home.setPublic(isPublic);
plugin.getDatabase().saveHome(home); plugin.getDatabase().saveHome(home);
} }
@@ -2,8 +2,6 @@ package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException; import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
@@ -29,13 +27,13 @@ public class WarpsManager {
final Warp warp = existingWarp final Warp warp = existingWarp
.map(existing -> { .map(existing -> {
existing.x = position.x; existing.setX(position.getX());
existing.y = position.y; existing.setY(position.getY());
existing.z = position.z; existing.setZ(position.getZ());
existing.world = position.world; existing.setWorld(position.getWorld());
existing.server = position.server; existing.setServer(position.getServer());
existing.yaw = position.yaw; existing.setYaw(position.getYaw());
existing.pitch = position.pitch; existing.setPitch(position.getPitch());
return existing; return existing;
}) })
.orElse(new Warp(position, new PositionMeta(name, ""))); .orElse(new Warp(position, new PositionMeta(name, "")));
@@ -47,7 +45,7 @@ public class WarpsManager {
if (warp.isEmpty()) { if (warp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
} }
plugin.getDatabase().deleteWarp(warp.get().uuid); plugin.getDatabase().deleteWarp(warp.get().getUuid());
} }
public void relocateWarp(@NotNull String name, @NotNull Position position) { public void relocateWarp(@NotNull String name, @NotNull Position position) {
@@ -65,7 +63,7 @@ public class WarpsManager {
} }
final Warp warp = optionalWarp.get(); final Warp warp = optionalWarp.get();
warp.meta.name = newName; warp.getMeta().setName(newName);
plugin.getDatabase().saveWarp(warp); plugin.getDatabase().saveWarp(warp);
} }
@@ -76,7 +74,7 @@ public class WarpsManager {
} }
final Warp warp = optionalWarp.get(); final Warp warp = optionalWarp.get();
warp.meta.description = description; warp.getMeta().setDescription(description);
plugin.getDatabase().saveWarp(warp); plugin.getDatabase().saveWarp(warp);
} }
@@ -57,7 +57,7 @@ public abstract class OnlineUser extends User {
* @param node The permission node string * @param node The permission node string
* @return {@code true} if the player has the node; {@code false} otherwise * @return {@code true} if the player has the node; {@code false} otherwise
*/ */
public abstract boolean hasPermission(@NotNull @Pattern(Permission.PERMISSION_PATTERN) String node); public abstract boolean hasPermission(@NotNull String node);
/** /**
* Returns a {@link Map} of a player's permission nodes * Returns a {@link Map} of a player's permission nodes
@@ -10,16 +10,8 @@ import java.util.UUID;
*/ */
public class Home extends SavedPosition { public class Home extends SavedPosition {
/** private final User owner;
* The {@link User} who owns this home private boolean isPublic;
*/
@NotNull
public final User owner;
/**
* {@code true} if this home is public
*/
public boolean isPublic;
public Home(double x, double y, double z, float yaw, float pitch, public Home(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server, @NotNull World world, @NotNull Server server,
@@ -27,13 +19,31 @@ public class Home extends SavedPosition {
@NotNull User owner, boolean isPublic) { @NotNull User owner, boolean isPublic) {
super(x, y, z, yaw, pitch, world, server, positionMeta, uuid); super(x, y, z, yaw, pitch, world, server, positionMeta, uuid);
this.owner = owner; this.owner = owner;
this.isPublic = isPublic; this.setPublic(isPublic);
} }
public Home(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User owner) { public Home(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User owner) {
super(position, meta); super(position, meta);
this.owner = owner; this.owner = owner;
this.isPublic = false; this.setPublic(false);
} }
/**
* The {@link User} who owns this home
*/
@NotNull
public User getOwner() {
return owner;
}
/**
* {@code true} if this home is public
*/
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
} }
@@ -7,56 +7,98 @@ import org.jetbrains.annotations.NotNull;
*/ */
public class Location { public class Location {
/** private double x;
* The double-precision defined x coordinate of the location private double y;
*/ private double z;
public double x; private float yaw;
private float pitch;
/** private World world;
* The double-precision defined y coordinate of the location
*/
public double y;
/**
* The double-precision defined z coordinate of the location
*/
public double z;
/**
* The float-precision defined yaw facing of the location
*/
public float yaw;
/**
* The float-precision defined pitch facing of the location
*/
public float pitch;
/**
* The {@link World} the location is on
*/
public World world;
public Location(double x, double y, double z, @NotNull World world) { public Location(double x, double y, double z, @NotNull World world) {
this.x = x; this.setX(x);
this.y = y; this.setY(y);
this.z = z; this.setZ(z);
this.yaw = 0; this.setYaw(0);
this.pitch = 0; this.setPitch(0);
this.world = world; this.setWorld(world);
} }
public Location(double x, double y, double z, float yaw, float pitch, public Location(double x, double y, double z, float yaw, float pitch,
@NotNull World world) { @NotNull World world) {
this.x = x; this.setX(x);
this.y = y; this.setY(y);
this.z = z; this.setZ(z);
this.yaw = yaw; this.setYaw(yaw);
this.pitch = pitch; this.setPitch(pitch);
this.world = world; this.setWorld(world);
} }
public Location() { public Location() {
} }
/**
* The double-precision defined x coordinate of the location
*/
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
/**
* The double-precision defined y coordinate of the location
*/
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
/**
* The double-precision defined z coordinate of the location
*/
public double getZ() {
return z;
}
public void setZ(double z) {
this.z = z;
}
/**
* The float-precision defined yaw facing of the location
*/
public float getYaw() {
return yaw;
}
public void setYaw(float yaw) {
this.yaw = yaw;
}
/**
* The float-precision defined pitch facing of the location
*/
public float getPitch() {
return pitch;
}
public void setPitch(float pitch) {
this.pitch = pitch;
}
/**
* The {@link World} the location is on
*/
public World getWorld() {
return world;
}
public void setWorld(World world) {
this.world = world;
}
} }
@@ -10,24 +10,21 @@ import java.util.UUID;
*/ */
public class Position extends Location { public class Position extends Location {
/** private Server server;
* The {@link Server} the position is on
*/
public Server server;
public Position(double x, double y, double z, float yaw, float pitch, public Position(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server) { @NotNull World world, @NotNull Server server) {
super(x, y, z, yaw, pitch, world); super(x, y, z, yaw, pitch, world);
this.server = server; this.setServer(server);
} }
public Position(@NotNull Location location, @NotNull Server server) { public Position(@NotNull Location location, @NotNull Server server) {
super(location.x, location.y, location.z, location.yaw, location.pitch, location.world); super(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), location.getWorld());
this.server = server; this.setServer(server);
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
public Position() { private Position() {
} }
/** /**
@@ -36,13 +33,13 @@ public class Position extends Location {
* @param newPosition The position to update to * @param newPosition The position to update to
*/ */
public void update(@NotNull Position newPosition) { public void update(@NotNull Position newPosition) {
this.x = newPosition.x; this.setX(newPosition.getX());
this.y = newPosition.y; this.setY(newPosition.getY());
this.z = newPosition.z; this.setZ(newPosition.getZ());
this.yaw = newPosition.yaw; this.setYaw(newPosition.getYaw());
this.pitch = newPosition.pitch; this.setPitch(newPosition.getPitch());
this.world = newPosition.world; this.setWorld(newPosition.getWorld());
this.server = newPosition.server; this.setServer(newPosition.getServer());
} }
/** /**
@@ -60,12 +57,12 @@ public class Position extends Location {
// Parse, handle relatives, and return, catching NumberFormatExceptions and returning an empty optional // Parse, handle relatives, and return, catching NumberFormatExceptions and returning an empty optional
try { try {
final double x = parseCoordinate(args[0], relativeTo.x); final double x = parseCoordinate(args[0], relativeTo.getX());
final double y = parseCoordinate(args[1], relativeTo.y); final double y = parseCoordinate(args[1], relativeTo.getY());
final double z = parseCoordinate(args[2], relativeTo.z); final double z = parseCoordinate(args[2], relativeTo.getZ());
final World world = args.length > 3 ? new World(args[3], UUID.randomUUID()) : relativeTo.world; final World world = args.length > 3 ? new World(args[3], UUID.randomUUID()) : relativeTo.getWorld();
final Server server = args.length > 4 ? new Server(args[4]) : relativeTo.server; final Server server = args.length > 4 ? new Server(args[4]) : relativeTo.getServer();
return Optional.of(new Position(x, y, z, relativeTo.yaw, relativeTo.pitch, world, server)); return Optional.of(new Position(x, y, z, relativeTo.getYaw(), relativeTo.getPitch(), world, server));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
return Optional.empty(); return Optional.empty();
} }
@@ -91,4 +88,15 @@ public class Position extends Location {
return Double.parseDouble(value); return Double.parseDouble(value);
} }
} }
/**
* The {@link Server} the position is on
*/
public Server getServer() {
return server;
}
public void setServer(Server server) {
this.server = server;
}
} }
@@ -8,49 +8,32 @@ import org.jetbrains.annotations.Nullable;
import java.time.Instant; import java.time.Instant;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
/** /**
* Represents metadata about a {@link Position}, used in {@link SavedPosition} implementations * Represents metadata about a {@link Position}, used in {@link SavedPosition} implementations
*/ */
public class PositionMeta { public class PositionMeta {
/** private String name;
* The name of a position @Nullable
*/ private String description;
@NotNull private Map<String, String> tags;
public String name; private Instant creationTime;
/**
* A description of a position
*/
@NotNull
public String description;
/**
* Map of metadata tags for a position
*/
@NotNull
public Map<String, String> tags;
/**
* The time the position was created
*/
@NotNull
public Instant creationTime;
public PositionMeta(@NotNull String name, @NotNull String description, @NotNull Instant creationTime, public PositionMeta(@NotNull String name, @NotNull String description, @NotNull Instant creationTime,
@Nullable String serializedTags) { @Nullable String serializedTags) {
this.name = name; this.setName(name);
this.description = description; this.setDescription(description);
this.creationTime = creationTime; this.setCreationTime(creationTime);
this.tags = deserializeTags(serializedTags); this.setTags(deserializeTags(serializedTags));
} }
public PositionMeta(@NotNull String name, @NotNull String description) { public PositionMeta(@NotNull String name, @NotNull String description) {
this.name = name; this.setName(name);
this.description = description; this.setDescription(description);
this.creationTime = Instant.now(); this.setCreationTime(Instant.now());
this.tags = new HashMap<>(); this.setTags(new HashMap<>());
} }
/** /**
@@ -80,14 +63,59 @@ public class PositionMeta {
@Nullable @Nullable
public String getSerializedTags() { public String getSerializedTags() {
try { try {
if (tags.isEmpty()) { if (getTags().isEmpty()) {
return null; return null;
} }
return new Gson().toJson(tags); return new Gson().toJson(getTags());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
/**
* The name of a position
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* A description of a position
*/
@NotNull
public String getDescription() {
return Optional.ofNullable(description).orElse("");
}
public void setDescription(@Nullable String description) {
this.description = description;
}
/**
* Map of metadata tags for a position
*/
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
/**
* The time the position was created
*/
@NotNull
public Instant getCreationTime() {
return creationTime;
}
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}
} }
@@ -9,23 +9,14 @@ import java.util.UUID;
*/ */
public abstract class SavedPosition extends Position implements Comparable<SavedPosition> { public abstract class SavedPosition extends Position implements Comparable<SavedPosition> {
/** private PositionMeta meta;
* Metadata about this position (name, description) private final UUID uuid;
*/
@NotNull
public PositionMeta meta;
/**
* A unique ID representing this position
*/
@NotNull
public final UUID uuid;
protected SavedPosition(double x, double y, double z, float yaw, float pitch, protected SavedPosition(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server, @NotNull World world, @NotNull Server server,
@NotNull PositionMeta meta, @NotNull UUID uuid) { @NotNull PositionMeta meta, @NotNull UUID uuid) {
super(x, y, z, yaw, pitch, world, server); super(x, y, z, yaw, pitch, world, server);
this.meta = meta; this.setMeta(meta);
this.uuid = uuid; this.uuid = uuid;
} }
@@ -36,15 +27,43 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
* @param meta {@link PositionMeta} information about this position * @param meta {@link PositionMeta} information about this position
*/ */
protected SavedPosition(@NotNull Position position, @NotNull PositionMeta meta) { protected SavedPosition(@NotNull Position position, @NotNull PositionMeta meta) {
super(position.x, position.y, position.z, position.yaw, position.pitch, super(position.getX(), position.getY(), position.getZ(), position.getYaw(), position.getPitch(),
position.world, position.server); position.getWorld(), position.getServer());
this.meta = meta; this.setMeta(meta);
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
} }
// Compare based on names for alphabetical sorting // Compare based on names for alphabetical sorting
@Override @Override
public int compareTo(@NotNull SavedPosition o) { public int compareTo(@NotNull SavedPosition o) {
return this.meta.name.compareTo(o.meta.name); return this.getMeta().getName().compareTo(o.getMeta().getName());
}
/**
* Metadata about this position (name, description)
*/
@NotNull
public PositionMeta getMeta() {
return meta;
}
public void setMeta(@NotNull PositionMeta meta) {
this.meta = meta;
}
/**
* The name of this position. Shortcut for {@link #getMeta()}.{@link PositionMeta#getName()}
*/
@NotNull
public String getName() {
return getMeta().getName();
}
/**
* A unique ID representing this position
*/
@NotNull
public UUID getUuid() {
return uuid;
} }
} }
@@ -17,27 +17,25 @@ import java.nio.file.Path;
public class Server { public class Server {
/** /**
* Default (unknown) server identifier * Default server identifier
*/ */
@NotNull
public static Server getDefault() { public static Server getDefault() {
final Server server = new Server(); final Server server = new Server();
try { try {
final Path serverDirectory = Path.of(System.getProperty("user.dir")); final Path serverDirectory = Path.of(System.getProperty("user.dir"));
server.name = serverDirectory.getFileName().toString().trim(); server.setName(serverDirectory.getFileName().toString().trim());
} catch (Exception e) { } catch (Exception e) {
server.name = "server"; server.setName("server");
} }
return server; return server;
} }
/**
* Proxy-defined name of this server
*/
@YamlKey("server_name") @YamlKey("server_name")
public String name = getDefault().name; private String name = getDefault().getName();
public Server(@NotNull String name) { public Server(@NotNull String name) {
this.name = name; this.setName(name);
} }
private Server() { private Server() {
@@ -47,9 +45,20 @@ public class Server {
public boolean equals(@NotNull Object other) { public boolean equals(@NotNull Object other) {
// If the name of this server matches another, the servers are the same. // If the name of this server matches another, the servers are the same.
if (other instanceof Server server) { if (other instanceof Server server) {
return server.name.equalsIgnoreCase(this.name); return server.getName().equalsIgnoreCase(this.getName());
} }
return super.equals(other); return super.equals(other);
} }
/**
* Proxy-defined name of this server
*/
@NotNull
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} }
@@ -48,7 +48,7 @@ public class Warp extends SavedPosition {
* @return true if the user has permission to teleport to this warp * @return true if the user has permission to teleport to this warp
*/ */
public boolean hasPermission(boolean restrictWarps, @NotNull OnlineUser user) { public boolean hasPermission(boolean restrictWarps, @NotNull OnlineUser user) {
return hasPermission(restrictWarps, user, meta.name); return hasPermission(restrictWarps, user, getMeta().getName());
} }
/** /**
@@ -3,6 +3,7 @@ package net.william278.huskhomes.position;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
/** /**
@@ -10,38 +11,62 @@ import java.util.UUID;
*/ */
public class World { public class World {
private String name;
private UUID uuid;
@Nullable
private Environment environment;
public World(@NotNull String name, @NotNull UUID uuid) {
this.setName(name);
this.setUuid(uuid);
}
public World(@NotNull String name, @NotNull UUID uuid, @Nullable Environment environment) {
this.setName(name);
this.setUuid(uuid);
this.setEnvironment(environment);
}
@SuppressWarnings("unused")
public World() {
}
/** /**
* The name of this world, as defined by the world directory name * The name of this world, as defined by the world directory name
*/ */
public String name; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/** /**
* UUID of this world, as defined by the {@code uid.dat} file in the world directory * UUID of this world, as defined by the {@code uid.dat} file in the world directory
*/ */
public UUID uuid; @NotNull
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
/** /**
* Environment of the world ({@link Environment#OVERWORLD}, {@link Environment#NETHER}, {@link Environment#THE_END}, * Environment of the world ({@link Environment#OVERWORLD}, {@link Environment#NETHER}, {@link Environment#THE_END},
* or {@link Environment#CUSTOM}) * or {@link Environment#CUSTOM})
*/ */
@Nullable @NotNull
public Environment environment; public Environment getEnvironment() {
return Optional.ofNullable(environment).orElse(Environment.OVERWORLD);
public World(@NotNull String name, @NotNull UUID uuid) {
this.name = name;
this.uuid = uuid;
} }
public World(@NotNull String name, @NotNull UUID uuid, @Nullable Environment environment) { public void setEnvironment(@Nullable Environment environment) {
this.name = name;
this.uuid = uuid;
this.environment = environment; this.environment = environment;
} }
@SuppressWarnings("unused")
public World() {
}
/** /**
* Identifies the environment of the world * Identifies the environment of the world
*/ */
@@ -55,7 +80,7 @@ public class World {
@Override @Override
public boolean equals(@NotNull Object obj) { public boolean equals(@NotNull Object obj) {
if (obj instanceof World world) { if (obj instanceof World world) {
return world.uuid.equals(uuid); return world.getUuid().equals(getUuid());
} }
return super.equals(obj); return super.equals(obj);
} }
@@ -46,7 +46,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
final float z = (float) (radius * Math.cos(angle)); final float z = (float) (radius * Math.cos(angle));
final float x = (float) (radius * Math.sin(angle)); final float x = (float) (radius * Math.sin(angle));
return new Location(Math.round(origin.x) + x, 128d, Math.round(origin.z) + z, origin.world); return new Location(Math.round(origin.getX()) + x, 128d, Math.round(origin.getZ()) + z, origin.getWorld());
} }
/** /**
@@ -85,7 +85,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
} }
@Override @Override
protected Optional<Position> getRandomPosition(@NotNull World world, @NotNull String[] args) { public Optional<Position> getRandomPosition(@NotNull World world, @NotNull String[] args) {
Optional<Location> location = generateSafeLocation(world).join(); Optional<Location> location = generateSafeLocation(world).join();
int attempts = 0; int attempts = 0;
while (location.isEmpty()) { while (location.isEmpty()) {
@@ -6,7 +6,6 @@ import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/** /**
* Represents an engine for generating random position targets * Represents an engine for generating random position targets
@@ -46,7 +45,7 @@ public abstract class RandomTeleportEngine {
protected final Position getOrigin(@NotNull World world) { protected final Position getOrigin(@NotNull World world) {
return plugin.getLocalCachedSpawn() return plugin.getLocalCachedSpawn()
.flatMap(spawn -> { .flatMap(spawn -> {
if (!spawn.worldUuid.equals(world.uuid.toString())) { if (!spawn.worldUuid.equals(world.getUuid().toString())) {
return Optional.empty(); return Optional.empty();
} }
return spawn.getPosition(plugin.getServerName()); return spawn.getPosition(plugin.getServerName());
@@ -178,27 +178,24 @@ public class Teleport {
} }
// If the target position is local, finalize economy transactions and teleport the player // If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().isCrossServer() || target.server.equals(plugin.getServerName())) { if (!plugin.getSettings().isCrossServer() || target.getServer().equals(plugin.getServerName())) {
return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports()); return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports());
} }
// If the target position is on another server, execute a cross-server teleport // If the target position is on another server, execute a cross-server teleport
final CompletableFuture<TeleportResult> teleportFuture = new CompletableFuture<>(); final CompletableFuture<TeleportResult> teleportFuture = new CompletableFuture<>();
plugin.getDatabase() plugin.getDatabase().setCurrentTeleport(teleporter, this);
.setCurrentTeleport(teleporter, this) plugin.getMessenger()
.thenApply(ignored -> plugin .sendPlayer(teleporter, target.getServer())
.getMessenger() .thenApply(completed -> completed
.sendPlayer(teleporter, target.server) ? TeleportResult.COMPLETED_CROSS_SERVER
.thenApply(completed -> completed : TeleportResult.FAILED_INVALID_SERVER)
? TeleportResult.COMPLETED_CROSS_SERVER
: TeleportResult.FAILED_INVALID_SERVER))
.orTimeout(10, TimeUnit.SECONDS) .orTimeout(10, TimeUnit.SECONDS)
.exceptionally(throwable -> { .exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Cross-server teleport timed out for " + teleporter.username); plugin.getLoggingAdapter().log(Level.WARNING, "Cross-server teleport timed out for " + teleporter.username);
plugin.getDatabase().setCurrentTeleport(teleporter, null); plugin.getDatabase().setCurrentTeleport(teleporter, null);
return CompletableFuture.completedFuture(TeleportResult.FAILED_INVALID_SERVER); return TeleportResult.FAILED_INVALID_SERVER;
}) });
.thenAccept(result -> result.thenAcceptAsync(teleportFuture::complete));
return teleportFuture; return teleportFuture;
} }
@@ -53,7 +53,7 @@ public class TimedTeleport extends Teleport {
} }
// Check if the teleporter is already warming up to teleport // Check if the teleporter is already warming up to teleport
if (plugin.getCache().currentlyOnWarmup.contains(teleporter.uuid)) { if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.uuid)) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING) return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this)); .thenApply(resultState -> CompletedTeleport.from(resultState, this));
} }
@@ -98,7 +98,7 @@ public class TimedTeleport extends Teleport {
} }
// Mark the player as warming up and display the message // Mark the player as warming up and display the message
plugin.getCache().currentlyOnWarmup.add(teleporter.uuid); plugin.getCache().getCurrentlyOnWarmup().add(teleporter.uuid);
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft)) plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft))
.ifPresent(teleporter::sendMessage); .ifPresent(teleporter::sendMessage);
@@ -118,7 +118,7 @@ public class TimedTeleport extends Teleport {
// Tick (decrement) the timed teleport timer and end it if done // Tick (decrement) the timed teleport timer and end it if done
if (tickWarmup()) { if (tickWarmup()) {
plugin.getCache().currentlyOnWarmup.remove(teleporter.uuid); plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.uuid);
timedTeleportFuture.complete(null); timedTeleportFuture.complete(null);
executor.shutdown(); executor.shutdown();
} }
@@ -195,9 +195,9 @@ public class TimedTeleport extends Teleport {
*/ */
private boolean hasTeleporterMoved() { private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d; final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.x - teleporter.getPosition().x) + double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) +
Math.abs(startLocation.y - teleporter.getPosition().y) + Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.z - teleporter.getPosition().z); Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
return movementDistance > maxMovementDistance; return movementDistance > maxMovementDistance;
} }
@@ -43,8 +43,8 @@ public class RequestTests {
Assertions.assertNotNull(readRequest.getPayload().position); Assertions.assertNotNull(readRequest.getPayload().position);
assert readRequest.getPayload().position != null && DUMMY_PAYLOAD.getPayload().position != null; assert readRequest.getPayload().position != null && DUMMY_PAYLOAD.getPayload().position != null;
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.x, readRequest.getPayload().position.x); Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.getX(), readRequest.getPayload().position.getX());
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.y, readRequest.getPayload().position.y); Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.getY(), readRequest.getPayload().position.getY());
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.z, readRequest.getPayload().position.z); Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.getZ(), readRequest.getPayload().position.getZ());
} }
} }
@@ -25,8 +25,8 @@ public class NormalDistributionTests {
final double[] xValues = new double[locations.size()]; final double[] xValues = new double[locations.size()];
final double[] zValues = new double[locations.size()]; final double[] zValues = new double[locations.size()];
for (int i = 0; i < locations.size(); i++) { for (int i = 0; i < locations.size(); i++) {
xValues[i] = locations.get(i).x; xValues[i] = locations.get(i).getX();
zValues[i] = locations.get(i).z; zValues[i] = locations.get(i).getZ();
} }
final Plot plot = Plot.plot(Plot.plotOpts() final Plot plot = Plot.plot(Plot.plotOpts()
.title("RTP Normal Distribution demo") .title("RTP Normal Distribution demo")