Add fabric builds for older MC versions & add checkstyle (#449)

* Remove instance getters, improve command logic, register APi

* Publish multiple fabric builds, enforce checkstyle

* Bump guava

* Bump to 4.4.2
This commit is contained in:
William authored and GitHub committed 2023-07-02 13:26:12 +01:00
1 parent 51baf196b3
commit c9f5262292
219 files changed
+8032 -1392

No files matched your search

+6 -1
View File
@@ -106,7 +106,10 @@ jobs:
pl3xmap | suggests | * pl3xmap | suggests | *
luckperms | suggests | * luckperms | suggests | *
plan-player-analytics | suggests | * plan-player-analytics | suggests | *
files-primary: target/HuskHomes-Fabric-*.jar files-primary: target/HuskHomes-Fabric-1.20.1-*.jar
files-secondary: |
target/HuskHomes-Fabric-1.19.4-*.jar
target/HuskHomes-Fabric-1.19.2-*.jar
name: HuskHomes (Fabric) v${{ env.version_name }} name: HuskHomes (Fabric) v${{ env.version_name }}
version: ${{ env.version_name }} version: ${{ env.version_name }}
version-type: alpha version-type: alpha
@@ -114,6 +117,8 @@ jobs:
loaders: | loaders: |
fabric fabric
game-versions: | game-versions: |
1.19.2
1.19.4
1.20.1 1.20.1
java: 17 java: 17
- name: Upload GitHub Artifact (Spigot) - name: Upload GitHub Artifact (Spigot)
+6 -1
View File
@@ -94,7 +94,10 @@ jobs:
pl3xmap | suggests | * pl3xmap | suggests | *
luckperms | suggests | * luckperms | suggests | *
plan-player-analytics | suggests | * plan-player-analytics | suggests | *
files-primary: target/HuskHomes-Fabric-*.jar files-primary: target/HuskHomes-Fabric-1.20.1-*.jar
files-secondary: |
target/HuskHomes-Fabric-1.19.4-*.jar
target/HuskHomes-Fabric-1.19.2-*.jar
name: HuskHomes (Fabric) v${{ github.event.release.tag_name }} name: HuskHomes (Fabric) v${{ github.event.release.tag_name }}
version: ${{ github.event.release.tag_name }} version: ${{ github.event.release.tag_name }}
version-type: release version-type: release
@@ -102,6 +105,8 @@ jobs:
loaders: | loaders: |
fabric fabric
game-versions: | game-versions: |
1.19.2
1.19.4
1.20.1 1.20.1
java: 17 java: 17
- name: Upload GitHub Artifact (Spigot) - name: Upload GitHub Artifact (Spigot)
+1 -1
View File
@@ -44,7 +44,7 @@ HuskHomes can be used on your Spigot, Sponge or Fabric server, and with a MySQL
**⭐ Extensible API & open-source** — Still not enough? Extend the plugin with the HuskHomes API. Or, submit a pull request—we're open-source! **⭐ Extensible API & open-source** — Still not enough? Extend the plugin with the HuskHomes API. Or, submit a pull request—we're open-source!
## Building ## Building
HuskHomes requires Java 17 to build. To build, simply run the following in the root of the repository: HuskHomes requires Java 17 to build. To build for all platforms, simply run the following in the root of the repository:
```bash ```bash
./gradlew clean build ./gradlew clean build
+7 -10
View File
@@ -4,6 +4,7 @@ plugins {
id 'com.github.johnrengelman.shadow' version '8.1.1' id 'com.github.johnrengelman.shadow' version '8.1.1'
id 'org.cadixdev.licenser' version '0.6.1' apply false id 'org.cadixdev.licenser' version '0.6.1' apply false
id 'org.ajoberstar.grgit' version '5.2.0' id 'org.ajoberstar.grgit' version '5.2.0'
id 'checkstyle'
id 'maven-publish' id 'maven-publish'
id 'java' id 'java'
} }
@@ -11,7 +12,7 @@ plugins {
group 'net.william278' group 'net.william278'
version "$ext.plugin_version${versionMetadata()}" version "$ext.plugin_version${versionMetadata()}"
description "$ext.plugin_description" description "$ext.plugin_description"
defaultTasks 'licenseFormat', 'build' defaultTasks 'licenseFormat', 'check', 'build'
ext { ext {
set 'version', version.toString() set 'version', version.toString()
@@ -20,16 +21,12 @@ ext {
set 'jedis_version', jedis_version.toString() set 'jedis_version', jedis_version.toString()
set 'sqlite_driver_version', sqlite_driver_version.toString() set 'sqlite_driver_version', sqlite_driver_version.toString()
set 'mysql_driver_version', mysql_driver_version.toString() set 'mysql_driver_version', mysql_driver_version.toString()
set 'fabric_minecraft_version', fabric_minecraft_version.toString()
set 'fabric_yarn_mappings', fabric_yarn_mappings.toString()
set 'fabric_loader_version', fabric_loader_version.toString()
set 'fabric_api_version', fabric_api_version.toString()
} }
allprojects { allprojects {
apply plugin: 'com.github.johnrengelman.shadow' apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'org.cadixdev.licenser' apply plugin: 'org.cadixdev.licenser'
apply plugin: 'checkstyle'
apply plugin: 'java' apply plugin: 'java'
compileJava.options.encoding = 'UTF-8' compileJava.options.encoding = 'UTF-8'
@@ -65,16 +62,16 @@ allprojects {
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.3' testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.3'
} }
test {
useJUnitPlatform()
}
license { license {
header = rootProject.file('HEADER') header = rootProject.file('HEADER')
include '**/*.java' include '**/*.java'
newLine = true newLine = true
} }
checkstyle {
toolVersion = '10.12.0'
}
processResources { processResources {
filesMatching(['**/*.json', '**/*.yml']) { filesMatching(['**/*.json', '**/*.yml']) {
filter ReplaceTokens as Class, beginToken: '${', endToken: '}', filter ReplaceTokens as Class, beginToken: '${', endToken: '}',
@@ -22,9 +22,9 @@ package net.william278.huskhomes;
import net.kyori.adventure.platform.bukkit.BukkitAudiences; import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.william278.annotaml.Annotaml; import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.Version; import net.william278.desertwell.util.Version;
import net.william278.huskhomes.api.HuskHomesAPI;
import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.Command; import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Settings;
@@ -62,6 +62,7 @@ import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.plugin.messaging.PluginMessageListener; import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import space.arim.morepaperlib.MorePaperLib; import space.arim.morepaperlib.MorePaperLib;
import space.arim.morepaperlib.scheduling.GracefulScheduling; import space.arim.morepaperlib.scheduling.GracefulScheduling;
@@ -79,6 +80,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
* Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskHomes/8430">HuskHomes on Bukkit</a>. * Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskHomes/8430">HuskHomes on Bukkit</a>.
*/ */
private static final int METRICS_ID = 8430; private static final int METRICS_ID = 8430;
private Set<SavedUser> savedUsers; private Set<SavedUser> savedUsers;
private Settings settings; private Settings settings;
private Locales locales; private Locales locales;
@@ -94,34 +96,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
private Map<String, List<String>> globalPlayerList; private Map<String, List<String>> globalPlayerList;
private Set<UUID> currentlyOnWarmup; private Set<UUID> currentlyOnWarmup;
private Server server; private Server server;
@Nullable
private Broker broker;
private BukkitAudiences audiences; private BukkitAudiences audiences;
private MorePaperLib paperLib; private MorePaperLib paperLib;
@Nullable
private static BukkitHuskHomes instance; private Broker broker;
public static BukkitHuskHomes getInstance() {
return instance;
}
// Default public constructor // Default public constructor
@SuppressWarnings("unused")
public BukkitHuskHomes() { public BukkitHuskHomes() {
super(); super();
} }
// Super constructor for unit testing // Super constructor for unit testing
@SuppressWarnings("unused") @TestOnly
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) { protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description,
@NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file); super(loader, description, dataFolder, file);
} }
@Override
public void onLoad() {
instance = this;
}
@Override @Override
public void onEnable() { public void onEnable() {
// Create adventure audience // Create adventure audience
@@ -142,7 +133,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Initialize the database // Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> {
this.database = switch (getSettings().getDatabaseType()) { this.database = switch (getSettings().getDatabaseType()) {
case MYSQL -> new MySqlDatabase(this); case MYSQL, MARIADB -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this); case SQLITE -> new SqLiteDatabase(this);
}; };
@@ -190,6 +181,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Register commands // Register commands
initialize("commands", (plugin) -> this.commands = registerCommands()); initialize("commands", (plugin) -> this.commands = registerCommands());
// Initialize the API
initialize("API", (plugin) -> HuskHomesAPI.register(this));
// Hook into bStats and check for updates // Hook into bStats and check for updates
initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID)); initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID));
this.checkForUpdates(); this.checkForUpdates();
@@ -197,19 +191,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@NotNull @NotNull
public List<Command> registerCommands() { public List<Command> registerCommands() {
return Arrays.stream(BukkitCommand.Type.values()) return BukkitCommand.Type.getCommands(this);
.map(type -> {
final Command command = type.getCommand();
if (settings.isCommandDisabled(command)) {
new BukkitCommand(new DisabledCommand(command.getName(), this), this).register();
return null;
} else {
new BukkitCommand(command, this).register();
return command;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
} }
@Override @Override
@@ -259,7 +241,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
} }
/** /**
* Returns the adventure Bukkit audiences * Returns the adventure Bukkit audiences.
* *
* @return The adventure Bukkit audiences * @return The adventure Bukkit audiences
*/ */
@@ -277,7 +259,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override @Override
public List<OnlineUser> getOnlineUsers() { public List<OnlineUser> getOnlineUsers() {
return Bukkit.getOnlinePlayers().stream() return Bukkit.getOnlinePlayers().stream()
.map(player -> (OnlineUser) BukkitUser.adapt(player)) .map(player -> (OnlineUser) BukkitUser.adapt(player, this))
.toList(); .toList();
} }
@@ -369,7 +351,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Update the world spawn location, too // Update the world spawn location, too
BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> { BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> {
assert bukkitLocation.getWorld() != null; assert bukkitLocation.getWorld() != null : "World was null when setting server spawn";
bukkitLocation.getWorld().setSpawnLocation(bukkitLocation); bukkitLocation.getWorld().setSpawnLocation(bukkitLocation);
}); });
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
@@ -451,14 +433,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
try { try {
final Metrics metrics = new Metrics(this, metricsId); final Metrics metrics = new Metrics(this, metricsId);
metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().doCrossServer()))); metrics.addCustomChart(new SimplePie("bungee_mode",
() -> Boolean.toString(getSettings().doCrossServer())));
if (getSettings().doCrossServer()) { if (getSettings().doCrossServer()) {
metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().getBrokerType().getDisplayName())); metrics.addCustomChart(new SimplePie("messenger_type",
() -> getSettings().getBrokerType().getDisplayName()));
} }
metrics.addCustomChart(new SimplePie("language", () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().getDisplayName())); metrics.addCustomChart(new SimplePie("language",
metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().doEconomy()))); () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook()))); metrics.addCustomChart(new SimplePie("database_type",
() -> getSettings().getDatabaseType().getDisplayName()));
metrics.addCustomChart(new SimplePie("using_economy",
() -> Boolean.toString(getSettings().doEconomy())));
metrics.addCustomChart(new SimplePie("using_map",
() -> Boolean.toString(getSettings().doMapHook())));
getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName))); getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName)));
} catch (Throwable e) { } catch (Throwable e) {
log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")");
@@ -467,8 +458,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override @Override
public void initializePluginChannels() { public void initializePluginChannels() {
Bukkit.getMessenger().registerIncomingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID, this); final String channelId = PluginMessageBroker.BUNGEE_CHANNEL_ID;
Bukkit.getMessenger().registerOutgoingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID); Bukkit.getMessenger().registerIncomingPluginChannel(this, channelId, this);
Bukkit.getMessenger().registerOutgoingPluginChannel(this, channelId);
} }
@Override @Override
@@ -483,8 +475,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override @Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) {
if (broker != null && broker instanceof PluginMessageBroker pluginMessenger if (broker != null && broker instanceof PluginMessageBroker pluginMessenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message); pluginMessenger.onReceive(channel, BukkitUser.adapt(player, this), message);
} }
} }
@@ -498,4 +490,5 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
public HuskHomes getPlugin() { public HuskHomes getPlugin() {
return this; return this;
} }
} }
@@ -28,6 +28,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.BukkitAdapter; import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -36,32 +37,53 @@ import java.util.Objects;
/** /**
* The HuskHomes API implementation for the Bukkit platform, providing methods to access player data, homes, warps * The HuskHomes API implementation for the Bukkit platform, providing methods to access player data, homes, warps
* and process teleports * and process teleports
* <p> *
* Retrieve an instance of the API class via {@link #getInstance()}. * <p>Retrieve an instance of the API class via {@link #getInstance()}.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class HuskHomesAPI extends BaseHuskHomesAPI { public class HuskHomesAPI extends BaseHuskHomesAPI {
/** // Instance of the plugin
* <b>(Internal use only)</b> - Instance of the API class
*/
private static HuskHomesAPI instance; private static HuskHomesAPI instance;
/** /**
* <b>(Internal use only)</b> - Constructor, instantiating the API * <b>(Internal use only)</b> - Constructor, instantiating the API.
*/ */
private HuskHomesAPI() { @ApiStatus.Internal
super(BukkitHuskHomes.getInstance()); private HuskHomesAPI(@NotNull BukkitHuskHomes plugin) {
super(plugin);
} }
/** /**
* Entrypoint to the HuskHomes API - returns an instance of the API * Get an instance of the HuskHomes API.
* *
* @return instance of the HuskHomes API * @return instance of the HuskHomes API
* @throws NotRegisteredException if the API has not yet been registered.
*/ */
@NotNull @NotNull
public static HuskHomesAPI getInstance() { public static HuskHomesAPI getInstance() throws NotRegisteredException {
return instance == null ? instance = new HuskHomesAPI() : instance; if (instance == null) {
throw new NotRegisteredException();
}
return instance;
}
/**
* <b>(Internal use only)</b> - Register the API for this platform.
*
* @param plugin the plugin instance
*/
@ApiStatus.Internal
public static void register(@NotNull BukkitHuskHomes plugin) {
instance = new HuskHomesAPI(plugin);
}
/**
* <b>(Internal use only)</b> - Unregister the API for this platform.
*/
@ApiStatus.Internal
public static void unregister() {
instance = null;
} }
/** /**
@@ -73,7 +95,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
*/ */
@NotNull @NotNull
public OnlineUser adaptUser(@NotNull Player player) { public OnlineUser adaptUser(@NotNull Player player) {
return BukkitUser.adapt(player); return BukkitUser.adapt(player, (BukkitHuskHomes) plugin);
} }
/** /**
@@ -101,7 +123,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
} }
/** /**
* Returns a {@link Location} instance for the given bukkit {@link Location}. * Returns a {@link Location} instance for the given bukkit {@link Location} on the server.
* *
* @param location the bukkit location to get the {@link Location} instance for * @param location the bukkit location to get the {@link Location} instance for
* @return the {@link Location} instance for the given bukkit {@link Location} * @return the {@link Location} instance for the given bukkit {@link Location}
@@ -113,7 +135,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
} }
/** /**
* Returns a {@link Position} instance for the given bukkit {@link Location} on the given {@link Server}. * Returns a {@link Position} instance for the given bukkit {@link Location} on the server.
* *
* @param location the bukkit location to get the {@link Position} instance for * @param location the bukkit location to get the {@link Position} instance for
* @param server the {@link Server} the position is on * @param server the {@link Server} the position is on
@@ -127,10 +149,10 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
} }
/** /**
* Returns a {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on. * Returns a {@link Position} instance for the given bukkit {@link Location} on the server.
* *
* @param location the bukkit location to get the {@link Position} instance for * @param location the bukkit location to get the {@link Position} instance for
* @return the {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on * @return the {@link Position} instance for the given {@link Location} on the server
* @since 4.0 * @since 4.0
*/ */
@NotNull @NotNull
@@ -139,9 +161,9 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
} }
/** /**
* Get the {@link Server}, containing the ID of the server the plugin is running on * Get the name of this server.
* *
* @return the {@link Server} * @return the server name
* @since 4.0 * @since 4.0
*/ */
@NotNull @NotNull
@@ -31,25 +31,28 @@ import java.util.logging.Level;
public class BrigadierUtil { public class BrigadierUtil {
/** /**
* Uses commodore to register command completions * Uses commodore to register command completions.
* *
* @param plugin instance of the registering Bukkit plugin * @param plugin instance of the registering Bukkit plugin
* @param bukkitCommand the Bukkit PluginCommand to register completions for * @param bukkitCommand the Bukkit PluginCommand to register completions for
* @param command the {@link Command} to register completions for * @param command the {@link Command} to register completions for
*/ */
protected static void registerCommodore(@NotNull BukkitHuskHomes plugin, @NotNull org.bukkit.command.Command bukkitCommand, protected static void registerCommodore(@NotNull BukkitHuskHomes plugin,
@NotNull org.bukkit.command.Command bukkitCommand,
@NotNull Command command) { @NotNull Command command) {
final InputStream commandCommodore = plugin.getResource("commodore/" + bukkitCommand.getName() + ".commodore"); final InputStream commodoreFile = plugin.getResource(
if (commandCommodore == null) { "commodore/" + bukkitCommand.getName() + ".commodore"
);
if (commodoreFile == null) {
return; return;
} }
try { try {
CommodoreProvider.getCommodore(plugin).register(bukkitCommand, CommodoreProvider.getCommodore(plugin).register(bukkitCommand,
CommodoreFileReader.INSTANCE.parse(commandCommodore), CommodoreFileReader.INSTANCE.parse(commodoreFile),
player -> player.hasPermission(command.getPermission())); player -> player.hasPermission(command.getPermission()));
} catch (IOException e) { } catch (IOException e) {
plugin.log(Level.SEVERE, "Failed to read command commodore completions for " plugin.log(Level.SEVERE, "Failed to read command commodore completions for "
+ bukkitCommand.getName(), e); + bukkitCommand.getName(), e);
} }
} }
@@ -21,6 +21,7 @@ package net.william278.huskhomes.command;
import me.lucko.commodore.CommodoreProvider; import me.lucko.commodore.CommodoreProvider;
import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.CommandUser;
@@ -36,6 +37,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.*;
import java.util.function.Function;
public class BukkitCommand implements CommandExecutor, TabCompleter { public class BukkitCommand implements CommandExecutor, TabCompleter {
@@ -50,7 +52,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
@Override @Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command, public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command,
@NotNull String label, @NotNull String[] args) { @NotNull String label, @NotNull String[] args) {
this.command.onExecuted(sender instanceof Player player ? BukkitUser.adapt(player) : plugin.getConsole(), args); this.command.onExecuted(sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole(), args);
return true; return true;
} }
@@ -61,7 +63,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
if (!(this.command instanceof TabProvider provider)) { if (!(this.command instanceof TabProvider provider)) {
return List.of(); return List.of();
} }
final CommandUser user = sender instanceof Player player ? BukkitUser.adapt(player) : plugin.getConsole(); final CommandUser user = sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole();
return provider.getSuggestions(user, args); return provider.getSuggestions(user, args);
} }
@@ -73,7 +75,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
} }
// Register permissions // Register permissions
addPermission(plugin, command.getPermission(), command.getUsage(), getPermissionDefault(command.isOperatorCommand())); addPermission(
plugin,
command.getPermission(),
command.getUsage(),
getPermissionDefault(command.isOperatorCommand())
);
final List<Permission> childNodes = command.getAdditionalPermissions() final List<Permission> childNodes = command.getAdditionalPermissions()
.entrySet().stream() .entrySet().stream()
.map((entry) -> addPermission(plugin, entry.getKey(), "", getPermissionDefault(entry.getValue()))) .map((entry) -> addPermission(plugin, entry.getKey(), "", getPermissionDefault(entry.getValue())))
@@ -81,7 +88,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
.toList(); .toList();
if (!childNodes.isEmpty()) { if (!childNodes.isEmpty()) {
addPermission(plugin, command.getPermission("*"), command.getUsage(), PermissionDefault.FALSE, addPermission(plugin, command.getPermission("*"), command.getUsage(), PermissionDefault.FALSE,
childNodes.toArray(new Permission[0])); childNodes.toArray((plugin) -> new Permission[0]));
} }
// Set command parameters // Set command parameters
@@ -97,8 +104,9 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
} }
@Nullable @Nullable
protected static Permission addPermission(@NotNull BukkitHuskHomes plugin, @NotNull String node, @NotNull String description, protected static Permission addPermission(@NotNull BukkitHuskHomes plugin, @NotNull String node,
@NotNull PermissionDefault permissionDefault, @NotNull Permission... children) { @NotNull String description, @NotNull PermissionDefault permissionDefault,
@NotNull Permission... children) {
final Map<String, Boolean> childNodes = Arrays.stream(children) final Map<String, Boolean> childNodes = Arrays.stream(children)
.map(Permission::getName) .map(Permission::getName)
.collect(HashMap::new, (map, child) -> map.put(child, true), HashMap::putAll); .collect(HashMap::new, (map, child) -> map.put(child, true), HashMap::putAll);
@@ -125,46 +133,62 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
} }
/** /**
* Commands available on the Bukkit HuskHomes implementation * Commands available on the Bukkit HuskHomes implementation.
*/ */
public enum Type { public enum Type {
HOME_COMMAND(new PrivateHomeCommand(BukkitHuskHomes.getInstance())), HOME_COMMAND(PrivateHomeCommand::new),
SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())), SET_HOME_COMMAND(SetHomeCommand::new),
HOME_LIST_COMMAND(new PrivateHomeListCommand(BukkitHuskHomes.getInstance())), HOME_LIST_COMMAND(PrivateHomeListCommand::new),
DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())), DEL_HOME_COMMAND(DelHomeCommand::new),
EDIT_HOME_COMMAND(new EditHomeCommand(BukkitHuskHomes.getInstance())), EDIT_HOME_COMMAND(EditHomeCommand::new),
PUBLIC_HOME_COMMAND(new PublicHomeCommand(BukkitHuskHomes.getInstance())), PUBLIC_HOME_COMMAND(PublicHomeCommand::new),
PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(BukkitHuskHomes.getInstance())), PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new),
WARP_COMMAND(new WarpCommand(BukkitHuskHomes.getInstance())), WARP_COMMAND(WarpCommand::new),
SET_WARP_COMMAND(new SetWarpCommand(BukkitHuskHomes.getInstance())), SET_WARP_COMMAND(SetWarpCommand::new),
WARP_LIST_COMMAND(new WarpListCommand(BukkitHuskHomes.getInstance())), WARP_LIST_COMMAND(WarpListCommand::new),
DEL_WARP_COMMAND(new DelWarpCommand(BukkitHuskHomes.getInstance())), DEL_WARP_COMMAND(DelWarpCommand::new),
EDIT_WARP_COMMAND(new EditWarpCommand(BukkitHuskHomes.getInstance())), EDIT_WARP_COMMAND(EditWarpCommand::new),
TP_COMMAND(new TpCommand(BukkitHuskHomes.getInstance())), TP_COMMAND(TpCommand::new),
TP_HERE_COMMAND(new TpHereCommand(BukkitHuskHomes.getInstance())), TP_HERE_COMMAND(TpHereCommand::new),
TPA_COMMAND(new TeleportRequestCommand(BukkitHuskHomes.getInstance(), TeleportRequest.Type.TPA)), TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)),
TPA_HERE_COMMAND(new TeleportRequestCommand(BukkitHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)), TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)),
TPACCEPT_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), true)), TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)),
TPDECLINE_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), false)), TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)),
RTP_COMMAND(new RtpCommand(BukkitHuskHomes.getInstance())), RTP_COMMAND(RtpCommand::new),
TP_IGNORE_COMMAND(new TpIgnoreCommand(BukkitHuskHomes.getInstance())), TP_IGNORE_COMMAND(TpIgnoreCommand::new),
TP_OFFLINE_COMMAND(new TpOfflineCommand(BukkitHuskHomes.getInstance())), TP_OFFLINE_COMMAND(TpOfflineCommand::new),
TP_ALL_COMMAND(new TpAllCommand(BukkitHuskHomes.getInstance())), TP_ALL_COMMAND(TpAllCommand::new),
TPA_ALL_COMMAND(new TpaAllCommand(BukkitHuskHomes.getInstance())), TPA_ALL_COMMAND(TpaAllCommand::new),
SPAWN_COMMAND(new SpawnCommand(BukkitHuskHomes.getInstance())), SPAWN_COMMAND(SpawnCommand::new),
SET_SPAWN_COMMAND(new SetSpawnCommand(BukkitHuskHomes.getInstance())), SET_SPAWN_COMMAND(SetSpawnCommand::new),
BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance())), BACK_COMMAND(BackCommand::new),
HUSKHOMES_COMMAND(new HuskHomesCommand(BukkitHuskHomes.getInstance())); HUSKHOMES_COMMAND(HuskHomesCommand::new);
private final Command command; private final Function<HuskHomes, Command> supplier;
Type(@NotNull Command command) { Type(@NotNull Function<HuskHomes, Command> supplier) {
this.command = command; this.supplier = supplier;
} }
@NotNull @NotNull
public Command getCommand() { public Command createCommand(@NotNull HuskHomes plugin) {
return command; return supplier.apply(plugin);
} }
@NotNull
public static List<Command> getCommands(@NotNull BukkitHuskHomes plugin) {
return Arrays.stream(values())
.map((type) -> {
Command command = type.createCommand(plugin);
if (plugin.getSettings().isCommandDisabled(command)) {
command = new DisabledCommand(command.getName(), plugin);
}
new BukkitCommand(command, plugin).register();
return command;
})
.filter((command) -> !(command instanceof DisabledCommand))
.toList();
}
} }
} }
@@ -36,83 +36,90 @@ import java.util.List;
public interface BukkitEventDispatcher extends EventDispatcher { public interface BukkitEventDispatcher extends EventDispatcher {
@Override @Override
default <T extends Event> boolean fireIsCancelled(@NotNull T event) { default <T extends Event> @NotNull boolean fireIsCancelled(@NotNull T event) {
Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event); Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event);
return event instanceof Cancellable cancellable && cancellable.isCancelled(); return event instanceof Cancellable cancellable && cancellable.isCancelled();
} }
@Override @Override
@NotNull
default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) {
return teleport.getType() == Teleport.Type.BACK ? new TeleportBackEvent(teleport) : new TeleportEvent(teleport); return teleport.getType() == Teleport.Type.BACK ? new TeleportBackEvent(teleport) : new TeleportEvent(teleport);
} }
@Override @Override
default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
return new TeleportWarmupEvent(teleport, duration); return new TeleportWarmupEvent(teleport, duration);
} }
@Override @Override
default ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) { default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender,
@NotNull TeleportRequest request) {
return new SendTeleportRequestEvent(sender, request); return new SendTeleportRequestEvent(sender, request);
} }
@Override @Override
default IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request) {
return new ReceiveTeleportRequestEvent(recipient, request); return new ReceiveTeleportRequestEvent(recipient, request);
} }
@Override @Override
default IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request) {
return new ReplyTeleportRequestEvent(recipient, request); return new ReplyTeleportRequestEvent(recipient, request);
} }
@Override @Override
default IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) { default @NotNull IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name,
@NotNull Position position, @NotNull CommandUser creator) {
return new HomeCreateEvent(owner, name, position, creator); return new HomeCreateEvent(owner, name, position, creator);
} }
@Override @Override
default IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) {
return new HomeEditEvent(home, editor); return new HomeEditEvent(home, editor);
} }
@Override @Override
default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) {
return new HomeDeleteEvent(home, deleter); return new HomeDeleteEvent(home, deleter);
} }
@Override @Override
default IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator) { default @NotNull IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position,
@NotNull CommandUser creator) {
return new WarpCreateEvent(name, position, creator); return new WarpCreateEvent(name, position, creator);
} }
@Override @Override
default IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) {
return new WarpEditEvent(warp, editor); return new WarpEditEvent(warp, editor);
} }
@Override @Override
default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) {
return new WarpDeleteEvent(warp, deleter); return new WarpDeleteEvent(warp, deleter);
} }
@Override @Override
default IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList) { default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer,
boolean publicHomeList) {
return new HomeListEvent(homes, listViewer, publicHomeList); return new HomeListEvent(homes, listViewer, publicHomeList);
} }
@Override @Override
default IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> warps, @NotNull CommandUser listViewer) { default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> warps, @NotNull CommandUser listViewer) {
return new WarpListEvent(warps, listViewer); return new WarpListEvent(warps, listViewer);
} }
@Override @Override
default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) {
return new DeleteAllHomesEvent(user, deleter); return new DeleteAllHomesEvent(user, deleter);
} }
@Override @Override
default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { default @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) {
return new DeleteAllWarpsEvent(deleter); return new DeleteAllWarpsEvent(deleter);
} }
@@ -37,7 +37,8 @@ public class HomeCreateEvent extends Event implements IHomeCreateEvent, Cancella
private final CommandUser creator; private final CommandUser creator;
private boolean cancelled; private boolean cancelled;
public HomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) { public HomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position,
@NotNull CommandUser creator) {
this.owner = owner; this.owner = owner;
this.name = name; this.name = name;
this.position = position; this.position = position;
@@ -21,7 +21,7 @@ package net.william278.huskhomes.hook;
import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.PlaceholderAPIPlugin;
import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.SavedUser;
@@ -33,21 +33,21 @@ import java.util.List;
public class PlaceholderAPIHook extends Hook { public class PlaceholderAPIHook extends Hook {
public PlaceholderAPIHook(@NotNull HuskHomes plugin) { public PlaceholderAPIHook(@NotNull BukkitHuskHomes plugin) {
super(plugin, "PlaceholderAPI"); super(plugin, "PlaceholderAPI");
} }
@Override @Override
public void initialize() { public void initialize() {
new HuskHomesExpansion(plugin).register(); new HuskHomesExpansion((BukkitHuskHomes) plugin).register();
} }
public static class HuskHomesExpansion extends PlaceholderExpansion { public static class HuskHomesExpansion extends PlaceholderExpansion {
@NotNull @NotNull
private final HuskHomes plugin; private final BukkitHuskHomes plugin;
private HuskHomesExpansion(@NotNull HuskHomes plugin) { private HuskHomesExpansion(@NotNull BukkitHuskHomes plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@@ -59,7 +59,7 @@ public class PlaceholderAPIHook extends Hook {
} }
// Return the requested data // Return the requested data
final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer()); final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer(), plugin);
return switch (params) { return switch (params) {
case "homes_count" -> String.valueOf(plugin.getManager().homes() case "homes_count" -> String.valueOf(plugin.getManager().homes()
.getUserHomes() .getUserHomes()
@@ -29,7 +29,7 @@ import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* A hook that hooks into the Vault API to provide economy features * A hook that hooks into the Vault API to provide economy features.
*/ */
public class VaultEconomyHook extends EconomyHook { public class VaultEconomyHook extends EconomyHook {
@@ -38,7 +38,8 @@ public class EssentialsXImporter extends Importer {
public EssentialsXImporter(@NotNull HuskHomes plugin) { public EssentialsXImporter(@NotNull HuskHomes plugin) {
super("EssentialsX", List.of(ImportData.HOMES, ImportData.WARPS), plugin); super("EssentialsX", List.of(ImportData.HOMES, ImportData.WARPS), plugin);
this.essentials = (Essentials) ((BukkitHuskHomes) plugin).getServer().getPluginManager().getPlugin("Essentials"); this.essentials = (Essentials) ((BukkitHuskHomes) plugin).getServer()
.getPluginManager().getPlugin("Essentials");
} }
private int importHomes() { private int importHomes() {
@@ -38,24 +38,24 @@ public class BukkitEventListener extends EventListener implements Listener {
protected boolean checkForBed = true; protected boolean checkForBed = true;
public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) { public BukkitEventListener(@NotNull BukkitHuskHomes plugin) {
super(huskHomes); super(plugin);
huskHomes.getServer().getPluginManager().registerEvents(this, huskHomes); plugin.getServer().getPluginManager().registerEvents(this, plugin);
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer())); super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin));
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerLeave(PlayerQuitEvent event) { public void onPlayerLeave(PlayerQuitEvent event) {
super.handlePlayerLeave(BukkitUser.adapt(event.getPlayer())); super.handlePlayerLeave(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin));
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) { public void onPlayerDeath(PlayerDeathEvent event) {
super.handlePlayerDeath(BukkitUser.adapt(event.getEntity())); super.handlePlayerDeath(BukkitUser.adapt(event.getEntity(), (BukkitHuskHomes) plugin));
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
@@ -63,7 +63,7 @@ public class BukkitEventListener extends EventListener implements Listener {
if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) { if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) {
return; return;
} }
super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer())); super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin));
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@@ -71,29 +71,37 @@ public class BukkitEventListener extends EventListener implements Listener {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
// Return if the disconnecting entity is a Citizens NPC, or if the teleport was naturally caused // Return if the disconnecting entity is a Citizens NPC, or if the teleport was naturally caused
if (player.hasMetadata("NPC")) return; if (player.hasMetadata("NPC")) {
return;
}
if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND
|| event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) return; || event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) {
return;
}
final BukkitUser bukkitUser = BukkitUser.adapt(player); final BukkitUser bukkitUser = BukkitUser.adapt(player, (BukkitHuskHomes) plugin);
BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation -> BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation ->
handlePlayerTeleport(bukkitUser, Position.at(sourceLocation, plugin.getServerName()))); handlePlayerTeleport(bukkitUser, Position.at(sourceLocation, plugin.getServerName())));
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) { public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) {
if (!checkForBed) return; if (!checkForBed || !(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) {
if (!(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) return; return;
if (event.getClickedBlock() == null) return; }
if (!(event.getClickedBlock().getBlockData() instanceof Bed if (event.getClickedBlock() == null || !(event.getClickedBlock().getBlockData() instanceof Bed
|| event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return; || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) {
return;
}
final Location location = event.getPlayer().getBedSpawnLocation(); final Location location = event.getPlayer().getBedSpawnLocation();
if (location == null) return; if (location == null) {
return;
}
// Update the player's respawn location // Update the player's respawn location
BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> super.handlePlayerUpdateSpawnPoint( BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> super.handlePlayerUpdateSpawnPoint(
BukkitUser.adapt(event.getPlayer()), BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin),
Position.at(adaptedLocation, plugin.getServerName())) Position.at(adaptedLocation, plugin.getServerName()))
); );
} }
@@ -38,34 +38,45 @@ import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* Bukkit implementation of an {@link OnlineUser} * Bukkit's implementation of an {@link OnlineUser}.
*/ */
public class BukkitUser extends OnlineUser { public class BukkitUser extends OnlineUser {
private final BukkitHuskHomes plugin; private final BukkitHuskHomes plugin;
private final Player player; private final Player player;
private BukkitUser(@NotNull Player player) { private BukkitUser(@NotNull Player player, @NotNull BukkitHuskHomes plugin) {
super(player.getUniqueId(), player.getName()); super(player.getUniqueId(), player.getName());
this.plugin = BukkitHuskHomes.getInstance();
this.player = player; this.player = player;
this.plugin = plugin;
} }
/** /**
* Adapt a {@link Player} to a {@link OnlineUser} * Adapt a {@link Player} to a {@link OnlineUser}.
* *
* @param player the online {@link Player} to adapt * @param player the online {@link Player} to adapt
* @return the adapted {@link OnlineUser} * @return the adapted {@link OnlineUser}
*/ */
@NotNull @NotNull
public static BukkitUser adapt(@NotNull Player player) { public static BukkitUser adapt(@NotNull Player player, @NotNull BukkitHuskHomes plugin) {
return new BukkitUser(player); return new BukkitUser(player, plugin);
}
/**
* Return the {@link Player} wrapped by this {@link BukkitUser}.
*
* @return the {@link Player} wrapped by this {@link BukkitUser}
*/
@NotNull
public Player getPlayer() {
return player;
} }
@Override @Override
public Position getPosition() { public Position getPosition() {
return Position.at(BukkitAdapter.adaptLocation(player.getLocation()) return Position.at(BukkitAdapter.adaptLocation(player.getLocation()).orElseThrow(
.orElseThrow(() -> new IllegalStateException("Failed to get the position of a BukkitPlayer (null)")), () -> new IllegalStateException("Failed to get the position of a BukkitPlayer (null)")
),
plugin.getServerName()); plugin.getServerName());
} }
@@ -104,7 +115,7 @@ public class BukkitUser extends OnlineUser {
} }
@Override @Override
public void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException { public void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException {
// Ensure the world exists // Ensure the world exists
final Optional<org.bukkit.Location> resolvedLocation = BukkitAdapter.adaptLocation(location); final Optional<org.bukkit.Location> resolvedLocation = BukkitAdapter.adaptLocation(location);
if (resolvedLocation.isEmpty() || resolvedLocation.get().getWorld() == null) { if (resolvedLocation.isEmpty() || resolvedLocation.get().getWorld() == null) {
@@ -120,7 +131,7 @@ public class BukkitUser extends OnlineUser {
// Run on the appropriate thread scheduler for this platform // Run on the appropriate thread scheduler for this platform
plugin.getScheduler().entitySpecificScheduler(player).run( plugin.getScheduler().entitySpecificScheduler(player).run(
() -> { () -> {
if (asynchronous || plugin.getScheduler().isUsingFolia()) { if (async || plugin.getScheduler().isUsingFolia()) {
PaperLib.teleportAsync(player, bukkitLocation, PlayerTeleportEvent.TeleportCause.PLUGIN); PaperLib.teleportAsync(player, bukkitLocation, PlayerTeleportEvent.TeleportCause.PLUGIN);
return; return;
} }
@@ -131,7 +142,7 @@ public class BukkitUser extends OnlineUser {
} }
/** /**
* Get the player momentum and return if they are moving * Get the player momentum and return if they are moving.
* *
* @return {@code true} if the player is moving, {@code false} otherwise * @return {@code true} if the player is moving, {@code false} otherwise
**/ **/
@@ -141,7 +152,7 @@ public class BukkitUser extends OnlineUser {
} }
/** /**
* Return the value of the player's "vanished" metadata tag if they have it * Return the value of the player's "vanished" metadata tag if they have it.
* *
* @return {@code true} if the player is vanished, {@code false} otherwise * @return {@code true} if the player is vanished, {@code false} otherwise
*/ */
@@ -155,18 +166,10 @@ public class BukkitUser extends OnlineUser {
} }
/** /**
* Send a Bukkit plugin message to the player * Send a Bukkit plugin message to the player.
*/ */
public void sendPluginMessage(@NotNull String channel, final byte[] message) { public void sendPluginMessage(@NotNull String channel, final byte[] message) {
player.sendPluginMessage(plugin, channel, message); player.sendPluginMessage(plugin, channel, message);
} }
/**
* Return the {@link Player} wrapped by this {@link BukkitUser}
*
* @return the {@link Player} wrapped by this {@link BukkitUser}
*/
public Player getPlayer() {
return player;
}
} }
@@ -28,12 +28,12 @@ import org.jetbrains.annotations.Nullable;
import java.util.Optional; import java.util.Optional;
/** /**
* Static class providing utility methods for adapting Bukkit objects to HuskHomes and vice versa * Static class providing utility methods for adapting Bukkit objects to HuskHomes and vice versa.
*/ */
public final class BukkitAdapter { public final class BukkitAdapter {
/** /**
* Adapt a Bukkit {@link org.bukkit.Location} to a HuskHomes {@link Location} * Adapt a Bukkit {@link org.bukkit.Location} to a HuskHomes {@link Location}.
* *
* @param location the Bukkit {@link org.bukkit.Location} to adapt * @param location the Bukkit {@link org.bukkit.Location} to adapt
* @return the adapted {@link Location} * @return the adapted {@link Location}
@@ -45,8 +45,9 @@ public final class BukkitAdapter {
} }
if (world == null) { if (world == null) {
world = Bukkit.getWorlds().stream() world = Bukkit.getWorlds().stream()
.filter(w -> w.getEnvironment().name().equalsIgnoreCase(location.getWorld().getEnvironment().name())) .filter(w -> w.getEnvironment().name().equalsIgnoreCase(
.findFirst().orElse(null); location.getWorld().getEnvironment().name())).findFirst()
.orElse(null);
} }
if (world == null) { if (world == null) {
return Optional.empty(); return Optional.empty();
@@ -62,13 +63,15 @@ public final class BukkitAdapter {
} }
/** /**
* Adapt a HuskHomes {@link org.bukkit.Location} to a Bukkit {@link org.bukkit.Location} * Adapt a HuskHomes {@link org.bukkit.Location} to a Bukkit {@link org.bukkit.Location}.
* *
* @param location the HuskHomes {@link org.bukkit.Location} to adapt * @param location the HuskHomes {@link org.bukkit.Location} to adapt
* @return the adapted {@link org.bukkit.Location} * @return the adapted {@link org.bukkit.Location}
*/ */
public static Optional<Location> adaptLocation(@NotNull org.bukkit.Location location) { public static Optional<Location> adaptLocation(@NotNull org.bukkit.Location location) {
if (location.getWorld() == null) return Optional.empty(); if (location.getWorld() == null) {
return Optional.empty();
}
return Optional.of(Location.at(location.getX(), location.getY(), location.getZ(), return Optional.of(Location.at(location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch(), location.getYaw(), location.getPitch(),
adaptWorld(location.getWorld()).orElse(new net.william278.huskhomes.position.World()))); adaptWorld(location.getWorld()).orElse(new net.william278.huskhomes.position.World())));
@@ -78,12 +81,13 @@ public final class BukkitAdapter {
if (world == null) { if (world == null) {
return Optional.empty(); return Optional.empty();
} }
return Optional.of(World.from(world.getName(), world.getUID(), return Optional.of(World.from(
world.getName(), world.getUID(),
switch (world.getEnvironment()) { switch (world.getEnvironment()) {
case NORMAL -> World.Environment.OVERWORLD; case NORMAL -> World.Environment.OVERWORLD;
case NETHER -> World.Environment.NETHER; case NETHER -> World.Environment.NETHER;
case THE_END -> World.Environment.THE_END; case THE_END -> World.Environment.THE_END;
case CUSTOM -> World.Environment.CUSTOM; default -> World.Environment.CUSTOM;
}) })
); );
} }
@@ -54,49 +54,50 @@ public interface BukkitSafetyResolver extends SafetyResolver {
} }
/** /**
* Search for a safe ground location near the given location * Search for a safe ground location near the given location.
* *
* @param location The location to search around * @param location The location to search around
* @param snapshot The chunk snapshot to search * @param chunk The chunk snapshot to search
* @param minY The minimum Y value of the world * @param minY The minimum Y value of the world
* @return An optional safe location, within 4 blocks of the given location * @return An optional safe location, within 4 blocks of the given location
*/ */
private Optional<Location> findSafeLocationNear(@NotNull Location location, @NotNull ChunkSnapshot snapshot, int minY) { private Optional<Location> findSafeLocationNear(@NotNull Location location, @NotNull ChunkSnapshot chunk,
int minY) {
final int chunkX = ((int) location.getX()) & 0xF; final int chunkX = ((int) location.getX()) & 0xF;
final int chunkZ = ((int) location.getZ()) & 0xF; final int chunkZ = ((int) location.getZ()) & 0xF;
for (int dX = -SEARCH_RADIUS; dX <= SEARCH_RADIUS; dX++) { for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
for (int dZ = -SEARCH_RADIUS; dZ <= SEARCH_RADIUS; dZ++) { for (int dz = -SEARCH_RADIUS; dz <= SEARCH_RADIUS; dz++) {
final int x = chunkX + dX; final int x = chunkX + dx;
final int z = chunkZ + dZ; final int z = chunkZ + dz;
if (x < 0 || x >= 16 || z < 0 || z >= 16) { if (x < 0 || x >= 16 || z < 0 || z >= 16) {
continue; continue;
} }
final int y = Math.max((minY + 1), snapshot.getHighestBlockYAt(x, z)) + 1; final int y = Math.max((minY + 1), chunk.getHighestBlockYAt(x, z)) + 1;
final Material blockType = snapshot.getBlockType(x, y - 1, z); final Material blockType = chunk.getBlockType(x, y - 1, z);
final Material bodyBlockType = snapshot.getBlockType(x, y, z); final Material bodyBlockType = chunk.getBlockType(x, y, z);
final Material headBlockType = snapshot.getBlockType(x, y + 1, z); final Material headBlockType = chunk.getBlockType(x, y + 1, z);
if (isBlockSafeForStanding(blockType.getKey().toString()) if (isBlockSafeForStanding(blockType.getKey().toString())
&& isBlockSafeForOccupation(bodyBlockType.getKey().toString()) && isBlockSafeForOccupation(bodyBlockType.getKey().toString())
&& isBlockSafeForOccupation(headBlockType.getKey().toString())) { && isBlockSafeForOccupation(headBlockType.getKey().toString())) {
double locx = Math.floor(location.getX()) + dX; double locx = Math.floor(location.getX()) + dx;
if (locx < 0) { if (locx < 0) {
locx += 1.5d; locx += 1.5d;
} else { } else {
locx = locx + 0.5d; locx = locx + 0.5d;
} }
double locz = Math.floor(location.getZ()) + dZ; double locz = Math.floor(location.getZ()) + dz;
if (locz < 0) { if (locz < 0) {
locz += 1.5d; locz += 1.5d;
} else { } else {
locz = locz + 0.5d; locz = locz + 0.5d;
} }
return Optional.of(Location.at( return Optional.of(Location.at(
locx, locx,
y, y,
locz, locz,
location.getWorld() location.getWorld()
)); ));
} }
} }
} }
@@ -77,7 +77,7 @@ public class BukkitPluginTests {
@DisplayName("Test Command Registration") @DisplayName("Test Command Registration")
public void testCommandRegistration() { public void testCommandRegistration() {
for (BukkitCommand.Type command : BukkitCommand.Type.values()) { for (BukkitCommand.Type command : BukkitCommand.Type.values()) {
Assertions.assertNotNull(plugin.getCommand(command.getCommand().getName())); Assertions.assertNotNull(plugin.getCommand(command.createCommand(plugin).getName()));
} }
Assertions.assertEquals(BukkitCommand.Type.values().length, plugin.getCommands().size()); Assertions.assertEquals(BukkitCommand.Type.values().length, plugin.getCommands().size());
} }
@@ -86,7 +86,7 @@ public class BukkitPluginTests {
@DisplayName("Test Player Adapter") @DisplayName("Test Player Adapter")
public void testPlayerAdaption() { public void testPlayerAdaption() {
PlayerMock player = server.addPlayer(); PlayerMock player = server.addPlayer();
Assertions.assertNotNull(BukkitUser.adapt(player)); Assertions.assertNotNull(BukkitUser.adapt(player, plugin));
} }
} }
@@ -105,22 +105,22 @@ public class BukkitPluginTests {
.orElseThrow(() -> new IllegalStateException("Failed to load locale")); .orElseThrow(() -> new IllegalStateException("Failed to load locale"));
final String simpleLocaleText = plugin.getLocales().getRawLocale("error_in_game_only") final String simpleLocaleText = plugin.getLocales().getRawLocale("error_in_game_only")
.orElseThrow(() -> new IllegalStateException("Failed to load raw locale")); .orElseThrow(() -> new IllegalStateException("Failed to load raw locale"));
BukkitUser.adapt(player).sendMessage(simpleLocale); BukkitUser.adapt(player, plugin).sendMessage(simpleLocale);
player.assertSaid(simpleLocaleText); player.assertSaid(simpleLocaleText);
} }
@Test @Test
@DisplayName("Test Message Dispatching") @DisplayName("Test Message Dispatching")
public void testMessageDispatching() { public void testMessageDispatching() {
PlayerMock player = server.addPlayer(); final BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin);
final MineDown locale = plugin.getLocales() final MineDown locale = plugin.getLocales()
.getLocale("teleporting_action_bar_warmup", Integer.toString(3)) .getLocale("teleporting_action_bar_warmup", Integer.toString(3))
.orElseThrow(() -> new IllegalStateException("Failed to load locale")); .orElseThrow(() -> new IllegalStateException("Failed to load locale"));
BukkitUser.adapt(player).sendActionBar(locale); user.sendActionBar(locale);
BukkitUser.adapt(player).sendMessage(locale); user.sendMessage(locale);
BukkitUser.adapt(player).sendTitle(locale, false); user.sendTitle(locale, false);
BukkitUser.adapt(player).sendTitle(locale, true); user.sendTitle(locale, true);
} }
@Test @Test
@@ -135,11 +135,11 @@ public class BukkitPluginTests {
@DisplayName("Test Locale Parsing") @DisplayName("Test Locale Parsing")
public void testLocaleParsing() { public void testLocaleParsing() {
final Map<String, String> rawLocales = plugin.getLocales().rawLocales; final Map<String, String> rawLocales = plugin.getLocales().rawLocales;
BukkitUser bukkitUser = BukkitUser.adapt(server.addPlayer()); BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin);
rawLocales.forEach((key, value) -> { rawLocales.forEach((key, value) -> {
Optional<MineDown> locale = plugin.getLocales().getLocale(key); Optional<MineDown> locale = plugin.getLocales().getLocale(key);
Assertions.assertTrue(locale.isPresent()); Assertions.assertTrue(locale.isPresent());
bukkitUser.sendMessage(locale.get()); user.sendMessage(locale.get());
}); });
} }
@@ -174,7 +174,7 @@ public class BukkitPluginTests {
final PlayerMock player = server.addPlayer(); final PlayerMock player = server.addPlayer();
player.setOp(true); player.setOp(true);
final BukkitUser playerUser = BukkitUser.adapt(player); final BukkitUser playerUser = BukkitUser.adapt(player, plugin);
return commands.stream() return commands.stream()
.flatMap(command -> Stream.of(Arguments.of(command, playerUser, command.getName()))); .flatMap(command -> Stream.of(Arguments.of(command, playerUser, command.getName())));
} }
@@ -194,14 +194,18 @@ public class BukkitPluginTests {
@DisplayName("Test Validator Accepts Valid Names") @DisplayName("Test Validator Accepts Valid Names")
@ParameterizedTest(name = "Valid Name: \"{0}\"") @ParameterizedTest(name = "Valid Name: \"{0}\"")
@ValueSource(strings = {"ValidName", "Valid_Name", "Valid-Name", "ValidN4me", "ValidName123", "ValidName-123", "ValidName_123", "V"}) @ValueSource(strings = {
"ValidName", "Valid_Name", "Valid-Name", "ValidN4me", "ValidName123", "VN-123", "ValidName_123", "V"
})
public void testValidNameIsValid(@NotNull String name) { public void testValidNameIsValid(@NotNull String name) {
Assertions.assertTrue(plugin.getValidator().isValidName(name)); Assertions.assertTrue(plugin.getValidator().isValidName(name));
} }
@DisplayName("Test Validator Rejects Invalid Names") @DisplayName("Test Validator Rejects Invalid Names")
@ParameterizedTest(name = "Invalid Name: \"{0}\"") @ParameterizedTest(name = "Invalid Name: \"{0}\"")
@ValueSource(strings = {"Invalid Name", "•♣♠", "Invali♣Name", "Invalid.Name", "", " ", "\0", "InvalidName12345678901234567890"}) @ValueSource(strings = {
"Invalid Name", "•♣♠", "Invali♣Name", "Invalid.Name", "", " ", "\0", "InvalidName12345678901234567890"
})
public void testInvalidNameIsInvalid(@NotNull String name) { public void testInvalidNameIsInvalid(@NotNull String name) {
Assertions.assertFalse(plugin.getValidator().isValidName(name)); Assertions.assertFalse(plugin.getValidator().isValidName(name));
} }
@@ -212,8 +216,8 @@ public class BukkitPluginTests {
"Lorem ipsum text", "Lorem ipsum text with special characters •♣♠", "Lorem ipsum text", "Lorem ipsum text with special characters •♣♠",
"Lorem ipsum text with special characters •♣♠ and numbers 1234567890", "Lorem ipsum text with special characters •♣♠ and numbers 1234567890",
"Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace", "Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace",
"Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace and a very long" + "Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace and a very long"
" description that is 255 characters long and should be accepted by the validator" + " description that is 255 characters long and should be accepted by the validator"
}) })
public void testValidDescriptionIsValid(@NotNull String description) { public void testValidDescriptionIsValid(@NotNull String description) {
Assertions.assertTrue(plugin.getValidator().isValidDescription(description)); Assertions.assertTrue(plugin.getValidator().isValidDescription(description));
@@ -221,10 +225,12 @@ public class BukkitPluginTests {
@DisplayName("Test Validator Rejects Invalid Descriptions") @DisplayName("Test Validator Rejects Invalid Descriptions")
@ParameterizedTest(name = "Invalid Description: \"{0}\"") @ParameterizedTest(name = "Invalid Description: \"{0}\"")
@ValueSource(strings = {"Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace and" + @ValueSource(strings = {
"a very long description that is more than 256 characters long and should be rejected " + "Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace and"
"by the validator because it is far, far too long and thus exceeds the maximum length " + + "a very long description that is more than 256 characters long and should be rejected "
"of 255 characters that are allowed for a description of a home or a warp."}) + "by the validator because it is far, far too long and thus exceeds the maximum length "
+ "of 255 characters that are allowed for a description of a home or a warp."
})
public void testInvalidDescriptionIsInvalid(@NotNull String description) { public void testInvalidDescriptionIsInvalid(@NotNull String description) {
Assertions.assertFalse(plugin.getValidator().isValidDescription(description)); Assertions.assertFalse(plugin.getValidator().isValidDescription(description));
} }
@@ -241,7 +247,7 @@ public class BukkitPluginTests {
@BeforeAll @BeforeAll
public static void setup() { public static void setup() {
player = BukkitUser.adapt(server.addPlayer()); player = BukkitUser.adapt(server.addPlayer(), plugin);
} }
@DisplayName("Test Applying Cooldown") @DisplayName("Test Applying Cooldown")
@@ -283,7 +289,14 @@ public class BukkitPluginTests {
@DisplayName("Warp Tests") @DisplayName("Warp Tests")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class WarpTests { public class WarpTests {
private static final List<String> WARP_NAMES = List.of("warple", "example", "exmaination", "123234__44", "a", "1"); private static final List<String> WARP_NAMES = List.of(
"warple",
"example",
"exmaination",
"123234__44",
"a",
"1"
);
@DisplayName("Test Warp Creation") @DisplayName("Test Warp Creation")
@ParameterizedTest(name = "Warp Name: \"{0}\"") @ParameterizedTest(name = "Warp Name: \"{0}\"")
@@ -302,7 +315,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Rename: \"{0}\" > \"{0}2\"") @ParameterizedTest(name = "Rename: \"{0}\" > \"{0}2\"")
@MethodSource("provideWarpData") @MethodSource("provideWarpData")
@Order(2) @Order(2)
public void testWarpRenaming(@NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testWarpRenaming(@NotNull String name, @NotNull Position position) {
final String newName = (name + "2"); final String newName = (name + "2");
plugin.getManager().warps().setWarpName(name, newName); plugin.getManager().warps().setWarpName(name, newName);
Assertions.assertTrue(plugin.getDatabase().getWarp(newName).isPresent()); Assertions.assertTrue(plugin.getDatabase().getWarp(newName).isPresent());
@@ -322,7 +336,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Edit Description: \"{0}\"") @ParameterizedTest(name = "Edit Description: \"{0}\"")
@MethodSource("provideWarpData") @MethodSource("provideWarpData")
@Order(3) @Order(3)
public void testWarpChangingDescription(@NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testWarpChangingDescription(@NotNull String name, @NotNull Position position) {
final String description = "This is a test description for " + name + "."; final String description = "This is a test description for " + name + ".";
plugin.getManager().warps().setWarpDescription(name, description); plugin.getManager().warps().setWarpDescription(name, description);
final Optional<String> warpDescription = plugin.getDatabase().getWarp(name) final Optional<String> warpDescription = plugin.getDatabase().getWarp(name)
@@ -338,8 +353,11 @@ public class BukkitPluginTests {
@Order(4) @Order(4)
public void testWarpRelocation(@NotNull String name, @NotNull Position position) { public void testWarpRelocation(@NotNull String name, @NotNull Position position) {
final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow();
final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, final Position newPosition = Position.at(
0, 0, world, plugin.getServerName()); position.getX() + 10, position.getY() + 10, position.getZ() + 10,
0, 0,
world, plugin.getServerName()
);
plugin.getManager().warps().setWarpPosition(name, newPosition); plugin.getManager().warps().setWarpPosition(name, newPosition);
final Optional<Position> warpPosition = plugin.getDatabase().getWarp(name).map(warp -> warp); final Optional<Position> warpPosition = plugin.getDatabase().getWarp(name).map(warp -> warp);
@@ -355,8 +373,11 @@ public class BukkitPluginTests {
@Order(5) @Order(5)
public void testWarpOverwrite(@NotNull String name, @NotNull Position position) { public void testWarpOverwrite(@NotNull String name, @NotNull Position position) {
final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow();
final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, final Position newPosition = Position.at(
0, 0, world, plugin.getServerName()); position.getX() + 10, position.getY() + 10, position.getZ() + 10,
0, 0,
world, plugin.getServerName()
);
plugin.getManager().warps().createWarp(name, newPosition, true); plugin.getManager().warps().createWarp(name, newPosition, true);
final Optional<Position> warpPosition = plugin.getDatabase().getWarp(name).map(warp -> warp); final Optional<Position> warpPosition = plugin.getDatabase().getWarp(name).map(warp -> warp);
@@ -370,7 +391,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Delete Warp: \"{0}\"") @ParameterizedTest(name = "Delete Warp: \"{0}\"")
@MethodSource("provideWarpData") @MethodSource("provideWarpData")
@Order(6) @Order(6)
public void testWarpDeletion(@NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testWarpDeletion(@NotNull String name, @NotNull Position position) {
plugin.getManager().warps().deleteWarp(name); plugin.getManager().warps().deleteWarp(name);
Assertions.assertFalse(plugin.getDatabase().getWarp(name).isPresent()); Assertions.assertFalse(plugin.getDatabase().getWarp(name).isPresent());
Assertions.assertFalse(plugin.getManager().warps() Assertions.assertFalse(plugin.getManager().warps()
@@ -385,7 +407,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Query: \"{0}\"") @ParameterizedTest(name = "Query: \"{0}\"")
@MethodSource("provideWarpData") @MethodSource("provideWarpData")
@Order(8) @Order(8)
public void testWarpCaseInsensitiveQuery(@NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testWarpCaseInsensitiveQuery(@NotNull String name, @NotNull Position position) {
final String nameUpper = name.toUpperCase(); final String nameUpper = name.toUpperCase();
final Optional<Warp> nameUpperWarp = plugin.getDatabase().getWarp(nameUpper, true); final Optional<Warp> nameUpperWarp = plugin.getDatabase().getWarp(nameUpper, true);
Assertions.assertTrue(nameUpperWarp.isPresent()); Assertions.assertTrue(nameUpperWarp.isPresent());
@@ -421,13 +444,21 @@ public class BukkitPluginTests {
@DisplayName("Home Tests") @DisplayName("Home Tests")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class HomeTests { public class HomeTests {
private static final List<String> HOME_NAMES = List.of("mr_home", "homble", "seaside", "hovel", "tokyo-3", "testington", "h"); private static final List<String> HOME_NAMES = List.of(
"mr_home",
"homble",
"seaside",
"hovel",
"tokyo-3",
"testington",
"h"
);
private static BukkitUser homeOwner; private static BukkitUser homeOwner;
@DisplayName("Ensure User Data") @DisplayName("Ensure User Data")
@BeforeAll @BeforeAll
public static void createHomeUser() { public static void createHomeUser() {
homeOwner = BukkitUser.adapt(server.addPlayer("TestUser278")); homeOwner = BukkitUser.adapt(server.addPlayer("TestUser278"), plugin);
plugin.getDatabase().ensureUser(homeOwner); plugin.getDatabase().ensureUser(homeOwner);
Assertions.assertTrue(plugin.getDatabase().getUserData(homeOwner.getUuid()).isPresent()); Assertions.assertTrue(plugin.getDatabase().getUserData(homeOwner.getUuid()).isPresent());
} }
@@ -449,7 +480,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Rename: \"{1}\" > \"{1}2\"") @ParameterizedTest(name = "Rename: \"{1}\" > \"{1}2\"")
@MethodSource("provideHomeData") @MethodSource("provideHomeData")
@Order(2) @Order(2)
public void testHomeRenaming(@NotNull OnlineUser owner, @NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testHomeRenaming(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) {
final String newName = "new_" + name; final String newName = "new_" + name;
plugin.getManager().homes().setHomeName(owner, name, newName); plugin.getManager().homes().setHomeName(owner, name, newName);
Assertions.assertTrue(plugin.getDatabase().getHome(owner, newName).isPresent()); Assertions.assertTrue(plugin.getDatabase().getHome(owner, newName).isPresent());
@@ -476,7 +508,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Edit Description: \"{1}\"") @ParameterizedTest(name = "Edit Description: \"{1}\"")
@MethodSource("provideHomeData") @MethodSource("provideHomeData")
@Order(3) @Order(3)
public void testHomeDescription(@NotNull OnlineUser owner, @NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testHomeDescription(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) {
final String description = "This is a test description for the home " + name + "!"; final String description = "This is a test description for the home " + name + "!";
plugin.getManager().homes().setHomeDescription(owner, name, description); plugin.getManager().homes().setHomeDescription(owner, name, description);
Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent());
@@ -494,8 +527,11 @@ public class BukkitPluginTests {
@Order(4) @Order(4)
public void testHomeRelocation(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) { public void testHomeRelocation(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) {
final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow();
final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, final Position newPosition = Position.at(
0, 0, world, plugin.getServerName()); position.getX() + 10, position.getY() + 10, position.getZ() + 10,
0, 0,
world, plugin.getServerName()
);
plugin.getManager().homes().setHomePosition(owner, name, newPosition); plugin.getManager().homes().setHomePosition(owner, name, newPosition);
Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent());
@@ -512,8 +548,11 @@ public class BukkitPluginTests {
@Order(5) @Order(5)
public void testHomeOverwrite(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) { public void testHomeOverwrite(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) {
final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow();
final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, final Position newPosition = Position.at(
0, 0, world, plugin.getServerName()); position.getX() + 10, position.getY() + 10, position.getZ() + 10,
0, 0,
world, plugin.getServerName()
);
plugin.getManager().homes().setHomePosition(owner, name, newPosition); plugin.getManager().homes().setHomePosition(owner, name, newPosition);
Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent());
@@ -528,7 +567,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Make Public: \"{1}\"") @ParameterizedTest(name = "Make Public: \"{1}\"")
@MethodSource("provideHomeData") @MethodSource("provideHomeData")
@Order(6) @Order(6)
public void testHomeMakePublic(@NotNull OnlineUser owner, @NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testHomeMakePublic(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position p) {
plugin.getManager().homes().setHomePrivacy(owner, name, true); plugin.getManager().homes().setHomePrivacy(owner, name, true);
Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent());
@@ -542,7 +582,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Make Private: \"{1}\"") @ParameterizedTest(name = "Make Private: \"{1}\"")
@MethodSource("provideHomeData") @MethodSource("provideHomeData")
@Order(7) @Order(7)
public void testHomeMakePrivate(@NotNull OnlineUser owner, @NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testHomeMakePrivate(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position p) {
plugin.getManager().homes().setHomePrivacy(owner, name, false); plugin.getManager().homes().setHomePrivacy(owner, name, false);
Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent());
@@ -558,7 +599,8 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Query: \"{1}\"") @ParameterizedTest(name = "Query: \"{1}\"")
@MethodSource("provideHomeData") @MethodSource("provideHomeData")
@Order(8) @Order(8)
public void testWarpCaseInsensitiveQuery(@NotNull OnlineUser owner, @NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { @SuppressWarnings("unused")
public void testWarpCaseInsensitiveQuery(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position p) {
final String nameUpper = name.toUpperCase(); final String nameUpper = name.toUpperCase();
final Optional<Home> nameUpperWarp = plugin.getDatabase().getHome(owner, nameUpper, true); final Optional<Home> nameUpperWarp = plugin.getDatabase().getHome(owner, nameUpper, true);
Assertions.assertTrue(nameUpperWarp.isPresent()); Assertions.assertTrue(nameUpperWarp.isPresent());
@@ -574,7 +616,7 @@ public class BukkitPluginTests {
@ParameterizedTest(name = "Delete: \"{1}\"") @ParameterizedTest(name = "Delete: \"{1}\"")
@MethodSource("provideHomeData") @MethodSource("provideHomeData")
@Order(9) @Order(9)
public void testHomeDeletion(@NotNull OnlineUser owner, @NotNull String name, @SuppressWarnings("unused") @NotNull Position position) { public void testHomeDeletion(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) {
plugin.getManager().homes().deleteHome(owner, name); plugin.getManager().homes().deleteHome(owner, name);
Assertions.assertFalse(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertFalse(plugin.getDatabase().getHome(owner, name).isPresent());
Assertions.assertFalse(plugin.getManager().homes().getUserHomes() Assertions.assertFalse(plugin.getManager().homes().getUserHomes()
@@ -603,4 +645,4 @@ public class BukkitPluginTests {
} }
} }
} }
+1 -1
View File
@@ -25,7 +25,7 @@ dependencies {
compileOnly 'com.mysql:mysql-connector-j:' + mysql_driver_version compileOnly 'com.mysql:mysql-connector-j:' + mysql_driver_version
compileOnly 'org.jetbrains:annotations:24.0.1' compileOnly 'org.jetbrains:annotations:24.0.1'
compileOnly 'com.google.guava:guava:32.0.1-jre' compileOnly 'com.google.guava:guava:32.1.0-jre'
compileOnly 'com.github.plan-player-analytics:Plan:5.5.2391' compileOnly 'com.github.plan-player-analytics:Plan:5.5.2391'
compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.5.0' compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.5.0'
compileOnly 'us.dynmap:DynmapCoreAPI:3.4' compileOnly 'us.dynmap:DynmapCoreAPI:3.4'
@@ -61,17 +61,25 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
* Represents a cross-platform instance of the plugin * Represents a cross-platform instance of the plugin.
*/ */
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver { public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver {
/**
* The spigot resource ID, used for update checking.
*/
int SPIGOT_RESOURCE_ID = 83767; int SPIGOT_RESOURCE_ID = 83767;
/**
* Get the user representing the server console.
*
* @return the {@link ConsoleUser}
*/
@NotNull @NotNull
ConsoleUser getConsole(); ConsoleUser getConsole();
/** /**
* The {@link Set} of online {@link OnlineUser}s on this server * The {@link Set} of online {@link OnlineUser}s on this server.
* *
* @return a {@link Set} of currently online {@link OnlineUser}s * @return a {@link Set} of currently online {@link OnlineUser}s
*/ */
@@ -121,7 +129,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
} }
/** /**
* Initialize a faucet of the plugin * Initialize a faucet of the plugin.
* *
* @param name the name of the faucet * @param name the name of the faucet
* @param runner a runnable for initializing the faucet * @param runner a runnable for initializing the faucet
@@ -137,7 +145,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
} }
/** /**
* The plugin {@link Settings} loaded from file * The plugin {@link Settings} loaded from file.
* *
* @return the plugin {@link Settings} * @return the plugin {@link Settings}
*/ */
@@ -147,7 +155,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
void setSettings(@NotNull Settings settings); void setSettings(@NotNull Settings settings);
/** /**
* The plugin messages loaded from file * The plugin messages loaded from file.
* *
* @return The plugin {@link Locales} * @return The plugin {@link Locales}
*/ */
@@ -157,17 +165,29 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
void setLocales(@NotNull Locales locales); void setLocales(@NotNull Locales locales);
/** /**
* The local {@link Spawn} location of this server, as cached to disk * The local {@link Spawn} location of this server, as cached to disk.
* *
* @return the {@link Spawn} location data * @return the {@link Spawn} location data
* @see #getSpawn() for the canonical spawn point to use * @see #getSpawn() for the canonical spawn point to use
*/ */
Optional<Spawn> getServerSpawn(); Optional<Spawn> getServerSpawn();
/**
* Update the local {@link Spawn} config file.
*
* @param spawn the new {@link Spawn} data
*/
void setServerSpawn(@NotNull Spawn spawn); void setServerSpawn(@NotNull Spawn spawn);
/** /**
* The canonical spawn {@link Position} of this server, if it has been set * Update the {@link Spawn} position to a location on the server.
*
* @param location the new {@link Spawn} location
*/
void setServerSpawn(@NotNull Location location);
/**
* The canonical spawn {@link Position} of this server, if it has been set.
* *
* @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set * @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set
*/ */
@@ -178,7 +198,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
} }
/** /**
* Returns the {@link Server} the plugin is on * Returns the {@link Server} the plugin is on.
* *
* @return The {@link Server} object * @return The {@link Server} object
*/ */
@@ -193,7 +213,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
UnsafeBlocks getUnsafeBlocks(); UnsafeBlocks getUnsafeBlocks();
/** /**
* The {@link Database} that store persistent plugin data * The {@link Database} that store persistent plugin data.
* *
* @return the {@link Database} implementation for accessing data * @return the {@link Database} implementation for accessing data
*/ */
@@ -201,7 +221,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Database getDatabase(); Database getDatabase();
/** /**
* The {@link Validator} for validating home names and descriptions * The {@link Validator} for validating home names and descriptions.
* *
* @return the {@link Validator} instance * @return the {@link Validator} instance
*/ */
@@ -209,7 +229,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Validator getValidator(); Validator getValidator();
/** /**
* The {@link Manager} that manages home, warp and user data * The {@link Manager} that manages home, warp and user data.
* *
* @return the {@link Manager} implementation * @return the {@link Manager} implementation
*/ */
@@ -217,7 +237,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Manager getManager(); Manager getManager();
/** /**
* The {@link Broker} that sends cross-network messages * The {@link Broker} that sends cross-network messages.
* *
* @return the {@link Broker} implementation * @return the {@link Broker} implementation
*/ */
@@ -225,7 +245,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Broker getMessenger(); Broker getMessenger();
/** /**
* The {@link RandomTeleportEngine} that manages random teleports * The {@link RandomTeleportEngine} that manages random teleports.
* *
* @return the {@link RandomTeleportEngine} implementation * @return the {@link RandomTeleportEngine} implementation
*/ */
@@ -233,22 +253,14 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
RandomTeleportEngine getRandomTeleportEngine(); RandomTeleportEngine getRandomTeleportEngine();
/** /**
* Sets the {@link RandomTeleportEngine} to be used for processing random teleports * Sets the {@link RandomTeleportEngine} to be used for processing random teleports.
* *
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use * @param randomTeleportEngine the {@link RandomTeleportEngine} to use
*/ */
void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine); void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine);
/** /**
* Update the {@link Spawn} position to a location on the server * Set of active {@link Hook}s running on the server.
*
* @param location the new {@link Spawn} location
*/
void setServerSpawn(@NotNull Location location);
/**
* Set of active {@link Hook}s running on the server
* *
* @return the {@link Set} of active {@link Hook}s * @return the {@link Set} of active {@link Hook}s
*/ */
@@ -277,7 +289,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
} }
/** /**
* Returns a resource read from the plugin resources folder * Returns a resource read from the plugin resources folder.
* *
* @param name the name of the resource * @param name the name of the resource
* @return the resource read as an {@link InputStream} * @return the resource read as an {@link InputStream}
@@ -286,7 +298,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
InputStream getResource(@NotNull String name); InputStream getResource(@NotNull String name);
/** /**
* Returns the plugin data folder containing the plugin config, etc * Returns the plugin data folder containing the plugin config, etc.
* *
* @return the plugin data folder * @return the plugin data folder
*/ */
@@ -294,7 +306,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
File getDataFolder(); File getDataFolder();
/** /**
* Returns a list of worlds on the server * Returns a list of worlds on the server.
* *
* @return a list of worlds on the server * @return a list of worlds on the server
*/ */
@@ -302,7 +314,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
List<World> getWorlds(); List<World> getWorlds();
/** /**
* Returns the plugin version * Returns the plugin version.
* *
* @return the plugin {@link Version} * @return the plugin {@link Version}
*/ */
@@ -310,7 +322,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Version getVersion(); Version getVersion();
/** /**
* Returns a list of enabled commands * Returns a list of enabled commands.
* *
* @return A list of registered and enabled {@link Command}s * @return A list of registered and enabled {@link Command}s
*/ */
@@ -396,7 +408,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
} }
/** /**
* Reloads the {@link Settings} and {@link Locales} from their respective config files * Reloads the {@link Settings} and {@link Locales} from their respective config files.
* *
* @return {@code true} if the reload was successful, {@code false} otherwise * @return {@code true} if the reload was successful, {@code false} otherwise
*/ */
@@ -407,8 +419,14 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
setSettings(Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get()); setSettings(Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get());
// Load locales from language preset default // Load locales from language preset default
final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + getSettings().getLanguage() + ".yml"))).get(); final Locales languagePresets = Annotaml.create(
setLocales(Annotaml.create(new File(getDataFolder(), "messages_" + getSettings().getLanguage() + ".yml"), languagePresets).get()); Locales.class,
Objects.requireNonNull(getResource("locales/" + getSettings().getLanguage() + ".yml"))
).get();
setLocales(Annotaml.create(new File(
getDataFolder(),
"messages_" + getSettings().getLanguage() + ".yml"
), languagePresets).get());
// Load server from file // Load server from file
if (getSettings().doCrossServer()) { if (getSettings().doCrossServer()) {
@@ -448,26 +466,26 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
getUpdateChecker().check().thenAccept(checked -> { getUpdateChecker().check().thenAccept(checked -> {
if (!checked.isUpToDate()) { if (!checked.isUpToDate()) {
log(Level.WARNING, "A new version of HuskHomes is available: v" log(Level.WARNING, "A new version of HuskHomes is available: v"
+ checked.getLatestVersion() + " (running v" + getVersion() + ")"); + checked.getLatestVersion() + " (running v" + getVersion() + ")");
} }
}); });
} }
} }
/** /**
* Registers the plugin with bStats metrics * Registers the plugin with bStats metrics.
* *
* @param metricsId the bStats id for the plugin * @param metricsId the bStats id for the plugin
*/ */
void registerMetrics(int metricsId); void registerMetrics(int metricsId);
/** /**
* Initialize plugin messaging channels * Initialize plugin messaging channels.
*/ */
void initializePluginChannels(); void initializePluginChannels();
/** /**
* Log a message to the console * Log a message to the console.
* *
* @param level the level to log at * @param level the level to log at
* @param message the message to log * @param message the message to log
@@ -476,7 +494,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
void log(@NotNull Level level, @NotNull String message, Throwable... exceptions); void log(@NotNull Level level, @NotNull String message, Throwable... exceptions);
/** /**
* Create a resource key namespaced with the plugin id * Create a resource key namespaced with the plugin id.
* *
* @param data the string ID elements to join * @param data the string ID elements to join
* @return the key * @return the key
@@ -33,6 +33,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver; import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.time.Duration; import java.time.Duration;
@@ -59,8 +60,9 @@ public abstract class BaseHuskHomesAPI {
protected final HuskHomes plugin; protected final HuskHomes plugin;
/** /**
* <b>(Internal use only)</b> - Constructor, instantiating the base API class * <b>(Internal use only)</b> - Constructor, instantiating the base API class.
*/ */
@ApiStatus.Internal
protected BaseHuskHomesAPI(@NotNull HuskHomes plugin) { protected BaseHuskHomesAPI(@NotNull HuskHomes plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@@ -88,19 +90,20 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get the timestamp of when a user's cooldown for performing an {@link TransactionResolver.Action action} expires * Get the timestamp of when a user's cooldown for performing an {@link TransactionResolver.Action action} expires.
* *
* @param user The {@link User} to get data for. * @param user The {@link User} to get data for.
* @param action The {@link TransactionResolver.Action} to get the cooldown for * @param action The {@link TransactionResolver.Action} to get the cooldown for
* @return An {@link Optional} containing the {@link Instant} the cooldown expires, if there is one * @return An {@link Optional} containing the {@link Instant} the cooldown expires, if there is one
* @since 4.4 * @since 4.4
*/ */
public final CompletableFuture<Optional<Instant>> getCooldown(@NotNull User user, @NotNull TransactionResolver.Action action) { public final CompletableFuture<Optional<Instant>> getCooldown(@NotNull User user,
@NotNull TransactionResolver.Action action) {
return plugin.supplyAsync(() -> plugin.getDatabase().getCooldown(action, user)); return plugin.supplyAsync(() -> plugin.getDatabase().getCooldown(action, user));
} }
/** /**
* Set a cooldown for a user performing an {@link TransactionResolver.Action action} * Set a cooldown for a user performing an {@link TransactionResolver.Action action}.
* *
* @param user The {@link User} to set data for. * @param user The {@link User} to set data for.
* @param action The {@link TransactionResolver.Action} to set the cooldown for * @param action The {@link TransactionResolver.Action} to set the cooldown for
@@ -108,7 +111,8 @@ public abstract class BaseHuskHomesAPI {
* @throws IllegalArgumentException if the expiry is in the past * @throws IllegalArgumentException if the expiry is in the past
* @since 4.4 * @since 4.4
*/ */
public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action, @NotNull Instant expiry) throws IllegalArgumentException { public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action,
@NotNull Instant expiry) throws IllegalArgumentException {
if (Instant.now().isAfter(expiry)) { if (Instant.now().isAfter(expiry)) {
throw new IllegalArgumentException("Cooldown expiry time must be in the future"); throw new IllegalArgumentException("Cooldown expiry time must be in the future");
} }
@@ -116,7 +120,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set a cooldown for a user performing an {@link TransactionResolver.Action action} * Set a cooldown for a user performing an {@link TransactionResolver.Action action}.
* *
* @param user The {@link User} to set data for. * @param user The {@link User} to set data for.
* @param action The {@link TransactionResolver.Action} to set the cooldown for * @param action The {@link TransactionResolver.Action} to set the cooldown for
@@ -124,12 +128,13 @@ public abstract class BaseHuskHomesAPI {
* @throws IllegalArgumentException if the duration is negative * @throws IllegalArgumentException if the duration is negative
* @since 4.4 * @since 4.4
*/ */
public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action, @NotNull Duration duration) throws IllegalArgumentException { public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action,
@NotNull Duration duration) throws IllegalArgumentException {
this.setCooldown(user, action, Instant.now().plus(duration)); this.setCooldown(user, action, Instant.now().plus(duration));
} }
/** /**
* Remove a cooldown for a user performing an {@link TransactionResolver.Action action} * Remove a cooldown for a user performing an {@link TransactionResolver.Action action}.
* *
* @param user The {@link User} to remove the cooldown for * @param user The {@link User} to remove the cooldown for
* @param action The {@link TransactionResolver.Action} to remove the cooldown for * @param action The {@link TransactionResolver.Action} to remove the cooldown for
@@ -140,7 +145,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Returns the last position, as used in the {@code /back} command, for this user * Returns the last position, as used in the {@code /back} command, for this user.
* *
* @param user The {@link User} to get the last position for * @param user The {@link User} to get the last position for
* @return The user's last {@link Position}, if there is one * @return The user's last {@link Position}, if there is one
@@ -151,7 +156,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the last {@link Position}, as used in the {@code /back} command, for this user * Set the last {@link Position}, as used in the {@code /back} command, for this user.
* *
* @param user The {@link User} to set the last position for * @param user The {@link User} to set the last position for
* @param position The {@link Position} to set as the user's last position * @param position The {@link Position} to set as the user's last position
@@ -162,7 +167,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Returns where the user last disconnected from a server * Returns where the user last disconnected from a server.
* *
* @param user The {@link User} to get the last disconnect position for * @param user The {@link User} to get the last disconnect position for
* @return The user's offline {@link Position}, if there is one * @return The user's offline {@link Position}, if there is one
@@ -173,9 +178,9 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Returns where the user last set their spawn point by right-clicking a bed or respawn anchor * Returns where the user last set their spawn point by right-clicking a bed or respawn anchor.
* <p> *
* The optional returned by this method will be empty unless HuskHomes is running cross-server mode * <p>The optional returned by this method will be empty unless HuskHomes is running cross-server mode
* and global respawning is enabled * and global respawning is enabled
* *
* @param user The {@link User} to get the respawn position of * @param user The {@link User} to get the respawn position of
@@ -191,7 +196,7 @@ public abstract class BaseHuskHomesAPI {
/** /**
* Returns if a user is currently warming up for a timed teleport; that is, they are in the state where they * Returns if a user is currently warming up for a timed teleport; that is, they are in the state where they
* must stand still and not take damage for the set amount of seconds before a teleport can be executed. * must stand still and not take damage for the set number of seconds before a teleport can be executed.
* *
* @param user The {@link User} to check * @param user The {@link User} to check
* @return {@code true} if the user is currently warming up, otherwise {@code false} * @return {@code true} if the user is currently warming up, otherwise {@code false}
@@ -202,7 +207,8 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Save {@link SavedUser} to the database, updating it if data for the user already exists, or adding new user data if it doesn't. * Save {@link SavedUser} to the database, updating it if data for the user already exists,
* or adding new user data if it doesn't.
* *
* @param savedUser The {@link SavedUser} to save * @param savedUser The {@link SavedUser} to save
* @since 3.0 * @since 3.0
@@ -254,11 +260,9 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a list of {@link Home}s set by the given user that they have made public * Get a list of {@link Home}s set by the given user that they have made public.
* *
* @param user The {@link User} to get the public homes of * @return A {@link CompletableFuture} with the user's public homes (where {@link Home#isPublic()})
* @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user that
* they have made public (where {@link Home#isPublic()})
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) { public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) {
@@ -268,7 +272,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a list of public homes local to this server * Get a list of public homes local to this server.
* *
* @param user The {@link User} to get the local public homes of * @param user The {@link User} to get the local public homes of
* @return A {@link CompletableFuture} that will complete with a list of public {@link Home}s local to the server * @return A {@link CompletableFuture} that will complete with a list of public {@link Home}s local to the server
@@ -279,7 +283,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a list of homes that have been made public ("public homes") * Get a list of homes that have been made public ("public homes").
* *
* @return A {@link CompletableFuture} that will complete with a list of public {@link Home}s * @return A {@link CompletableFuture} that will complete with a list of public {@link Home}s
* @since 3.0 * @since 3.0
@@ -289,11 +293,11 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a {@link Home} from the database owned by a given {@link User} with the specified name * Get a {@link Home} from the database owned by a given {@link User} with the specified name.
* *
* @param user The {@link User} to get the home of * @param user The {@link User} to get the home of
* @param homeName The name of the home to get * @param homeName The name of the home to get
* @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional} * @return A {@link CompletableFuture} with the {@link Home} if it exists, otherwise an empty {@link Optional}
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) { public final CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) {
@@ -302,17 +306,17 @@ public abstract class BaseHuskHomesAPI {
/** /**
* Get a {@link Home} from the database by its' unique id * Get a {@link Home} from the database by its {@link UUID unique ID}.
* *
* @param homeUuid The {@link UUID} of the home to get * @param homeUuid The {@link UUID} of the home to get
* @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional} * @return A {@link CompletableFuture} with the {@link Home} if it exists, otherwise an empty {@link Optional}
*/ */
public final CompletableFuture<Optional<Home>> getHome(@NotNull UUID homeUuid) { public final CompletableFuture<Optional<Home>> getHome(@NotNull UUID homeUuid) {
return plugin.supplyAsync(() -> plugin.getDatabase().getHome(homeUuid)); return plugin.supplyAsync(() -> plugin.getDatabase().getHome(homeUuid));
} }
/** /**
* Create a home for a given user with the specified name and position * Create a home for a given user with the specified name and position.
* *
* @param owner The {@link User} to create the home for * @param owner The {@link User} to create the home for
* @param name The name of the home * @param name The name of the home
@@ -324,7 +328,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Delete a home for a given user with the specified name * Delete a home for a given user with the specified name.
* *
* @param owner The {@link User} to delete the home for * @param owner The {@link User} to delete the home for
* @param name The name of the home * @param name The name of the home
@@ -335,7 +339,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Delete a home * Delete a home.
* *
* @param home The {@link Home} to delete * @param home The {@link Home} to delete
* @since 4.0 * @since 4.0
@@ -345,7 +349,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Rename a home for a given user * Rename a home for a given user.
* *
* @param owner The {@link User} to rename the home for * @param owner The {@link User} to rename the home for
* @param oldName The name of the home to rename * @param oldName The name of the home to rename
@@ -357,7 +361,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Rename a home * Rename a home.
* *
* @param home The {@link Home} to rename * @param home The {@link Home} to rename
* @param newName The new name of the home * @param newName The new name of the home
@@ -368,7 +372,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the privacy of a home * Set the privacy of a home.
* *
* @param owner The {@link User} to set the privacy of the home for * @param owner The {@link User} to set the privacy of the home for
* @param name The name of the home * @param name The name of the home
@@ -380,7 +384,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the privacy of a home * Set the privacy of a home.
* *
* @param home The {@link Home} to set the privacy of * @param home The {@link Home} to set the privacy of
* @param isPublic Whether the home should be public or not * @param isPublic Whether the home should be public or not
@@ -391,7 +395,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the description of a home * Set the description of a home.
* *
* @param owner The {@link User} to set the description of the home for * @param owner The {@link User} to set the description of the home for
* @param name The name of the home * @param name The name of the home
@@ -403,7 +407,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the description of a home * Set the description of a home.
* *
* @param home The {@link Home} to set the description of * @param home The {@link Home} to set the description of
* @param description The description of the home * @param description The description of the home
@@ -414,7 +418,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Relocate a home for a given user * Relocate a home for a given user.
* *
* @param owner The {@link User} to relocate the home for * @param owner The {@link User} to relocate the home for
* @param name The name of the home * @param name The name of the home
@@ -426,7 +430,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Relocate a home * Relocate a home.
* *
* @param home The {@link Home} to relocate * @param home The {@link Home} to relocate
* @param position The new {@link Position} of the home * @param position The new {@link Position} of the home
@@ -438,7 +442,7 @@ public abstract class BaseHuskHomesAPI {
/** /**
* Set the meta tags of a home * Set the meta tags of a home.
* *
* @param owner The {@link User} to set the meta tags of the home for * @param owner The {@link User} to set the meta tags of the home for
* @param name The name of the home * @param name The name of the home
@@ -450,7 +454,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the meta tags of a home * Set the meta tags of a home.
* *
* @param home The {@link Home} to set the meta tags of * @param home The {@link Home} to set the meta tags of
* @param tags The meta tags to set * @param tags The meta tags to set
@@ -461,14 +465,15 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Edit the meta tags of a home * Edit the meta tags of a home.
* *
* @param owner The {@link User} to edit the meta tags of the home for * @param owner The {@link User} to edit the meta tags of the home for
* @param name The name of the home * @param name The name of the home
* @param tagEditor The {@link Consumer} to edit the meta tags with * @param tagEditor The {@link Consumer} to edit the meta tags with
* @since 4.0 * @since 4.0
*/ */
public final void editHomeMetaTags(@NotNull User owner, @NotNull String name, @NotNull Consumer<Map<String, String>> tagEditor) { public final void editHomeMetaTags(@NotNull User owner, @NotNull String name,
@NotNull Consumer<Map<String, String>> tagEditor) {
plugin.runAsync(() -> plugin.getDatabase().getHome(owner, name).ifPresent(home -> { plugin.runAsync(() -> plugin.getDatabase().getHome(owner, name).ifPresent(home -> {
final Map<String, String> tags = home.getMeta().getTags(); final Map<String, String> tags = home.getMeta().getTags();
tagEditor.accept(tags); tagEditor.accept(tags);
@@ -477,7 +482,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a list of {@link Warp}s local to this server * Get a list of {@link Warp}s local to this server.
* *
* @return A {@link CompletableFuture} that will complete with a list of {@link Warp}s local to the server * @return A {@link CompletableFuture} that will complete with a list of {@link Warp}s local to the server
* @since 4.0 * @since 4.0
@@ -487,7 +492,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a list of {@link Warp}s * Get a list of {@link Warp}s.
* *
* @return A {@link CompletableFuture} that will complete with a list of {@link Warp}s * @return A {@link CompletableFuture} that will complete with a list of {@link Warp}s
* @since 3.0 * @since 3.0
@@ -497,10 +502,10 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a {@link Warp} from the database with the specified name * Get a {@link Warp} from the database with the specified name.
* *
* @param warpName The name of the warp to get * @param warpName The name of the warp to get
* @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional} * @return A {@link CompletableFuture} with the {@link Warp} if it exists, otherwise an empty {@link Optional}
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) { public final CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) {
@@ -508,17 +513,17 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a {@link Warp} from the database by its' unique id * Get a {@link Warp} from the database by its {@link UUID unique ID}.
* *
* @param warpUuid The {@link UUID} of the warp to get * @param warpUuid The {@link UUID} of the warp to get
* @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional} * @return A {@link CompletableFuture} with the {@link Warp} if it exists, otherwise an empty {@link Optional}
*/ */
public final CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID warpUuid) { public final CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID warpUuid) {
return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpUuid)); return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpUuid));
} }
/** /**
* Create a new {@link Warp} with the given name and {@link Position} * Create a new {@link Warp} with the given name and {@link Position}.
* *
* @param name The name of the warp * @param name The name of the warp
* @param position The {@link Position} of the warp * @param position The {@link Position} of the warp
@@ -529,7 +534,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Delete a {@link Warp} with the given name * Delete a {@link Warp} with the given name.
* *
* @param name The name of the warp to delete * @param name The name of the warp to delete
*/ */
@@ -538,7 +543,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Delete a {@link Warp} * Delete a {@link Warp}.
* *
* @param warp The {@link Warp} to delete * @param warp The {@link Warp} to delete
*/ */
@@ -547,7 +552,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Rename a {@link Warp} by name * Rename a {@link Warp} by name.
* *
* @param oldName The name of the warp to rename * @param oldName The name of the warp to rename
* @param newName The new name of the warp * @param newName The new name of the warp
@@ -557,7 +562,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Rename a {@link Warp} * Rename a {@link Warp}.
* *
* @param warp The {@link Warp} to rename * @param warp The {@link Warp} to rename
* @param newName The new name of the warp * @param newName The new name of the warp
@@ -567,7 +572,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the description of a {@link Warp} by name * Set the description of a {@link Warp} by name.
* *
* @param name The name of the warp to set the description of * @param name The name of the warp to set the description of
* @param description The new description of the warp * @param description The new description of the warp
@@ -577,7 +582,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the description of a {@link Warp} * Set the description of a {@link Warp}.
* *
* @param warp The {@link Warp} to set the description of * @param warp The {@link Warp} to set the description of
* @param description The new description of the warp * @param description The new description of the warp
@@ -587,7 +592,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the {@link Position} of a {@link Warp} by name * Set the {@link Position} of a {@link Warp} by name.
* *
* @param name The name of the warp to set the {@link Position} of * @param name The name of the warp to set the {@link Position} of
* @param position The new {@link Position} of the warp * @param position The new {@link Position} of the warp
@@ -597,7 +602,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the {@link Position} of a {@link Warp} * Set the {@link Position} of a {@link Warp}.
* *
* @param warp The {@link Warp} to set the {@link Position} of * @param warp The {@link Warp} to set the {@link Position} of
* @param position The new {@link Position} of the warp * @param position The new {@link Position} of the warp
@@ -607,7 +612,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the meta tags of a {@link Warp} by name * Set the meta tags of a {@link Warp} by name.
* *
* @param name The name of the warp to set the meta tags of * @param name The name of the warp to set the meta tags of
* @param tags The new meta tags of the warp * @param tags The new meta tags of the warp
@@ -618,7 +623,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the meta tags of a {@link Warp} * Set the meta tags of a {@link Warp}.
* *
* @param warp The {@link Warp} to set the meta tags of * @param warp The {@link Warp} to set the meta tags of
* @param tags The new meta tags of the warp * @param tags The new meta tags of the warp
@@ -629,7 +634,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Edit the meta tags of a {@link Warp} by name * Edit the meta tags of a {@link Warp} by name.
* *
* @param name The name of the warp to edit the meta tags of * @param name The name of the warp to edit the meta tags of
* @param tagEditor A {@link Consumer} that will be passed the current meta tags of the warp * @param tagEditor A {@link Consumer} that will be passed the current meta tags of the warp
@@ -646,8 +651,10 @@ public abstract class BaseHuskHomesAPI {
/** /**
* Get the canonical {@link Position} of the spawn point. Note that if cross-server and global spawn * Get the canonical {@link Position} of the spawn point.
* are enabled in the config, this may not return a position on this server. *
* <p>Note that if cross-server and global spawn are enabled in the config,
* this may not return a position on this server.
* *
* @return A {@link CompletableFuture} that will complete with the {@link Position} of the spawn point * @return A {@link CompletableFuture} that will complete with the {@link Position} of the spawn point
*/ */
@@ -656,7 +663,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get the maximum number of set homes a given {@link OnlineUser} can make * Get the maximum number of set homes a given {@link OnlineUser} can make.
* *
* @param user The {@link OnlineUser} to get the maximum number of homes for * @param user The {@link OnlineUser} to get the maximum number of homes for
* @return The maximum number of homes the user can set * @return The maximum number of homes the user can set
@@ -667,9 +674,9 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get the number of homes an {@link OnlineUser} can set for free * Get the number of homes an {@link OnlineUser} can set for free.
* <p> *
* This is irrelevant unless the server is using economy features with HuskHomes * <p>This is irrelevant unless the server is using economy features with HuskHomes.
* *
* @param user The {@link OnlineUser} to get the number of free home slots for * @param user The {@link OnlineUser} to get the number of free home slots for
* @return The number of homes the user can set for free * @return The number of homes the user can set for free
@@ -680,7 +687,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get the number of homes an {@link OnlineUser} can make public * Get the number of homes an {@link OnlineUser} can make public.
* *
* @param user The {@link OnlineUser} to get the number of public home slots for * @param user The {@link OnlineUser} to get the number of public home slots for
* @return The number of homes the user can make public * @return The number of homes the user can make public
@@ -691,7 +698,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a {@link TeleportBuilder} to construct and execute a (timed) teleport * Get a {@link TeleportBuilder} to construct and execute a (timed) teleport.
* *
* @param teleporter The {@link OnlineUser} to teleport * @param teleporter The {@link OnlineUser} to teleport
* @return A {@link TeleportBuilder} to construct and execute a (timed) teleport * @return A {@link TeleportBuilder} to construct and execute a (timed) teleport
@@ -703,7 +710,7 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a {@link TeleportBuilder} to construct and execute a (timed) teleport * Get a {@link TeleportBuilder} to construct and execute a (timed) teleport.
* *
* @return A {@link TeleportBuilder} to construct and execute a (timed) teleport * @return A {@link TeleportBuilder} to construct and execute a (timed) teleport
* @since 4.0 * @since 4.0
@@ -716,7 +723,7 @@ public abstract class BaseHuskHomesAPI {
/** /**
* Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be * Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be
* generated by the current {@link RandomTeleportEngine} * generated by the current {@link RandomTeleportEngine}.
* *
* @param user The {@link OnlineUser} to teleport * @param user The {@link OnlineUser} to teleport
* @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still * @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still
@@ -724,7 +731,8 @@ public abstract class BaseHuskHomesAPI {
* @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine} * @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine}
* @since 3.0 * @since 3.0
*/ */
public final void randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport, @NotNull String... rtpArgs) { public final void randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport,
@NotNull String... rtpArgs) {
plugin.getRandomTeleportEngine() plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().getWorld(), rtpArgs) .getRandomPosition(user.getPosition().getWorld(), rtpArgs)
.thenAccept(position -> { .thenAccept(position -> {
@@ -751,7 +759,7 @@ public abstract class BaseHuskHomesAPI {
/** /**
* Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be * Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be
* generated by the current {@link RandomTeleportEngine} * generated by the current {@link RandomTeleportEngine}.
* *
* @param user The {@link OnlineUser} to teleport * @param user The {@link OnlineUser} to teleport
* @since 3.0 * @since 3.0
@@ -761,9 +769,10 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Set the {@link RandomTeleportEngine} to use for processing random teleports. The engine will be used to process all * Set the {@link RandomTeleportEngine} to use for processing random teleports.
* random teleports, including both {@code /rtp} command executions and API ({@link #randomlyTeleportPlayer(OnlineUser)}) *
* calls. * <p>The engine will be used to process all random {@link Teleport teleports},
* including both {@code /rtp} command executions and {@link #randomlyTeleportPlayer(OnlineUser) API calls}.
* *
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use to process random teleports * @param randomTeleportEngine the {@link RandomTeleportEngine} to use to process random teleports
* @see RandomTeleportEngine * @see RandomTeleportEngine
@@ -774,21 +783,20 @@ public abstract class BaseHuskHomesAPI {
} }
/** /**
* Get a {@link MineDown}-formatted locale by key from the plugin {@link Locales} file * Get a {@link MineDown}-formatted locale by key from the plugin {@link Locales} file.
* *
* @param localeKey The key of the locale to get * @param localeKey The key of the locale to get
* @param replacements Replacement strings to apply to the locale * @param replacements Replacement strings to apply to the locale
* @return The {@link MineDown}-formatted locale * @return The {@link MineDown}-formatted locale
* @apiNote Since v3.0.4, this method returns a `adventure.MineDown` object, targeting * @apiNote Since v3.0.4, this returns MineDown-<a href="https://docs.adventure.kyori.net/">Adventure</a> components
* <a href="https://docs.adventure.kyori.net/">Adventure</a> platforms, rather than a bungee components object. * @since 3.0
* @since 3.0.4
*/ */
public final Optional<MineDown> getLocale(@NotNull String localeKey, @NotNull String... replacements) { public final Optional<MineDown> getLocale(@NotNull String localeKey, @NotNull String... replacements) {
return plugin.getLocales().getLocale(localeKey, replacements); return plugin.getLocales().getLocale(localeKey, replacements);
} }
/** /**
* Get a raw locale string by key from the plugin {@link Locales} file * Get a raw locale string by key from the plugin {@link Locales} file.
* *
* @param localeKey The key of the locale to get * @param localeKey The key of the locale to get
* @param replacements Replacement strings to apply to the locale * @param replacements Replacement strings to apply to the locale
@@ -799,4 +807,23 @@ public abstract class BaseHuskHomesAPI {
return plugin.getLocales().getRawLocale(localeKey, replacements); return plugin.getLocales().getRawLocale(localeKey, replacements);
} }
/**
* An exception indicating the plugin has been accessed before it has been registered.
*/
static final class NotRegisteredException extends IllegalStateException {
private static final String MESSAGE = """
Could not access the HuskHomes API as it has not yet been registered. This could be because:
1) HuskHomes has failed to enable successfully
2) Your plugin isn't set to load after HuskHomes has
(Check if it set as a (soft)depend in plugin.yml or to load: BEFORE in paper-plugin.yml?)
3) You are attempting to access HuskHomes on plugin construction/before your plugin has enabled.""";
NotRegisteredException() {
super(MESSAGE);
}
}
} }
@@ -36,8 +36,8 @@ public class BackCommand extends InGameCommand {
protected BackCommand(@NotNull HuskHomes plugin) { protected BackCommand(@NotNull HuskHomes plugin) {
super("back", List.of(), "", plugin); super("back", List.of(), "", plugin);
addAdditionalPermissions(Map.of( addAdditionalPermissions(Map.of(
"death", false, "death", false,
"previous", false "previous", false
)); ));
} }
@@ -32,7 +32,8 @@ public abstract class Command extends Node {
private final String usage; private final String usage;
private final Map<String, Boolean> additionalPermissions; private final Map<String, Boolean> additionalPermissions;
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage, @NotNull HuskHomes plugin) { protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, plugin); super(name, aliases, plugin);
this.usage = usage; this.usage = usage;
this.additionalPermissions = new HashMap<>(); this.additionalPermissions = new HashMap<>();
@@ -70,8 +71,8 @@ public abstract class Command extends Node {
return "/" + getName() + " " + getRawUsage(); return "/" + getName() + " " + getRawUsage();
} }
public final void addAdditionalPermissions(@NotNull Map<String, Boolean> additionalPermissions) { public final void addAdditionalPermissions(@NotNull Map<String, Boolean> permissions) {
additionalPermissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value)); permissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value));
} }
@NotNull @NotNull
@@ -44,7 +44,8 @@ public class DelHomeCommand extends SavedPositionCommand<Home> {
@Override @Override
public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) { public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) {
if (executor instanceof OnlineUser user && !home.getOwner().equals(user) && !user.hasPermission(getOtherPermission())) { if (executor instanceof OnlineUser user && !home.getOwner().equals(user)
&& !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(user::sendMessage); .ifPresent(user::sendMessage);
return; return;
@@ -72,10 +72,12 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
case "description" -> setHomeDescription(executor, home, ownerEditing, args); case "description" -> setHomeDescription(executor, home, ownerEditing, args);
case "relocate" -> setHomePosition(executor, home, ownerEditing); case "relocate" -> setHomePosition(executor, home, ownerEditing);
case "privacy" -> setHomePrivacy(executor, home, ownerEditing, args); case "privacy" -> setHomePrivacy(executor, home, ownerEditing, args);
default -> throw new IllegalStateException("Unexpected value: " + operation.get().toLowerCase());
} }
} }
private void setHomeName(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) { private void setHomeName(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing,
@NotNull String[] args) {
final String oldName = home.getName(); final String oldName = home.getName();
final Optional<String> optionalName = parseStringArg(args, 1); final Optional<String> optionalName = parseStringArg(args, 1);
if (optionalName.isEmpty()) { if (optionalName.isEmpty()) {
@@ -106,7 +108,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
}); });
} }
private void setHomeDescription(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) { private void setHomeDescription(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing,
@NotNull String[] args) {
final String oldDescription = home.getMeta().getDescription(); final String oldDescription = home.getMeta().getDescription();
final Optional<String> optionalDescription = parseGreedyArguments(args); final Optional<String> optionalDescription = parseGreedyArguments(args);
if (optionalDescription.isEmpty()) { if (optionalDescription.isEmpty()) {
@@ -127,7 +130,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
} }
if (ownerEditing) { if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_description", home.getName(), oldDescription, newDescription) plugin.getLocales().getLocale("edit_home_update_description",
home.getName(), oldDescription, newDescription)
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
} else { } else {
plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(), plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(),
@@ -157,21 +161,24 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
plugin.getLocales().getLocale("edit_home_update_location", home.getName()) plugin.getLocales().getLocale("edit_home_update_location", home.getName())
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
} else { } else {
plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName()) plugin.getLocales().getLocale("edit_home_update_location_other",
home.getOwner().getUsername(), home.getName())
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
} }
}); });
} }
private void setHomePrivacy(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) { private void setHomePrivacy(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing,
@NotNull String[] args) {
if (!executor.hasPermission(getPermission("privacy"))) { if (!executor.hasPermission(getPermission("privacy"))) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
} }
// Check against economy // Check against the economy hook
if (executor instanceof OnlineUser user && !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) { if (executor instanceof OnlineUser user
&& !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) {
return; return;
} }
@@ -184,7 +191,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
try { try {
plugin.getManager().homes().setHomePrivacy(event.getHome(), home.isPublic()); plugin.getManager().homes().setHomePrivacy(event.getHome(), home.isPublic());
} catch (ValidationException e) { } catch (ValidationException e) {
int maxHomes = plugin.getManager().homes().getMaxPublicHomes(executor instanceof OnlineUser user ? user : null); int maxHomes = plugin.getManager().homes()
.getMaxPublicHomes(executor instanceof OnlineUser user ? user : null);
e.dispatchHomeError(executor, false, plugin, Integer.toString(maxHomes)); e.dispatchHomeError(executor, false, plugin, Integer.toString(maxHomes));
return; return;
} }
@@ -208,7 +216,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
} }
/** /**
* Get a formatted home editor chat window for a supplied {@link Home} * Get a formatted home editor chat window for a supplied {@link Home}.
* *
* @param home The home to display * @param home The home to display
* @param otherViewer If the viewer of the editor is not the homeowner * @param otherViewer If the viewer of the editor is not the homeowner
@@ -219,55 +227,61 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
@NotNull @NotNull
private List<MineDown> getHomeEditorWindow(@NotNull Home home, boolean otherViewer, private List<MineDown> getHomeEditorWindow(@NotNull Home home, boolean otherViewer,
boolean showTeleportButton, boolean showPrivacyToggleButton) { boolean showTeleportButton, boolean showPrivacyToggleButton) {
return new ArrayList<>() {{ final List<MineDown> messages = new ArrayList<>();
if (!otherViewer) { if (!otherViewer) {
plugin.getLocales().getLocale("edit_home_menu_title", home.getName()) plugin.getLocales().getLocale("edit_home_menu_title", home.getName())
.ifPresent(this::add); .ifPresent(messages::add);
} else { } else {
plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().getUsername(), home.getName()) plugin.getLocales().getLocale("edit_home_menu_title_other",
.ifPresent(this::add); home.getOwner().getUsername(), home.getName())
} .ifPresent(messages::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.getMeta().getCreationTime().atZone(ZoneId.systemDefault())), .format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
home.getUuid().toString().split(Pattern.quote("-"))[0], home.getUuid().toString().split(Pattern.quote("-"))[0],
home.getUuid().toString()) home.getUuid().toString())
.ifPresent(this::add); .ifPresent(messages::add);
if (home.getMeta().getDescription().length() > 0) { if (home.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_home_menu_description", plugin.getLocales().getLocale("edit_home_menu_description",
plugin.getLocales().truncateText(home.getMeta().getDescription(), 50), plugin.getLocales().truncateText(home.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(home.getMeta().getDescription(), 40)) plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))
.ifPresent(this::add); .ifPresent(messages::add);
} }
if (!plugin.getSettings().doCrossServer()) { if (!plugin.getSettings().doCrossServer()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName()) plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(this::add); .ifPresent(messages::add);
} else { } else {
plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer()) plugin.getLocales().getLocale("edit_home_menu_world_server",
.ifPresent(this::add); home.getWorld().getName(), home.getServer())
} .ifPresent(messages::add);
}
plugin.getLocales().getLocale("edit_home_menu_coordinates", plugin.getLocales().getLocale("edit_home_menu_coordinates",
String.format("%.1f", home.getX()), String.format("%.1f", home.getY()), String.format("%.1f", home.getZ()), String.format("%.1f", home.getX()),
String.format("%.2f", home.getYaw()), String.format("%.2f", home.getPitch())) String.format("%.1f", home.getY()),
.ifPresent(this::add); String.format("%.1f", home.getZ()),
String.format("%.2f", home.getYaw()),
String.format("%.2f", home.getPitch()))
.ifPresent(messages::add);
if (showTeleportButton) { if (showTeleportButton) {
plugin.getLocales().getLocale("edit_home_menu_use_buttons", home.getSafeIdentifier()) plugin.getLocales().getLocale("edit_home_menu_use_buttons", home.getSafeIdentifier())
.ifPresent(this::add); .ifPresent(messages::add);
} }
plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", home.getSafeIdentifier(), plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons",
showPrivacyToggleButton ? plugin.getLocales() home.getSafeIdentifier(),
.getRawLocale("edit_home_menu_privacy_button_" showPrivacyToggleButton ? plugin.getLocales()
+ (home.isPublic() ? "private" : "public"), home.getSafeIdentifier()) .getRawLocale("edit_home_menu_privacy_button_"
.orElse("") : "") + (home.isPublic() ? "private" : "public"), home.getSafeIdentifier())
.map(MineDown::new).ifPresent(this::add); .orElse("") : "")
plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", home.getSafeIdentifier()) .map(MineDown::new).ifPresent(messages::add);
.ifPresent(this::add); plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", home.getSafeIdentifier())
}}; .ifPresent(messages::add);
return messages;
} }
} }
@@ -61,6 +61,7 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
case "rename" -> setWarpName(executor, warp, args); case "rename" -> setWarpName(executor, warp, args);
case "description" -> setWarpDescription(executor, warp, args); case "description" -> setWarpDescription(executor, warp, args);
case "relocate" -> setWarpPosition(executor, warp); case "relocate" -> setWarpPosition(executor, warp);
default -> throw new IllegalStateException("Unexpected value: " + operation.get().toLowerCase());
} }
} }
@@ -106,7 +107,8 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
return; return;
} }
plugin.getLocales().getLocale("edit_warp_update_description", warp.getName(), warp.getMeta().getDescription()) plugin.getLocales().getLocale("edit_warp_update_description",
warp.getName(), warp.getMeta().getDescription())
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
}); });
} }
@@ -133,49 +135,54 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
} }
/** /**
* Get a formatted warp editor chat window for a supplied {@link Warp} * Get a formatted warp editor chat window for a supplied {@link Warp}.
* *
* @param warp The warp to display * @param warp The warp to display
* @return List of {@link MineDown} messages to send to the editor that form the menu * @return List of {@link MineDown} messages to send to the editor that form the menu
*/ */
@NotNull @NotNull
private List<MineDown> getWarpEditorWindow(@NotNull Warp warp) { private List<MineDown> getWarpEditorWindow(@NotNull Warp warp) {
return new ArrayList<>() {{ final List<MineDown> messages = new ArrayList<>();
plugin.getLocales().getLocale("edit_warp_menu_title", warp.getName()) plugin.getLocales().getLocale("edit_warp_menu_title", warp.getName())
.ifPresent(this::add); .ifPresent(messages::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.getMeta().getCreationTime().atZone(ZoneId.systemDefault())), .format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
warp.getUuid().toString().split(Pattern.quote("-"))[0], warp.getUuid().toString().split(Pattern.quote("-"))[0],
warp.getUuid().toString()) warp.getUuid().toString())
.ifPresent(this::add); .ifPresent(messages::add);
if (warp.getMeta().getDescription().length() > 0) { if (warp.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_warp_menu_description", plugin.getLocales().getLocale("edit_warp_menu_description",
plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50), plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40)) plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40))
.ifPresent(this::add); .ifPresent(messages::add);
} }
if (!plugin.getSettings().doCrossServer()) { if (!plugin.getSettings().doCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world", warp.getWorld().getName()).ifPresent(this::add); plugin.getLocales().getLocale("edit_warp_menu_world",
} else { warp.getWorld().getName()).ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer()).ifPresent(this::add); } else {
} plugin.getLocales().getLocale("edit_warp_menu_world_server",
warp.getWorld().getName(), warp.getServer()).ifPresent(messages::add);
}
plugin.getLocales().getLocale("edit_warp_menu_coordinates", plugin.getLocales().getLocale("edit_warp_menu_coordinates",
String.format("%.1f", warp.getX()), String.format("%.1f", warp.getY()), String.format("%.1f", warp.getZ()), String.format("%.1f", warp.getX()),
String.format("%.2f", warp.getYaw()), String.format("%.2f", warp.getPitch())) String.format("%.1f", warp.getY()),
.ifPresent(this::add); String.format("%.1f", warp.getZ()),
String.format("%.2f", warp.getYaw()),
String.format("%.2f", warp.getPitch()))
.ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getSafeIdentifier()) plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getSafeIdentifier())
.ifPresent(this::add); .ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getSafeIdentifier()) plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getSafeIdentifier())
.ifPresent(this::add); .ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getSafeIdentifier()) plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getSafeIdentifier())
.ifPresent(this::add); .ifPresent(messages::add);
}}; return messages;
} }
} }
@@ -100,12 +100,15 @@ public class HuskHomesCommand extends Command implements TabProvider {
.getNearestValidPage(parseIntArg(args, 1).orElse(1))); .getNearestValidPage(parseIntArg(args, 1).orElse(1)));
case "reload" -> { case "reload" -> {
if (!plugin.loadConfigs()) { if (!plugin.loadConfigs()) {
executor.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)")); executor.sendMessage(new MineDown(
"[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"
));
return; return;
} }
executor.sendMessage(new MineDown(""" executor.sendMessage(new MineDown(
[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a) "[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)\n"
[ℹ If you have modified the database or cross-server message broker settings, you need to restart your server for these changes to take effect.](gray)""" + "[ℹ If you have modified the database or cross-server message broker settings,"
+ " you need to restart your server for these changes to take effect.](gray)"
)); ));
} }
case "update" -> updateChecker.check().thenAccept(checked -> { case "update" -> updateChecker.check().thenAccept(checked -> {
@@ -32,7 +32,8 @@ public abstract class ListCommand extends Command {
protected final Map<UUID, PaginatedList> cachedLists; protected final Map<UUID, PaginatedList> cachedLists;
protected ListCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage, @NotNull HuskHomes plugin) { protected ListCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, usage, plugin); super(name, aliases, usage, plugin);
this.cachedLists = new HashMap<>(); this.cachedLists = new HashMap<>();
} }
@@ -156,23 +156,23 @@ public abstract class Node implements Executable {
.orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName())); .orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName()));
} }
protected Optional<Position> parsePositionArgs(@NotNull Position basePosition, @NotNull String[] args, int startIndex) { protected Optional<Position> parsePositionArgs(@NotNull Position basePosition, @NotNull String[] args, int from) {
// Parse x, y, and z // Parse x, y, and z
final Optional<Double> x = parseCoordinateArg(args, startIndex, basePosition.getX()); final Optional<Double> x = parseCoordinateArg(args, from, basePosition.getX());
final Optional<Double> y = parseCoordinateArg(args, startIndex + 1, basePosition.getY()); final Optional<Double> y = parseCoordinateArg(args, from + 1, basePosition.getY());
final Optional<Double> z = parseCoordinateArg(args, startIndex + 2, basePosition.getZ()); final Optional<Double> z = parseCoordinateArg(args, from + 2, basePosition.getZ());
if (x.isEmpty() || y.isEmpty() || z.isEmpty()) { if (x.isEmpty() || y.isEmpty() || z.isEmpty()) {
return Optional.empty(); return Optional.empty();
} }
// Parse world and server name // Parse world and server name
final Optional<World> world = parseWorldArg(args, startIndex + 3); final Optional<World> world = parseWorldArg(args, from + 3);
final Optional<String> server = parseStringArg(args, startIndex + 4); final Optional<String> server = parseStringArg(args, from + 4);
// Parse yaw, pitch // Parse yaw, pitch
int angleStartIndex = (world.isEmpty() ? 3 : server.isEmpty() ? 4 : 5); int angleStartIndex = (world.isEmpty() ? 3 : server.isEmpty() ? 4 : 5);
final Optional<Float> yaw = parseFloatArg(args, startIndex + angleStartIndex); final Optional<Float> yaw = parseFloatArg(args, from + angleStartIndex);
final Optional<Float> pitch = parseFloatArg(args, startIndex + angleStartIndex + 1); final Optional<Float> pitch = parseFloatArg(args, from + angleStartIndex + 1);
return Optional.of(Position.at(x.get(), y.get(), z.get(), return Optional.of(Position.at(x.get(), y.get(), z.get(),
yaw.orElse(basePosition.getYaw()), pitch.orElse(basePosition.getPitch()), yaw.orElse(basePosition.getYaw()), pitch.orElse(basePosition.getPitch()),
@@ -74,7 +74,7 @@ public class PrivateHomeListCommand extends ListCommand {
} }
if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid()) if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid())
&& !executor.hasPermission(getPermission("other"))) { && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
@@ -93,7 +93,8 @@ public class PrivateHomeListCommand extends ListCommand {
})); }));
} }
private Optional<PaginatedList> generateList(@NotNull CommandUser executor, @NotNull User user, @NotNull List<Home> homes) { private Optional<PaginatedList> generateList(@NotNull CommandUser executor, @NotNull User user,
@NotNull List<Home> homes) {
if (homes.isEmpty()) { if (homes.isEmpty()) {
if (!executor.equals(user)) { if (!executor.equals(user)) {
plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername()) plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername())
@@ -109,7 +110,10 @@ public class PrivateHomeListCommand extends ListCommand {
plugin.getLocales() plugin.getLocales()
.getRawLocale("home_list_item", .getRawLocale("home_list_item",
Locales.escapeText(home.getName()), home.getSafeIdentifier(), Locales.escapeText(home.getName()), home.getSafeIdentifier(),
Locales.escapeText(plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))) Locales.escapeText(plugin.getLocales().wrapText(
home.getMeta().getDescription(),
40
)))
.orElse(home.getName())).sorted().collect(Collectors.toList()), .orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales() plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage()) .getBaseList(plugin.getSettings().getListItemsPerPage())
@@ -46,7 +46,7 @@ public class PublicHomeCommand extends HomeCommand implements TabProvider {
@NotNull @NotNull
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) { public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
if (args.length <= 2) { if (args.length <= 2) {
return filter(plugin.getManager().homes().getPublicHomeNames(), args); return filter(plugin.getManager().homes().getPublicHomeIdentifiers(), args);
} }
return List.of(); return List.of();
} }
@@ -71,7 +71,10 @@ public class PublicHomeListCommand extends ListCommand {
.getRawLocale("public_home_list_item", .getRawLocale("public_home_list_item",
Locales.escapeText(home.getName()), home.getSafeIdentifier(), Locales.escapeText(home.getName()), home.getSafeIdentifier(),
Locales.escapeText(home.getOwner().getUsername()), Locales.escapeText(home.getOwner().getUsername()),
Locales.escapeText(plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))) Locales.escapeText(plugin.getLocales().wrapText(
home.getMeta().getDescription(),
40
)))
.orElse(home.getName())).sorted().collect(Collectors.toList()), .orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales() plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage()) .getBaseList(plugin.getSettings().getListItemsPerPage())
@@ -80,14 +80,15 @@ public class RtpCommand extends Command implements UserListTabProvider {
} }
/** /**
* Validates the RTP command, returning the world to randomly teleport in if successful * Validates the RTP command, returning the world to randomly teleport in if successful.
* *
* @param teleporter The user to teleport * @param teleporter The user to teleport
* @param executor The user executing the command * @param executor The user executing the command
* @param args The command arguments * @param args The command arguments
* @return The world to randomly teleport in, if successful * @return The world to randomly teleport in, if successful
*/ */
private Optional<World> validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull String[] args) { private Optional<World> validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor,
@NotNull String[] args) {
// Check permissions if the user is being teleported by another player // Check permissions if the user is being teleported by another player
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) { if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
@@ -127,7 +128,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
} }
/** /**
* Executes the random teleport * Executes the random teleport.
* *
* @param teleporter The player to teleport * @param teleporter The player to teleport
* @param executor The player executing the command * @param executor The player executing the command
@@ -45,7 +45,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
protected SavedPositionCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull Class<T> positionType, protected SavedPositionCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull Class<T> positionType,
@NotNull List<String> arguments, @NotNull HuskHomes plugin) { @NotNull List<String> arguments, @NotNull HuskHomes plugin) {
super(name, aliases, "<name>" + ((arguments.size() > 0) ? " [" + String.join("|", arguments) + "]" : ""), plugin); super(name, aliases, "<name>" + formatUsage(arguments), plugin);
this.positionType = positionType; this.positionType = positionType;
this.arguments = arguments; this.arguments = arguments;
@@ -78,18 +78,18 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
private Optional<Home> resolveHome(@NotNull CommandUser executor, @NotNull String homeName) { private Optional<Home> resolveHome(@NotNull CommandUser executor, @NotNull String homeName) {
if (homeName.contains(Home.IDENTIFIER_DELIMITER)) { if (homeName.contains(Home.IDENTIFIER_DELIMITER)) {
final String ownerUsername = homeName.substring(0, homeName.indexOf(Home.IDENTIFIER_DELIMITER)); final String ownerUsername = homeName.substring(0, homeName.indexOf(Home.IDENTIFIER_DELIMITER));
final String ownerHomeName = homeName.substring(homeName.indexOf(Home.IDENTIFIER_DELIMITER) + 1); final String ownerHome = homeName.substring(homeName.indexOf(Home.IDENTIFIER_DELIMITER) + 1);
if (ownerUsername.isBlank() || ownerHomeName.isBlank()) { if (ownerUsername.isBlank() || ownerHome.isBlank()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
} }
final Optional<Home> optionalHome = plugin.getDatabase().getUserDataByName(ownerUsername) final Optional<Home> optionalHome = plugin.getDatabase().getUserDataByName(ownerUsername)
.flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHomeName)); .flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHome));
if (optionalHome.isEmpty()) { if (optionalHome.isEmpty()) {
plugin.getLocales().getLocale(executor.hasPermission(getOtherPermission()) plugin.getLocales().getLocale(executor.hasPermission(getOtherPermission())
? "error_home_invalid_other" : "error_public_home_invalid", ownerUsername, ownerHomeName) ? "error_home_invalid_other" : "error_public_home_invalid", ownerUsername, ownerHome)
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
} }
@@ -97,7 +97,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
final Home home = optionalHome.get(); final Home home = optionalHome.get();
if (executor instanceof OnlineUser user && !home.isPublic() && !user.equals(home.getOwner()) if (executor instanceof OnlineUser user && !home.isPublic() && !user.equals(home.getOwner())
&& !user.hasPermission(getOtherPermission())) { && !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHomeName) plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHome)
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
} }
@@ -138,7 +138,8 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
return Optional.empty(); return Optional.empty();
} }
if (executor instanceof OnlineUser user && plugin.getSettings().doPermissionRestrictWarps() if (executor instanceof OnlineUser user && plugin.getSettings().doPermissionRestrictWarps()
&& !user.hasPermission(Warp.getWildcardPermission()) && !user.hasPermission(Warp.getPermission(warpName))) { && !user.hasPermission(Warp.getWildcardPermission())
&& !user.hasPermission(Warp.getPermission(warpName))) {
plugin.getLocales().getLocale("error_warp_invalid", warpName) plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
@@ -180,6 +181,11 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
} }
} }
@NotNull
private static String formatUsage(List<String> arguments) {
return ((arguments.size() > 0) ? " [" + String.join("|", arguments) + "]" : "");
}
@Override @Override
@NotNull @NotNull
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) { public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
@@ -188,14 +194,14 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
case 0, 1 -> { case 0, 1 -> {
if (args.length == 1 && args[0].contains(Home.IDENTIFIER_DELIMITER)) { if (args.length == 1 && args[0].contains(Home.IDENTIFIER_DELIMITER)) {
if (executor.hasPermission(getOtherPermission())) { if (executor.hasPermission(getOtherPermission())) {
yield filter(plugin.getManager().homes().getUserHomeNames(), args); yield filter(plugin.getManager().homes().getUserHomeIdentifiers(), args);
} }
yield filter(plugin.getManager().homes().getUserHomeNames(), args); yield filter(plugin.getManager().homes().getUserHomeIdentifiers(), args);
} }
if (executor instanceof OnlineUser user) { if (executor instanceof OnlineUser user) {
yield filter(plugin.getManager().homes().getUserHomes().get(user.getUsername()), args); yield filter(plugin.getManager().homes().getUserHomes().get(user.getUsername()), args);
} }
yield filter(plugin.getManager().homes().getUserHomeNames(), args); yield filter(plugin.getManager().homes().getUserHomeIdentifiers(), args);
} }
case 2 -> filter(arguments.stream().toList(), args); case 2 -> filter(arguments.stream().toList(), args);
default -> List.of(); default -> List.of();
@@ -41,8 +41,9 @@ public class SetSpawnCommand extends InGameCommand {
if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalSpawn()) { if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalSpawn()) {
final String warpName = plugin.getSettings().getGlobalSpawnName(); final String warpName = plugin.getSettings().getGlobalSpawnName();
plugin.getManager().warps().createWarp(warpName, position, true); plugin.getManager().warps().createWarp(warpName, position, true);
plugin.getLocales().getRawLocale("spawn_warp_default_description") plugin.getLocales().getRawLocale("spawn_warp_default_description").ifPresent(
.ifPresent(description -> plugin.getManager().warps().setWarpDescription(warpName, description)); description -> plugin.getManager().warps().setWarpDescription(warpName, description)
);
} else { } else {
plugin.setServerSpawn(position); plugin.setServerSpawn(position);
} }
@@ -59,8 +59,8 @@ public class SpawnCommand extends Command {
this.teleportToSpawn(optionalTeleporter.get(), executor, spawn.get(), args); this.teleportToSpawn(optionalTeleporter.get(), executor, spawn.get(), args);
} }
public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor, @NotNull Position spawn, public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor,
@NotNull String[] args) { @NotNull Position spawn, @NotNull String[] args) {
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) { if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
@@ -115,16 +115,16 @@ public class TpCommand extends Command implements TabProvider {
@Override @Override
@NotNull @NotNull
public final List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) { public final List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
final Position basePosition = getBasePosition(user); final Position relative = getBasePosition(user);
final boolean serveCoordinateCompletions = user.hasPermission(getPermission("coordinates")); final boolean serveCoordinateCompletions = user.hasPermission(getPermission("coordinates"));
switch (args.length) { switch (args.length) {
case 0, 1 -> { case 0, 1 -> {
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) basePosition.getX()), Integer.toString((int) relative.getX()),
((int) basePosition.getX() + " " + (int) basePosition.getY()), ((int) relative.getX() + " " + (int) relative.getY()),
((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ())) ((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ()))
: List.of()); : List.of());
completions.addAll(plugin.getPlayerList(false)); completions.addAll(plugin.getPlayerList(false));
return completions.stream() return completions.stream()
@@ -134,15 +134,17 @@ public class TpCommand extends Command implements TabProvider {
case 2 -> { case 2 -> {
final ArrayList<String> completions = new ArrayList<>(); final ArrayList<String> completions = new ArrayList<>();
if (isCoordinate(args, 0)) { if (isCoordinate(args, 0)) {
completions.addAll(List.of("~", Integer.toString((int) basePosition.getY()))); completions.addAll(List.of("~", Integer.toString((int) relative.getY())));
completions.addAll(List.of("~ ~", (int) basePosition.getY() + " " + (int) basePosition.getZ())); completions.addAll(List.of("~ ~", (int) relative.getY() + " " + (int) relative.getZ()));
} else { } else {
completions.addAll(serveCoordinateCompletions completions.addAll(
? List.of("~", "~ ~", "~ ~ ~", serveCoordinateCompletions
Integer.toString((int) basePosition.getX()), ? List.of("~", "~ ~", "~ ~ ~",
((int) basePosition.getX() + " " + (int) basePosition.getY()), Integer.toString((int) relative.getX()),
((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ())) ((int) relative.getX() + " " + (int) relative.getY()),
: List.of()); ((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ()))
: List.of()
);
completions.addAll(plugin.getPlayerList(false)); completions.addAll(plugin.getPlayerList(false));
} }
return completions.stream() return completions.stream()
@@ -155,13 +157,13 @@ public class TpCommand extends Command implements TabProvider {
if (!serveCoordinateCompletions) { if (!serveCoordinateCompletions) {
return completions; return completions;
} }
completions.addAll(List.of("~", Integer.toString((int) basePosition.getZ()))); completions.addAll(List.of("~", Integer.toString((int) relative.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) basePosition.getY()))); completions.addAll(List.of("~", Integer.toString((int) relative.getY())));
completions.addAll(List.of("~ ~", (int) basePosition.getY() + " " + (int) basePosition.getZ())); completions.addAll(List.of("~ ~", (int) relative.getY() + " " + (int) relative.getZ()));
} }
return completions.stream() return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase())) .filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase()))
@@ -173,7 +175,7 @@ public class TpCommand extends Command implements TabProvider {
if (!serveCoordinateCompletions) { if (!serveCoordinateCompletions) {
return completions; return completions;
} }
completions.addAll(List.of("~", Integer.toString((int) basePosition.getZ()))); completions.addAll(List.of("~", Integer.toString((int) relative.getZ())));
} }
return completions.stream() return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase())) .filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase()))
@@ -28,14 +28,19 @@ import java.util.Optional;
/** /**
* A command used for responding to tp requests - can either be a /tpaccept or /tpdecline command, controlled by the * A command used for responding to tp requests - can either be a /tpaccept or /tpdecline command, controlled by the
* acceptRequestCommand flag * acceptRequestCommand flag.
*/ */
public class TpRespondCommand extends InGameCommand implements UserListTabProvider { public class TpRespondCommand extends InGameCommand implements UserListTabProvider {
private final boolean accept; private final boolean accept;
protected TpRespondCommand(@NotNull HuskHomes plugin, boolean accept) { protected TpRespondCommand(@NotNull HuskHomes plugin, boolean accept) {
super(accept ? "tpaccept" : "tpdecline", accept ? List.of("tpyes") : List.of("tpno", "tpdeny"), "[player]", plugin); super(
accept ? "tpaccept" : "tpdecline",
accept ? List.of("tpyes") : List.of("tpno", "tpdeny"),
"[player]",
plugin
);
this.accept = accept; this.accept = accept;
} }
@@ -48,7 +48,8 @@ public class WarpCommand extends SavedPositionCommand<Warp> {
@Override @Override
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) { public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
if (plugin.getSettings().doPermissionRestrictWarps()) { if (plugin.getSettings().doPermissionRestrictWarps()) {
if (!executor.hasPermission(warp.getPermission()) && !executor.hasPermission(Warp.getWildcardPermission())) { if (!executor.hasPermission(warp.getPermission())
&& !executor.hasPermission(Warp.getWildcardPermission())) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
@@ -70,7 +70,10 @@ public class WarpListCommand extends ListCommand {
plugin.getLocales() plugin.getLocales()
.getRawLocale("warp_list_item", .getRawLocale("warp_list_item",
Locales.escapeText(warp.getName()), warp.getSafeIdentifier(), Locales.escapeText(warp.getName()), warp.getSafeIdentifier(),
Locales.escapeText(plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40))) Locales.escapeText(plugin.getLocales().wrapText(
warp.getMeta().getDescription(),
40
)))
.orElse(warp.getName())).sorted().collect(Collectors.toList()), .orElse(warp.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales() plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage()) .getBaseList(plugin.getSettings().getListItemsPerPage())
@@ -32,7 +32,7 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
/** /**
* Loaded locales used by the plugin to display styled messages * Loaded locales used by the plugin to display styled messages.
*/ */
@YamlFile(rootedMap = true, header = """ @YamlFile(rootedMap = true, header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
@@ -45,7 +45,7 @@ import java.util.Optional;
public class Locales { public class Locales {
/** /**
* The raw set of locales loaded from yaml * The raw set of locales loaded from yaml.
*/ */
public Map<String, String> rawLocales = new HashMap<>(); public Map<String, String> rawLocales = new HashMap<>();
@@ -54,7 +54,7 @@ public class Locales {
} }
/** /**
* Returns a raw, un-formatted locale loaded from the locales file * Returns a raw, unformatted locale loaded from the locale file.
* *
* @param localeId String identifier of the locale, corresponding to a key in the file * @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the locale corresponding to the id, if it exists * @return An {@link Optional} containing the locale corresponding to the id, if it exists
@@ -64,12 +64,12 @@ public class Locales {
} }
/** /**
* Returns a raw, un-formatted locale loaded from the locales file, with replacements applied * Returns a raw, unformatted locale loaded from the locale file, with replacements applied.
* <p> *
* Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements * <p>Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements
* *
* @param localeId String identifier of the locale, corresponding to a key in the file * @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with * @param replacements An ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists * @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists
*/ */
public Optional<String> getRawLocale(@NotNull String localeId, @NotNull String... replacements) { public Optional<String> getRawLocale(@NotNull String localeId, @NotNull String... replacements) {
@@ -77,7 +77,7 @@ public class Locales {
} }
/** /**
* Returns a MineDown-formatted locale from the locales file * Returns a MineDown-formatted locale from the locale file.
* *
* @param localeId String identifier of the locale, corresponding to a key in the file * @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists * @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists
@@ -87,13 +87,13 @@ public class Locales {
} }
/** /**
* Returns a MineDown-formatted locale from the locales file, with replacements applied * Returns a MineDown-formatted locale from the locale file, with replacements applied.
* <p> *
* Note that replacements will be MineDown-escaped before application * <p>Note that replacements will be MineDown-escaped before application
* *
* @param localeId String identifier of the locale, corresponding to a key in the file * @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with * @param replacements An ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists * @return An {@link Optional} with the replacement-applied, formatted locale corresponding to the id, if it exists
*/ */
public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) { public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) {
return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText) return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText)
@@ -101,10 +101,10 @@ public class Locales {
} }
/** /**
* Apply placeholder replacements to a raw locale * Apply placeholder replacements to a raw locale.
* *
* @param rawLocale The raw, unparsed locale * @param rawLocale The raw, unparsed locale
* @param replacements Ordered array of replacement strings to fill in placeholders with * @param replacements An ordered array of replacement strings to fill in placeholders with
* @return the raw locale, with inserted placeholders * @return the raw locale, with inserted placeholders
*/ */
@NotNull @NotNull
@@ -119,7 +119,7 @@ public class Locales {
} }
/** /**
* Escape a string from {@link MineDown} formatting for use in a MineDown-formatted locale * Escape a string from {@link MineDown} formatting for use in a MineDown-formatted locale.
* *
* @param string The string to escape * @param string The string to escape
* @return The escaped string * @return The escaped string
@@ -150,7 +150,7 @@ public class Locales {
} }
/** /**
* Formats a description string, wrapping text on whitespace after 40 characters * Formats a description string, wrapping text on whitespace after 40 characters.
* *
* @param string The string to format * @param string The string to format
* @return The line-break formatted string, or a String literal {@code "N/A"} if the input string is empty * @return The line-break formatted string, or a String literal {@code "N/A"} if the input string is empty
@@ -189,7 +189,7 @@ public class Locales {
} }
/** /**
* Represents where a locale should be displayed * Represents where a locale should be displayed.
*/ */
public enum DisplaySlot { public enum DisplaySlot {
CHAT, CHAT,
@@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull;
import java.nio.file.Path; import java.nio.file.Path;
/** /**
* Represents a server on a proxied network * Represents a server on a proxied network.
*/ */
@YamlFile(header = """ @YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
@@ -39,7 +39,7 @@ import java.nio.file.Path;
public class Server { public class Server {
/** /**
* Default server identifier * Default server identifier.
*/ */
@NotNull @NotNull
public static String getDefaultServerName() { public static String getDefaultServerName() {
@@ -72,7 +72,7 @@ public class Server {
} }
/** /**
* Proxy-defined name of this server * Proxy-defined name of this server.
*/ */
@NotNull @NotNull
public String getName() { public String getName() {
@@ -55,7 +55,7 @@ public class Settings {
private boolean checkForUpdates = true; private boolean checkForUpdates = true;
// Database settings // Database settings
@YamlComment("Type of database to use (MYSQL, SQLITE)") @YamlComment("Type of database to use (SQLITE, MYSQL or MARIADB)")
@YamlKey("database.type") @YamlKey("database.type")
private Database.Type databaseType = Database.Type.SQLITE; private Database.Type databaseType = Database.Type.SQLITE;
@@ -76,9 +76,13 @@ public class Settings {
private String mySqlPassword = "pa55w0rd"; private String mySqlPassword = "pa55w0rd";
@YamlKey("database.mysql.credentials.parameters") @YamlKey("database.mysql.credentials.parameters")
private String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"; private String mySqlConnectionParameters = "?autoReconnect=true"
+ "&useSSL=false"
+ "&useUnicode=true"
+ "&characterEncoding=UTF-8";
@YamlComment("MYSQL database Hikari connection pool properties. Don't modify this unless you know what you're doing!") @YamlComment("MYSQL database Hikari connection pool properties. "
+ "Don't modify this unless you know what you're doing!")
@YamlKey("database.mysql.connection_pool.size") @YamlKey("database.mysql.connection_pool.size")
private int mySqlConnectionPoolSize = 12; private int mySqlConnectionPoolSize = 12;
@@ -96,15 +100,7 @@ public class Settings {
@YamlComment("Names of tables to use on your database. Don't modify this unless you know what you're doing!") @YamlComment("Names of tables to use on your database. Don't modify this unless you know what you're doing!")
@YamlKey("database.table_names") @YamlKey("database.table_names")
private Map<String, String> tableNames = Map.of( private Map<String, String> tableNames = Database.Table.getConfigMap();
Database.Table.PLAYER_DATA.name().toLowerCase(), Database.Table.PLAYER_DATA.getDefaultName(),
Database.Table.PLAYER_COOLDOWNS_DATA.name().toLowerCase(), Database.Table.PLAYER_COOLDOWNS_DATA.getDefaultName(),
Database.Table.POSITION_DATA.name().toLowerCase(), Database.Table.POSITION_DATA.getDefaultName(),
Database.Table.SAVED_POSITION_DATA.name().toLowerCase(), Database.Table.SAVED_POSITION_DATA.getDefaultName(),
Database.Table.HOME_DATA.name().toLowerCase(), Database.Table.HOME_DATA.getDefaultName(),
Database.Table.WARP_DATA.name().toLowerCase(), Database.Table.WARP_DATA.getDefaultName(),
Database.Table.TELEPORT_DATA.name().toLowerCase(), Database.Table.TELEPORT_DATA.getDefaultName()
);
// General settings // General settings
@@ -112,11 +108,13 @@ public class Settings {
@YamlKey("general.max_homes") @YamlKey("general.max_homes")
private int maxHomes = 10; private int maxHomes = 10;
@YamlComment("The maximum public homes a user can create. Override with the huskhomes.max_public_homes.<number> permission.") @YamlComment("The maximum public homes a user can create. "
+ "Override with the huskhomes.max_public_homes.<number> permission.")
@YamlKey("general.max_public_homes") @YamlKey("general.max_public_homes")
private int maxPublicHomes = 10; private int maxPublicHomes = 10;
@YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>) should stack if the user inherits multiple nodes.") @YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>)"
+ "should stack if the user inherits multiple nodes.")
@YamlKey("general.stack_permission_limits") @YamlKey("general.stack_permission_limits")
private boolean stackPermissionLimits = false; private boolean stackPermissionLimits = false;
@@ -124,7 +122,7 @@ public class Settings {
@YamlKey("general.permission_restrict_warps") @YamlKey("general.permission_restrict_warps")
private boolean permissionRestrictWarps = false; private boolean permissionRestrictWarps = false;
@YamlComment("Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite it.") @YamlComment("Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite.")
@YamlKey("general.overwrite_existing_homes_warps") @YamlKey("general.overwrite_existing_homes_warps")
private boolean overwriteExistingHomesWarps = true; private boolean overwriteExistingHomesWarps = true;
@@ -160,7 +158,7 @@ public class Settings {
@YamlKey("general.back_command_return_by_death") @YamlKey("general.back_command_return_by_death")
private boolean backCommandReturnByDeath = true; private boolean backCommandReturnByDeath = true;
@YamlComment("Whether /back should work with other plugins that use the PlayerTeleportEvent (this can cause conflicts)") @YamlComment("Whether /back should work with other plugins that use the PlayerTeleportEvent (can cause conflicts)")
@YamlKey("general.back_command_save_teleport_event") @YamlKey("general.back_command_save_teleport_event")
private boolean backCommandSaveOnTeleportEvent = false; private boolean backCommandSaveOnTeleportEvent = false;
@@ -178,12 +176,7 @@ public class Settings {
@YamlComment("Which sound effects to play for various actions") @YamlComment("Which sound effects to play for various actions")
@YamlKey("general.sound_effects") @YamlKey("general.sound_effects")
private Map<String, String> soundEffects = Map.of( private Map<String, String> soundEffects = SoundEffectAction.getConfigMap();
SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_WARMUP.name().toLowerCase(), SoundEffectAction.TELEPORTATION_WARMUP.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_CANCELLED.name().toLowerCase(), SoundEffectAction.TELEPORTATION_CANCELLED.defaultSoundEffect,
SoundEffectAction.TELEPORT_REQUEST_RECEIVED.name().toLowerCase(), SoundEffectAction.TELEPORT_REQUEST_RECEIVED.defaultSoundEffect
);
@YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)") @YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)")
@YamlKey("general.brigadier_tab_completion") @YamlKey("general.brigadier_tab_completion")
@@ -199,7 +192,8 @@ public class Settings {
@YamlKey("cross_server.messenger_type") @YamlKey("cross_server.messenger_type")
private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE; private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE;
@YamlComment("Specify a common ID for grouping servers running HuskHomes on your proxy. Don't modify this unless you know what you're doing!") @YamlComment("Specify a common ID for grouping servers running HuskHomes on your proxy. "
+ "Don't modify this unless you know what you're doing!")
@YamlKey("cross_server.cluster_id") @YamlKey("cross_server.cluster_id")
private String clusterId = ""; private String clusterId = "";
@@ -242,7 +236,7 @@ public class Settings {
@YamlKey("rtp.distribution_mean") @YamlKey("rtp.distribution_mean")
private float rtpDistributionMean = 0.75f; private float rtpDistributionMean = 0.75f;
@YamlComment("Standard deviation of the normal distribution used to calculate the distance from the center of the world") @YamlComment("Standard deviation of the normal distribution for distributing players randomly")
@YamlKey("rtp.distribution_deviation") @YamlKey("rtp.distribution_deviation")
private float rtpDistributionStandardDeviation = 2f; private float rtpDistributionStandardDeviation = 2f;
@@ -370,7 +364,7 @@ public class Settings {
@NotNull @NotNull
public String getTableName(@NotNull Database.Table table) { public String getTableName(@NotNull Database.Table table) {
return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getDefaultName()); return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getName());
} }
public int getMaxHomes() { public int getMaxHomes() {
@@ -563,7 +557,7 @@ public class Settings {
return disabledCommands.stream().anyMatch(disabled -> { return disabledCommands.stream().anyMatch(disabled -> {
final String command = (disabled.startsWith("/") ? disabled.substring(1) : disabled); final String command = (disabled.startsWith("/") ? disabled.substring(1) : disabled);
return command.equalsIgnoreCase(type.getName()) return command.equalsIgnoreCase(type.getName())
|| type.getAliases().stream().anyMatch(alias -> alias.equalsIgnoreCase(command)); || type.getAliases().stream().anyMatch(alias -> alias.equalsIgnoreCase(command));
}); });
} }
@@ -572,18 +566,28 @@ public class Settings {
} }
/** /**
* Represents actions that have a sound effect associated with performing them * Represents actions that have a sound effect associated with performing them.
*/ */
public enum SoundEffectAction { public enum SoundEffectAction {
TELEPORTATION_COMPLETE("entity.enderman.teleport"), TELEPORTATION_COMPLETE("entity.enderman.teleport"),
TELEPORTATION_WARMUP("block.note_block.banjo"), TELEPORTATION_WARMUP("block.note_block.banjo"),
TELEPORTATION_CANCELLED("entity.item.break"), TELEPORTATION_CANCELLED("entity.item.break"),
TELEPORT_REQUEST_RECEIVED("entity.experience_orb.pickup"); TELEPORT_REQUEST_RECEIVED("entity.experience_orb.pickup");
private final String defaultSoundEffect; private final String defaultEffect;
SoundEffectAction(@NotNull String defaultSoundEffect) { SoundEffectAction(@NotNull String defaultEffect) {
this.defaultSoundEffect = defaultSoundEffect; this.defaultEffect = defaultEffect;
} }
@NotNull
public static Map<String, String> getConfigMap() {
return Arrays.stream(values())
.collect(Collectors.toMap(
SoundEffectAction::name,
action -> action.defaultEffect)
);
}
} }
} }
@@ -29,7 +29,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
/** /**
* Used to store the server spawn location * Used to store the server spawn location.
*/ */
@YamlFile(header = """ @YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
@@ -49,7 +49,7 @@ public class Spawn {
public String worldUuid; public String worldUuid;
/** /**
* Returns the {@link Position} of the spawn * Returns the {@link Position} of the spawn.
* *
* @param server The server the spawn is on * @param server The server the spawn is on
* @return The {@link Position} of the spawn * @return The {@link Position} of the spawn
@@ -60,7 +60,7 @@ public class Spawn {
} }
/** /**
* Set the {@link Location} of the spawn * Set the {@link Location} of the spawn.
* *
* @param location The {@link Location} of the spawn * @param location The {@link Location} of the spawn
*/ */
@@ -30,6 +30,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver; import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -38,23 +39,20 @@ import java.nio.charset.StandardCharsets;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.*;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* An abstract representation of the plugin database, storing home, warp and player data. * An abstract representation of the plugin database, storing home, warp and player data.
* <p> *
* Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator. * <p>Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator.
*/ */
public abstract class Database { public abstract class Database {
protected final HuskHomes plugin; protected final HuskHomes plugin;
/** /**
* Loads SQL table creation schema statements from a resource file as a string array * Loads SQL table creation schema statements from a resource file as a string array.
* *
* @param schemaFileName database script resource file to load from * @param schemaFileName database script resource file to load from
* @return Array of string-formatted table creation schema statements * @return Array of string-formatted table creation schema statements
@@ -68,24 +66,31 @@ public abstract class Database {
} }
/** /**
* Format all table name placeholder strings in a SQL statement * Format all table name placeholder strings in an SQL statement.
* *
* @param sql the SQL statement with unformatted table name placeholders * @param sql the SQL statement with unformatted table name placeholders
* @return the formatted statement, with table placeholders replaced with the correct names * @return the formatted statement, with table placeholders replaced with the correct names
*/ */
protected final String formatStatementTables(@NotNull String sql) { protected final String formatStatementTables(@NotNull String sql) {
return sql return sql
.replaceAll("%positions_table%", plugin.getSettings().getTableName(Table.POSITION_DATA)) .replaceAll("%positions_table%", plugin.getSettings()
.replaceAll("%players_table%", plugin.getSettings().getTableName(Table.PLAYER_DATA)) .getTableName(Table.POSITION_DATA))
.replaceAll("%cooldowns_table%", plugin.getSettings().getTableName(Table.PLAYER_COOLDOWNS_DATA)) .replaceAll("%players_table%", plugin.getSettings()
.replaceAll("%teleports_table%", plugin.getSettings().getTableName(Table.TELEPORT_DATA)) .getTableName(Table.PLAYER_DATA))
.replaceAll("%saved_positions_table%", plugin.getSettings().getTableName(Table.SAVED_POSITION_DATA)) .replaceAll("%cooldowns_table%", plugin.getSettings()
.replaceAll("%homes_table%", plugin.getSettings().getTableName(Table.HOME_DATA)) .getTableName(Table.PLAYER_COOLDOWNS_DATA))
.replaceAll("%warps_table%", plugin.getSettings().getTableName(Table.WARP_DATA)); .replaceAll("%teleports_table%", plugin.getSettings()
.getTableName(Table.TELEPORT_DATA))
.replaceAll("%saved_positions_table%", plugin.getSettings()
.getTableName(Table.SAVED_POSITION_DATA))
.replaceAll("%homes_table%", plugin.getSettings()
.getTableName(Table.HOME_DATA))
.replaceAll("%warps_table%", plugin.getSettings()
.getTableName(Table.WARP_DATA));
} }
/** /**
* Create a database instance, pulling table names from the plugin config * Create a database instance, pulling table names from the plugin config.
* *
* @param plugin the implementing plugin instance * @param plugin the implementing plugin instance
*/ */
@@ -99,7 +104,7 @@ public abstract class Database {
public abstract void initialize() throws IllegalStateException; public abstract void initialize() throws IllegalStateException;
/** /**
* <b>(Internal use only)</b> - Sets a position to the position table in the database * <b>(Internal use only)</b> - Sets a position to the position table in the database.
* *
* @param position The {@link Position} to set * @param position The {@link Position} to set
* @param connection SQL connection * @param connection SQL connection
@@ -109,44 +114,50 @@ public abstract class Database {
protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException; protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException;
/** /**
* <b>(Internal use only)</b> - Updates position data * <b>(Internal use only)</b> - Updates position data.
* *
* @param positionId ID of the position to update * @param positionId ID of the position to update
* @param position the Position.at * @param position the Position.at
* @param connection SQL connection * @param connection SQL connection
* @throws SQLException if an SQL exception occurs doing this * @throws SQLException if an SQL exception occurs doing this
*/ */
protected abstract void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException; @ApiStatus.Internal
protected abstract void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException;
/** /**
* <b>(Internal use only)</b> - Sets a {@link SavedPosition} to the database * <b>(Internal use only)</b> - Sets a {@link SavedPosition} to the database.
* *
* @param position The {@link SavedPosition} to set * @param position The {@link SavedPosition} to set
* @param connection SQL connection * @param connection SQL connection
* @return The newly inserted row ID * @return The newly inserted row ID
* @throws SQLException if an SQL exception occurs doing this * @throws SQLException if an SQL exception occurs doing this
*/ */
protected abstract int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException; @ApiStatus.Internal
protected abstract int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException;
/** /**
* <b>(Internal use only)</b> - Updates a saved position metadata * <b>(Internal use only)</b> - Updates a saved position metadata.
* *
* @param savedPositionId ID of the metadata to update * @param savedPositionId ID of the metadata to update
* @param savedPosition the new saved position * @param savedPosition the new saved position
* @param connection SQL connection * @param connection SQL connection
* @throws SQLException if an SQL exception occurs doing this * @throws SQLException if an SQL exception occurs doing this
*/ */
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition, @NotNull Connection connection) throws SQLException; @ApiStatus.Internal
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition,
@NotNull Connection connection) throws SQLException;
/** /**
* Ensure a {@link User} has a {@link SavedUser} entry in the database and that their username is up-to-date * Ensure a {@link User} has a {@link SavedUser} entry in the database and that their username is up-to-date.
* *
* @param user The {@link User} to ensure * @param user The {@link User} to ensure
*/ */
public abstract void ensureUser(@NotNull User user); public abstract void ensureUser(@NotNull User user);
/** /**
* Get {@link SavedUser} for a user by their Minecraft username (<i>case-insensitive</i>) * Get {@link SavedUser} for a user by their Minecraft username (<i>case-insensitive</i>).
* *
* @param name Username of the {@link SavedUser} to get (<i>case-insensitive</i>) * @param name Username of the {@link SavedUser} to get (<i>case-insensitive</i>)
* @return An optional with the {@link SavedUser} present if they exist * @return An optional with the {@link SavedUser} present if they exist
@@ -154,7 +165,7 @@ public abstract class Database {
public abstract Optional<SavedUser> getUserDataByName(@NotNull String name); public abstract Optional<SavedUser> getUserDataByName(@NotNull String name);
/** /**
* Get {@link SavedUser} for a user by their Minecraft account {@link UUID} * Get {@link SavedUser} for a user by their Minecraft account {@link UUID}.
* *
* @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get * @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get
* @return An optional with the {@link SavedUser} present if they exist * @return An optional with the {@link SavedUser} present if they exist
@@ -162,23 +173,24 @@ public abstract class Database {
public abstract Optional<SavedUser> getUserData(@NotNull UUID uuid); public abstract Optional<SavedUser> getUserData(@NotNull UUID uuid);
/** /**
* Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action} * Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
* *
* @return An optional containing the {@link Instant} the cooldown expires at, or empty if the {@link User} has no cooldown * @return An optional with the {@link Instant} the cooldown expires, or empty if the {@link User} has no cooldown
*/ */
public abstract Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user); public abstract Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user);
/** /**
* Set the cooldown of a {@link User} for a specific {@link TransactionResolver.Action} * Set the cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
* *
* @param action The {@link TransactionResolver.Action} to set the cooldown for * @param action The {@link TransactionResolver.Action} to set the cooldown for
* @param user The {@link User} to set the cooldown for * @param user The {@link User} to set the cooldown for
* @param cooldownExpiry The {@link Instant} the cooldown expires at * @param cooldownExpiry The {@link Instant} the cooldown expires at
*/ */
public abstract void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry); public abstract void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry);
/** /**
* Remove the cooldown of a {@link User} for a specific {@link TransactionResolver.Action} * Remove the cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
* *
* @param action The {@link TransactionResolver.Action} to remove the cooldown for * @param action The {@link TransactionResolver.Action} to remove the cooldown for
* @param user The {@link User} to remove the cooldown for * @param user The {@link User} to remove the cooldown for
@@ -186,7 +198,7 @@ public abstract class Database {
public abstract void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user); public abstract void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user);
/** /**
* Get a list of {@link Home}s set by a {@link User} * Get a list of {@link Home}s set by a {@link User}.
* *
* @param user {@link User} to get the homes of * @param user {@link User} to get the homes of
* @return A future returning void when complete * @return A future returning void when complete
@@ -194,14 +206,14 @@ public abstract class Database {
public abstract List<Home> getHomes(@NotNull User user); public abstract List<Home> getHomes(@NotNull User user);
/** /**
* Get a list of all {@link Warp}s that have been set * Get a list of all {@link Warp}s that have been set.
* *
* @return A list containing all {@link Warp}s * @return A list containing all {@link Warp}s
*/ */
public abstract List<Warp> getWarps(); public abstract List<Warp> getWarps();
/** /**
* Get a list of publicly-set {@link Warp}s on <i>this {@link Server}</i> * Get a list of publicly-set {@link Warp}s on <i>this {@link Server server}</i>.
* *
* @param plugin The plugin instance * @param plugin The plugin instance
* @return A list containing all {@link Warp}s set on this server * @return A list containing all {@link Warp}s set on this server
@@ -214,14 +226,14 @@ public abstract class Database {
} }
/** /**
* Get a list of all publicly-set {@link Home}s * Get a list of all publicly-set {@link Home}s.
* *
* @return A list containing all publicly-set {@link Home}s * @return A list containing all publicly-set {@link Home}s
*/ */
public abstract List<Home> getPublicHomes(); public abstract List<Home> getPublicHomes();
/** /**
* Get a list of publicly-set {@link Home}s on <i>this {@link Server}</i> * Get a list of publicly-set {@link Home}s on <i>this {@link Server server}</i>.
* *
* @param plugin The plugin instance * @param plugin The plugin instance
* @return A list containing all publicly-set {@link Home}s on this server * @return A list containing all publicly-set {@link Home}s on this server
@@ -234,19 +246,19 @@ public abstract class Database {
} }
/** /**
* Get a {@link Home} with the given name, set by the given {@link User} * Get a {@link Home} with the given name, set by the given {@link User}.
* *
* @param user The {@link User} who set the home * @param user The {@link User} who set the home
* @param homeName The name of the home to get * @param homeName The name of the home to get
* @return An optional with the {@link Home} present if it exists * @return An optional with the {@link Home} present if it exists
* @apiNote Whether the name lookup query is case-insensitive is determined by the {@code general.case_insensitive_names} setting * @apiNote Whether lookup is case-sensitive is determined by the {@code general.case_insensitive_names} setting
*/ */
public final Optional<Home> getHome(@NotNull User user, @NotNull String homeName) { public final Optional<Home> getHome(@NotNull User user, @NotNull String homeName) {
return this.getHome(user, homeName, plugin.getSettings().caseInsensitiveNames()); return this.getHome(user, homeName, plugin.getSettings().caseInsensitiveNames());
} }
/** /**
* Get a {@link Home} with the given name, set by the given {@link User} * Get a {@link Home} with the given name, set by the given {@link User}.
* *
* @param user The {@link User} who set the home * @param user The {@link User} who set the home
* @param homeName The name of the home to get * @param homeName The name of the home to get
@@ -256,7 +268,7 @@ public abstract class Database {
public abstract Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive); public abstract Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive);
/** /**
* Get a {@link Home} by its unique id * Get a {@link Home} by its {@link UUID unique ID}.
* *
* @param uuid the {@link UUID} of the home to get * @param uuid the {@link UUID} of the home to get
* @return An optional with the {@link Home} present if it exists * @return An optional with the {@link Home} present if it exists
@@ -264,18 +276,18 @@ public abstract class Database {
public abstract Optional<Home> getHome(@NotNull UUID uuid); public abstract Optional<Home> getHome(@NotNull UUID uuid);
/** /**
* Get a {@link Warp} with the given name * Get a {@link Warp} with the given name.
* *
* @param warpName The name of the warp to get * @param warpName The name of the warp to get
* @return An optional with the {@link Warp} present if it exists * @return An optional with the {@link Warp} present if it exists
* @apiNote Whether the name lookup query is case-insensitive is determined by the {@code general.case_insensitive_names} setting * @apiNote Whether lookup is case-insensitive is determined by the {@code general.case_insensitive_names} setting
*/ */
public final Optional<Warp> getWarp(@NotNull String warpName) { public final Optional<Warp> getWarp(@NotNull String warpName) {
return getWarp(warpName, plugin.getSettings().caseInsensitiveNames()); return getWarp(warpName, plugin.getSettings().caseInsensitiveNames());
} }
/** /**
* Get a {@link Warp} with the given name * Get a {@link Warp} with the given name.
* *
* @param warpName The name of the warp to get * @param warpName The name of the warp to get
* @param caseInsensitive Whether the search should be case-insensitive * @param caseInsensitive Whether the search should be case-insensitive
@@ -284,7 +296,7 @@ public abstract class Database {
public abstract Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive); public abstract Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive);
/** /**
* Get a {@link Warp} by its unique id * Get a {@link Warp} by its {@link UUID unique ID}.
* *
* @param uuid the {@link UUID} of the warp to get * @param uuid the {@link UUID} of the warp to get
* @return An optional with the {@link Warp} present if it exists * @return An optional with the {@link Warp} present if it exists
@@ -292,7 +304,7 @@ public abstract class Database {
public abstract Optional<Warp> getWarp(@NotNull UUID uuid); public abstract Optional<Warp> getWarp(@NotNull UUID uuid);
/** /**
* Get the current {@link Teleport} being executed by the specified {@link OnlineUser} * Get the current {@link Teleport} being executed by the specified {@link OnlineUser}.
* *
* @param onlineUser The {@link OnlineUser} to check * @param onlineUser The {@link OnlineUser} to check
* @return An optional with the {@link Teleport} present if they are teleporting cross-server * @return An optional with the {@link Teleport} present if they are teleporting cross-server
@@ -300,23 +312,23 @@ public abstract class Database {
public abstract Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser); public abstract Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser);
/** /**
* Updates a user in the database with new {@link SavedUser} * Updates a user in the database with new {@link SavedUser}.
* *
* @param savedUser The {@link SavedUser} to update * @param savedUser The {@link SavedUser} to update
*/ */
public abstract void updateUserData(@NotNull SavedUser savedUser); public abstract void updateUserData(@NotNull SavedUser savedUser);
/** /**
* Sets or clears the current {@link Teleport} being executed by a {@link User} * Sets or clears the current {@link Teleport} being executed by a {@link User}.
* *
* @param user The {@link User} to set the current teleport of. * @param user The {@link User} to set the current teleport of.
* Pass as {@code null} to clear the player's current teleport.<p> * Pass as {@code null} to clear the player's current teleport
* @param teleport The {@link Teleport} to set as their current cross-server teleport * @param teleport The {@link Teleport} to set as their current cross-server teleport
*/ */
public abstract void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport); public abstract void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport);
/** /**
* Clears the current {@link Teleport} being executed by a {@link User} * Clears the current {@link Teleport} being executed by a {@link User}.
* *
* @param user The {@link User} to clear the current teleport of * @param user The {@link User} to clear the current teleport of
*/ */
@@ -325,7 +337,7 @@ public abstract class Database {
} }
/** /**
* Get the last teleport {@link Position} of a specified {@link User} * Get the last teleport {@link Position} of a specified {@link User}.
* *
* @param user The {@link User} to check * @param user The {@link User} to check
* @return An optional with the {@link Position} present if it has been set * @return An optional with the {@link Position} present if it has been set
@@ -333,7 +345,7 @@ public abstract class Database {
public abstract Optional<Position> getLastPosition(@NotNull User user); public abstract Optional<Position> getLastPosition(@NotNull User user);
/** /**
* Sets the last teleport {@link Position} of a {@link User} * Sets the last teleport {@link Position} of a {@link User}.
* *
* @param user The {@link User} to set the last position of * @param user The {@link User} to set the last position of
* @param position The {@link Position} to set as their last position * @param position The {@link Position} to set as their last position
@@ -341,7 +353,7 @@ public abstract class Database {
public abstract void setLastPosition(@NotNull User user, @NotNull Position position); public abstract void setLastPosition(@NotNull User user, @NotNull Position position);
/** /**
* Get the offline {@link Position} of a specified {@link User} * Get the offline {@link Position} of a specified {@link User}.
* *
* @param user The {@link User} to check * @param user The {@link User} to check
* @return An optional with the {@link Position} present if it has been set * @return An optional with the {@link Position} present if it has been set
@@ -349,7 +361,7 @@ public abstract class Database {
public abstract Optional<Position> getOfflinePosition(@NotNull User user); public abstract Optional<Position> getOfflinePosition(@NotNull User user);
/** /**
* Sets the offline {@link Position} of a {@link User} * Sets the offline {@link Position} of a {@link User}.
* *
* @param user The {@link User} to set the offline position of * @param user The {@link User} to set the offline position of
* @param position The {@link Position} to set as their offline position * @param position The {@link Position} to set as their offline position
@@ -357,7 +369,7 @@ public abstract class Database {
public abstract void setOfflinePosition(@NotNull User user, @NotNull Position position); public abstract void setOfflinePosition(@NotNull User user, @NotNull Position position);
/** /**
* Get the respawn {@link Position} of a specified {@link User} * Get the respawn {@link Position} of a specified {@link User}.
* *
* @param user The {@link User} to check * @param user The {@link User} to check
* @return An optional with the {@link Position} present if it has been set * @return An optional with the {@link Position} present if it has been set
@@ -365,11 +377,11 @@ public abstract class Database {
public abstract Optional<Position> getRespawnPosition(@NotNull User user); public abstract Optional<Position> getRespawnPosition(@NotNull User user);
/** /**
* Sets or clears the respawn {@link Position} of a {@link User} * Sets or clears the respawn {@link Position} of a {@link User}.
* *
* @param user The {@link User} to set the respawn position of * @param user The {@link User} to set the respawn position of
* @param position The {@link Position} to set as their respawn position * @param position The {@link Position} to set as their respawn position
* Pass as {@code null} to clear the player's current respawn position.<p> * Pass as {@code null} to clear the player's current respawn position.
*/ */
public abstract void setRespawnPosition(@NotNull User user, @Nullable Position position); public abstract void setRespawnPosition(@NotNull User user, @Nullable Position position);
@@ -410,23 +422,24 @@ public abstract class Database {
public abstract void deleteWarp(@NotNull UUID uuid); public abstract void deleteWarp(@NotNull UUID uuid);
/** /**
* Deletes all {@link Warp}s set on the database table * Deletes all {@link Warp}s set on the database table.
* *
* @return An integer; the number of deleted warps * @return An integer; the number of deleted warps
*/ */
public abstract int deleteAllWarps(); public abstract int deleteAllWarps();
/** /**
* Close any remaining connection to the database source * Close any remaining connection to the database source.
*/ */
public abstract void terminate(); public abstract void terminate();
/** /**
* Identifies types of databases * Identifies types of databases.
*/ */
public enum Type { public enum Type {
MYSQL("MySQL"), MYSQL("MySQL"),
MARIADB("MariaDB"),
SQLITE("SQLite"); SQLITE("SQLite");
private final String displayName; private final String displayName;
@@ -442,7 +455,7 @@ public abstract class Database {
} }
/** /**
* Represents the names of tables in the database * Represents the names of tables in the database.
*/ */
public enum Table { public enum Table {
PLAYER_DATA("huskhomes_users"), PLAYER_DATA("huskhomes_users"),
@@ -460,8 +473,18 @@ public abstract class Database {
} }
@NotNull @NotNull
public String getDefaultName() { public String getName() {
return defaultName; return defaultName;
} }
@NotNull
public static Map<String, String> getConfigMap() {
return Arrays.stream(values())
.collect(Collectors.toMap(
Table::name,
action -> action.defaultName
));
}
} }
} }
@@ -38,7 +38,7 @@ import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* A MySQL implementation of the plugin {@link Database} * A MySQL implementation of the plugin {@link Database}.
*/ */
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
public class MySqlDatabase extends Database { public class MySqlDatabase extends Database {
@@ -51,7 +51,7 @@ public class MySqlDatabase extends Database {
} }
/** /**
* Fetch the auto-closeable connection from the hikariDataSource * Fetch the auto-closeable connection from the hikariDataSource.
* *
* @return The {@link Connection} to the MySQL database * @return The {@link Connection} to the MySQL database
* @throws SQLException if the connection fails for some reason * @throws SQLException if the connection fails for some reason
@@ -64,13 +64,15 @@ public class MySqlDatabase extends Database {
public void initialize() throws IllegalStateException { public void initialize() throws IllegalStateException {
// Initialize the Hikari pooled connection // Initialize the Hikari pooled connection
dataSource = new HikariDataSource(); dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://" + dataSource.setJdbcUrl("jdbc:" + (plugin.getSettings().getDatabaseType() == Type.MARIADB ? "mariadb" : "mysql")
plugin.getSettings().getMySqlHost() + + "://"
":" + + plugin.getSettings().getMySqlHost()
plugin.getSettings().getMySqlPort() + + ":"
"/" + + plugin.getSettings().getMySqlPort()
plugin.getSettings().getMySqlDatabase() + + "/"
plugin.getSettings().getMySqlConnectionParameters()); + plugin.getSettings().getMySqlDatabase()
+ plugin.getSettings().getMySqlConnectionParameters()
);
// Authenticate with the database // Authenticate with the database
dataSource.setUsername(plugin.getSettings().getMySqlUsername()); dataSource.setUsername(plugin.getSettings().getMySqlUsername());
@@ -85,19 +87,24 @@ public class MySqlDatabase extends Database {
dataSource.setPoolName(DATA_POOL_NAME); dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties // Set additional connection pool properties
dataSource.setDataSourceProperties(new Properties() {{ final Properties properties = new Properties();
put("cachePrepStmts", "true"); properties.putAll(
put("prepStmtCacheSize", "250"); Map.of("cachePrepStmts", "true",
put("prepStmtCacheSqlLimit", "2048"); "prepStmtCacheSize", "250",
put("useServerPrepStmts", "true"); "prepStmtCacheSqlLimit", "2048",
put("useLocalSessionState", "true"); "useServerPrepStmts", "true",
put("useLocalTransactionState", "true"); "useLocalSessionState", "true",
put("rewriteBatchedStatements", "true"); "useLocalTransactionState", "true"
put("cacheResultSetMetadata", "true"); ));
put("cacheServerConfiguration", "true"); properties.putAll(
put("elideSetAutoCommits", "true"); Map.of(
put("maintainTimeStats", "false"); "rewriteBatchedStatements", "true",
}}); "cacheResultSetMetadata", "true",
"cacheServerConfiguration", "true",
"elideSetAutoCommits", "true",
"maintainTimeStats", "false")
);
dataSource.setDataSourceProperties(properties);
// Prepare database schema; make tables if they don't exist // Prepare database schema; make tables if they don't exist
try (Connection connection = dataSource.getConnection()) { try (Connection connection = dataSource.getConnection()) {
@@ -107,20 +114,22 @@ public class MySqlDatabase extends Database {
statement.execute(tableCreationStatement); statement.execute(tableCreationStatement);
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IllegalStateException("Failed to create database tables. Please ensure you are running MySQL v8.0+ " + throw new IllegalStateException("Failed to create database tables. Make sure you're running MySQL v8.0+"
"and that your connecting user account has privileges to create tables.", e); + "and that your connecting user account has privileges to create tables.", e);
} }
} catch (SQLException | IOException e) { } catch (SQLException | IOException e) {
throw new IllegalStateException("Failed to establish a connection to the MySQL database. " + throw new IllegalStateException("Failed to establish a connection to the MySQL database. "
"Please check the supplied database credentials in the config file", e); + "Please check the supplied database credentials in the config file", e);
} }
} }
@Override @Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) INSERT INTO `%positions_table%`
VALUES (?,?,?,?,?,?,?,?);"""), (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.getX()); statement.setDouble(1, position.getX());
@@ -142,7 +151,8 @@ public class MySqlDatabase extends Database {
} }
@Override @Override
protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException { protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%positions_table%` UPDATE `%positions_table%`
SET `x`=?, SET `x`=?,
@@ -168,10 +178,13 @@ public class MySqlDatabase extends Database {
} }
@Override @Override
protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `tags`, `timestamp`) INSERT INTO `%saved_positions_table%`
VALUES (?,?,?,?,?);"""), (`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection)); statement.setInt(1, setPosition(position, connection));
@@ -190,7 +203,8 @@ public class MySqlDatabase extends Database {
} }
@Override @Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
SELECT `position_id` SELECT `position_id`
FROM `%saved_positions_table%` FROM `%saved_positions_table%`
@@ -220,7 +234,8 @@ public class MySqlDatabase extends Database {
@Override @Override
public void ensureUser(@NotNull User onlineUser) { public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUserData -> { getUserData(onlineUser.getUuid()).ifPresentOrElse(
existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.getUsername())) { if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
// Update a player's name if it has changed in the database // Update a player's name if it has changed in the database
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
@@ -233,7 +248,9 @@ public class MySqlDatabase extends Database {
statement.setString(2, existingUserData.getUserUuid().toString()); statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
} }
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.getUsername() + ")"); plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
+ "'s name in the database (" + existingUserData.getUsername()
+ " -> " + onlineUser.getUsername() + ")");
} catch (SQLException e) { } catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
} }
@@ -331,7 +348,8 @@ public class MySqlDatabase extends Database {
} }
@Override @Override
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
@@ -368,11 +386,15 @@ public class MySqlDatabase extends Database {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`,
`timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=? WHERE `owner_uuid`=?
ORDER BY `name`;"""))) { ORDER BY `name`;"""))) {
@@ -408,10 +430,13 @@ public class MySqlDatabase extends Database {
final List<Warp> warps = new ArrayList<>(); final List<Warp> warps = new ArrayList<>();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%` FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
ORDER BY `name`;"""))) { ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
@@ -442,14 +467,18 @@ public class MySqlDatabase extends Database {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`,
`description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`,
`server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `public`=true WHERE `public`=true
ORDER BY `name`;"""))) { ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
userHomes.add(Home.from(resultSet.getDouble("x"), userHomes.add(Home.from(resultSet.getDouble("x"),
@@ -480,11 +509,16 @@ public class MySqlDatabase extends Database {
public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=? WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
@@ -521,11 +555,16 @@ public class MySqlDatabase extends Database {
public Optional<Home> getHome(@NotNull UUID uuid) { public Optional<Home> getHome(@NotNull UUID uuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `%homes_table%`.`uuid`=?;"""))) { WHERE `%homes_table%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
@@ -559,10 +598,13 @@ public class MySqlDatabase extends Database {
public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) { public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%` FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive); statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName); statement.setString(2, warpName);
@@ -595,10 +637,13 @@ public class MySqlDatabase extends Database {
public Optional<Warp> getWarp(@NotNull UUID uuid) { public Optional<Warp> getWarp(@NotNull UUID uuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%` FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
WHERE `%warps_table%`.uuid=?;"""))) { WHERE `%warps_table%`.uuid=?;"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
@@ -675,7 +720,7 @@ public class MySqlDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername(), e);
} }
} }
@@ -39,23 +39,23 @@ import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* An SQLite implementation of the plugin {@link Database} * An SQLite implementation of the plugin {@link Database}.
*/ */
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
public class SqLiteDatabase extends Database { public class SqLiteDatabase extends Database {
/** /**
* Path to the SQLite HuskHomesData.db file * Path to the SQLite HuskHomesData.db file.
*/ */
private final File databaseFile; private final File databaseFile;
/** /**
* The name of the database file * The name of the database file.
*/ */
private static final String DATABASE_FILE_NAME = "HuskHomesData.db"; private static final String DATABASE_FILE_NAME = "HuskHomesData.db";
/** /**
* The persistent SQLite database connection * The persistent SQLite database connection.
*/ */
private Connection connection; private Connection connection;
@@ -91,7 +91,9 @@ public class SqLiteDatabase extends Database {
config.setSynchronous(SQLiteConfig.SynchronousMode.FULL); config.setSynchronous(SQLiteConfig.SynchronousMode.FULL);
// Establish the connection // Establish the connection
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties()); connection = DriverManager.getConnection(
"jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties()
);
} catch (IOException e) { } catch (IOException e) {
plugin.log(Level.SEVERE, "An exception occurred creating the database file", e); plugin.log(Level.SEVERE, "An exception occurred creating the database file", e);
} catch (SQLException e) { } catch (SQLException e) {
@@ -123,8 +125,10 @@ public class SqLiteDatabase extends Database {
@Override @Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) INSERT INTO `%positions_table%`
VALUES (?,?,?,?,?,?,?,?);"""), (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.getX()); statement.setDouble(1, position.getX());
@@ -148,7 +152,8 @@ public class SqLiteDatabase extends Database {
} }
@Override @Override
protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException { protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%positions_table%` UPDATE `%positions_table%`
SET `x`=?, SET `x`=?,
@@ -174,10 +179,13 @@ public class SqLiteDatabase extends Database {
} }
@Override @Override
protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `tags`, `timestamp`) INSERT INTO `%saved_positions_table%`
VALUES (?,?,?,?,?);"""), (`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) { Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection)); statement.setInt(1, setPosition(position, connection));
@@ -198,7 +206,8 @@ public class SqLiteDatabase extends Database {
} }
@Override @Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
SELECT `position_id` SELECT `position_id`
FROM `%saved_positions_table%` FROM `%saved_positions_table%`
@@ -228,7 +237,8 @@ public class SqLiteDatabase extends Database {
@Override @Override
public void ensureUser(@NotNull User onlineUser) { public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUser -> { getUserData(onlineUser.getUuid()).ifPresentOrElse(
existingUser -> {
if (!existingUser.getUsername().equals(onlineUser.getUsername())) { if (!existingUser.getUsername().equals(onlineUser.getUsername())) {
// Update a player's name if it has changed in the database // Update a player's name if it has changed in the database
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -239,7 +249,9 @@ public class SqLiteDatabase extends Database {
statement.setString(1, onlineUser.getUsername()); statement.setString(1, onlineUser.getUsername());
statement.setString(2, existingUser.getUserUuid().toString()); statement.setString(2, existingUser.getUserUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.getUsername() + ")"); plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
+ "'s name in the database (" + existingUser.getUsername()
+ " -> " + onlineUser.getUsername() + ")");
} catch (SQLException e) { } catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
} }
@@ -343,7 +355,8 @@ public class SqLiteDatabase extends Database {
} }
@Override @Override
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
VALUES (?,?,?,?);"""))) { VALUES (?,?,?,?);"""))) {
@@ -361,11 +374,15 @@ public class SqLiteDatabase extends Database {
public List<Home> getHomes(@NotNull User user) { public List<Home> getHomes(@NotNull User user) {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=? WHERE `owner_uuid`=?
ORDER BY `name`;"""))) { ORDER BY `name`;"""))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
@@ -399,12 +416,14 @@ public class SqLiteDatabase extends Database {
public List<Warp> getWarps() { public List<Warp> getWarps() {
final List<Warp> warps = new ArrayList<>(); final List<Warp> warps = new ArrayList<>();
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%` FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
ORDER BY `name`;"""))) { ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
warps.add(Warp.from(resultSet.getDouble("x"), warps.add(Warp.from(resultSet.getDouble("x"),
@@ -431,14 +450,18 @@ public class SqLiteDatabase extends Database {
public List<Home> getPublicHomes() { public List<Home> getPublicHomes() {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `public`=true WHERE `public`=true
ORDER BY `name`;"""))) { ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
userHomes.add(Home.from(resultSet.getDouble("x"), userHomes.add(Home.from(resultSet.getDouble("x"),
@@ -468,11 +491,16 @@ public class SqLiteDatabase extends Database {
@Override @Override
public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=? WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
@@ -507,11 +535,16 @@ public class SqLiteDatabase extends Database {
@Override @Override
public Optional<Home> getHome(@NotNull UUID uuid) { public Optional<Home> getHome(@NotNull UUID uuid) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%` FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `%homes_table%`.`uuid`=?;"""))) { WHERE `%homes_table%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
@@ -543,10 +576,13 @@ public class SqLiteDatabase extends Database {
@Override @Override
public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) { public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%` FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive); statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName); statement.setString(2, warpName);
@@ -577,10 +613,13 @@ public class SqLiteDatabase extends Database {
@Override @Override
public Optional<Warp> getWarp(@NotNull UUID uuid) { public Optional<Warp> getWarp(@NotNull UUID uuid) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%` FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%saved_positions_table%`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
WHERE `%warps_table%`.uuid=?;"""))) { WHERE `%warps_table%`.uuid=?;"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
@@ -652,7 +691,7 @@ public class SqLiteDatabase extends Database {
statement.setString(3, savedUser.getUserUuid().toString()); statement.setString(3, savedUser.getUserUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername(), e);
} }
} }
@@ -20,21 +20,21 @@
package net.william278.huskhomes.event; package net.william278.huskhomes.event;
/** /**
* Base interface for a cancellable event * Base interface for a cancellable event.
*/ */
public interface Cancellable extends Event { public interface Cancellable extends Event {
/** /**
* Set whether the event should be canceled * Set whether the event should be canceled.
* *
* @param cancelled {@code true} if the event should be canceled * @param cancelled {@code true} if the event should be canceled
*/ */
void setCancelled(boolean cancelled); void setCancelled(boolean cancelled);
/** /**
* Check whether the event is cancelled * Check whether the event is canceled.
* *
* @return {@code true} if the event is cancelled * @return {@code true} if the event is canceled
*/ */
boolean isCancelled(); boolean isCancelled();
@@ -20,7 +20,7 @@
package net.william278.huskhomes.event; package net.william278.huskhomes.event;
/** /**
* Interface for an event fired by HuskHomes * Interface for an event fired by HuskHomes.
*/ */
public interface Event { public interface Event {
} }
@@ -36,12 +36,12 @@ import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
* An abstract dispatcher of events * An abstract dispatcher of events.
*/ */
public interface EventDispatcher { public interface EventDispatcher {
/** /**
* Fire an event synchronously, then run a callback asynchronously * Fire an event synchronously, then run a callback asynchronously.
* *
* @param event The event to fire * @param event The event to fire
* @param callback The callback to run after the event has been fired * @param callback The callback to run after the event has been fired
@@ -56,42 +56,62 @@ public interface EventDispatcher {
} }
/** /**
* Fire an event on this thread, and return whether the event was canceled * Fire an event on this thread, and return whether the event was canceled.
* *
* @param event The event to fire * @param event The event to fire
* @param <T> The type of event to fire * @param <T> The type of event to fire
* @return Whether the event was canceled * @return Whether the event was canceled
*/ */
<T extends Event> boolean fireIsCancelled(@NotNull T event); <T extends Event> boolean fireIsCancelled(@NotNull T event);
@NotNull
ITeleportEvent getTeleportEvent(@NotNull Teleport teleport); ITeleportEvent getTeleportEvent(@NotNull Teleport teleport);
@NotNull
ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration); ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration);
@NotNull
ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request); ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request);
IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request); @NotNull
IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request);
IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request); @NotNull
IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request);
IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator); @NotNull
IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position,
@NotNull CommandUser creator);
@NotNull
IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor); IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor);
@NotNull
IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter); IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter);
@NotNull
IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator); IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator);
@NotNull
IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor); IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor);
@NotNull
IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter); IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter);
IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList); @NotNull
IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer,
boolean publicHomeList);
@NotNull
IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> homes, @NotNull CommandUser listViewer); IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> homes, @NotNull CommandUser listViewer);
@NotNull
IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter); IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter);
@NotNull
IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter); IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter);
@NotNull @NotNull
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when all homes are deleted * Representation of an event that fires when all homes are deleted.
*/ */
public interface IDeleteAllHomesEvent extends Cancellable { public interface IDeleteAllHomesEvent extends Cancellable {
/** /**
* Get the player whose homes are being deleted * Get the player whose homes are being deleted.
* *
* @return the {@link User} whose homes are being deleted * @return the {@link User} whose homes are being deleted
*/ */
@NotNull @NotNull
User getHomeOwner(); User getHomeOwner();
/**
* Get the user who is deleting the homes.
*
* @return the {@link CommandUser} who is deleting the homes
*/
@NotNull @NotNull
CommandUser getDeleter(); CommandUser getDeleter();
@@ -23,10 +23,15 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when all warps are deleted * Representation of an event that fires when all warps are deleted.
*/ */
public interface IDeleteAllWarpsEvent extends Cancellable { public interface IDeleteAllWarpsEvent extends Cancellable {
/**
* Get the user who is deleting the warps.
*
* @return the {@link CommandUser} who is deleting the warps
*/
@NotNull @NotNull
CommandUser getDeleter(); CommandUser getDeleter();
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when a single home is deleted * Representation of an event that fires when a single home is deleted.
*/ */
public interface IHomeDeleteEvent extends Cancellable { public interface IHomeDeleteEvent extends Cancellable {
/** /**
* Get the home being deleted * Get the home being deleted.
* *
* @return the {@link Home} being deleted * @return the {@link Home} being deleted
*/ */
@NotNull @NotNull
Home getHome(); Home getHome();
/**
* Get the user who is deleting the home.
*
* @return the {@link CommandUser} who is deleting the home
*/
@NotNull @NotNull
CommandUser getDeleter(); CommandUser getDeleter();
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when a home is edited * Representation of an event that fires when a home is edited.
*/ */
public interface IHomeEditEvent extends Cancellable { public interface IHomeEditEvent extends Cancellable {
/** /**
* Get the home about to be saved * Get the home about to be saved.
* *
* @return the {@link Home} being saved * @return the {@link Home} being saved
*/ */
@NotNull @NotNull
Home getHome(); Home getHome();
/**
* Get the user who is editing the home.
*
* @return the {@link CommandUser} who is editing the home
*/
@NotNull @NotNull
CommandUser getEditor(); CommandUser getEditor();
@@ -26,22 +26,27 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
/** /**
* Represents an event that fires when a player requests to view a list of homes * Represents an event that fires when a player requests to view a list of homes.
*/ */
public interface IHomeListEvent extends Cancellable { public interface IHomeListEvent extends Cancellable {
/** /**
* Get the list of homes to be displayed * Get the list of homes to be displayed.
* *
* @return the list of homes * @return the list of homes
*/ */
@NotNull @NotNull
List<Home> getHomes(); List<Home> getHomes();
/**
* Set the list of homes to be displayed.
*
* @param homes the list of homes
*/
void setHomes(@NotNull List<Home> homes); void setHomes(@NotNull List<Home> homes);
/** /**
* Get the player viewing the home list * Get the player viewing the home list.
* *
* @return the player viewing the home list * @return the player viewing the home list
*/ */
@@ -49,7 +54,7 @@ public interface IHomeListEvent extends Cancellable {
CommandUser getListViewer(); CommandUser getListViewer();
/** /**
* Indicates if the player has requested to view a list of public homes * Indicates if the player has requested to view a list of public homes.
* *
* @return true if the player has requested to view a list of public homes * @return true if the player has requested to view a list of public homes
*/ */
@@ -23,12 +23,12 @@ import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when a teleport is about to occur * Representation of an event that fires when a teleport is about to occur.
*/ */
public interface ITeleportEvent extends Cancellable { public interface ITeleportEvent extends Cancellable {
/** /**
* Get the teleport being carried out * Get the teleport being carried out.
* *
* @return the {@link Teleport} being carried out * @return the {@link Teleport} being carried out
*/ */
@@ -23,19 +23,19 @@ import net.william278.huskhomes.teleport.TimedTeleport;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when a timed teleport warmup starts * Representation of an event that fires when a timed teleport warmup starts.
*/ */
public interface ITeleportWarmupEvent extends Cancellable { public interface ITeleportWarmupEvent extends Cancellable {
/** /**
* The duration of the timed teleport before the user is teleported * The duration of the timed teleport before the user is teleported.
* *
* @return the teleport warmup duration * @return the teleport warmup duration
*/ */
int getWarmupDuration(); int getWarmupDuration();
/** /**
* The {@link TimedTeleport} being processed * The {@link TimedTeleport} being processed.
* *
* @return the timed teleport that has started * @return the timed teleport that has started
*/ */
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when a single warp is deleted * Representation of an event that fires when a single warp is deleted.
*/ */
public interface IWarpDeleteEvent extends Cancellable { public interface IWarpDeleteEvent extends Cancellable {
/** /**
* Get the warp being deleted * Get the warp being deleted.
* *
* @return the {@link Warp} being deleted * @return the {@link Warp} being deleted
*/ */
@NotNull @NotNull
Warp getWarp(); Warp getWarp();
/**
* Get the user who is deleting the warp.
*
* @return the {@link CommandUser} who is deleting the warp
*/
@NotNull @NotNull
CommandUser getDeleter(); CommandUser getDeleter();
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Representation of an event that fires when a warp is created or updated * Representation of an event that fires when a warp is created or updated.
*/ */
public interface IWarpEditEvent extends Cancellable { public interface IWarpEditEvent extends Cancellable {
/** /**
* Get the warp being created or updated * Get the warp being created or updated.
* *
* @return the {@link Warp} being saved * @return the {@link Warp} being saved
*/ */
@NotNull @NotNull
Warp getWarp(); Warp getWarp();
/**
* Get the user who is editing the warp.
*
* @return the {@link CommandUser} who is editing the warp
*/
@NotNull @NotNull
CommandUser getEditor(); CommandUser getEditor();
@@ -26,22 +26,27 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
/** /**
* Represents an event that fires when a player requests to view a list of warps * Represents an event that fires when a player requests to view a list of warps.
*/ */
public interface IWarpListEvent extends Cancellable { public interface IWarpListEvent extends Cancellable {
/** /**
* Get the list of warps to be displayed * Get the list of warps to be displayed.
* *
* @return the list of warps * @return the list of warps
*/ */
@NotNull @NotNull
List<Warp> getWarps(); List<Warp> getWarps();
/**
* Set the list of warps to be displayed.
*
* @param warps the list of warps
*/
void setWarps(@NotNull List<Warp> warps); void setWarps(@NotNull List<Warp> warps);
/** /**
* Get the user viewing the warp list * Get the user viewing the warp list.
* *
* @return the user viewing the warp list * @return the user viewing the warp list
*/ */
@@ -44,7 +44,7 @@ import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* Hook to display warps and public homes on <a href="https://github.com/BlueMap-Minecraft/BlueMap">BlueMap</a> maps * Hook to display warps and public homes on <a href="https://github.com/BlueMap-Minecraft/BlueMap">BlueMap</a> maps.
*/ */
public class BlueMapHook extends MapHook { public class BlueMapHook extends MapHook {
@@ -63,15 +63,15 @@ public class BlueMapHook extends MapHook {
for (World world : plugin.getWorlds()) { for (World world : plugin.getWorlds()) {
this.editMapWorld(world, (mapWorld -> { this.editMapWorld(world, (mapWorld -> {
final MarkerSet publicHomeMarkers = MarkerSet.builder().label(getPublicHomesMarkerSetName()).build(); final MarkerSet homeMarkers = MarkerSet.builder().label(getPublicHomesMarkerSetName()).build();
final MarkerSet warpsMarkers = MarkerSet.builder().label(getWarpsMarkerSetName()).build(); final MarkerSet warpsMarkers = MarkerSet.builder().label(getWarpsMarkerSetName()).build();
for (BlueMapMap map : mapWorld.getMaps()) { for (BlueMapMap map : mapWorld.getMaps()) {
map.getMarkerSets().put(getPublicHomesKey(), publicHomeMarkers); map.getMarkerSets().put(getPublicHomesKey(), homeMarkers);
map.getMarkerSets().put(getWarpsKey(), warpsMarkers); map.getMarkerSets().put(getWarpsKey(), warpsMarkers);
} }
publicHomesMarkerSets.put(world.getName(), publicHomeMarkers); publicHomesMarkerSets.put(world.getName(), homeMarkers);
warpsMarkerSets.put(world.getName(), warpsMarkers); warpsMarkerSets.put(world.getName(), warpsMarkers);
})); }));
} }
@@ -34,7 +34,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.Optional; import java.util.Optional;
/** /**
* Hook to display warps and public homes on Dynmap * Hook to display warps and public homes on Dynmap.
*/ */
public class DynmapHook extends MapHook { public class DynmapHook extends MapHook {
@@ -171,8 +171,12 @@ public class DynmapHook extends MapHook {
return getDynmap().map(api -> { return getDynmap().map(api -> {
publicHomesMarkers = api.getMarkerAPI().getMarkerSet(getPublicHomesKey()); publicHomesMarkers = api.getMarkerAPI().getMarkerSet(getPublicHomesKey());
if (publicHomesMarkers == null) { if (publicHomesMarkers == null) {
publicHomesMarkers = api.getMarkerAPI().createMarkerSet(getPublicHomesKey(), getPublicHomesMarkerSetName(), publicHomesMarkers = api.getMarkerAPI().createMarkerSet(
api.getMarkerAPI().getMarkerIcons(), false); getPublicHomesKey(),
getPublicHomesMarkerSetName(),
api.getMarkerAPI().getMarkerIcons(),
false
);
} else { } else {
publicHomesMarkers.setMarkerSetLabel(getPublicHomesMarkerSetName()); publicHomesMarkers.setMarkerSetLabel(getPublicHomesMarkerSetName());
} }
@@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Locale; import java.util.Locale;
/** /**
* A hook that provides economy features * A hook that provides economy features.
*/ */
public abstract class EconomyHook extends Hook { public abstract class EconomyHook extends Hook {
@@ -37,7 +37,7 @@ public abstract class EconomyHook extends Hook {
} }
/** /**
* Get the balance of a player * Get the balance of a player.
* *
* @param player the player to get the balance of * @param player the player to get the balance of
* @return the balance of the player * @return the balance of the player
@@ -45,7 +45,7 @@ public abstract class EconomyHook extends Hook {
public abstract double getPlayerBalance(@NotNull OnlineUser player); public abstract double getPlayerBalance(@NotNull OnlineUser player);
/** /**
* Set the balance of a player * Set the balance of a player.
* *
* @param player the player to set the balance of * @param player the player to set the balance of
* @param amount the amount to set the balance to * @param amount the amount to set the balance to
@@ -53,7 +53,7 @@ public abstract class EconomyHook extends Hook {
public abstract void changePlayerBalance(@NotNull OnlineUser player, final double amount); public abstract void changePlayerBalance(@NotNull OnlineUser player, final double amount);
/** /**
* Format a balance to a string * Format a balance to a string.
* *
* @param amount the amount to format * @param amount the amount to format
* @return the formatted string * @return the formatted string
@@ -61,14 +61,14 @@ public abstract class EconomyHook extends Hook {
public abstract String formatCurrency(final double amount); public abstract String formatCurrency(final double amount);
/** /**
* Send the player a message notifying them that they have been charged * Send the player a message notifying them that they have been charged for performing an action.
* for performing an action
* *
* @param user the user to notify * @param user the user to notify
* @param plugin the plugin instance * @param plugin the plugin instance
* @param action the action that was performed * @param action the action that was performed
*/ */
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull TransactionResolver.Action action) { public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin,
@NotNull TransactionResolver.Action action) {
plugin.getSettings().getEconomyCost(action) plugin.getSettings().getEconomyCost(action)
.flatMap(cost -> plugin.getLocales().getLocale( .flatMap(cost -> plugin.getLocales().getLocale(
"economy_transaction_complete", "economy_transaction_complete",
@@ -81,14 +81,12 @@ public abstract class EconomyHook extends Hook {
} }
/** /**
* Send the player a message notifying them that they have been charged * Send the player a message notifying them that they have been charged for performing an action.
* for performing an action
* *
* @param user the user to notify * @param user the user to notify
* @param plugin the plugin instance * @param plugin the plugin instance
* @param action the action that was performed * @param action the action that was performed
* @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead, * @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead
* using the new {@link TransactionResolver.Action} enum
*/ */
@Deprecated(since = "4.4", forRemoval = true) @Deprecated(since = "4.4", forRemoval = true)
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull Action action) { public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull Action action) {
@@ -96,7 +94,7 @@ public abstract class EconomyHook extends Hook {
} }
/** /**
* Economy actions for which a player can be charged * Economy actions for which a player can be charged.
* *
* @deprecated Use the new {@link TransactionResolver.Action} enum instead * @deprecated Use the new {@link TransactionResolver.Action} enum instead
*/ */
@@ -124,7 +122,7 @@ public abstract class EconomyHook extends Hook {
} }
/** /**
* Create an action with a default cost * Create an action with a default cost.
* *
* @return the default cost * @return the default cost
* @deprecated Use the new {@link TransactionResolver.Action#getDefaultCost()} instead * @deprecated Use the new {@link TransactionResolver.Action#getDefaultCost()} instead
@@ -135,7 +133,7 @@ public abstract class EconomyHook extends Hook {
} }
/** /**
* Translate this legacy Action to the new {@link TransactionResolver.Action} * Translate this legacy Action to the new {@link TransactionResolver.Action}.
* *
* @return the equivalent {@link TransactionResolver.Action} * @return the equivalent {@link TransactionResolver.Action}
*/ */
@@ -23,22 +23,22 @@ import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* A plugin hook, where HuskHomes hooks into another plugin * A plugin hook, where HuskHomes hooks into another plugin.
*/ */
public abstract class Hook { public abstract class Hook {
/** /**
* The plugin that this hook is for * The plugin that this hook is for.
*/ */
protected final HuskHomes plugin; protected final HuskHomes plugin;
/** /**
* The name of the hook * The name of the hook.
*/ */
protected final String name; protected final String name;
/** /**
* Construct a new {@link Hook} * Construct a new {@link Hook}.
* *
* @param plugin the {@link HuskHomes} instance * @param plugin the {@link HuskHomes} instance
*/ */
@@ -48,14 +48,18 @@ public abstract class Hook {
} }
/** /**
* Initialize the hook and return {@code true} if it could be enabled * Initialize the hook and return {@code true} if it could be enabled.
*/ */
public abstract void initialize() ; public abstract void initialize();
/**
* Get the name of the hook.
*
* @return the name of the hook
*/
@NotNull @NotNull
public String getName() { public String getName() {
return name; return name;
} }
} }
@@ -32,7 +32,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* A hook for a mapping plugin, such as Dynmap * A hook for a mapping plugin, such as Dynmap.
*/ */
public abstract class MapHook extends Hook { public abstract class MapHook extends Hook {
@@ -44,7 +44,7 @@ public abstract class MapHook extends Hook {
} }
/** /**
* Populate the map with public homes and warps * Populate the map with public homes and warps.
*/ */
protected void populateMap() { protected void populateMap() {
if (plugin.getSettings().doPublicHomesOnMap()) { if (plugin.getSettings().doPublicHomesOnMap()) {
@@ -60,47 +60,47 @@ public abstract class MapHook extends Hook {
} }
/** /**
* Update a home, adding it to the map if it exists, or updating it on the map if it doesn't * Update a home, adding it to the map if it exists, or updating it on the map if it doesn't.
* *
* @param home the home to update * @param home the home to update
*/ */
public abstract void updateHome(@NotNull Home home); public abstract void updateHome(@NotNull Home home);
/** /**
* Removes a home from the map * Removes a home from the map.
* *
* @param home the home to remove * @param home the home to remove
*/ */
public abstract void removeHome(@NotNull Home home); public abstract void removeHome(@NotNull Home home);
/** /**
* Clears homes owned by a player from the map * Clears homes owned by a player from the map.
* *
* @param user the player whose homes to clear * @param user the player whose homes to clear
*/ */
public abstract void clearHomes(@NotNull User user); public abstract void clearHomes(@NotNull User user);
/** /**
* Update a warp, adding it to the map if it exists, or updating it on the map if it doesn't * Update a warp, adding it to the map if it exists, or updating it on the map if it doesn't.
* *
* @param warp the warp to update * @param warp the warp to update
*/ */
public abstract void updateWarp(@NotNull Warp warp); public abstract void updateWarp(@NotNull Warp warp);
/** /**
* Removes a warp from the map * Removes a warp from the map.
* *
* @param warp the warp to remove * @param warp the warp to remove
*/ */
public abstract void removeWarp(@NotNull Warp warp); public abstract void removeWarp(@NotNull Warp warp);
/** /**
* Clears all warps from the map * Clears all warps from the map.
*/ */
public abstract void clearWarps(); public abstract void clearWarps();
/** /**
* Returns if the position is valid to be set on this server * Returns if the position is valid to be set on this server.
* *
* @param position the position to check * @param position the position to check
* @return if the position is valid * @return if the position is valid
@@ -140,7 +140,7 @@ public abstract class MapHook extends Hook {
} }
/** /**
* Creates an HTML Dynmap marker information popup widget * Creates an HTML Dynmap marker information popup widget.
*/ */
protected static class MarkerInformationPopup { protected static class MarkerInformationPopup {
@NotNull @NotNull
@@ -158,7 +158,8 @@ public abstract class MapHook extends Hook {
} }
@NotNull @NotNull
protected static DynmapHook.MarkerInformationPopup warp(@NotNull Warp warp, @NotNull String thumbnail, @NotNull HuskHomes plugin) { protected static DynmapHook.MarkerInformationPopup warp(@NotNull Warp warp, @NotNull String thumbnail,
@NotNull HuskHomes plugin) {
return MarkerInformationPopup.create(warp.getName()) return MarkerInformationPopup.create(warp.getName())
.thumbnail(thumbnail) .thumbnail(thumbnail)
.field("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60)) .field("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60))
@@ -167,7 +168,8 @@ public abstract class MapHook extends Hook {
} }
@NotNull @NotNull
protected static DynmapHook.MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail, @NotNull HuskHomes plugin) { protected static DynmapHook.MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail,
@NotNull HuskHomes plugin) {
return MarkerInformationPopup.create(home.getName()) return MarkerInformationPopup.create(home.getName())
.thumbnail(thumbnail) .thumbnail(thumbnail)
.field("Owner", home.getOwner().getUsername()) .field("Owner", home.getOwner().getUsername())
@@ -37,7 +37,7 @@ import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel * Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel.
*/ */
public class PlanHook extends Hook { public class PlanHook extends Hook {
@@ -66,12 +66,8 @@ public class PlanHook extends Hook {
private void registerDataExtension() { private void registerDataExtension() {
try { try {
ExtensionService.getInstance().register(new PlanDataExtension(plugin.getDatabase())); ExtensionService.getInstance().register(new PlanDataExtension(plugin.getDatabase()));
} catch (IllegalStateException planIsNotEnabled) { } catch (IllegalStateException | IllegalArgumentException e) {
plugin.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled); plugin.log(Level.SEVERE, "Failed to register HuskHomes Plan extension", e);
// Plan is not enabled, handle exception
} catch (IllegalArgumentException dataExtensionImplementationIsInvalid) {
plugin.log(Level.SEVERE, "Plan extension hook failed to register. Data hook implementation is invalid.", dataExtensionImplementationIsInvalid);
// The DataExtension implementation has an implementation error, handle exception
} }
} }
@@ -71,7 +71,8 @@ public abstract class Importer extends Hook {
protected abstract int importData(@NotNull ImportData importData) throws Throwable; protected abstract int importData(@NotNull ImportData importData) throws Throwable;
protected final void log(@NotNull CommandUser user, @NotNull Level level, @NotNull String message, @NotNull Throwable... e) { protected final void log(@NotNull CommandUser user, @NotNull Level level, @NotNull String message,
@NotNull Throwable... e) {
message = "[Importer] " + message; message = "[Importer] " + message;
if (user instanceof OnlineUser online) { if (user instanceof OnlineUser online) {
final TextColor color = level == Level.SEVERE || level == Level.WARNING final TextColor color = level == Level.SEVERE || level == Level.WARNING
@@ -93,7 +94,7 @@ public abstract class Importer extends Hook {
} }
/** /**
* Represents types of data that can be imported * Represents types of data that can be imported.
*/ */
public enum ImportData { public enum ImportData {
USERS("User Data"), USERS("User Data"),
@@ -38,7 +38,7 @@ import java.util.Optional;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* A handler for when events take place * A handler for when events take place.
*/ */
public class EventListener { public class EventListener {
@@ -50,7 +50,7 @@ public class EventListener {
} }
/** /**
* Handle when a {@link OnlineUser} joins the server * Handle when a {@link OnlineUser} joins the server.
* *
* @param onlineUser the joining {@link OnlineUser} * @param onlineUser the joining {@link OnlineUser}
*/ */
@@ -64,7 +64,9 @@ public class EventListener {
this.handleInboundTeleport(onlineUser); this.handleInboundTeleport(onlineUser);
// Synchronize the global player list // Synchronize the global player list
plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(onlineUser, plugin.getLocalPlayerList()), 40L); plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(
onlineUser, plugin.getLocalPlayerList()), 40L
);
// Request updated player lists from other servers // Request updated player lists from other servers
if (plugin.getOnlineUsers().size() == 1) { if (plugin.getOnlineUsers().size() == 1) {
@@ -91,7 +93,7 @@ public class EventListener {
} }
/** /**
* Handle when a {@link OnlineUser} leaves the server * Handle when a {@link OnlineUser} leaves the server.
* *
* @param onlineUser the leaving {@link OnlineUser} * @param onlineUser the leaving {@link OnlineUser}
*/ */
@@ -123,7 +125,7 @@ public class EventListener {
} }
/** /**
* Handle inbound cross-server teleports * Handle inbound cross-server teleports.
* *
* @param teleporter user to handle the checks for * @param teleporter user to handle the checks for
*/ */
@@ -135,7 +137,10 @@ public class EventListener {
} }
try { try {
teleporter.teleportLocally((Position) teleport.getTarget(), plugin.getSettings().doAsynchronousTeleports()); teleporter.teleportLocally(
(Position) teleport.getTarget(),
plugin.getSettings().doAsynchronousTeleports()
);
} catch (TeleportationException e) { } catch (TeleportationException e) {
e.displayMessage(teleporter); e.displayMessage(teleporter);
} }
@@ -145,7 +150,7 @@ public class EventListener {
} }
/** /**
* Handle an inbound global respawn * Handle an inbound global respawn.
* *
* @param teleporter the user to handle the checks for * @param teleporter the user to handle the checks for
*/ */
@@ -207,7 +212,7 @@ public class EventListener {
} }
/** /**
* Handle when a {@link OnlineUser} dies * Handle when a {@link OnlineUser} dies.
* *
* @param onlineUser the {@link OnlineUser} who died * @param onlineUser the {@link OnlineUser} who died
*/ */
@@ -219,7 +224,7 @@ public class EventListener {
} }
/** /**
* Handle when a {@link OnlineUser} respawns after dying * Handle when a {@link OnlineUser} respawns after dying.
* *
* @param onlineUser the respawning {@link OnlineUser} * @param onlineUser the respawning {@link OnlineUser}
*/ */
@@ -228,7 +233,7 @@ public class EventListener {
// Display the return by death via /back notification // Display the return by death via /back notification
final boolean canReturnByDeath = plugin.getCommand(BackCommand.class) final boolean canReturnByDeath = plugin.getCommand(BackCommand.class)
.map(command -> onlineUser.hasPermission(command.getPermission()) .map(command -> onlineUser.hasPermission(command.getPermission())
&& onlineUser.hasPermission(command.getPermission("death"))) && onlineUser.hasPermission(command.getPermission("death")))
.orElse(false); .orElse(false);
if (plugin.getSettings().doBackCommandReturnByDeath() && canReturnByDeath) { if (plugin.getSettings().doBackCommandReturnByDeath() && canReturnByDeath) {
plugin.getLocales().getLocale("return_by_death_notification") plugin.getLocales().getLocale("return_by_death_notification")
@@ -266,7 +271,7 @@ public class EventListener {
} }
/** /**
* Handle when a player teleports * Handle when a player teleports.
* *
* @param onlineUser the {@link OnlineUser} who teleported * @param onlineUser the {@link OnlineUser} who teleported
* @param sourcePosition the source {@link Position} they came from * @param sourcePosition the source {@link Position} they came from
@@ -281,7 +286,7 @@ public class EventListener {
} }
/** /**
* Handle when an {@link OnlineUser}'s spawn point is updated * Handle when an {@link OnlineUser}'s spawn point is updated.
* *
* @param onlineUser the {@link OnlineUser} whose spawn point was updated * @param onlineUser the {@link OnlineUser} whose spawn point was updated
* @param position the new spawn point * @param position the new spawn point
@@ -293,10 +298,10 @@ public class EventListener {
} }
/** /**
* Handle when the plugin is disabling (server is shutting down) * Handle when the plugin is disabling (server is shutting down).
*/ */
public final void handlePluginDisable() { public final void handlePluginDisable() {
plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion()); plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion());
} }
} }
@@ -53,7 +53,9 @@ public class HomesManager {
} }
/** /**
* Cached user homes - maps a username to a list of their homes * Cached user homes - maps a username to a list of their homes.
*
* @return a map of usernames to a list of their home names.
*/ */
@NotNull @NotNull
public Map<String, List<String>> getUserHomes() { public Map<String, List<String>> getUserHomes() {
@@ -62,15 +64,20 @@ public class HomesManager {
HashMap::putAll); HashMap::putAll);
} }
/**
* Get a list of all cached set home identifiers.
*
* @return a list of all cached set home identifiers
*/
@NotNull @NotNull
public List<String> getUserHomeNames() { public List<String> getUserHomeIdentifiers() {
return userHomes.entrySet().stream() return userHomes.entrySet().stream()
.flatMap(e -> e.getValue().stream().map(Home::getIdentifier)) .flatMap(e -> e.getValue().stream().map(Home::getIdentifier))
.toList(); .toList();
} }
/** /**
* Cached public homes - maps a username to a list of their public homes * Cached public homes - maps a username to a list of their public homes.
*/ */
@NotNull @NotNull
public Map<String, List<String>> getPublicHomes() { public Map<String, List<String>> getPublicHomes() {
@@ -79,17 +86,33 @@ public class HomesManager {
HashMap::putAll); HashMap::putAll);
} }
/**
* Get a list of all cached public home identifiers.
*
* @return a list of all cached public home identifiers
*/
@NotNull @NotNull
public List<String> getPublicHomeNames() { public List<String> getPublicHomeIdentifiers() {
return publicHomes.stream() return publicHomes.stream()
.map(Home::getIdentifier) .map(Home::getIdentifier)
.toList(); .toList();
} }
/**
* Cache user homes for a given user.
*
* @param user the user to cache homes for
*/
public void cacheUserHomes(@NotNull User user) { public void cacheUserHomes(@NotNull User user) {
userHomes.put(user.getUsername(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user))); userHomes.put(user.getUsername(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user)));
} }
/**
* Cache a home for a given user.
*
* @param home the home to cache
* @param propagate whether to propagate the cache update to other servers (if cross-server is enabled)
*/
public void cacheHome(@NotNull Home home, boolean propagate) { public void cacheHome(@NotNull Home home, boolean propagate) {
userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> { userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> {
v.remove(home); v.remove(home);
@@ -132,6 +155,13 @@ public class HomesManager {
} }
} }
/**
* Propagate the update of a home/warp to other servers (if cross-server is enabled).
*
* <p>This works by broking a message requesting that other servers fetch the updated home from the database.
*
* @param homeId the UUID of the home/warp to update
*/
private void propagateCacheUpdate(@NotNull UUID homeId) { private void propagateCacheUpdate(@NotNull UUID homeId) {
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().doCrossServer()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
@@ -196,7 +226,8 @@ public class HomesManager {
this.cacheHome(home, true); this.cacheHome(home, true);
} }
public void createHome(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) throws ValidationException { public void createHome(@NotNull OnlineUser owner, @NotNull String name,
@NotNull Position position) throws ValidationException {
createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true); createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true);
} }
@@ -226,7 +257,8 @@ public class HomesManager {
return deleted; return deleted;
} }
public void setHomePosition(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException { public void setHomePosition(@NotNull User owner, @NotNull String name,
@NotNull Position position) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name); final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) { if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND); throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -241,7 +273,8 @@ public class HomesManager {
this.cacheHome(home, true); this.cacheHome(home, true);
} }
public void setHomeName(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException { public void setHomeName(@NotNull User owner, @NotNull String name,
@NotNull String newName) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name); final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) { if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND); throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -260,7 +293,8 @@ public class HomesManager {
this.cacheHome(home, true); this.cacheHome(home, true);
} }
public void setHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException { public void setHomeDescription(@NotNull User owner, @NotNull String name,
@NotNull String description) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name); final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) { if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND); throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -303,7 +337,8 @@ public class HomesManager {
this.cacheHome(home, true); this.cacheHome(home, true);
} }
public void setHomeMetaTags(@NotNull User owner, @NotNull String name, @NotNull Map<String, String> tags) throws ValidationException { public void setHomeMetaTags(@NotNull User owner, @NotNull String name,
@NotNull Map<String, String> tags) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name); final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) { if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND); throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -38,7 +38,7 @@ import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* Manages {@link TeleportRequest}s between players * Manages {@link TeleportRequest}s between players.
*/ */
public class RequestsManager { public class RequestsManager {
@@ -53,7 +53,7 @@ public class RequestsManager {
} }
/** /**
* Return if a user is ignoring tpa requests * Return if a user is ignoring tpa requests.
* *
* @param user the user to check * @param user the user to check
* @return {@code true} if the user is ignoring tpa requests * @return {@code true} if the user is ignoring tpa requests
@@ -63,7 +63,7 @@ public class RequestsManager {
} }
/** /**
* Add a teleport request to a user's request queue * Add a teleport request to a user's request queue.
* *
* @param request the {@link TeleportRequest} to add * @param request the {@link TeleportRequest} to add
* @param recipient the {@link User} recipient of the request * @param recipient the {@link User} recipient of the request
@@ -73,7 +73,7 @@ public class RequestsManager {
} }
/** /**
* Remove {@link TeleportRequest}(s) sent by a requester, by name, from a recipient's queue * Remove {@link TeleportRequest}(s) sent by a requester, by name, from a recipient's queue.
* *
* @param requesterName the sender's username, whose requests should be removed * @param requesterName the sender's username, whose requests should be removed
* @param recipient the {@link User} recipient of the request * @param recipient the {@link User} recipient of the request
@@ -86,7 +86,7 @@ public class RequestsManager {
} }
/** /**
* Get the last received teleport request for a user * Get the last received teleport request for a user.
* *
* @param recipient the user to get the request for * @param recipient the user to get the request for
* @return the last received request, if present * @return the last received request, if present
@@ -200,7 +200,7 @@ public class RequestsManager {
plugin.fireEvent(plugin.getReceiveTeleportRequestEvent(recipient, request), (event -> { plugin.fireEvent(plugin.getReceiveTeleportRequestEvent(recipient, request), (event -> {
addTeleportRequest(request, recipient); addTeleportRequest(request, recipient);
plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere") plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere")
+ "_request_received", request.getRequesterName()) + "_request_received", request.getRequesterName())
.ifPresent(recipient::sendMessage); .ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName()) plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
.ifPresent(recipient::sendMessage); .ifPresent(recipient::sendMessage);
@@ -210,7 +210,7 @@ public class RequestsManager {
} }
/** /**
* Respond to a teleport request with the given status by name of the sender * Respond to a teleport request with the given status by name of the sender.
* *
* @param recipient The user receiving the request * @param recipient The user receiving the request
* @param senderName The name of the user sending the request * @param senderName The name of the user sending the request
@@ -236,7 +236,7 @@ public class RequestsManager {
} }
/** /**
* Respond to the last received teleport request for a user, if there is one * Respond to the last received teleport request for a user if there is one.
* *
* @param recipient The user receiving the request * @param recipient The user receiving the request
* @param accepted Whether the request should be accepted or not * @param accepted Whether the request should be accepted or not
@@ -266,13 +266,14 @@ public class RequestsManager {
} }
/** /**
* Handle; respond to; a teleport request * Handle the response to a teleport request.
* *
* @param request The request to handle * @param request The request to handle
* @param recipient The recipient of the request * @param recipient The recipient of the request
* @param accepted Whether the request should be accepted or not * @param accepted Whether the request should be accepted or not
*/ */
private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient, boolean accepted) { private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient,
boolean accepted) {
// Remove the request(s) from the sender from the recipient's queue // Remove the request(s) from the sender from the recipient's queue
removeTeleportRequest(request.getRequesterName(), recipient); removeTeleportRequest(request.getRequesterName(), recipient);
@@ -329,7 +330,7 @@ public class RequestsManager {
} }
/** /**
* Handle a teleport request response for a local user * Handle a teleport request response for a local user.
* *
* @param requester The user who sent the request * @param requester The user who sent the request
* @param request The {@link TeleportRequest} to handle * @param request The {@link TeleportRequest} to handle
@@ -94,7 +94,7 @@ public class WarpsManager {
} }
/** /**
* Cached warp names * Cached warp names.
*/ */
@NotNull @NotNull
public List<String> getWarps() { public List<String> getWarps() {
@@ -112,7 +112,8 @@ public class WarpsManager {
.toList(); .toList();
} }
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException { public void createWarp(@NotNull String name, @NotNull Position position,
boolean overwrite) throws ValidationException {
final Optional<Warp> existingWarp = plugin.getDatabase().getWarp(name); final Optional<Warp> existingWarp = plugin.getDatabase().getWarp(name);
if (existingWarp.isPresent() && !overwrite) { if (existingWarp.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN); throw new ValidationException(ValidationException.Type.NAME_TAKEN);
@@ -35,7 +35,7 @@ public abstract class Broker {
protected final HuskHomes plugin; protected final HuskHomes plugin;
/** /**
* Create a new broker * Create a new broker.
* *
* @param plugin the HuskHomes plugin instance * @param plugin the HuskHomes plugin instance
*/ */
@@ -44,9 +44,9 @@ public abstract class Broker {
} }
/** /**
* Handle an inbound {@link Message} * Handle an inbound {@link Message}.
* *
* @param receiver The user who received the message, if a receiver exists * @param receiver The user who received the message if a receiver exists
* @param message The message * @param message The message
*/ */
protected void handle(@NotNull OnlineUser receiver, @NotNull Message message) { protected void handle(@NotNull OnlineUser receiver, @NotNull Message message) {
@@ -117,18 +117,19 @@ public abstract class Broker {
plugin.getManager().homes().updatePublicHomeCache(); plugin.getManager().homes().updatePublicHomeCache();
plugin.getManager().warps().updateWarpCache(); plugin.getManager().warps().updateWarpCache();
} }
default -> throw new IllegalStateException("Unexpected value: " + message.getType());
} }
} }
/** /**
* Initialize the message broker * Initialize the message broker.
* *
* @throws RuntimeException if the broker fails to initialize * @throws RuntimeException if the broker fails to initialize
*/ */
public abstract void initialize() throws IllegalStateException; public abstract void initialize() throws IllegalStateException;
/** /**
* Send a message to the broker * Send a message to the broker.
* *
* @param message the message to send * @param message the message to send
* @param sender the sender of the message * @param sender the sender of the message
@@ -136,7 +137,7 @@ public abstract class Broker {
protected abstract void send(@NotNull Message message, @NotNull OnlineUser sender); protected abstract void send(@NotNull Message message, @NotNull OnlineUser sender);
/** /**
* Move an {@link OnlineUser} to a new server on the proxy network * Move an {@link OnlineUser} to a new server on the proxy network.
* *
* @param user the user to move * @param user the user to move
* @param server the server to move the user to * @param server the server to move the user to
@@ -144,7 +145,7 @@ public abstract class Broker {
public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server); public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server);
/** /**
* Terminate the broker * Terminate the broker.
*/ */
public abstract void close(); public abstract void close();
@@ -160,7 +161,7 @@ public abstract class Broker {
} }
/** /**
* Identifies types of message brokers * Identifies types of message brokers.
*/ */
public enum Type { public enum Type {
PLUGIN_MESSAGE("Plugin Messages"), PLUGIN_MESSAGE("Plugin Messages"),
@@ -33,7 +33,7 @@ import java.util.UUID;
public class Message { public class Message {
/** /**
* Message target indicating all players * Message target indicating all players.
*/ */
public static final String TARGET_ALL = "ALL"; public static final String TARGET_ALL = "ALL";
@@ -111,7 +111,7 @@ public class Message {
} }
/** /**
* Builder for {@link Message}s * Builder for {@link Message}s.
*/ */
public static class Builder { public static class Builder {
private Type type; private Type type;
@@ -160,7 +160,7 @@ public class Message {
} }
/** /**
* Different types of cross-server messages * Different types of cross-server messages.
*/ */
public enum Type { public enum Type {
TELEPORT_TO_POSITION, TELEPORT_TO_POSITION,
@@ -30,7 +30,7 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
/** /**
* Represents a payload sent in a cross-server {@link Message} * Represents a payload sent in a cross-server {@link Message}.
*/ */
public class Payload { public class Payload {
@@ -53,7 +53,7 @@ public class Payload {
private List<String> stringList; private List<String> stringList;
/** /**
* Returns an empty cross-server message payload * Returns an empty cross-server message payload.
* *
* @return an empty payload * @return an empty payload
*/ */
@@ -63,7 +63,7 @@ public class Payload {
} }
/** /**
* Returns a payload containing a {@link Position} * Returns a payload containing a {@link Position}.
* *
* @param position the position to send * @param position the position to send
* @return a payload containing the position * @return a payload containing the position
@@ -76,7 +76,7 @@ public class Payload {
} }
/** /**
* Returns a payload containing a {@link TeleportRequest} * Returns a payload containing a {@link TeleportRequest}.
* *
* @param teleportRequest the teleport to send * @param teleportRequest the teleport to send
* @return a payload containing the teleport request * @return a payload containing the teleport request
@@ -89,7 +89,7 @@ public class Payload {
} }
/** /**
* A string field * A string field.
*/ */
@NotNull @NotNull
public static Payload withString(@NotNull String target) { public static Payload withString(@NotNull String target) {
@@ -99,7 +99,7 @@ public class Payload {
} }
/** /**
* A string list field * A string list field.
*/ */
@NotNull @NotNull
public static Payload withStringList(@NotNull List<String> target) { public static Payload withStringList(@NotNull List<String> target) {
@@ -112,7 +112,7 @@ public class Payload {
} }
/** /**
* A position field * A position field.
*/ */
public Optional<Position> getPosition() { public Optional<Position> getPosition() {
return Optional.ofNullable(position); return Optional.ofNullable(position);
@@ -120,21 +120,21 @@ public class Payload {
/** /**
* A teleport request field * A teleport request field.
*/ */
public Optional<TeleportRequest> getTeleportRequest() { public Optional<TeleportRequest> getTeleportRequest() {
return Optional.ofNullable(teleportRequest); return Optional.ofNullable(teleportRequest);
} }
/** /**
* A string field * A string field.
*/ */
public Optional<String> getString() { public Optional<String> getString() {
return Optional.ofNullable(string); return Optional.ofNullable(string);
} }
/** /**
* A string list field * A string list field.
*/ */
public Optional<List<String>> getStringList() { public Optional<List<String>> getStringList() {
return Optional.ofNullable(stringList); return Optional.ofNullable(stringList);
@@ -31,18 +31,15 @@ import java.util.logging.Level;
/** /**
* <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">Plugin Messaging channel</a> message * <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">Plugin Messaging channel</a> message
* broker implementation * broker implementation.
*/ */
public class PluginMessageBroker extends Broker { public class PluginMessageBroker extends Broker {
/** /**
* The name of BungeeCord's provided plugin channel. * The name of BungeeCord's provided plugin channel.
* *
* @implNote Technically, the effective identifier of this channel is {@code bungeecord:main}, but Spigot remaps * <p>Internally, this is <a href="https://wiki.vg/Plugin_channels#bungeecord:main">{@code bungeecord:main}</a>,
* {@code BungeeCord} automatically to the new one (<a href="https://wiki.vg/Plugin_channels#bungeecord:main">source</a>). * but Spigot remaps {@code BungeeCord} automatically to the new one (hence BungeeCord is kept for back-compat).
* Spigot's <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">official documentation</a>
* still instructs usage of {@code BungeeCord} as the name to use, however. It's all a bit inconsistent, so just in case
* it's best to leave it how it is for to maintain backwards compatibility.
*/ */
public static final String BUNGEE_CHANNEL_ID = "BungeeCord"; public static final String BUNGEE_CHANNEL_ID = "BungeeCord";
@@ -55,7 +52,6 @@ public class PluginMessageBroker extends Broker {
plugin.initializePluginChannels(); plugin.initializePluginChannels();
} }
@SuppressWarnings("UnstableApiUsage")
public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) { public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) {
if (!channel.equals(BUNGEE_CHANNEL_ID)) { if (!channel.equals(BUNGEE_CHANNEL_ID)) {
return; return;
@@ -79,7 +75,6 @@ public class PluginMessageBroker extends Broker {
} }
@Override @Override
@SuppressWarnings("UnstableApiUsage")
protected void send(@NotNull Message message, @NotNull OnlineUser sender) { protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput(); final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF(message.getScope().getPluginMessageChannel()); messageWriter.writeUTF(message.getScope().getPluginMessageChannel());
@@ -102,7 +97,6 @@ public class PluginMessageBroker extends Broker {
} }
@Override @Override
@SuppressWarnings("UnstableApiUsage")
public void changeServer(@NotNull OnlineUser user, @NotNull String server) { public void changeServer(@NotNull OnlineUser user, @NotNull String server) {
final ByteArrayDataOutput outputStream = ByteStreams.newDataOutput(); final ByteArrayDataOutput outputStream = ByteStreams.newDataOutput();
@@ -115,4 +109,5 @@ public class PluginMessageBroker extends Broker {
@Override @Override
public void close() { public void close() {
} }
}
}
@@ -30,7 +30,7 @@ import redis.clients.jedis.JedisPubSub;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* Redis PubSub broker implementation * Redis PubSub broker implementation.
*/ */
public class RedisBroker extends PluginMessageBroker { public class RedisBroker extends PluginMessageBroker {
private JedisPool jedisPool; private JedisPool jedisPool;
@@ -78,13 +78,13 @@ public class RedisBroker extends PluginMessageBroker {
if (message.getScope() == Message.Scope.PLAYER) { if (message.getScope() == Message.Scope.PLAYER) {
plugin.getOnlineUsers().stream() plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL) .filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget())) || online.getUsername().equals(message.getTarget()))
.forEach(receiver -> handle(receiver, message)); .forEach(receiver -> handle(receiver, message));
return; return;
} }
if (message.getTarget().equals(plugin.getServerName()) if (message.getTarget().equals(plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) { || message.getTarget().equals(Message.TARGET_ALL)) {
plugin.getOnlineUsers().stream() plugin.getOnlineUsers().stream()
.findAny() .findAny()
.ifPresent(receiver -> handle(receiver, message)); .ifPresent(receiver -> handle(receiver, message));
@@ -25,10 +25,13 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
/** /**
* Represents a home set by a {@link User} * Represents a home set by a {@link User}.
*/ */
public class Home extends SavedPosition { public class Home extends SavedPosition {
/**
* The delimiter used to separate the owner's name from the home name in the home identifier.
*/
public static final String IDENTIFIER_DELIMITER = "."; public static final String IDENTIFIER_DELIMITER = ".";
private final User owner; private final User owner;
private boolean isPublic; private boolean isPublic;
@@ -46,19 +49,47 @@ public class Home extends SavedPosition {
this.setPublic(false); this.setPublic(false);
} }
/**
* Creates a new {@link Home} from a series of coordinates, a viewing angle, a {@link World}, a server name, a
* {@link PositionMeta}, a {@link UUID}, a {@link User} and a boolean representing whether the home is public.
*
* @param x The x coordinate of the home
* @param y The y coordinate of the home
* @param z The z coordinate of the home
* @param yaw The yaw of the home
* @param pitch The pitch of the home
* @param world The {@link World} the home is in
* @param server The name of the server the home is in
* @param positionMeta The {@link PositionMeta} of the home
* @param uuid The {@link UUID} of the home
* @param owner The {@link User} who owns the home
* @param isPublic Whether the home is public
* @return the new {@link Home}
*/
@NotNull @NotNull
public static Home from(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server, public static Home from(double x, double y, double z, float yaw, float pitch, @NotNull World world,
@NotNull PositionMeta positionMeta, @NotNull UUID uuid, @NotNull User owner, boolean isPublic) { @NotNull String server, @NotNull PositionMeta positionMeta, @NotNull UUID uuid,
@NotNull User owner, boolean isPublic) {
return new Home(x, y, z, yaw, pitch, world, server, positionMeta, uuid, owner, isPublic); return new Home(x, y, z, yaw, pitch, world, server, positionMeta, uuid, owner, isPublic);
} }
/**
* Creates a new {@link Home} from a {@link Position} and {@link PositionMeta}.
*
* @param position The {@link Position} to create the home from
* @param meta The {@link PositionMeta} to create the home from
* @param owner The {@link User} who owns the home
* @return the new {@link Home}
*/
@NotNull @NotNull
public static Home from(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User owner) { public static Home from(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User owner) {
return new Home(position, meta, owner); return new Home(position, meta, owner);
} }
/** /**
* The {@link User} who owns this home * Get the {@link User} who owns this home.
*
* @return the {@link User} who owns this home
*/ */
@NotNull @NotNull
public User getOwner() { public User getOwner() {
@@ -66,22 +97,45 @@ public class Home extends SavedPosition {
} }
/** /**
* {@code true} if this home is public * Returns whether this home is public.
*
* @return {@code true} if this home is public.
*/ */
public boolean isPublic() { public boolean isPublic() {
return isPublic; return isPublic;
} }
public void setPublic(boolean aPublic) { /**
isPublic = aPublic; * Sets whether this home is public.
*
* @param isPublic {@code true} if this home is public
*/
public void setPublic(boolean isPublic) {
this.isPublic = isPublic;
} }
/**
* Get a version of the canonical home identifier string that is safe for use in formatted locales.
* Safe identifiers will only contain alphanumeric ASCII characters (a-z, A-Z, 0-9), underscores and dashes.
*
* <p>This typically consists of the owner's username, a delimiter, and the home {@link #getUuid() UUID}.
*
* @return the locale-safe canonical home identifier string
*/
@NotNull @NotNull
@Override @Override
public String getSafeIdentifier() { public String getSafeIdentifier() {
return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getSafeIdentifier(); return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getSafeIdentifier();
} }
/**
* Get the canonical home identifier string.
*
* <p>This typically consists of the owner's username, a delimiter, and the home {@link #getName() name}.
*
* @return the canonical home identifier string
* @see #getSafeIdentifier() #getSafeIdentifier() to get a locale-safe version of this string
*/
@NotNull @NotNull
@Override @Override
public String getIdentifier() { public String getIdentifier() {
@@ -23,9 +23,10 @@ import com.google.gson.annotations.Expose;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Represents a local position on this server * Represents a local position on this server.
*/ */
public class Location { public class Location {
@Expose @Expose
private double x; private double x;
@Expose @Expose
@@ -62,7 +63,7 @@ public class Location {
} }
/** /**
* Update the position to match that of another position * Update the position to match that of another position.
* *
* @param position The position to update to * @param position The position to update to
*/ */
@@ -76,7 +77,7 @@ public class Location {
} }
/** /**
* The double-precision defined x coordinate of the location * The double-precision defined x coordinate of the location.
*/ */
public double getX() { public double getX() {
return x; return x;
@@ -87,7 +88,7 @@ public class Location {
} }
/** /**
* The double-precision defined y coordinate of the location * The double-precision defined y coordinate of the location.
*/ */
public double getY() { public double getY() {
return y; return y;
@@ -98,7 +99,7 @@ public class Location {
} }
/** /**
* The double-precision defined z coordinate of the location * The double-precision defined z coordinate of the location.
*/ */
public double getZ() { public double getZ() {
return z; return z;
@@ -109,7 +110,7 @@ public class Location {
} }
/** /**
* The float-precision defined yaw facing of the location * The float-precision defined yaw facing of the location.
*/ */
public float getYaw() { public float getYaw() {
return yaw; return yaw;
@@ -120,7 +121,7 @@ public class Location {
} }
/** /**
* The float-precision defined pitch facing of the location * The float-precision defined pitch facing of the location.
*/ */
public float getPitch() { public float getPitch() {
return pitch; return pitch;
@@ -131,7 +132,7 @@ public class Location {
} }
/** /**
* The {@link World} the location is on * The {@link World} the location is on.
*/ */
public World getWorld() { public World getWorld() {
return world; return world;
@@ -140,4 +141,5 @@ public class Location {
public void setWorld(World world) { public void setWorld(World world) {
this.world = world; this.world = world;
} }
} }
@@ -24,20 +24,22 @@ import net.william278.huskhomes.teleport.Target;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Represents a position - a {@link Location} somewhere on the proxy network or server * Represents a position - a {@link Location} somewhere on the proxy network or server.
*/ */
public class Position extends Location implements Target { public class Position extends Location implements Target {
@Expose @Expose
private String server; private String server;
protected Position(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server) { protected Position(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull String server) {
super(x, y, z, yaw, pitch, world); super(x, y, z, yaw, pitch, world);
this.setServer(server); this.setServer(server);
} }
protected Position(@NotNull Location location, @NotNull String server) { protected Position(@NotNull Location location, @NotNull String server) {
super(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), location.getWorld()); super(location.getX(), location.getY(), location.getZ(), location.getYaw(),
location.getPitch(), location.getWorld());
this.setServer(server); this.setServer(server);
} }
@@ -46,12 +48,14 @@ public class Position extends Location implements Target {
} }
@NotNull @NotNull
public static Position at(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server) { public static Position at(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull String server) {
return new Position(x, y, z, yaw, pitch, world, server); return new Position(x, y, z, yaw, pitch, world, server);
} }
@NotNull @NotNull
public static Position at(double x, double y, double z, @NotNull World world, @NotNull String server) { public static Position at(double x, double y, double z,
@NotNull World world, @NotNull String server) {
return Position.at(x, y, z, 0, 0, world, server); return Position.at(x, y, z, 0, 0, world, server);
} }
@@ -67,7 +71,7 @@ public class Position extends Location implements Target {
} }
/** /**
* The name of the server the position is on * The name of the server the position is on.
*/ */
@NotNull @NotNull
public String getServer() { public String getServer() {
@@ -80,10 +84,10 @@ public class Position extends Location implements Target {
@Override @Override
public String toString() { public String toString() {
return "x: " + (int) getX() + ", " + return "x: " + (int) getX() + ", "
"y: " + (int) getY() + ", " + + "y: " + (int) getY() + ", "
"z: " + (int) getZ() + " " + + "z: " + (int) getZ() + " "
"(" + getWorld().getName() + " / " + getServer() + ")"; + "(" + getWorld().getName() + " / " + getServer() + ")";
} }
} }
@@ -29,7 +29,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* 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 {
@@ -58,7 +58,7 @@ public class PositionMeta {
} }
/** /**
* Deserialize a JSON string into a {@link Map} of meta tags * Deserialize a JSON string into a {@link Map} of meta tags.
* *
* @param serializedTags The JSON string to deserialize * @param serializedTags The JSON string to deserialize
* @return The deserialized {@link Map} * @return The deserialized {@link Map}
@@ -78,7 +78,7 @@ public class PositionMeta {
} }
/** /**
* Serialize a {@link Map} of meta tags into a JSON string * Serialize a {@link Map} of meta tags into a JSON string.
* *
* @return The serialized JSON string * @return The serialized JSON string
*/ */
@@ -96,7 +96,7 @@ public class PositionMeta {
} }
/** /**
* The name of a position * The name of a position.
*/ */
public String getName() { public String getName() {
return name; return name;
@@ -107,7 +107,7 @@ public class PositionMeta {
} }
/** /**
* A description of a position * A description of a position.
*/ */
@NotNull @NotNull
public String getDescription() { public String getDescription() {
@@ -119,7 +119,7 @@ public class PositionMeta {
} }
/** /**
* Map of metadata tags for a position * Map of metadata tags for a position.
*/ */
public Map<String, String> getTags() { public Map<String, String> getTags() {
return tags; return tags;
@@ -130,7 +130,7 @@ public class PositionMeta {
} }
/** /**
* The time the position was created * The time the position was created.
*/ */
@NotNull @NotNull
public Instant getCreationTime() { public Instant getCreationTime() {
@@ -25,7 +25,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
/** /**
* Represents a persistently-saved {@link Position} * Represents a persistently-saved {@link Position}.
*/ */
public abstract class SavedPosition extends Position implements Comparable<SavedPosition> { public abstract class SavedPosition extends Position implements Comparable<SavedPosition> {
@@ -40,7 +40,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
} }
/** /**
* Create a new {@link SavedPosition} from a {@link Position} and {@link PositionMeta} * Create a new {@link SavedPosition} from a {@link Position} and {@link PositionMeta}.
* *
* @param position The {@link Position} to save * @param position The {@link Position} to save
* @param meta {@link PositionMeta} information about this position * @param meta {@link PositionMeta} information about this position
@@ -53,7 +53,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
} }
/** /**
* Metadata about this position (name, description) * Metadata about this position (name, description).
*/ */
@NotNull @NotNull
public PositionMeta getMeta() { public PositionMeta getMeta() {
@@ -65,7 +65,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
} }
/** /**
* The name of this position. Shortcut for {@link #getMeta()}.{@link PositionMeta#getName()} * The name of this position. Shortcut for {@link #getMeta()}.{@link PositionMeta#getName()}.
*/ */
@NotNull @NotNull
public String getName() { public String getName() {
@@ -73,7 +73,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
} }
/** /**
* A unique ID representing this position * A unique ID representing this position.
*/ */
@NotNull @NotNull
public UUID getUuid() { public UUID getUuid() {
@@ -24,7 +24,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
/** /**
* Represents a server warp * Represents a server warp.
*/ */
public class Warp extends SavedPosition { public class Warp extends SavedPosition {
@@ -36,7 +36,7 @@ public class Warp extends SavedPosition {
} }
/** /**
* Create a new {@link Warp} from a {@link Position} and {@link PositionMeta} * Create a new {@link Warp} from a {@link Position} and {@link PositionMeta}.
* *
* @param position The {@link Position} to save as a warp * @param position The {@link Position} to save as a warp
* @param meta {@link PositionMeta} information about this position * @param meta {@link PositionMeta} information about this position
@@ -26,7 +26,7 @@ import java.util.Optional;
import java.util.UUID; import java.util.UUID;
/** /**
* Represents a world on a server * Represents a world on a server.
*/ */
public class World { public class World {
@@ -56,7 +56,7 @@ public class 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.
*/ */
@NotNull @NotNull
public String getName() { public String getName() {
@@ -68,7 +68,7 @@ public class World {
} }
/** /**
* 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.
*/ */
@NotNull @NotNull
public UUID getUuid() { public UUID getUuid() {
@@ -81,9 +81,9 @@ public class World {
/** /**
* 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}).
* <p> *
* Will return {@link Environment#OVERWORLD} if the environment is null * <p>Will return {@link Environment#OVERWORLD} if the environment is null
*/ */
@NotNull @NotNull
public Environment getEnvironment() { public Environment getEnvironment() {
@@ -95,7 +95,7 @@ public class World {
} }
/** /**
* Identifies the environment of the world * Identifies the environment of the world.
*/ */
public enum Environment { public enum Environment {
OVERWORLD, OVERWORLD,
@@ -74,7 +74,7 @@ public final class NormalDistributionEngine extends RandomTeleportEngine {
} }
/** /**
* Generate a safe ground-level {@link Location} through a randomized normally-distributed radius and random angle * Generate a safe ground-level {@link Location} through a randomized normally-distributed radius and random angle.
* *
* @param world The world to generate the location in * @param world The world to generate the location in
* @return A generated location * @return A generated location
@@ -101,9 +101,9 @@ public final class NormalDistributionEngine extends RandomTeleportEngine {
} }
/** /**
* Generates a random angle in the range [0, 360] * Generates a random angle in the range {@code [0, 360]}.
* *
* @return a random angle in the range [0, 360] * @return a random angle in the range {@code [0, 360]}
*/ */
private static float getRandomAngle() { private static float getRandomAngle() {
return (float) (Math.random() * 360); return (float) (Math.random() * 360);
@@ -28,7 +28,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
/** /**
* Represents an engine for generating random position targets * Represents an engine for generating random position targets.
*/ */
public abstract class RandomTeleportEngine { public abstract class RandomTeleportEngine {
@@ -37,7 +37,7 @@ public abstract class RandomTeleportEngine {
public long maxAttempts = 12; public long maxAttempts = 12;
/** /**
* Constructor for a random teleport engine * Constructor for a random teleport engine.
* *
* @param plugin The HuskHomes plugin instance * @param plugin The HuskHomes plugin instance
* @param name The name of the implementing random teleport engine * @param name The name of the implementing random teleport engine
@@ -53,12 +53,13 @@ public abstract class RandomTeleportEngine {
} }
/** /**
* Get the origin (center) position for the world * Get the origin (center) position for the world.
*
* <p>Note that this will return the {@link HuskHomes#getServerSpawn() server spawn position} if it is in the same
* world as the world passed to this method, otherwise it will return a position at 0, 128, 0 on the provided world.
* *
* @param world The world to get the origin position for * @param world The world to get the origin position for
* @return The origin position * @return The origin position
* @implNote This will return the {@link HuskHomes#getServerSpawn() server spawn position} if it is in the same
* world as the world passed to this method, otherwise it will return a position at 0, 128, 0 on the provided world.
*/ */
@NotNull @NotNull
protected Position getCenterPoint(@NotNull World world) { protected Position getCenterPoint(@NotNull World world) {
@@ -75,13 +76,13 @@ public abstract class RandomTeleportEngine {
/** /**
* Gets a random position in the {@link World}, or {@link Optional#empty()} if no position could be found in * Gets a random position in the {@link World}, or {@link Optional#empty()} if no position could be found in
* the configured number of attempts * the configured number of attempts.
* *
* @param world The world to find a random position in * @param world The world to find a random position in
* @param args The arguments to pass to the random teleport engine * @param args The arguments to pass to the random teleport engine
* @return The position, optionally, which will be empty if the random teleport engine timed out after a * @return An Optional position, if one could be found in the {@link #maxAttempts max attempts}
* {@link #maxAttempts configured number of attempts}
*/ */
public abstract CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world, @NotNull String[] args); public abstract CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world,
@NotNull String[] args);
} }
@@ -27,7 +27,7 @@ import org.jetbrains.annotations.NotNull;
public interface Target { public interface Target {
/** /**
* Create a {@link Target} from a player name * Create a {@link Target} from a player name.
* *
* @param target the player name * @param target the player name
* @return the target * @return the target
@@ -52,8 +52,8 @@ public class Teleport {
protected final boolean updateLastPosition; protected final boolean updateLastPosition;
protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target, protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target,
@NotNull Type type, boolean updateLastPosition, @NotNull List<TransactionResolver.Action> actions, @NotNull Type type, boolean updateLastPosition,
@NotNull HuskHomes plugin) { @NotNull List<TransactionResolver.Action> actions, @NotNull HuskHomes plugin) {
this.plugin = plugin; this.plugin = plugin;
this.executor = executor; this.executor = executor;
this.teleporter = teleporter; this.teleporter = teleporter;
@@ -62,10 +62,8 @@ public class Teleport {
this.actions = actions; this.actions = actions;
this.async = plugin.getSettings().doAsynchronousTeleports(); this.async = plugin.getSettings().doAsynchronousTeleports();
this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class) this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class)
.map(command -> .map(command -> executor.hasPermission(command.getPermission())
executor.hasPermission(command.getPermission()) && && executor.hasPermission(command.getPermission("previous")))
executor.hasPermission(command.getPermission("previous"))
)
.orElse(false); .orElse(false);
} }
@@ -217,7 +215,7 @@ public class Teleport {
} }
/** /**
* Represents the type of teleport being used * Represents the type of teleport being used.
*/ */
public enum Type { public enum Type {
TELEPORT(0), TELEPORT(0),
@@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
import java.time.Instant; import java.time.Instant;
/** /**
* Represents a request between players for one user to teleport to another, or vice versa * Represents a request between players for one user to teleport to another, or vice versa.
*/ */
public class TeleportRequest { public class TeleportRequest {
@@ -50,7 +50,7 @@ public class TeleportRequest {
private String recipientName; private String recipientName;
/** /**
* Create a teleport request * Create a teleport request.
* *
* @param requester The user making the request * @param requester The user making the request
*/ */
@@ -67,7 +67,7 @@ public class TeleportRequest {
} }
/** /**
* Returns if the request has now expired * Returns if the request has now expired.
* *
* @return {@code true} the request has passed its expiry time * @return {@code true} the request has passed its expiry time
*/ */
@@ -76,7 +76,7 @@ public class TeleportRequest {
} }
/** /**
* The name of the request recipient * The name of the request recipient.
*/ */
@NotNull @NotNull
public String getRecipientName() { public String getRecipientName() {
@@ -88,7 +88,7 @@ public class TeleportRequest {
} }
/** /**
* The user making the request * The user making the request.
*/ */
@NotNull @NotNull
public String getRequesterName() { public String getRequesterName() {
@@ -100,7 +100,7 @@ public class TeleportRequest {
} }
/** /**
* The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request * The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request.
*/ */
@NotNull @NotNull
public Position getRequesterPosition() { public Position getRequesterPosition() {
@@ -112,7 +112,7 @@ public class TeleportRequest {
} }
/** /**
* The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE} * The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE}.
*/ */
@NotNull @NotNull
public TeleportRequest.Type getType() { public TeleportRequest.Type getType() {
@@ -124,8 +124,7 @@ public class TeleportRequest {
} }
/** /**
* The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} * The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} or {@link Status#DECLINED}.
* or {@link Status#DECLINED}
*/ */
@NotNull @NotNull
public TeleportRequest.Status getStatus() { public TeleportRequest.Status getStatus() {
@@ -137,38 +136,39 @@ public class TeleportRequest {
} }
/** /**
* Types of teleport requests ({@code /tpa} or {@code /tpahere}) * Types of teleport requests ({@code /tpa} or {@code /tpahere}).
*/ */
public enum Type { public enum Type {
/** /**
* The request is a {@code /tpa} request, where the requester is requesting to teleport <i>to</i> the recipient * The request is a {@code /tpa} request, where the requester is requesting to teleport <i>to</i> the recipient.
*/ */
TPA, TPA,
/** /**
* The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport <i>to them</i> * The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport
* <i>to them</i>.
*/ */
TPA_HERE TPA_HERE
} }
/** /**
* The current status of a teleport request * The current status of a teleport request.
*/ */
public enum Status { public enum Status {
/** /**
* The request is currently pending and can be accepted or declined * The request is currently pending and can be accepted or declined.
*/ */
PENDING, PENDING,
/** /**
* The teleport request has been accepted by the recipient and teleportation will commence * The teleport request has been accepted by the recipient and teleportation will commence.
*/ */
ACCEPTED, ACCEPTED,
/** /**
* The recipient has declined the teleport request * The recipient has declined the teleport request.
*/ */
DECLINED, DECLINED,
/** /**
* The recipient was ignoring teleport requests at the time it was sent; * The recipient was ignoring teleport requests at the time it was sent;
* the request has been automatically declined * the request has been automatically declined.
*/ */
IGNORED IGNORED
} }
@@ -24,14 +24,14 @@ import org.jetbrains.annotations.NotNull;
/** /**
* Represents a teleporter; the person performing the teleport. * Represents a teleporter; the person performing the teleport.
* <p> *
* Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference * <p>Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference
* that needs to be resolved first. * that needs to be resolved first.
*/ */
public interface Teleportable { public interface Teleportable {
/** /**
* Create a {@link Teleportable} from a player name * Create a {@link Teleportable} from a player name.
* *
* @param teleporter the player name * @param teleporter the player name
* @return the teleportable * @return the teleportable
@@ -42,7 +42,7 @@ public interface Teleportable {
} }
/** /**
* Get the username of the teleporter * Get the username of the teleporter.
* *
* @return the username string * @return the username string
*/ */
@@ -54,6 +54,9 @@ public class TeleportationException extends IllegalStateException {
case WORLD_NOT_FOUND -> plugin.getLocales() case WORLD_NOT_FOUND -> plugin.getLocales()
.getLocale("error_invalid_world") .getLocale("error_invalid_world")
.ifPresent(user::sendMessage); .ifPresent(user::sendMessage);
default -> {
// Silent; no message
}
} }
} }
@@ -64,7 +67,7 @@ public class TeleportationException extends IllegalStateException {
} }
/** /**
* Represents different causes of {@link TeleportationException}s * Represents different causes of {@link TeleportationException}s.
*/ */
public enum Type { public enum Type {
TELEPORTER_NOT_FOUND, TELEPORTER_NOT_FOUND,
@@ -119,9 +119,9 @@ public class TimedTeleport extends Teleport implements Runnable {
} }
/** /**
* Ticks a timed teleport, decrementing the time left until the teleport is complete * Ticks a timed teleport, decrementing the time left until the teleport is complete.
* <p> *
* A timed teleport will be canceled if certain criteria are met: * <p>A timed teleport will be canceled if certain criteria are met:
* <ul> * <ul>
* <li>The player has left the server</li> * <li>The player has left the server</li>
* <li>The plugin is disabling</li> * <li>The plugin is disabling</li>
@@ -169,9 +169,9 @@ public class TimedTeleport extends Teleport implements Runnable {
private boolean hasTeleporterMoved() { private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d; final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) + double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX())
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) + + Math.abs(startLocation.getY() - teleporter.getPosition().getY())
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ()); + Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
return movementDistance > maxMovementDistance; return movementDistance > maxMovementDistance;
} }
@@ -36,14 +36,15 @@ public record Username(@NotNull String name) implements Teleportable, Target {
/** /**
* Search for a local {@link OnlineUser} by their name. * Search for a local {@link OnlineUser} by their name.
* *
* <p>If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this
* method will search for the user by exact name.
*
* <p>Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for
* the closest name match.
*
* @param plugin The instance of {@link HuskHomes} * @param plugin The instance of {@link HuskHomes}
* @return An {@link Optional} containing the {@link OnlineUser} if found * @return An {@link Optional} containing the {@link OnlineUser} if found
* @throws TeleportationException If the user is not found * @throws TeleportationException If the user is not found
* @implNote If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this
* method will search for the user by exact name.
* <p>
* Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for
* the closest name match.
*/ */
@NotNull @NotNull
public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) { public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) {
@@ -52,7 +53,7 @@ public record Username(@NotNull String name) implements Teleportable, Target {
} }
/** /**
* Get the username {@link String} being represented by this object * Get the username {@link String} being represented by this object.
* *
* @return the username * @return the username
*/ */
@@ -38,7 +38,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
/** /**
* A cross-platform representation of a logged-in {@link User} * A cross-platform representation of a logged-in {@link User}.
*/ */
public abstract class OnlineUser extends User implements Teleportable, CommandUser { public abstract class OnlineUser extends User implements Teleportable, CommandUser {
@@ -47,29 +47,28 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Returns the current {@link Position} of this player * Returns the current {@link Position} of this player.
* *
* @return the player's current {@link Position} * @return the player's current {@link Position}
*/ */
public abstract Position getPosition(); public abstract Position getPosition();
/** /**
* Returns the player's current bed or respawn anchor {@link Position} * Returns the player's current bed or respawn anchor {@link Position}.
* *
* @return an optional with the player's current bed or respawn anchor {@link Position} if it has been set, * @return the player's current respawn {@link Position} if it has been set, or {@link Optional#empty()}
* otherwise an {@link Optional#empty()}
*/ */
public abstract Optional<Position> getBedSpawnPosition(); public abstract Optional<Position> getBedSpawnPosition();
/** /**
* Returns the health of this player * Returns the health of this player.
* *
* @return the player's health points * @return the player's health points
*/ */
public abstract double getHealth(); public abstract double getHealth();
/** /**
* Returns if the player has the permission node * Returns if the player has the permission node.
* *
* @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
@@ -77,7 +76,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract boolean hasPermission(@NotNull 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.
* *
* @return a {@link Map} of all permissions this player has to their set values * @return a {@link Map} of all permissions this player has to their set values
*/ */
@@ -85,7 +84,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract Map<String, Boolean> getPermissions(); public abstract Map<String, Boolean> getPermissions();
/** /**
* Dispatch a MineDown-formatted title or subtitle to the player * Dispatch a MineDown-formatted title or subtitle to the player.
* *
* @param mineDown the parsed {@link MineDown} to send * @param mineDown the parsed {@link MineDown} to send
* @param subTitle whether to send the title as a subtitle ({@code true} for a subtitle, {@code false} for a title) * @param subTitle whether to send the title as a subtitle ({@code true} for a subtitle, {@code false} for a title)
@@ -97,7 +96,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Dispatch a MineDown-formatted action bar message to this player * Dispatch a MineDown-formatted action bar message to this player.
* *
* @param mineDown the parsed {@link MineDown} to send * @param mineDown the parsed {@link MineDown} to send
*/ */
@@ -109,7 +108,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
/** /**
* Dispatch a MineDown-formatted chat message to this player * Dispatch a MineDown-formatted chat message to this player.
* *
* @param mineDown the parsed {@link MineDown} to send * @param mineDown the parsed {@link MineDown} to send
*/ */
@@ -120,7 +119,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Dispatch a MineDown-formatted message to this player * Dispatch a MineDown-formatted message to this player.
* *
* @param mineDown the parsed {@link MineDown} to send * @param mineDown the parsed {@link MineDown} to send
* @param slot the {@link Locales.DisplaySlot} to send the message to * @param slot the {@link Locales.DisplaySlot} to send the message to
@@ -138,25 +137,26 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Dispatch a Minecraft translatable keyed-message to this player * Dispatch a Minecraft translatable keyed-message to this player.
*
* <p>This method is intended for use with Minecraft's built-in translation keys.
* If the key is invalid, it will be substituted with {@code minecraft:block.minecraft.spawn.not_valid}
* *
* @param translationKey the translation key of the message to send * @param translationKey the translation key of the message to send
* @implNote This method is intended for use with Minecraft's built-in translation keys. If the key is invalid,
* it will be substituted with {@code minecraft:block.minecraft.spawn.not_valid}
*/ */
public void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid") public void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid")
@NotNull String translationKey) { @NotNull String translationKey) {
getAudience().sendMessage(Component.translatable(translationKey)); getAudience().sendMessage(Component.translatable(translationKey));
} }
/** /**
* Play the specified sound to this player * Play the specified sound to this player.
* *
* @param soundEffect the sound effect to play. If the sound name is invalid, the sound will not play * @param soundEffect the sound effect to play. If the sound name is invalid, the sound will not play
* @implNote If the key is invalid, it will be substituted with {@code minecraft:block.note_block.banjo} * @implNote If the key is invalid, it will be substituted with {@code minecraft:block.note_block.banjo}
*/ */
public void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo") public void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo")
@NotNull String soundEffect) throws IllegalArgumentException { @NotNull String soundEffect) throws IllegalArgumentException {
try { try {
getAudience().playSound( getAudience().playSound(
Sound.sound(Key.key(soundEffect), Sound.Source.PLAYER, 1.0f, 1.0f), Sound.sound(Key.key(soundEffect), Sound.Source.PLAYER, 1.0f, 1.0f),
@@ -168,7 +168,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Get the adventure {@link Audience} for this player * Get the adventure {@link Audience} for this player.
* *
* @return the adventure {@link Audience} for this player * @return the adventure {@link Audience} for this player
*/ */
@@ -176,16 +176,16 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract Audience getAudience(); public abstract Audience getAudience();
/** /**
* Teleport a player to the specified local {@link Location} * Teleport a player to the specified local {@link Location}.
* *
* @param location the {@link Location} to teleport the player to * @param location the {@link Location} to teleport the player to
* @param asynchronous if the teleport should be asynchronous * @param async if the teleport should be asynchronous
* @throws TeleportationException if the teleport fails * @throws TeleportationException if the teleport fails
*/ */
public abstract void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException; public abstract void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException;
/** /**
* Send a plugin message to the user * Send a plugin message to the user.
* *
* @param channel channel to send it on * @param channel channel to send it on
* @param message byte array of message data * @param message byte array of message data
@@ -193,21 +193,21 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract void sendPluginMessage(@NotNull String channel, byte[] message); public abstract void sendPluginMessage(@NotNull String channel, byte[] message);
/** /**
* Returns if a player is moving (i.e. they have momentum) * Returns if a player is moving (i.e., they have momentum).
* *
* @return {@code true} if the player is moving; {@code false} otherwise * @return {@code true} if the player is moving; {@code false} otherwise
*/ */
public abstract boolean isMoving(); public abstract boolean isMoving();
/** /**
* Returns if the player is tagged as being "vanished" by a /vanish plugin * Returns if the player is tagged as being "vanished" by a /vanish plugin.
* *
* @return {@code true} if the player is tagged as being "vanished" by a /vanish plugin; {@code false} otherwise * @return {@code true} if the player is tagged as being "vanished" by a /vanish plugin; {@code false} otherwise
*/ */
public abstract boolean isVanished(); public abstract boolean isVanished();
/** /**
* Get the maximum number of homes this user may set * Get the maximum number of homes this user may set.
* *
* @param defaultMaxHomes the default maximum number of homes if the user has not set a custom value * @param defaultMaxHomes the default maximum number of homes if the user has not set a custom value
* @param stack whether to stack numerical permissions that grant the user extra max homes * @param stack whether to stack numerical permissions that grant the user extra max homes
@@ -226,7 +226,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Get the number of homes this user may make public * Get the number of homes this user may make public.
* *
* @param defaultPublicHomes the default number of homes this user may make public * @param defaultPublicHomes the default number of homes this user may make public
* @param stack whether to stack numerical permissions that grant the user extra public homes * @param stack whether to stack numerical permissions that grant the user extra public homes
@@ -245,7 +245,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Get the number of free home slots this user may set * Get the number of free home slots this user may set.
* *
* @param defaultFreeHomes the default number of free home slots to give this user * @param defaultFreeHomes the default number of free home slots to give this user
* @param stack whether to stack numerical permissions that grant the user extra free homes * @param stack whether to stack numerical permissions that grant the user extra free homes
@@ -264,7 +264,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
} }
/** /**
* Gets a list of numbers from the prefixed permission nodes * Gets a list of numbers from the prefixed permission nodes.
* *
* @param nodePrefix the prefix of the permission nodes to get * @param nodePrefix the prefix of the permission nodes to get
* @return a list of numbers from the prefixed permission nodes, sorted by size * @return a list of numbers from the prefixed permission nodes, sorted by size
@@ -27,7 +27,7 @@ import java.time.temporal.ChronoUnit;
import java.util.UUID; import java.util.UUID;
/** /**
* Represents data about a player on the server * Represents data about a player on the server.
*/ */
public class SavedUser { public class SavedUser {
@@ -36,7 +36,7 @@ public class SavedUser {
private boolean ignoringTeleports; private boolean ignoringTeleports;
/** /**
* Create a new SavedUser object * Create a new SavedUser object.
* *
* @param user The user to create the object for * @param user The user to create the object for
* @param homeSlots The number of home slots the user has * @param homeSlots The number of home slots the user has
@@ -49,12 +49,15 @@ public class SavedUser {
} }
/** /**
* @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object * Create a new SavedUser object.
* <p> *
* User RTP cooldowns are no longer stored in {@link SavedUser} objects, * <p>Please note that User RTP cooldowns are no longer stored in {@link SavedUser} objects;
* please use the new API methods for getting/setting cooldowns * please use the new API methods for getting/setting cooldowns
*
* @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object.
*/ */
@Deprecated(since = "4.4", forRemoval = true) @Deprecated(since = "4.4", forRemoval = true)
@SuppressWarnings("unused")
public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) { public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) {
this(user, homeSlots, ignoringTeleports); this(user, homeSlots, ignoringTeleports);
} }
@@ -91,6 +94,8 @@ public class SavedUser {
} }
/** /**
* Get the user's RTP cooldown. This method will always return 5 seconds before the current time since v4.4.
*
* @deprecated Use the new API methods for setting and getting cooldowns * @deprecated Use the new API methods for setting and getting cooldowns
*/ */
@NotNull @NotNull
@@ -100,9 +105,12 @@ public class SavedUser {
} }
/** /**
* Set the user's RTP cooldown. This method has no effect since v4.4.
*
* @deprecated Use the new API methods for setting and getting cooldowns * @deprecated Use the new API methods for setting and getting cooldowns
*/ */
@Deprecated(since = "4.4", forRemoval = true) @Deprecated(since = "4.4", forRemoval = true)
@SuppressWarnings("unused")
public void setRtpCooldown(@NotNull Instant rtpCooldown) { public void setRtpCooldown(@NotNull Instant rtpCooldown) {
// Do nothing // Do nothing
} }
@@ -24,7 +24,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
/** /**
* Represents a user who has data saved in the database * Represents a user who has data saved in the database.
*/ */
public class User { public class User {
@@ -35,7 +35,7 @@ public class User {
private final String username; private final String username;
/** /**
* Get a user from a {@link UUID} and username * Get a user from a {@link UUID} and username.
* *
* @param uuid Minecraft account {@link UUID} of the player * @param uuid Minecraft account {@link UUID} of the player
* @param username Username of the player * @param username Username of the player
@@ -31,16 +31,15 @@ public interface SafetyResolver {
int SEARCH_RADIUS = 2; int SEARCH_RADIUS = 2;
/** /**
* Returns a safe ground location for the specified {@link Location} if possible * Returns a safe ground location for the specified {@link Location} if possible.
* *
* @param location the {@link Location} to find a safe ground location for * @param location the {@link Location} to find a safe ground location for
* @return a {@link CompletableFuture} that will complete with an optional of the safe ground position, if it is * @return a {@link CompletableFuture} with an optional safe ground position, if one could be found
* possible to find one
*/ */
CompletableFuture<Optional<Location>> findSafeGroundLocation(@NotNull Location location); CompletableFuture<Optional<Location>> findSafeGroundLocation(@NotNull Location location);
/** /**
* Returns if the block, by provided identifier, is unsafe to stand on * Returns if the block, by provided identifier, is unsafe to stand on.
* *
* @param blockId The block identifier (e.g. {@code minecraft:stone}) * @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise * @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
@@ -50,10 +49,10 @@ public interface SafetyResolver {
} }
/** /**
* Returns if the block, by provided identifier, is unsafe to stand in * Returns if the block, by provided identifier, is unsafe to stand in.
* *
* @param blockId The block identifier (e.g. {@code minecraft:stone}) * @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is able to be occupied, {@code false} otherwise * @return {@code true} if the block can be occupied, {@code false} otherwise
*/ */
default boolean isBlockSafeForOccupation(@NotNull String blockId) { default boolean isBlockSafeForOccupation(@NotNull String blockId) {
return !getPlugin().getUnsafeBlocks().isUnsafeToOccupy(blockId); return !getPlugin().getUnsafeBlocks().isUnsafeToOccupy(blockId);
@@ -30,15 +30,15 @@ import java.util.Optional;
import java.util.StringJoiner; import java.util.StringJoiner;
/** /**
* Class for validating and performing economy and cooldown transactions involving {@link Action}s * Class for validating and performing economy and cooldown transactions involving {@link Action}s.
*/ */
public interface TransactionResolver { public interface TransactionResolver {
/** /**
* Validates whether an {@link OnlineUser} can perform an {@link Action}, in terms of whether they have sufficient * Validates whether an {@link OnlineUser} can perform an {@link Action}, in terms of whether they have sufficient
* funds and are not on cooldown. This method will also send the user a message if they cannot perform the action. * funds and are not on cooldown. This method will also send the user a message if they cannot perform the action.
* <p> *
* This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise * <p>This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise
* {@code false}. * {@code false}.
* *
* @param player the {@link OnlineUser player} to perform the check on * @param player the {@link OnlineUser player} to perform the check on
@@ -52,11 +52,13 @@ public interface TransactionResolver {
// Validates if the user has funds to perform an action // Validates if the user has funds to perform an action
private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) { private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) {
return getPlugin().getSettings().getEconomyCost(action).map(Math::abs) return getPlugin().getSettings().getEconomyCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) ? Optional.empty() : Optional.of(c)) .flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c))
.map(c -> getEconomyHook() .map(c -> getEconomyHook()
.map(hook -> { .map(hook -> {
if (hook.getPlayerBalance(player) < c) { if (hook.getPlayerBalance(player) < c) {
getPlugin().getLocales().getLocale("error_insufficient_funds", hook.formatCurrency(c)) getPlugin().getLocales().getLocale("error_insufficient_funds",
hook.formatCurrency(c))
.ifPresent(player::sendMessage); .ifPresent(player::sendMessage);
return false; return false;
} }
@@ -110,7 +112,7 @@ public interface TransactionResolver {
} }
/** /**
* Execute an economy transaction if needed, updating the player's balance * Execute an economy transaction if needed, updating the player's balance.
* *
* @param player the {@link OnlineUser player} to deduct the cost from if needed * @param player the {@link OnlineUser player} to deduct the cost from if needed
* @param action the {@link Action action} to deduct the cost from if needed * @param action the {@link Action action} to deduct the cost from if needed
@@ -118,7 +120,8 @@ public interface TransactionResolver {
default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) { default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) {
getEconomyHook().ifPresent(hook -> getPlugin().getSettings() getEconomyHook().ifPresent(hook -> getPlugin().getSettings()
.getEconomyCost(action).map(Math::abs) .getEconomyCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) ? Optional.empty() : Optional.of(c)) .flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c))
.ifPresent(cost -> { .ifPresent(cost -> {
hook.changePlayerBalance(player, -cost); hook.changePlayerBalance(player, -cost);
hook.notifyDeducted(player, getPlugin(), action); hook.notifyDeducted(player, getPlugin(), action);
@@ -131,16 +134,9 @@ public interface TransactionResolver {
} }
/** /**
* @deprecated use {@link #validateTransaction(OnlineUser, Action)} instead * Execute an economy transaction if needed, updating the player's balance.
*/ *
@SuppressWarnings("removal") * @deprecated use {@link #performTransaction(OnlineUser, Action)} instead.
@Deprecated(since = "4.4", forRemoval = true)
default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
return this.validateTransaction(player, action.getTransactionAction());
}
/**
* @deprecated use {@link #performTransaction(OnlineUser, Action)} instead
*/ */
@SuppressWarnings("removal") @SuppressWarnings("removal")
@Deprecated(since = "4.4", forRemoval = true) @Deprecated(since = "4.4", forRemoval = true)
@@ -149,7 +145,19 @@ public interface TransactionResolver {
} }
/** /**
* Get the {@link EconomyHook} instance, if present * Get whether the {@link OnlineUser} can perform the {@link EconomyHook.Action},
* in terms of whether they have sufficient funds and are not on cooldown.
*
* @deprecated use {@link #validateTransaction(OnlineUser, Action)} instead.
*/
@SuppressWarnings("removal")
@Deprecated(since = "4.4", forRemoval = true)
default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
return this.validateTransaction(player, action.getTransactionAction());
}
/**
* Get the {@link EconomyHook} instance, if present.
* *
* @return the {@link EconomyHook} instance * @return the {@link EconomyHook} instance
*/ */
@@ -162,7 +170,7 @@ public interface TransactionResolver {
HuskHomes getPlugin(); HuskHomes getPlugin();
/** /**
* Represents actions that can be the subject of a transaction * Represents actions that can be the subject of a transaction.
*/ */
enum Action { enum Action {
@@ -204,7 +212,7 @@ public interface TransactionResolver {
} }
/** /**
* Create an action with a default cost * Create an action with a default cost.
* *
* @return the default cost * @return the default cost
*/ */
@@ -213,7 +221,7 @@ public interface TransactionResolver {
} }
/** /**
* Get the default cooldown for this action (in seconds) * Get the default cooldown for this action (in seconds).
* *
* @return the default cooldown in seconds * @return the default cooldown in seconds
*/ */
@@ -39,6 +39,28 @@ public class UnsafeBlocks {
@YamlKey("safe_occupation_blocks") @YamlKey("safe_occupation_blocks")
public List<String> safeOccupationBlocks; public List<String> safeOccupationBlocks;
/**
* Returns if the block, by provided identifier, are unsafe.
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafe(@NotNull String blockId) {
return unsafeBlocks.contains(this.formatBlockId(blockId));
}
/**
* Returns if the block, by provided identifier, is unsafe to stand in.
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafeToOccupy(@NotNull String blockId) {
return !safeOccupationBlocks.contains(this.formatBlockId(blockId));
}
// Format a block ID to be in the format namespace:id
@NotNull
private String formatBlockId(@NotNull String blockId) { private String formatBlockId(@NotNull String blockId) {
if (!blockId.startsWith(Key.MINECRAFT_NAMESPACE + ":")) { if (!blockId.startsWith(Key.MINECRAFT_NAMESPACE + ":")) {
blockId = Key.MINECRAFT_NAMESPACE + ":" + blockId; blockId = Key.MINECRAFT_NAMESPACE + ":" + blockId;
@@ -46,28 +68,6 @@ public class UnsafeBlocks {
return blockId; return blockId;
} }
/**
* Returns if the block, by provided identifier, is unsafe
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafe(@NotNull String blockId) {
blockId = this.formatBlockId(blockId);
return unsafeBlocks.contains(blockId);
}
/**
* Returns if the block, by provided identifier, is unsafe to stand in
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafeToOccupy(@NotNull String blockId) {
blockId = this.formatBlockId(blockId);
return !safeOccupationBlocks.contains(blockId);
}
@SuppressWarnings("unused") @SuppressWarnings("unused")
public UnsafeBlocks() { public UnsafeBlocks() {
} }
@@ -33,7 +33,8 @@ public class ValidationException extends IllegalArgumentException {
this.type = type; this.type = type;
} }
public void dispatchHomeError(@NotNull CommandUser viewer, boolean other, @NotNull HuskHomes plugin, @NotNull String... args) { public void dispatchHomeError(@NotNull CommandUser viewer, boolean other, @NotNull HuskHomes plugin,
@NotNull String... args) {
switch (type) { switch (type) {
case NOT_FOUND -> plugin.getLocales() case NOT_FOUND -> plugin.getLocales()
.getLocale(other ? "error_home_invalid_other" : "error_home_invalid", args) .getLocale(other ? "error_home_invalid_other" : "error_home_invalid", args)
@@ -48,13 +49,18 @@ public class ValidationException extends IllegalArgumentException {
.getLocale("error_home_description_characters", args) .getLocale("error_home_description_characters", args)
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
case NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_HOMES -> plugin.getLocales() case NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_HOMES -> plugin.getLocales()
.getLocale("error_set_home_maximum_homes", Integer.toString(plugin.getManager().homes() .getLocale("error_set_home_maximum_homes",
Integer.toString(plugin.getManager().homes()
.getMaxHomes(viewer instanceof OnlineUser user ? user : null))) .getMaxHomes(viewer instanceof OnlineUser user ? user : null)))
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
case REACHED_MAX_PUBLIC_HOMES -> plugin.getLocales() case REACHED_MAX_PUBLIC_HOMES -> plugin.getLocales()
.getLocale("error_edit_home_maximum_public_homes", Integer.toString(plugin.getManager().homes() .getLocale("error_edit_home_maximum_public_homes",
Integer.toString(plugin.getManager().homes()
.getMaxPublicHomes(viewer instanceof OnlineUser user ? user : null))) .getMaxPublicHomes(viewer instanceof OnlineUser user ? user : null)))
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
default -> {
// Do nothing (silently handle validation errors)
}
} }
} }
@@ -72,6 +78,9 @@ public class ValidationException extends IllegalArgumentException {
case DESCRIPTION_INVALID -> plugin.getLocales() case DESCRIPTION_INVALID -> plugin.getLocales()
.getLocale("error_warp_description_characters", args) .getLocale("error_warp_description_characters", args)
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
default -> {
// Do nothing (silently handle validation errors)
}
} }
} }
@@ -82,7 +91,7 @@ public class ValidationException extends IllegalArgumentException {
} }
/** /**
* The type of validation error * The type of validation error.
*/ */
public enum Type { public enum Type {
NOT_FOUND, NOT_FOUND,
@@ -37,7 +37,7 @@ public class Validator {
} }
/** /**
* Check if a name is valid * Check if a name is valid.
* *
* @param name The name to check * @param name The name to check
* @return True if the name is valid as per the plugin settings, false otherwise * @return True if the name is valid as per the plugin settings, false otherwise
@@ -49,7 +49,7 @@ public class Validator {
} }
/** /**
* Validate home and warp descriptions * Validate home and warp descriptions.
* *
* @param description The meta to validate * @param description The meta to validate
* @return Whether the meta is valid against the plugin settings * @return Whether the meta is valid against the plugin settings
Loaded 100 of 219 files, more files were not shown because too many files have changed in this diff. Show more