diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4dc3eb3..6053eaf3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,7 +106,10 @@ jobs: pl3xmap | suggests | * luckperms | 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 }} version: ${{ env.version_name }} version-type: alpha @@ -114,6 +117,8 @@ jobs: loaders: | fabric game-versions: | + 1.19.2 + 1.19.4 1.20.1 java: 17 - name: Upload GitHub Artifact (Spigot) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 962716ef..73eb9346 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -94,7 +94,10 @@ jobs: pl3xmap | suggests | * luckperms | 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 }} version: ${{ github.event.release.tag_name }} version-type: release @@ -102,6 +105,8 @@ jobs: loaders: | fabric game-versions: | + 1.19.2 + 1.19.4 1.20.1 java: 17 - name: Upload GitHub Artifact (Spigot) diff --git a/README.md b/README.md index 3e4f5869..bb997fbc 100644 --- a/README.md +++ b/README.md @@ -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! ## 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 ./gradlew clean build diff --git a/build.gradle b/build.gradle index f79da830..7a08dffb 100644 --- a/build.gradle +++ b/build.gradle @@ -4,6 +4,7 @@ plugins { id 'com.github.johnrengelman.shadow' version '8.1.1' id 'org.cadixdev.licenser' version '0.6.1' apply false id 'org.ajoberstar.grgit' version '5.2.0' + id 'checkstyle' id 'maven-publish' id 'java' } @@ -11,7 +12,7 @@ plugins { group 'net.william278' version "$ext.plugin_version${versionMetadata()}" description "$ext.plugin_description" -defaultTasks 'licenseFormat', 'build' +defaultTasks 'licenseFormat', 'check', 'build' ext { set 'version', version.toString() @@ -20,16 +21,12 @@ ext { set 'jedis_version', jedis_version.toString() set 'sqlite_driver_version', sqlite_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 { apply plugin: 'com.github.johnrengelman.shadow' apply plugin: 'org.cadixdev.licenser' + apply plugin: 'checkstyle' apply plugin: 'java' compileJava.options.encoding = 'UTF-8' @@ -65,16 +62,16 @@ allprojects { testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.3' } - test { - useJUnitPlatform() - } - license { header = rootProject.file('HEADER') include '**/*.java' newLine = true } + checkstyle { + toolVersion = '10.12.0' + } + processResources { filesMatching(['**/*.json', '**/*.yml']) { filter ReplaceTokens as Class, beginToken: '${', endToken: '}', diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 9c66e661..cbe2723b 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -22,9 +22,9 @@ package net.william278.huskhomes; import net.kyori.adventure.platform.bukkit.BukkitAudiences; import net.william278.annotaml.Annotaml; import net.william278.desertwell.util.Version; +import net.william278.huskhomes.api.HuskHomesAPI; import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.Command; -import net.william278.huskhomes.command.DisabledCommand; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; @@ -62,6 +62,7 @@ import org.bukkit.plugin.java.JavaPluginLoader; import org.bukkit.plugin.messaging.PluginMessageListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; import space.arim.morepaperlib.MorePaperLib; import space.arim.morepaperlib.scheduling.GracefulScheduling; @@ -79,6 +80,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask * Metrics ID for HuskHomes on Bukkit. */ private static final int METRICS_ID = 8430; + private Set savedUsers; private Settings settings; private Locales locales; @@ -94,34 +96,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask private Map> globalPlayerList; private Set currentlyOnWarmup; private Server server; - @Nullable - private Broker broker; private BukkitAudiences audiences; private MorePaperLib paperLib; - - private static BukkitHuskHomes instance; - - public static BukkitHuskHomes getInstance() { - return instance; - } + @Nullable + private Broker broker; // Default public constructor - @SuppressWarnings("unused") public BukkitHuskHomes() { super(); } // Super constructor for unit testing - @SuppressWarnings("unused") - protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) { + @TestOnly + protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, + @NotNull File dataFolder, @NotNull File file) { super(loader, description, dataFolder, file); } - @Override - public void onLoad() { - instance = this; - } - @Override public void onEnable() { // Create adventure audience @@ -142,7 +133,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask // Initialize the database initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { this.database = switch (getSettings().getDatabaseType()) { - case MYSQL -> new MySqlDatabase(this); + case MYSQL, MARIADB -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); }; @@ -190,6 +181,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask // Register commands initialize("commands", (plugin) -> this.commands = registerCommands()); + // Initialize the API + initialize("API", (plugin) -> HuskHomesAPI.register(this)); + // Hook into bStats and check for updates initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID)); this.checkForUpdates(); @@ -197,19 +191,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask @NotNull public List registerCommands() { - return Arrays.stream(BukkitCommand.Type.values()) - .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()); + return BukkitCommand.Type.getCommands(this); } @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 */ @@ -277,7 +259,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask @Override public List getOnlineUsers() { return Bukkit.getOnlinePlayers().stream() - .map(player -> (OnlineUser) BukkitUser.adapt(player)) + .map(player -> (OnlineUser) BukkitUser.adapt(player, this)) .toList(); } @@ -369,7 +351,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask // Update the world spawn location, too BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> { - assert bukkitLocation.getWorld() != null; + assert bukkitLocation.getWorld() != null : "World was null when setting server spawn"; bukkitLocation.getWorld().setSpawnLocation(bukkitLocation); }); } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { @@ -451,14 +433,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask try { 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()) { - 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("using_economy", () -> Boolean.toString(getSettings().doEconomy()))); - metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook()))); + + metrics.addCustomChart(new SimplePie("language", + () -> getSettings().getLanguage().toLowerCase())); + 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))); } catch (Throwable e) { log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); @@ -467,8 +458,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask @Override public void initializePluginChannels() { - Bukkit.getMessenger().registerIncomingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID, this); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID); + final String channelId = PluginMessageBroker.BUNGEE_CHANNEL_ID; + Bukkit.getMessenger().registerIncomingPluginChannel(this, channelId, this); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, channelId); } @Override @@ -483,8 +475,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask @Override public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { if (broker != null && broker instanceof PluginMessageBroker pluginMessenger - && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { - pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message); + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + pluginMessenger.onReceive(channel, BukkitUser.adapt(player, this), message); } } @@ -498,4 +490,5 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask public HuskHomes getPlugin() { return this; } + } diff --git a/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java b/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java index a8d6add3..fed4b34b 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java +++ b/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java @@ -28,6 +28,7 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.BukkitAdapter; import org.bukkit.entity.Player; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; 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 * and process teleports - *

- * Retrieve an instance of the API class via {@link #getInstance()}. + * + *

Retrieve an instance of the API class via {@link #getInstance()}. */ @SuppressWarnings("unused") public class HuskHomesAPI extends BaseHuskHomesAPI { - /** - * (Internal use only) - Instance of the API class - */ + // Instance of the plugin private static HuskHomesAPI instance; /** - * (Internal use only) - Constructor, instantiating the API + * (Internal use only) - Constructor, instantiating the API. */ - private HuskHomesAPI() { - super(BukkitHuskHomes.getInstance()); + @ApiStatus.Internal + 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 + * @throws NotRegisteredException if the API has not yet been registered. */ @NotNull - public static HuskHomesAPI getInstance() { - return instance == null ? instance = new HuskHomesAPI() : instance; + public static HuskHomesAPI getInstance() throws NotRegisteredException { + if (instance == null) { + throw new NotRegisteredException(); + } + return instance; + } + + /** + * (Internal use only) - Register the API for this platform. + * + * @param plugin the plugin instance + */ + @ApiStatus.Internal + public static void register(@NotNull BukkitHuskHomes plugin) { + instance = new HuskHomesAPI(plugin); + } + + /** + * (Internal use only) - Unregister the API for this platform. + */ + @ApiStatus.Internal + public static void unregister() { + instance = null; } /** @@ -73,7 +95,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI { */ @NotNull 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 * @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 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 - * @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 */ @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 */ @NotNull diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java b/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java index 3b975574..a026d183 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java @@ -31,25 +31,28 @@ import java.util.logging.Level; public class BrigadierUtil { /** - * Uses commodore to register command completions + * Uses commodore to register command completions. * * @param plugin instance of the registering Bukkit plugin * @param bukkitCommand the Bukkit PluginCommand 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) { - final InputStream commandCommodore = plugin.getResource("commodore/" + bukkitCommand.getName() + ".commodore"); - if (commandCommodore == null) { + final InputStream commodoreFile = plugin.getResource( + "commodore/" + bukkitCommand.getName() + ".commodore" + ); + if (commodoreFile == null) { return; } try { CommodoreProvider.getCommodore(plugin).register(bukkitCommand, - CommodoreFileReader.INSTANCE.parse(commandCommodore), + CommodoreFileReader.INSTANCE.parse(commodoreFile), player -> player.hasPermission(command.getPermission())); } catch (IOException e) { plugin.log(Level.SEVERE, "Failed to read command commodore completions for " - + bukkitCommand.getName(), e); + + bukkitCommand.getName(), e); } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java index d81aebf6..f45e2145 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java @@ -21,6 +21,7 @@ package net.william278.huskhomes.command; import me.lucko.commodore.CommodoreProvider; import net.william278.huskhomes.BukkitHuskHomes; +import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.CommandUser; @@ -36,6 +37,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; +import java.util.function.Function; public class BukkitCommand implements CommandExecutor, TabCompleter { @@ -50,7 +52,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command, @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; } @@ -61,7 +63,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { if (!(this.command instanceof TabProvider provider)) { 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); } @@ -73,7 +75,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } // Register permissions - addPermission(plugin, command.getPermission(), command.getUsage(), getPermissionDefault(command.isOperatorCommand())); + addPermission( + plugin, + command.getPermission(), + command.getUsage(), + getPermissionDefault(command.isOperatorCommand()) + ); final List childNodes = command.getAdditionalPermissions() .entrySet().stream() .map((entry) -> addPermission(plugin, entry.getKey(), "", getPermissionDefault(entry.getValue()))) @@ -81,7 +88,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { .toList(); if (!childNodes.isEmpty()) { addPermission(plugin, command.getPermission("*"), command.getUsage(), PermissionDefault.FALSE, - childNodes.toArray(new Permission[0])); + childNodes.toArray((plugin) -> new Permission[0])); } // Set command parameters @@ -97,8 +104,9 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } @Nullable - protected static Permission addPermission(@NotNull BukkitHuskHomes plugin, @NotNull String node, @NotNull String description, - @NotNull PermissionDefault permissionDefault, @NotNull Permission... children) { + protected static Permission addPermission(@NotNull BukkitHuskHomes plugin, @NotNull String node, + @NotNull String description, @NotNull PermissionDefault permissionDefault, + @NotNull Permission... children) { final Map childNodes = Arrays.stream(children) .map(Permission::getName) .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 { - HOME_COMMAND(new PrivateHomeCommand(BukkitHuskHomes.getInstance())), - SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())), - HOME_LIST_COMMAND(new PrivateHomeListCommand(BukkitHuskHomes.getInstance())), - DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())), - EDIT_HOME_COMMAND(new EditHomeCommand(BukkitHuskHomes.getInstance())), - PUBLIC_HOME_COMMAND(new PublicHomeCommand(BukkitHuskHomes.getInstance())), - PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(BukkitHuskHomes.getInstance())), - WARP_COMMAND(new WarpCommand(BukkitHuskHomes.getInstance())), - SET_WARP_COMMAND(new SetWarpCommand(BukkitHuskHomes.getInstance())), - WARP_LIST_COMMAND(new WarpListCommand(BukkitHuskHomes.getInstance())), - DEL_WARP_COMMAND(new DelWarpCommand(BukkitHuskHomes.getInstance())), - EDIT_WARP_COMMAND(new EditWarpCommand(BukkitHuskHomes.getInstance())), - TP_COMMAND(new TpCommand(BukkitHuskHomes.getInstance())), - TP_HERE_COMMAND(new TpHereCommand(BukkitHuskHomes.getInstance())), - TPA_COMMAND(new TeleportRequestCommand(BukkitHuskHomes.getInstance(), TeleportRequest.Type.TPA)), - TPA_HERE_COMMAND(new TeleportRequestCommand(BukkitHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)), - TPACCEPT_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), true)), - TPDECLINE_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), false)), - RTP_COMMAND(new RtpCommand(BukkitHuskHomes.getInstance())), - TP_IGNORE_COMMAND(new TpIgnoreCommand(BukkitHuskHomes.getInstance())), - TP_OFFLINE_COMMAND(new TpOfflineCommand(BukkitHuskHomes.getInstance())), - TP_ALL_COMMAND(new TpAllCommand(BukkitHuskHomes.getInstance())), - TPA_ALL_COMMAND(new TpaAllCommand(BukkitHuskHomes.getInstance())), - SPAWN_COMMAND(new SpawnCommand(BukkitHuskHomes.getInstance())), - SET_SPAWN_COMMAND(new SetSpawnCommand(BukkitHuskHomes.getInstance())), - BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance())), - HUSKHOMES_COMMAND(new HuskHomesCommand(BukkitHuskHomes.getInstance())); + HOME_COMMAND(PrivateHomeCommand::new), + SET_HOME_COMMAND(SetHomeCommand::new), + HOME_LIST_COMMAND(PrivateHomeListCommand::new), + DEL_HOME_COMMAND(DelHomeCommand::new), + EDIT_HOME_COMMAND(EditHomeCommand::new), + PUBLIC_HOME_COMMAND(PublicHomeCommand::new), + PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), + WARP_COMMAND(WarpCommand::new), + SET_WARP_COMMAND(SetWarpCommand::new), + WARP_LIST_COMMAND(WarpListCommand::new), + DEL_WARP_COMMAND(DelWarpCommand::new), + EDIT_WARP_COMMAND(EditWarpCommand::new), + TP_COMMAND(TpCommand::new), + TP_HERE_COMMAND(TpHereCommand::new), + TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), + TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), + TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), + TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), + RTP_COMMAND(RtpCommand::new), + TP_IGNORE_COMMAND(TpIgnoreCommand::new), + TP_OFFLINE_COMMAND(TpOfflineCommand::new), + TP_ALL_COMMAND(TpAllCommand::new), + TPA_ALL_COMMAND(TpaAllCommand::new), + SPAWN_COMMAND(SpawnCommand::new), + SET_SPAWN_COMMAND(SetSpawnCommand::new), + BACK_COMMAND(BackCommand::new), + HUSKHOMES_COMMAND(HuskHomesCommand::new); - private final Command command; + private final Function supplier; - Type(@NotNull Command command) { - this.command = command; + Type(@NotNull Function supplier) { + this.supplier = supplier; } @NotNull - public Command getCommand() { - return command; + public Command createCommand(@NotNull HuskHomes plugin) { + return supplier.apply(plugin); } + + @NotNull + public static List 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(); + } + } } \ No newline at end of file diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java index 6dc5bec3..a0c087a7 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java @@ -36,83 +36,90 @@ import java.util.List; public interface BukkitEventDispatcher extends EventDispatcher { @Override - default boolean fireIsCancelled(@NotNull T event) { + default @NotNull boolean fireIsCancelled(@NotNull T event) { Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event); return event instanceof Cancellable cancellable && cancellable.isCancelled(); } @Override + @NotNull default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { return teleport.getType() == Teleport.Type.BACK ? new TeleportBackEvent(teleport) : new TeleportEvent(teleport); } @Override - default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { + default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { return new TeleportWarmupEvent(teleport, duration); } @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); } @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); } @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); } @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); } @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); } @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); } @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); } @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); } @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); } @Override - default IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, boolean publicHomeList) { + default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, + boolean publicHomeList) { return new HomeListEvent(homes, listViewer, publicHomeList); } @Override - default IWarpListEvent getViewWarpListEvent(@NotNull List warps, @NotNull CommandUser listViewer) { + default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List warps, @NotNull CommandUser listViewer) { return new WarpListEvent(warps, listViewer); } @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); } @Override - default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { + default @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { return new DeleteAllWarpsEvent(deleter); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/HomeCreateEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/HomeCreateEvent.java index 9eb21fba..08986873 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/HomeCreateEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/HomeCreateEvent.java @@ -37,7 +37,8 @@ public class HomeCreateEvent extends Event implements IHomeCreateEvent, Cancella private final CommandUser creator; 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.name = name; this.position = position; diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java index 65de4a92..e175feb3 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java @@ -21,7 +21,7 @@ package net.william278.huskhomes.hook; import me.clip.placeholderapi.PlaceholderAPIPlugin; 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.OnlineUser; import net.william278.huskhomes.user.SavedUser; @@ -33,21 +33,21 @@ import java.util.List; public class PlaceholderAPIHook extends Hook { - public PlaceholderAPIHook(@NotNull HuskHomes plugin) { + public PlaceholderAPIHook(@NotNull BukkitHuskHomes plugin) { super(plugin, "PlaceholderAPI"); } @Override public void initialize() { - new HuskHomesExpansion(plugin).register(); + new HuskHomesExpansion((BukkitHuskHomes) plugin).register(); } public static class HuskHomesExpansion extends PlaceholderExpansion { @NotNull - private final HuskHomes plugin; + private final BukkitHuskHomes plugin; - private HuskHomesExpansion(@NotNull HuskHomes plugin) { + private HuskHomesExpansion(@NotNull BukkitHuskHomes plugin) { this.plugin = plugin; } @@ -59,7 +59,7 @@ public class PlaceholderAPIHook extends Hook { } // Return the requested data - final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer()); + final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer(), plugin); return switch (params) { case "homes_count" -> String.valueOf(plugin.getManager().homes() .getUserHomes() diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java index 170c5367..923524d7 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java @@ -29,7 +29,7 @@ import org.bukkit.plugin.RegisteredServiceProvider; 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 { diff --git a/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java b/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java index f1cfb2b4..696796f7 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java +++ b/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java @@ -38,7 +38,8 @@ public class EssentialsXImporter extends Importer { public EssentialsXImporter(@NotNull HuskHomes 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() { diff --git a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java index 84f017bc..911e8f3e 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java +++ b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java @@ -38,24 +38,24 @@ public class BukkitEventListener extends EventListener implements Listener { protected boolean checkForBed = true; - public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) { - super(huskHomes); - huskHomes.getServer().getPluginManager().registerEvents(this, huskHomes); + public BukkitEventListener(@NotNull BukkitHuskHomes plugin) { + super(plugin); + plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerJoin(PlayerJoinEvent event) { - super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer())); + super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin)); } @EventHandler(priority = EventPriority.NORMAL) 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) public void onPlayerDeath(PlayerDeathEvent event) { - super.handlePlayerDeath(BukkitUser.adapt(event.getEntity())); + super.handlePlayerDeath(BukkitUser.adapt(event.getEntity(), (BukkitHuskHomes) plugin)); } @EventHandler(priority = EventPriority.NORMAL) @@ -63,7 +63,7 @@ public class BukkitEventListener extends EventListener implements Listener { if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) { return; } - super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer())); + super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin)); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @@ -71,29 +71,37 @@ public class BukkitEventListener extends EventListener implements Listener { final Player player = event.getPlayer(); // 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 - || 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 -> handlePlayerTeleport(bukkitUser, Position.at(sourceLocation, plugin.getServerName()))); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) { - if (!checkForBed) return; - if (!(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) return; - if (event.getClickedBlock() == null) return; - if (!(event.getClickedBlock().getBlockData() instanceof Bed - || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return; + if (!checkForBed || !(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) { + return; + } + if (event.getClickedBlock() == null || !(event.getClickedBlock().getBlockData() instanceof Bed + || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) { + return; + } final Location location = event.getPlayer().getBedSpawnLocation(); - if (location == null) return; + if (location == null) { + return; + } // Update the player's respawn location BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> super.handlePlayerUpdateSpawnPoint( - BukkitUser.adapt(event.getPlayer()), + BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin), Position.at(adaptedLocation, plugin.getServerName())) ); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java index 53f54579..008ac5d2 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java +++ b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java @@ -38,34 +38,45 @@ import java.util.logging.Level; import java.util.stream.Collectors; /** - * Bukkit implementation of an {@link OnlineUser} + * Bukkit's implementation of an {@link OnlineUser}. */ public class BukkitUser extends OnlineUser { private final BukkitHuskHomes plugin; private final Player player; - private BukkitUser(@NotNull Player player) { + private BukkitUser(@NotNull Player player, @NotNull BukkitHuskHomes plugin) { super(player.getUniqueId(), player.getName()); - this.plugin = BukkitHuskHomes.getInstance(); 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 * @return the adapted {@link OnlineUser} */ @NotNull - public static BukkitUser adapt(@NotNull Player player) { - return new BukkitUser(player); + public static BukkitUser adapt(@NotNull Player player, @NotNull BukkitHuskHomes plugin) { + 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 public Position getPosition() { - return Position.at(BukkitAdapter.adaptLocation(player.getLocation()) - .orElseThrow(() -> new IllegalStateException("Failed to get the position of a BukkitPlayer (null)")), + return Position.at(BukkitAdapter.adaptLocation(player.getLocation()).orElseThrow( + () -> new IllegalStateException("Failed to get the position of a BukkitPlayer (null)") + ), plugin.getServerName()); } @@ -104,7 +115,7 @@ public class BukkitUser extends OnlineUser { } @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 final Optional resolvedLocation = BukkitAdapter.adaptLocation(location); 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 plugin.getScheduler().entitySpecificScheduler(player).run( () -> { - if (asynchronous || plugin.getScheduler().isUsingFolia()) { + if (async || plugin.getScheduler().isUsingFolia()) { PaperLib.teleportAsync(player, bukkitLocation, PlayerTeleportEvent.TeleportCause.PLUGIN); 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 **/ @@ -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 */ @@ -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) { 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; - } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitAdapter.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitAdapter.java index 0a480ef0..cf853422 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitAdapter.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitAdapter.java @@ -28,12 +28,12 @@ import org.jetbrains.annotations.Nullable; 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 { /** - * 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 * @return the adapted {@link Location} @@ -45,8 +45,9 @@ public final class BukkitAdapter { } if (world == null) { world = Bukkit.getWorlds().stream() - .filter(w -> w.getEnvironment().name().equalsIgnoreCase(location.getWorld().getEnvironment().name())) - .findFirst().orElse(null); + .filter(w -> w.getEnvironment().name().equalsIgnoreCase( + location.getWorld().getEnvironment().name())).findFirst() + .orElse(null); } if (world == null) { 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 * @return the adapted {@link org.bukkit.Location} */ public static Optional 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(), location.getYaw(), location.getPitch(), adaptWorld(location.getWorld()).orElse(new net.william278.huskhomes.position.World()))); @@ -78,12 +81,13 @@ public final class BukkitAdapter { if (world == null) { return Optional.empty(); } - return Optional.of(World.from(world.getName(), world.getUID(), + return Optional.of(World.from( + world.getName(), world.getUID(), switch (world.getEnvironment()) { case NORMAL -> World.Environment.OVERWORLD; case NETHER -> World.Environment.NETHER; case THE_END -> World.Environment.THE_END; - case CUSTOM -> World.Environment.CUSTOM; + default -> World.Environment.CUSTOM; }) ); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java index 921c9767..2cedf58f 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java @@ -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 snapshot The chunk snapshot to search + * @param chunk The chunk snapshot to search * @param minY The minimum Y value of the world * @return An optional safe location, within 4 blocks of the given location */ - private Optional findSafeLocationNear(@NotNull Location location, @NotNull ChunkSnapshot snapshot, int minY) { + private Optional findSafeLocationNear(@NotNull Location location, @NotNull ChunkSnapshot chunk, + int minY) { final int chunkX = ((int) location.getX()) & 0xF; final int chunkZ = ((int) location.getZ()) & 0xF; - for (int dX = -SEARCH_RADIUS; dX <= SEARCH_RADIUS; dX++) { - for (int dZ = -SEARCH_RADIUS; dZ <= SEARCH_RADIUS; dZ++) { - final int x = chunkX + dX; - final int z = chunkZ + dZ; + for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) { + for (int dz = -SEARCH_RADIUS; dz <= SEARCH_RADIUS; dz++) { + final int x = chunkX + dx; + final int z = chunkZ + dz; if (x < 0 || x >= 16 || z < 0 || z >= 16) { continue; } - final int y = Math.max((minY + 1), snapshot.getHighestBlockYAt(x, z)) + 1; - final Material blockType = snapshot.getBlockType(x, y - 1, z); - final Material bodyBlockType = snapshot.getBlockType(x, y, z); - final Material headBlockType = snapshot.getBlockType(x, y + 1, z); + final int y = Math.max((minY + 1), chunk.getHighestBlockYAt(x, z)) + 1; + final Material blockType = chunk.getBlockType(x, y - 1, z); + final Material bodyBlockType = chunk.getBlockType(x, y, z); + final Material headBlockType = chunk.getBlockType(x, y + 1, z); if (isBlockSafeForStanding(blockType.getKey().toString()) - && isBlockSafeForOccupation(bodyBlockType.getKey().toString()) - && isBlockSafeForOccupation(headBlockType.getKey().toString())) { - double locx = Math.floor(location.getX()) + dX; - if (locx < 0) { - locx += 1.5d; - } else { - locx = locx + 0.5d; - } - double locz = Math.floor(location.getZ()) + dZ; - if (locz < 0) { - locz += 1.5d; - } else { - locz = locz + 0.5d; - } - return Optional.of(Location.at( - locx, - y, - locz, - location.getWorld() - )); + && isBlockSafeForOccupation(bodyBlockType.getKey().toString()) + && isBlockSafeForOccupation(headBlockType.getKey().toString())) { + double locx = Math.floor(location.getX()) + dx; + if (locx < 0) { + locx += 1.5d; + } else { + locx = locx + 0.5d; + } + double locz = Math.floor(location.getZ()) + dz; + if (locz < 0) { + locz += 1.5d; + } else { + locz = locz + 0.5d; + } + return Optional.of(Location.at( + locx, + y, + locz, + location.getWorld() + )); } } } diff --git a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java index abfa63e4..d8fe5804 100644 --- a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java +++ b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java @@ -77,7 +77,7 @@ public class BukkitPluginTests { @DisplayName("Test Command Registration") public void testCommandRegistration() { 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()); } @@ -86,7 +86,7 @@ public class BukkitPluginTests { @DisplayName("Test Player Adapter") public void testPlayerAdaption() { 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")); final String simpleLocaleText = plugin.getLocales().getRawLocale("error_in_game_only") .orElseThrow(() -> new IllegalStateException("Failed to load raw locale")); - BukkitUser.adapt(player).sendMessage(simpleLocale); + BukkitUser.adapt(player, plugin).sendMessage(simpleLocale); player.assertSaid(simpleLocaleText); } @Test @DisplayName("Test Message Dispatching") public void testMessageDispatching() { - PlayerMock player = server.addPlayer(); + final BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin); final MineDown locale = plugin.getLocales() .getLocale("teleporting_action_bar_warmup", Integer.toString(3)) .orElseThrow(() -> new IllegalStateException("Failed to load locale")); - BukkitUser.adapt(player).sendActionBar(locale); - BukkitUser.adapt(player).sendMessage(locale); - BukkitUser.adapt(player).sendTitle(locale, false); - BukkitUser.adapt(player).sendTitle(locale, true); + user.sendActionBar(locale); + user.sendMessage(locale); + user.sendTitle(locale, false); + user.sendTitle(locale, true); } @Test @@ -135,11 +135,11 @@ public class BukkitPluginTests { @DisplayName("Test Locale Parsing") public void testLocaleParsing() { final Map rawLocales = plugin.getLocales().rawLocales; - BukkitUser bukkitUser = BukkitUser.adapt(server.addPlayer()); + BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin); rawLocales.forEach((key, value) -> { Optional locale = plugin.getLocales().getLocale(key); Assertions.assertTrue(locale.isPresent()); - bukkitUser.sendMessage(locale.get()); + user.sendMessage(locale.get()); }); } @@ -174,7 +174,7 @@ public class BukkitPluginTests { final PlayerMock player = server.addPlayer(); player.setOp(true); - final BukkitUser playerUser = BukkitUser.adapt(player); + final BukkitUser playerUser = BukkitUser.adapt(player, plugin); return commands.stream() .flatMap(command -> Stream.of(Arguments.of(command, playerUser, command.getName()))); } @@ -194,14 +194,18 @@ public class BukkitPluginTests { @DisplayName("Test Validator Accepts Valid Names") @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) { Assertions.assertTrue(plugin.getValidator().isValidName(name)); } @DisplayName("Test Validator Rejects Invalid Names") @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) { 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 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 and a very long" + - " description that is 255 characters long and should be accepted by the validator" + "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" }) public void testValidDescriptionIsValid(@NotNull String description) { Assertions.assertTrue(plugin.getValidator().isValidDescription(description)); @@ -221,10 +225,12 @@ public class BukkitPluginTests { @DisplayName("Test Validator Rejects Invalid Descriptions") @ParameterizedTest(name = "Invalid Description: \"{0}\"") - @ValueSource(strings = {"Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace and" + - "a very long description that is more than 256 characters long and should be rejected " + - "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."}) + @ValueSource(strings = { + "Lorem ipsum text with special characters •♣♠ and numbers 1234567890 and whitespace and" + + "a very long description that is more than 256 characters long and should be rejected " + + "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) { Assertions.assertFalse(plugin.getValidator().isValidDescription(description)); } @@ -241,7 +247,7 @@ public class BukkitPluginTests { @BeforeAll public static void setup() { - player = BukkitUser.adapt(server.addPlayer()); + player = BukkitUser.adapt(server.addPlayer(), plugin); } @DisplayName("Test Applying Cooldown") @@ -283,7 +289,14 @@ public class BukkitPluginTests { @DisplayName("Warp Tests") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class WarpTests { - private static final List WARP_NAMES = List.of("warple", "example", "exmaination", "123234__44", "a", "1"); + private static final List WARP_NAMES = List.of( + "warple", + "example", + "exmaination", + "123234__44", + "a", + "1" + ); @DisplayName("Test Warp Creation") @ParameterizedTest(name = "Warp Name: \"{0}\"") @@ -302,7 +315,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Rename: \"{0}\" > \"{0}2\"") @MethodSource("provideWarpData") @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"); plugin.getManager().warps().setWarpName(name, newName); Assertions.assertTrue(plugin.getDatabase().getWarp(newName).isPresent()); @@ -322,7 +336,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Edit Description: \"{0}\"") @MethodSource("provideWarpData") @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 + "."; plugin.getManager().warps().setWarpDescription(name, description); final Optional warpDescription = plugin.getDatabase().getWarp(name) @@ -338,8 +353,11 @@ public class BukkitPluginTests { @Order(4) public void testWarpRelocation(@NotNull String name, @NotNull Position position) { final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); - final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, - 0, 0, world, plugin.getServerName()); + final Position newPosition = Position.at( + position.getX() + 10, position.getY() + 10, position.getZ() + 10, + 0, 0, + world, plugin.getServerName() + ); plugin.getManager().warps().setWarpPosition(name, newPosition); final Optional warpPosition = plugin.getDatabase().getWarp(name).map(warp -> warp); @@ -355,8 +373,11 @@ public class BukkitPluginTests { @Order(5) public void testWarpOverwrite(@NotNull String name, @NotNull Position position) { final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); - final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, - 0, 0, world, plugin.getServerName()); + final Position newPosition = Position.at( + position.getX() + 10, position.getY() + 10, position.getZ() + 10, + 0, 0, + world, plugin.getServerName() + ); plugin.getManager().warps().createWarp(name, newPosition, true); final Optional warpPosition = plugin.getDatabase().getWarp(name).map(warp -> warp); @@ -370,7 +391,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Delete Warp: \"{0}\"") @MethodSource("provideWarpData") @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); Assertions.assertFalse(plugin.getDatabase().getWarp(name).isPresent()); Assertions.assertFalse(plugin.getManager().warps() @@ -385,7 +407,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Query: \"{0}\"") @MethodSource("provideWarpData") @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 Optional nameUpperWarp = plugin.getDatabase().getWarp(nameUpper, true); Assertions.assertTrue(nameUpperWarp.isPresent()); @@ -421,13 +444,21 @@ public class BukkitPluginTests { @DisplayName("Home Tests") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class HomeTests { - private static final List HOME_NAMES = List.of("mr_home", "homble", "seaside", "hovel", "tokyo-3", "testington", "h"); + private static final List HOME_NAMES = List.of( + "mr_home", + "homble", + "seaside", + "hovel", + "tokyo-3", + "testington", + "h" + ); private static BukkitUser homeOwner; @DisplayName("Ensure User Data") @BeforeAll public static void createHomeUser() { - homeOwner = BukkitUser.adapt(server.addPlayer("TestUser278")); + homeOwner = BukkitUser.adapt(server.addPlayer("TestUser278"), plugin); plugin.getDatabase().ensureUser(homeOwner); Assertions.assertTrue(plugin.getDatabase().getUserData(homeOwner.getUuid()).isPresent()); } @@ -449,7 +480,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Rename: \"{1}\" > \"{1}2\"") @MethodSource("provideHomeData") @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; plugin.getManager().homes().setHomeName(owner, name, newName); Assertions.assertTrue(plugin.getDatabase().getHome(owner, newName).isPresent()); @@ -476,7 +508,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Edit Description: \"{1}\"") @MethodSource("provideHomeData") @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 + "!"; plugin.getManager().homes().setHomeDescription(owner, name, description); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); @@ -494,8 +527,11 @@ public class BukkitPluginTests { @Order(4) public void testHomeRelocation(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) { final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); - final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, - 0, 0, world, plugin.getServerName()); + final Position newPosition = Position.at( + position.getX() + 10, position.getY() + 10, position.getZ() + 10, + 0, 0, + world, plugin.getServerName() + ); plugin.getManager().homes().setHomePosition(owner, name, newPosition); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); @@ -512,8 +548,11 @@ public class BukkitPluginTests { @Order(5) public void testHomeOverwrite(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) { final World world = BukkitAdapter.adaptWorld(server.getWorld("world")).orElseThrow(); - final Position newPosition = Position.at(position.getX() + 10, position.getY() + 10, position.getZ() + 10, - 0, 0, world, plugin.getServerName()); + final Position newPosition = Position.at( + position.getX() + 10, position.getY() + 10, position.getZ() + 10, + 0, 0, + world, plugin.getServerName() + ); plugin.getManager().homes().setHomePosition(owner, name, newPosition); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); @@ -528,7 +567,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Make Public: \"{1}\"") @MethodSource("provideHomeData") @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); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); @@ -542,7 +582,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Make Private: \"{1}\"") @MethodSource("provideHomeData") @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); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); @@ -558,7 +599,8 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Query: \"{1}\"") @MethodSource("provideHomeData") @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 Optional nameUpperWarp = plugin.getDatabase().getHome(owner, nameUpper, true); Assertions.assertTrue(nameUpperWarp.isPresent()); @@ -574,7 +616,7 @@ public class BukkitPluginTests { @ParameterizedTest(name = "Delete: \"{1}\"") @MethodSource("provideHomeData") @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); Assertions.assertFalse(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertFalse(plugin.getManager().homes().getUserHomes() @@ -603,4 +645,4 @@ public class BukkitPluginTests { } } -} \ No newline at end of file +} diff --git a/common/build.gradle b/common/build.gradle index b999af48..fabc5d46 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -25,7 +25,7 @@ dependencies { compileOnly 'com.mysql:mysql-connector-j:' + mysql_driver_version 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.BlueMap-Minecraft:BlueMapAPI:2.5.0' compileOnly 'us.dynmap:DynmapCoreAPI:3.4' diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index fe13db76..f6836b96 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -61,17 +61,25 @@ import java.util.stream.Collectors; 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 { + /** + * The spigot resource ID, used for update checking. + */ int SPIGOT_RESOURCE_ID = 83767; + /** + * Get the user representing the server console. + * + * @return the {@link ConsoleUser} + */ @NotNull 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 */ @@ -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 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} */ @@ -147,7 +155,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve void setSettings(@NotNull Settings settings); /** - * The plugin messages loaded from file + * The plugin messages loaded from file. * * @return The plugin {@link Locales} */ @@ -157,17 +165,29 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve 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 * @see #getSpawn() for the canonical spawn point to use */ Optional getServerSpawn(); + /** + * Update the local {@link Spawn} config file. + * + * @param spawn the new {@link Spawn} data + */ 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 */ @@ -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 */ @@ -193,7 +213,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve 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 */ @@ -201,7 +221,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve 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 */ @@ -209,7 +229,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve 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 */ @@ -217,7 +237,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve Manager getManager(); /** - * The {@link Broker} that sends cross-network messages + * The {@link Broker} that sends cross-network messages. * * @return the {@link Broker} implementation */ @@ -225,7 +245,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve Broker getMessenger(); /** - * The {@link RandomTeleportEngine} that manages random teleports + * The {@link RandomTeleportEngine} that manages random teleports. * * @return the {@link RandomTeleportEngine} implementation */ @@ -233,22 +253,14 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve 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 */ void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine); - /** - * Update the {@link Spawn} position to a location 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 + * Set of active {@link Hook}s running on the server. * * @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 * @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); /** - * 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 */ @@ -294,7 +306,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve 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 */ @@ -302,7 +314,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve List getWorlds(); /** - * Returns the plugin version + * Returns the plugin version. * * @return the plugin {@link Version} */ @@ -310,7 +322,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve Version getVersion(); /** - * Returns a list of enabled commands + * Returns a list of enabled commands. * * @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 */ @@ -407,8 +419,14 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve setSettings(Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get()); // Load locales from language preset default - final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + getSettings().getLanguage() + ".yml"))).get(); - setLocales(Annotaml.create(new File(getDataFolder(), "messages_" + getSettings().getLanguage() + ".yml"), languagePresets).get()); + final Locales languagePresets = Annotaml.create( + 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 if (getSettings().doCrossServer()) { @@ -448,26 +466,26 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve getUpdateChecker().check().thenAccept(checked -> { if (!checked.isUpToDate()) { 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 */ void registerMetrics(int metricsId); /** - * Initialize plugin messaging channels + * Initialize plugin messaging channels. */ void initializePluginChannels(); /** - * Log a message to the console + * Log a message to the console. * * @param level the level to log at * @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); /** - * 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 * @return the key diff --git a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index b5399b85..ff008edd 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -33,6 +33,7 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.TransactionResolver; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.time.Duration; @@ -59,8 +60,9 @@ public abstract class BaseHuskHomesAPI { protected final HuskHomes plugin; /** - * (Internal use only) - Constructor, instantiating the base API class + * (Internal use only) - Constructor, instantiating the base API class. */ + @ApiStatus.Internal protected BaseHuskHomesAPI(@NotNull HuskHomes 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 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 * @since 4.4 */ - public final CompletableFuture> getCooldown(@NotNull User user, @NotNull TransactionResolver.Action action) { + public final CompletableFuture> getCooldown(@NotNull User user, + @NotNull TransactionResolver.Action action) { 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 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 * @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)) { 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 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 * @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)); } /** - * 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 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 * @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 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 * @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 - *

- * The optional returned by this method will be empty unless HuskHomes is running cross-server mode + * Returns where the user last set their spawn point by right-clicking a bed or respawn anchor. + * + *

The optional returned by this method will be empty unless HuskHomes is running cross-server mode * and global respawning is enabled * * @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 - * 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 * @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 * @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} that will complete with a list of {@link Home}s set by the user that - * they have made public (where {@link Home#isPublic()}) + * @return A {@link CompletableFuture} with the user's public homes (where {@link Home#isPublic()}) * @since 3.0 */ public final CompletableFuture> 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 * @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 * @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 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 */ public final CompletableFuture> 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 - * @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> getHome(@NotNull UUID 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 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 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 * @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 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 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 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 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 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 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 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 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 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 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 name The name of the home * @param tagEditor The {@link Consumer} to edit the meta tags with * @since 4.0 */ - public final void editHomeMetaTags(@NotNull User owner, @NotNull String name, @NotNull Consumer> tagEditor) { + public final void editHomeMetaTags(@NotNull User owner, @NotNull String name, + @NotNull Consumer> tagEditor) { plugin.runAsync(() -> plugin.getDatabase().getHome(owner, name).ifPresent(home -> { final Map tags = home.getMeta().getTags(); 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 * @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 * @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 - * @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 */ public final CompletableFuture> 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 - * @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> getWarp(@NotNull UUID 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 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 */ @@ -538,7 +543,7 @@ public abstract class BaseHuskHomesAPI { } /** - * Delete a {@link Warp} + * Delete a {@link Warp}. * * @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 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 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 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 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 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 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 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 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 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 - * are enabled in the config, this may not return a position on this server. + * Get the canonical {@link Position} of the spawn point. + * + *

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 */ @@ -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 * @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 - *

- * This is irrelevant unless the server is using economy features with HuskHomes + * Get the number of homes an {@link OnlineUser} can set for free. + * + *

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 * @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 * @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 * @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 * @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 - * generated by the current {@link RandomTeleportEngine} + * generated by the current {@link RandomTeleportEngine}. * * @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 @@ -724,7 +731,8 @@ public abstract class BaseHuskHomesAPI { * @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine} * @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() .getRandomPosition(user.getPosition().getWorld(), rtpArgs) .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 - * generated by the current {@link RandomTeleportEngine} + * generated by the current {@link RandomTeleportEngine}. * * @param user The {@link OnlineUser} to teleport * @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 - * random teleports, including both {@code /rtp} command executions and API ({@link #randomlyTeleportPlayer(OnlineUser)}) - * calls. + * Set the {@link RandomTeleportEngine} to use for processing random teleports. + * + *

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 * @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 replacements Replacement strings to apply to the locale * @return The {@link MineDown}-formatted locale - * @apiNote Since v3.0.4, this method returns a `adventure.MineDown` object, targeting - * Adventure platforms, rather than a bungee components object. - * @since 3.0.4 + * @apiNote Since v3.0.4, this returns MineDown-Adventure components + * @since 3.0 */ public final Optional getLocale(@NotNull String localeKey, @NotNull String... 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 replacements Replacement strings to apply to the locale @@ -799,4 +807,23 @@ public abstract class BaseHuskHomesAPI { 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); + } + + } + + } diff --git a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java index c29fa099..4e74c3a6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java @@ -36,8 +36,8 @@ public class BackCommand extends InGameCommand { protected BackCommand(@NotNull HuskHomes plugin) { super("back", List.of(), "", plugin); addAdditionalPermissions(Map.of( - "death", false, - "previous", false + "death", false, + "previous", false )); } diff --git a/common/src/main/java/net/william278/huskhomes/command/Command.java b/common/src/main/java/net/william278/huskhomes/command/Command.java index 683df20e..07fe574c 100644 --- a/common/src/main/java/net/william278/huskhomes/command/Command.java +++ b/common/src/main/java/net/william278/huskhomes/command/Command.java @@ -32,7 +32,8 @@ public abstract class Command extends Node { private final String usage; private final Map additionalPermissions; - protected Command(@NotNull String name, @NotNull List aliases, @NotNull String usage, @NotNull HuskHomes plugin) { + protected Command(@NotNull String name, @NotNull List aliases, @NotNull String usage, + @NotNull HuskHomes plugin) { super(name, aliases, plugin); this.usage = usage; this.additionalPermissions = new HashMap<>(); @@ -70,8 +71,8 @@ public abstract class Command extends Node { return "/" + getName() + " " + getRawUsage(); } - public final void addAdditionalPermissions(@NotNull Map additionalPermissions) { - additionalPermissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value)); + public final void addAdditionalPermissions(@NotNull Map permissions) { + permissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value)); } @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java index 41f1bb3d..aaa24f81 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -44,7 +44,8 @@ public class DelHomeCommand extends SavedPositionCommand { @Override 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") .ifPresent(user::sendMessage); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java index 60235b39..3eb6e785 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -72,10 +72,12 @@ public class EditHomeCommand extends SavedPositionCommand { case "description" -> setHomeDescription(executor, home, ownerEditing, args); case "relocate" -> setHomePosition(executor, home, ownerEditing); 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 Optional optionalName = parseStringArg(args, 1); if (optionalName.isEmpty()) { @@ -106,7 +108,8 @@ public class EditHomeCommand extends SavedPositionCommand { }); } - 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 Optional optionalDescription = parseGreedyArguments(args); if (optionalDescription.isEmpty()) { @@ -127,7 +130,8 @@ public class EditHomeCommand extends SavedPositionCommand { } 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); } else { plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(), @@ -157,21 +161,24 @@ public class EditHomeCommand extends SavedPositionCommand { plugin.getLocales().getLocale("edit_home_update_location", home.getName()) .ifPresent(executor::sendMessage); } 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); } }); } - 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"))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); return; } - // Check against economy - if (executor instanceof OnlineUser user && !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) { + // Check against the economy hook + if (executor instanceof OnlineUser user + && !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) { return; } @@ -184,7 +191,8 @@ public class EditHomeCommand extends SavedPositionCommand { try { plugin.getManager().homes().setHomePrivacy(event.getHome(), home.isPublic()); } 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)); return; } @@ -208,7 +216,7 @@ public class EditHomeCommand extends SavedPositionCommand { } /** - * 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 otherViewer If the viewer of the editor is not the homeowner @@ -219,55 +227,61 @@ public class EditHomeCommand extends SavedPositionCommand { @NotNull private List getHomeEditorWindow(@NotNull Home home, boolean otherViewer, boolean showTeleportButton, boolean showPrivacyToggleButton) { - return new ArrayList<>() {{ - if (!otherViewer) { - plugin.getLocales().getLocale("edit_home_menu_title", home.getName()) - .ifPresent(this::add); - } else { - plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().getUsername(), home.getName()) - .ifPresent(this::add); - } + final List messages = new ArrayList<>(); + if (!otherViewer) { + plugin.getLocales().getLocale("edit_home_menu_title", home.getName()) + .ifPresent(messages::add); + } else { + plugin.getLocales().getLocale("edit_home_menu_title_other", + home.getOwner().getUsername(), home.getName()) + .ifPresent(messages::add); + } - plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic() ? "private" : "public"), - DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm") - .format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())), - home.getUuid().toString().split(Pattern.quote("-"))[0], - home.getUuid().toString()) - .ifPresent(this::add); + plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic() ? "private" : "public"), + DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm") + .format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())), + home.getUuid().toString().split(Pattern.quote("-"))[0], + home.getUuid().toString()) + .ifPresent(messages::add); - if (home.getMeta().getDescription().length() > 0) { - plugin.getLocales().getLocale("edit_home_menu_description", - plugin.getLocales().truncateText(home.getMeta().getDescription(), 50), - plugin.getLocales().wrapText(home.getMeta().getDescription(), 40)) - .ifPresent(this::add); - } + if (home.getMeta().getDescription().length() > 0) { + plugin.getLocales().getLocale("edit_home_menu_description", + plugin.getLocales().truncateText(home.getMeta().getDescription(), 50), + plugin.getLocales().wrapText(home.getMeta().getDescription(), 40)) + .ifPresent(messages::add); + } - if (!plugin.getSettings().doCrossServer()) { - plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName()) - .ifPresent(this::add); - } else { - plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer()) - .ifPresent(this::add); - } + if (!plugin.getSettings().doCrossServer()) { + plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName()) + .ifPresent(messages::add); + } else { + plugin.getLocales().getLocale("edit_home_menu_world_server", + home.getWorld().getName(), home.getServer()) + .ifPresent(messages::add); + } - plugin.getLocales().getLocale("edit_home_menu_coordinates", - String.format("%.1f", home.getX()), String.format("%.1f", home.getY()), String.format("%.1f", home.getZ()), - String.format("%.2f", home.getYaw()), String.format("%.2f", home.getPitch())) - .ifPresent(this::add); + plugin.getLocales().getLocale("edit_home_menu_coordinates", + String.format("%.1f", home.getX()), + String.format("%.1f", home.getY()), + String.format("%.1f", home.getZ()), + String.format("%.2f", home.getYaw()), + String.format("%.2f", home.getPitch())) + .ifPresent(messages::add); - if (showTeleportButton) { - plugin.getLocales().getLocale("edit_home_menu_use_buttons", home.getSafeIdentifier()) - .ifPresent(this::add); - } - plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", home.getSafeIdentifier(), - showPrivacyToggleButton ? plugin.getLocales() - .getRawLocale("edit_home_menu_privacy_button_" - + (home.isPublic() ? "private" : "public"), home.getSafeIdentifier()) - .orElse("") : "") - .map(MineDown::new).ifPresent(this::add); - plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", home.getSafeIdentifier()) - .ifPresent(this::add); - }}; + if (showTeleportButton) { + plugin.getLocales().getLocale("edit_home_menu_use_buttons", home.getSafeIdentifier()) + .ifPresent(messages::add); + } + plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", + home.getSafeIdentifier(), + showPrivacyToggleButton ? plugin.getLocales() + .getRawLocale("edit_home_menu_privacy_button_" + + (home.isPublic() ? "private" : "public"), home.getSafeIdentifier()) + .orElse("") : "") + .map(MineDown::new).ifPresent(messages::add); + plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", home.getSafeIdentifier()) + .ifPresent(messages::add); + return messages; } } diff --git a/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java index 7db0ee3c..c56c76a5 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java @@ -61,6 +61,7 @@ public class EditWarpCommand extends SavedPositionCommand { case "rename" -> setWarpName(executor, warp, args); case "description" -> setWarpDescription(executor, warp, args); case "relocate" -> setWarpPosition(executor, warp); + default -> throw new IllegalStateException("Unexpected value: " + operation.get().toLowerCase()); } } @@ -106,7 +107,8 @@ public class EditWarpCommand extends SavedPositionCommand { 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); }); } @@ -133,49 +135,54 @@ public class EditWarpCommand extends SavedPositionCommand { } /** - * 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 * @return List of {@link MineDown} messages to send to the editor that form the menu */ @NotNull private List getWarpEditorWindow(@NotNull Warp warp) { - return new ArrayList<>() {{ - plugin.getLocales().getLocale("edit_warp_menu_title", warp.getName()) - .ifPresent(this::add); + final List messages = new ArrayList<>(); + plugin.getLocales().getLocale("edit_warp_menu_title", warp.getName()) + .ifPresent(messages::add); - plugin.getLocales().getLocale("edit_warp_menu_metadata", - DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm") - .format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())), - warp.getUuid().toString().split(Pattern.quote("-"))[0], - warp.getUuid().toString()) - .ifPresent(this::add); + plugin.getLocales().getLocale("edit_warp_menu_metadata", + DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm") + .format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())), + warp.getUuid().toString().split(Pattern.quote("-"))[0], + warp.getUuid().toString()) + .ifPresent(messages::add); - if (warp.getMeta().getDescription().length() > 0) { - plugin.getLocales().getLocale("edit_warp_menu_description", - plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50), - plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40)) - .ifPresent(this::add); - } + if (warp.getMeta().getDescription().length() > 0) { + plugin.getLocales().getLocale("edit_warp_menu_description", + plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50), + plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40)) + .ifPresent(messages::add); + } - if (!plugin.getSettings().doCrossServer()) { - plugin.getLocales().getLocale("edit_warp_menu_world", warp.getWorld().getName()).ifPresent(this::add); - } else { - plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer()).ifPresent(this::add); - } + if (!plugin.getSettings().doCrossServer()) { + plugin.getLocales().getLocale("edit_warp_menu_world", + warp.getWorld().getName()).ifPresent(messages::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", - String.format("%.1f", warp.getX()), String.format("%.1f", warp.getY()), String.format("%.1f", warp.getZ()), - String.format("%.2f", warp.getYaw()), String.format("%.2f", warp.getPitch())) - .ifPresent(this::add); + plugin.getLocales().getLocale("edit_warp_menu_coordinates", + String.format("%.1f", warp.getX()), + String.format("%.1f", warp.getY()), + 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()) - .ifPresent(this::add); - plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getSafeIdentifier()) - .ifPresent(this::add); - plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getSafeIdentifier()) - .ifPresent(this::add); - }}; + plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getSafeIdentifier()) + .ifPresent(messages::add); + plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getSafeIdentifier()) + .ifPresent(messages::add); + plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getSafeIdentifier()) + .ifPresent(messages::add); + return messages; } } diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index 99ac1bc7..e5871ce5 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -100,12 +100,15 @@ public class HuskHomesCommand extends Command implements TabProvider { .getNearestValidPage(parseIntArg(args, 1).orElse(1))); case "reload" -> { 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; } - executor.sendMessage(new MineDown(""" - [HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a) - [ℹ 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)""" + executor.sendMessage(new MineDown( + "[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)" )); } case "update" -> updateChecker.check().thenAccept(checked -> { diff --git a/common/src/main/java/net/william278/huskhomes/command/ListCommand.java b/common/src/main/java/net/william278/huskhomes/command/ListCommand.java index 186c7bc4..71aba1db 100644 --- a/common/src/main/java/net/william278/huskhomes/command/ListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/ListCommand.java @@ -32,7 +32,8 @@ public abstract class ListCommand extends Command { protected final Map cachedLists; - protected ListCommand(@NotNull String name, @NotNull List aliases, @NotNull String usage, @NotNull HuskHomes plugin) { + protected ListCommand(@NotNull String name, @NotNull List aliases, @NotNull String usage, + @NotNull HuskHomes plugin) { super(name, aliases, usage, plugin); this.cachedLists = new HashMap<>(); } diff --git a/common/src/main/java/net/william278/huskhomes/command/Node.java b/common/src/main/java/net/william278/huskhomes/command/Node.java index 0606a1e5..1045e11b 100644 --- a/common/src/main/java/net/william278/huskhomes/command/Node.java +++ b/common/src/main/java/net/william278/huskhomes/command/Node.java @@ -156,23 +156,23 @@ public abstract class Node implements Executable { .orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName())); } - protected Optional parsePositionArgs(@NotNull Position basePosition, @NotNull String[] args, int startIndex) { + protected Optional parsePositionArgs(@NotNull Position basePosition, @NotNull String[] args, int from) { // Parse x, y, and z - final Optional x = parseCoordinateArg(args, startIndex, basePosition.getX()); - final Optional y = parseCoordinateArg(args, startIndex + 1, basePosition.getY()); - final Optional z = parseCoordinateArg(args, startIndex + 2, basePosition.getZ()); + final Optional x = parseCoordinateArg(args, from, basePosition.getX()); + final Optional y = parseCoordinateArg(args, from + 1, basePosition.getY()); + final Optional z = parseCoordinateArg(args, from + 2, basePosition.getZ()); if (x.isEmpty() || y.isEmpty() || z.isEmpty()) { return Optional.empty(); } // Parse world and server name - final Optional world = parseWorldArg(args, startIndex + 3); - final Optional server = parseStringArg(args, startIndex + 4); + final Optional world = parseWorldArg(args, from + 3); + final Optional server = parseStringArg(args, from + 4); // Parse yaw, pitch int angleStartIndex = (world.isEmpty() ? 3 : server.isEmpty() ? 4 : 5); - final Optional yaw = parseFloatArg(args, startIndex + angleStartIndex); - final Optional pitch = parseFloatArg(args, startIndex + angleStartIndex + 1); + final Optional yaw = parseFloatArg(args, from + angleStartIndex); + final Optional pitch = parseFloatArg(args, from + angleStartIndex + 1); return Optional.of(Position.at(x.get(), y.get(), z.get(), yaw.orElse(basePosition.getYaw()), pitch.orElse(basePosition.getPitch()), diff --git a/common/src/main/java/net/william278/huskhomes/command/PrivateHomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/PrivateHomeListCommand.java index 55364305..16043f80 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PrivateHomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PrivateHomeListCommand.java @@ -74,7 +74,7 @@ public class PrivateHomeListCommand extends ListCommand { } if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid()) - && !executor.hasPermission(getPermission("other"))) { + && !executor.hasPermission(getPermission("other"))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); return; @@ -93,7 +93,8 @@ public class PrivateHomeListCommand extends ListCommand { })); } - private Optional generateList(@NotNull CommandUser executor, @NotNull User user, @NotNull List homes) { + private Optional generateList(@NotNull CommandUser executor, @NotNull User user, + @NotNull List homes) { if (homes.isEmpty()) { if (!executor.equals(user)) { plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername()) @@ -109,7 +110,10 @@ public class PrivateHomeListCommand extends ListCommand { plugin.getLocales() .getRawLocale("home_list_item", 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()), plugin.getLocales() .getBaseList(plugin.getSettings().getListItemsPerPage()) diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java index 2aa94b8d..5a56b7f7 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -46,7 +46,7 @@ public class PublicHomeCommand extends HomeCommand implements TabProvider { @NotNull public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { if (args.length <= 2) { - return filter(plugin.getManager().homes().getPublicHomeNames(), args); + return filter(plugin.getManager().homes().getPublicHomeIdentifiers(), args); } return List.of(); } diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java index dc2e232a..12625dce 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java @@ -71,7 +71,10 @@ public class PublicHomeListCommand extends ListCommand { .getRawLocale("public_home_list_item", Locales.escapeText(home.getName()), home.getSafeIdentifier(), 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()), plugin.getLocales() .getBaseList(plugin.getSettings().getListItemsPerPage()) diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index 3da5f311..e28d09bc 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -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 executor The user executing the command * @param args The command arguments * @return The world to randomly teleport in, if successful */ - private Optional validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull String[] args) { + private Optional validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, + @NotNull String[] args) { // Check permissions if the user is being teleported by another player if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) { 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 executor The player executing the command diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index 35ef518a..98147b04 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -45,7 +45,7 @@ public abstract class SavedPositionCommand extends Comm protected SavedPositionCommand(@NotNull String name, @NotNull List aliases, @NotNull Class positionType, @NotNull List arguments, @NotNull HuskHomes plugin) { - super(name, aliases, "" + ((arguments.size() > 0) ? " [" + String.join("|", arguments) + "]" : ""), plugin); + super(name, aliases, "" + formatUsage(arguments), plugin); this.positionType = positionType; this.arguments = arguments; @@ -78,18 +78,18 @@ public abstract class SavedPositionCommand extends Comm private Optional resolveHome(@NotNull CommandUser executor, @NotNull String homeName) { if (homeName.contains(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); - if (ownerUsername.isBlank() || ownerHomeName.isBlank()) { + final String ownerHome = homeName.substring(homeName.indexOf(Home.IDENTIFIER_DELIMITER) + 1); + if (ownerUsername.isBlank() || ownerHome.isBlank()) { plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); return Optional.empty(); } final Optional optionalHome = plugin.getDatabase().getUserDataByName(ownerUsername) - .flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHomeName)); + .flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHome)); if (optionalHome.isEmpty()) { 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); return Optional.empty(); } @@ -97,7 +97,7 @@ public abstract class SavedPositionCommand extends Comm final Home home = optionalHome.get(); if (executor instanceof OnlineUser user && !home.isPublic() && !user.equals(home.getOwner()) && !user.hasPermission(getOtherPermission())) { - plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHomeName) + plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHome) .ifPresent(executor::sendMessage); return Optional.empty(); } @@ -138,7 +138,8 @@ public abstract class SavedPositionCommand extends Comm return Optional.empty(); } 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) .ifPresent(executor::sendMessage); return Optional.empty(); @@ -180,6 +181,11 @@ public abstract class SavedPositionCommand extends Comm } } + @NotNull + private static String formatUsage(List arguments) { + return ((arguments.size() > 0) ? " [" + String.join("|", arguments) + "]" : ""); + } + @Override @NotNull public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { @@ -188,14 +194,14 @@ public abstract class SavedPositionCommand extends Comm case 0, 1 -> { if (args.length == 1 && args[0].contains(Home.IDENTIFIER_DELIMITER)) { 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) { 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); default -> List.of(); diff --git a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java index 5d85c5c3..6a5b230e 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java @@ -41,8 +41,9 @@ public class SetSpawnCommand extends InGameCommand { if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalSpawn()) { final String warpName = plugin.getSettings().getGlobalSpawnName(); plugin.getManager().warps().createWarp(warpName, position, true); - plugin.getLocales().getRawLocale("spawn_warp_default_description") - .ifPresent(description -> plugin.getManager().warps().setWarpDescription(warpName, description)); + plugin.getLocales().getRawLocale("spawn_warp_default_description").ifPresent( + description -> plugin.getManager().warps().setWarpDescription(warpName, description) + ); } else { plugin.setServerSpawn(position); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java index a44da280..ceb9f611 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java @@ -59,8 +59,8 @@ public class SpawnCommand extends Command { this.teleportToSpawn(optionalTeleporter.get(), executor, spawn.get(), args); } - public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor, @NotNull Position spawn, - @NotNull String[] args) { + public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor, + @NotNull Position spawn, @NotNull String[] args) { if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); diff --git a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java index 6a4b76c8..35cf33fe 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -115,16 +115,16 @@ public class TpCommand extends Command implements TabProvider { @Override @NotNull public final List suggest(@NotNull CommandUser user, @NotNull String[] args) { - final Position basePosition = getBasePosition(user); + final Position relative = getBasePosition(user); final boolean serveCoordinateCompletions = user.hasPermission(getPermission("coordinates")); switch (args.length) { case 0, 1 -> { final ArrayList completions = new ArrayList<>(); completions.addAll(serveCoordinateCompletions ? List.of("~", "~ ~", "~ ~ ~", - Integer.toString((int) basePosition.getX()), - ((int) basePosition.getX() + " " + (int) basePosition.getY()), - ((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ())) + Integer.toString((int) relative.getX()), + ((int) relative.getX() + " " + (int) relative.getY()), + ((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ())) : List.of()); completions.addAll(plugin.getPlayerList(false)); return completions.stream() @@ -134,15 +134,17 @@ public class TpCommand extends Command implements TabProvider { case 2 -> { final ArrayList completions = new ArrayList<>(); if (isCoordinate(args, 0)) { - completions.addAll(List.of("~", Integer.toString((int) basePosition.getY()))); - completions.addAll(List.of("~ ~", (int) basePosition.getY() + " " + (int) basePosition.getZ())); + completions.addAll(List.of("~", Integer.toString((int) relative.getY()))); + completions.addAll(List.of("~ ~", (int) relative.getY() + " " + (int) relative.getZ())); } else { - completions.addAll(serveCoordinateCompletions - ? List.of("~", "~ ~", "~ ~ ~", - Integer.toString((int) basePosition.getX()), - ((int) basePosition.getX() + " " + (int) basePosition.getY()), - ((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ())) - : List.of()); + completions.addAll( + serveCoordinateCompletions + ? List.of("~", "~ ~", "~ ~ ~", + Integer.toString((int) relative.getX()), + ((int) relative.getX() + " " + (int) relative.getY()), + ((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ())) + : List.of() + ); completions.addAll(plugin.getPlayerList(false)); } return completions.stream() @@ -155,13 +157,13 @@ public class TpCommand extends Command implements TabProvider { if (!serveCoordinateCompletions) { 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)) { if (!serveCoordinateCompletions) { return completions; } - completions.addAll(List.of("~", Integer.toString((int) basePosition.getY()))); - completions.addAll(List.of("~ ~", (int) basePosition.getY() + " " + (int) basePosition.getZ())); + completions.addAll(List.of("~", Integer.toString((int) relative.getY()))); + completions.addAll(List.of("~ ~", (int) relative.getY() + " " + (int) relative.getZ())); } return completions.stream() .filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase())) @@ -173,7 +175,7 @@ public class TpCommand extends Command implements TabProvider { if (!serveCoordinateCompletions) { return completions; } - completions.addAll(List.of("~", Integer.toString((int) basePosition.getZ()))); + completions.addAll(List.of("~", Integer.toString((int) relative.getZ()))); } return completions.stream() .filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase())) diff --git a/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java index 8645953b..d43319e9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java @@ -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 - * acceptRequestCommand flag + * acceptRequestCommand flag. */ public class TpRespondCommand extends InGameCommand implements UserListTabProvider { private final 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; } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index 2ce4141b..acd8f017 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -48,7 +48,8 @@ public class WarpCommand extends SavedPositionCommand { @Override public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) { 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") .ifPresent(executor::sendMessage); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java index 21cd937e..3ee3b1ec 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java @@ -70,7 +70,10 @@ public class WarpListCommand extends ListCommand { plugin.getLocales() .getRawLocale("warp_list_item", 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()), plugin.getLocales() .getBaseList(plugin.getSettings().getListItemsPerPage()) diff --git a/common/src/main/java/net/william278/huskhomes/config/Locales.java b/common/src/main/java/net/william278/huskhomes/config/Locales.java index c3666594..1e1fe66e 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Locales.java +++ b/common/src/main/java/net/william278/huskhomes/config/Locales.java @@ -32,7 +32,7 @@ import java.util.Map; 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 = """ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ @@ -45,7 +45,7 @@ import java.util.Optional; public class Locales { /** - * The raw set of locales loaded from yaml + * The raw set of locales loaded from yaml. */ public Map 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 * @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 - *

- * Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements + * Returns a raw, unformatted locale loaded from the locale file, with replacements applied. + * + *

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 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 */ public Optional 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 * @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 - *

- * Note that replacements will be MineDown-escaped before application + * Returns a MineDown-formatted locale from the locale file, with replacements applied. + * + *

Note that replacements will be MineDown-escaped before application * * @param localeId String identifier of the locale, corresponding to a key in the file - * @param replacements Ordered array of replacement strings to fill in placeholders with - * @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists + * @param replacements An ordered array of replacement strings to fill in placeholders with + * @return An {@link Optional} with the replacement-applied, formatted locale corresponding to the id, if it exists */ public Optional getLocale(@NotNull String localeId, @NotNull String... replacements) { 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 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 */ @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 * @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 * @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 { CHAT, diff --git a/common/src/main/java/net/william278/huskhomes/config/Server.java b/common/src/main/java/net/william278/huskhomes/config/Server.java index 803ccb2c..4c1798c9 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Server.java +++ b/common/src/main/java/net/william278/huskhomes/config/Server.java @@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull; import java.nio.file.Path; /** - * Represents a server on a proxied network + * Represents a server on a proxied network. */ @YamlFile(header = """ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ @@ -39,7 +39,7 @@ import java.nio.file.Path; public class Server { /** - * Default server identifier + * Default server identifier. */ @NotNull public static String getDefaultServerName() { @@ -72,7 +72,7 @@ public class Server { } /** - * Proxy-defined name of this server + * Proxy-defined name of this server. */ @NotNull public String getName() { diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index c87426e8..a23452d2 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -55,7 +55,7 @@ public class Settings { private boolean checkForUpdates = true; // Database settings - @YamlComment("Type of database to use (MYSQL, SQLITE)") + @YamlComment("Type of database to use (SQLITE, MYSQL or MARIADB)") @YamlKey("database.type") private Database.Type databaseType = Database.Type.SQLITE; @@ -76,9 +76,13 @@ public class Settings { private String mySqlPassword = "pa55w0rd"; @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") 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!") @YamlKey("database.table_names") - private Map tableNames = Map.of( - 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() - ); + private Map tableNames = Database.Table.getConfigMap(); // General settings @@ -112,11 +108,13 @@ public class Settings { @YamlKey("general.max_homes") private int maxHomes = 10; - @YamlComment("The maximum public homes a user can create. Override with the huskhomes.max_public_homes. permission.") + @YamlComment("The maximum public homes a user can create. " + + "Override with the huskhomes.max_public_homes. permission.") @YamlKey("general.max_public_homes") private int maxPublicHomes = 10; - @YamlComment("Whether permission limits (i.e. huskhomes.max_homes.) should stack if the user inherits multiple nodes.") + @YamlComment("Whether permission limits (i.e. huskhomes.max_homes.)" + + "should stack if the user inherits multiple nodes.") @YamlKey("general.stack_permission_limits") private boolean stackPermissionLimits = false; @@ -124,7 +122,7 @@ public class Settings { @YamlKey("general.permission_restrict_warps") private boolean permissionRestrictWarps = false; - @YamlComment("Whether running /sethome or /setwarp when a home/warp already exists should overwrite it.") + @YamlComment("Whether running /sethome or /setwarp when a home/warp already exists should overwrite.") @YamlKey("general.overwrite_existing_homes_warps") private boolean overwriteExistingHomesWarps = true; @@ -160,7 +158,7 @@ public class Settings { @YamlKey("general.back_command_return_by_death") 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") private boolean backCommandSaveOnTeleportEvent = false; @@ -178,12 +176,7 @@ public class Settings { @YamlComment("Which sound effects to play for various actions") @YamlKey("general.sound_effects") - private Map soundEffects = Map.of( - 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 - ); + private Map soundEffects = SoundEffectAction.getConfigMap(); @YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)") @YamlKey("general.brigadier_tab_completion") @@ -199,7 +192,8 @@ public class Settings { @YamlKey("cross_server.messenger_type") 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") private String clusterId = ""; @@ -242,7 +236,7 @@ public class Settings { @YamlKey("rtp.distribution_mean") 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") private float rtpDistributionStandardDeviation = 2f; @@ -370,7 +364,7 @@ public class Settings { @NotNull 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() { @@ -563,7 +557,7 @@ public class Settings { return disabledCommands.stream().anyMatch(disabled -> { final String command = (disabled.startsWith("/") ? disabled.substring(1) : disabled); 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 { TELEPORTATION_COMPLETE("entity.enderman.teleport"), TELEPORTATION_WARMUP("block.note_block.banjo"), TELEPORTATION_CANCELLED("entity.item.break"), TELEPORT_REQUEST_RECEIVED("entity.experience_orb.pickup"); - private final String defaultSoundEffect; + private final String defaultEffect; - SoundEffectAction(@NotNull String defaultSoundEffect) { - this.defaultSoundEffect = defaultSoundEffect; + SoundEffectAction(@NotNull String defaultEffect) { + this.defaultEffect = defaultEffect; } + + @NotNull + public static Map getConfigMap() { + return Arrays.stream(values()) + .collect(Collectors.toMap( + SoundEffectAction::name, + action -> action.defaultEffect) + ); + } + } } diff --git a/common/src/main/java/net/william278/huskhomes/config/Spawn.java b/common/src/main/java/net/william278/huskhomes/config/Spawn.java index 48444254..734419c8 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Spawn.java +++ b/common/src/main/java/net/william278/huskhomes/config/Spawn.java @@ -29,7 +29,7 @@ import org.jetbrains.annotations.NotNull; import java.util.UUID; /** - * Used to store the server spawn location + * Used to store the server spawn location. */ @YamlFile(header = """ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ @@ -49,7 +49,7 @@ public class Spawn { 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 * @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 */ diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index ce22c9d6..f30f0738 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -30,6 +30,7 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.TransactionResolver; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -38,23 +39,20 @@ import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; /** * An abstract representation of the plugin database, storing home, warp and player data. - *

- * Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator. + * + *

Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator. */ public abstract class Database { 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 * @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 * @return the formatted statement, with table placeholders replaced with the correct names */ protected final String formatStatementTables(@NotNull String sql) { return sql - .replaceAll("%positions_table%", plugin.getSettings().getTableName(Table.POSITION_DATA)) - .replaceAll("%players_table%", plugin.getSettings().getTableName(Table.PLAYER_DATA)) - .replaceAll("%cooldowns_table%", plugin.getSettings().getTableName(Table.PLAYER_COOLDOWNS_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)); + .replaceAll("%positions_table%", plugin.getSettings() + .getTableName(Table.POSITION_DATA)) + .replaceAll("%players_table%", plugin.getSettings() + .getTableName(Table.PLAYER_DATA)) + .replaceAll("%cooldowns_table%", plugin.getSettings() + .getTableName(Table.PLAYER_COOLDOWNS_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 */ @@ -99,7 +104,7 @@ public abstract class Database { public abstract void initialize() throws IllegalStateException; /** - * (Internal use only) - Sets a position to the position table in the database + * (Internal use only) - Sets a position to the position table in the database. * * @param position The {@link Position} to set * @param connection SQL connection @@ -109,44 +114,50 @@ public abstract class Database { protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException; /** - * (Internal use only) - Updates position data + * (Internal use only) - Updates position data. * * @param positionId ID of the position to update * @param position the Position.at * @param connection SQL connection * @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; /** - * (Internal use only) - Sets a {@link SavedPosition} to the database + * (Internal use only) - Sets a {@link SavedPosition} to the database. * * @param position The {@link SavedPosition} to set * @param connection SQL connection * @return The newly inserted row ID * @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; /** - * (Internal use only) - Updates a saved position metadata + * (Internal use only) - Updates a saved position metadata. * * @param savedPositionId ID of the metadata to update * @param savedPosition the new saved position * @param connection SQL connection * @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 */ public abstract void ensureUser(@NotNull User user); /** - * Get {@link SavedUser} for a user by their Minecraft username (case-insensitive) + * Get {@link SavedUser} for a user by their Minecraft username (case-insensitive). * * @param name Username of the {@link SavedUser} to get (case-insensitive) * @return An optional with the {@link SavedUser} present if they exist @@ -154,7 +165,7 @@ public abstract class Database { public abstract Optional 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 * @return An optional with the {@link SavedUser} present if they exist @@ -162,23 +173,24 @@ public abstract class Database { public abstract Optional 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 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 user The {@link User} to set the cooldown for * @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 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); /** - * 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 * @return A future returning void when complete @@ -194,14 +206,14 @@ public abstract class Database { public abstract List 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 */ public abstract List getWarps(); /** - * Get a list of publicly-set {@link Warp}s on this {@link Server} + * Get a list of publicly-set {@link Warp}s on this {@link Server server}. * * @param plugin The plugin instance * @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 */ public abstract List getPublicHomes(); /** - * Get a list of publicly-set {@link Home}s on this {@link Server} + * Get a list of publicly-set {@link Home}s on this {@link Server server}. * * @param plugin The plugin instance * @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 homeName The name of the home to get * @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 getHome(@NotNull User user, @NotNull String homeName) { 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 homeName The name of the home to get @@ -256,7 +268,7 @@ public abstract class Database { public abstract Optional 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 * @return An optional with the {@link Home} present if it exists @@ -264,18 +276,18 @@ public abstract class Database { public abstract Optional 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 * @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 getWarp(@NotNull String warpName) { 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 caseInsensitive Whether the search should be case-insensitive @@ -284,7 +296,7 @@ public abstract class Database { public abstract Optional 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 * @return An optional with the {@link Warp} present if it exists @@ -292,7 +304,7 @@ public abstract class Database { public abstract Optional 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 * @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 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 */ 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. - * Pass as {@code null} to clear the player's current teleport.

+ * Pass as {@code null} to clear the player's current teleport * @param teleport The {@link Teleport} to set as their current cross-server 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 */ @@ -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 * @return An optional with the {@link Position} present if it has been set @@ -333,7 +345,7 @@ public abstract class Database { public abstract Optional 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 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); /** - * 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 * @return An optional with the {@link Position} present if it has been set @@ -349,7 +361,7 @@ public abstract class Database { public abstract Optional 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 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); /** - * 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 * @return An optional with the {@link Position} present if it has been set @@ -365,11 +377,11 @@ public abstract class Database { public abstract Optional 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 position The {@link Position} to set as their respawn position - * Pass as {@code null} to clear the player's current respawn position.

+ * Pass as {@code null} to clear the player's current respawn 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); /** - * 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 */ public abstract int deleteAllWarps(); /** - * Close any remaining connection to the database source + * Close any remaining connection to the database source. */ public abstract void terminate(); /** - * Identifies types of databases + * Identifies types of databases. */ public enum Type { MYSQL("MySQL"), + MARIADB("MariaDB"), SQLITE("SQLite"); 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 { PLAYER_DATA("huskhomes_users"), @@ -460,8 +473,18 @@ public abstract class Database { } @NotNull - public String getDefaultName() { + public String getName() { return defaultName; } + + @NotNull + public static Map getConfigMap() { + return Arrays.stream(values()) + .collect(Collectors.toMap( + Table::name, + action -> action.defaultName + )); + } + } } diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index 9a0be5ea..51bbbb82 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -38,7 +38,7 @@ import java.util.*; import java.util.logging.Level; /** - * A MySQL implementation of the plugin {@link Database} + * A MySQL implementation of the plugin {@link Database}. */ @SuppressWarnings("DuplicatedCode") 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 * @throws SQLException if the connection fails for some reason @@ -64,13 +64,15 @@ public class MySqlDatabase extends Database { public void initialize() throws IllegalStateException { // Initialize the Hikari pooled connection dataSource = new HikariDataSource(); - dataSource.setJdbcUrl("jdbc:mysql://" + - plugin.getSettings().getMySqlHost() + - ":" + - plugin.getSettings().getMySqlPort() + - "/" + - plugin.getSettings().getMySqlDatabase() + - plugin.getSettings().getMySqlConnectionParameters()); + dataSource.setJdbcUrl("jdbc:" + (plugin.getSettings().getDatabaseType() == Type.MARIADB ? "mariadb" : "mysql") + + "://" + + plugin.getSettings().getMySqlHost() + + ":" + + plugin.getSettings().getMySqlPort() + + "/" + + plugin.getSettings().getMySqlDatabase() + + plugin.getSettings().getMySqlConnectionParameters() + ); // Authenticate with the database dataSource.setUsername(plugin.getSettings().getMySqlUsername()); @@ -85,19 +87,24 @@ public class MySqlDatabase extends Database { dataSource.setPoolName(DATA_POOL_NAME); // Set additional connection pool properties - dataSource.setDataSourceProperties(new Properties() {{ - put("cachePrepStmts", "true"); - put("prepStmtCacheSize", "250"); - put("prepStmtCacheSqlLimit", "2048"); - put("useServerPrepStmts", "true"); - put("useLocalSessionState", "true"); - put("useLocalTransactionState", "true"); - put("rewriteBatchedStatements", "true"); - put("cacheResultSetMetadata", "true"); - put("cacheServerConfiguration", "true"); - put("elideSetAutoCommits", "true"); - put("maintainTimeStats", "false"); - }}); + final Properties properties = new Properties(); + properties.putAll( + Map.of("cachePrepStmts", "true", + "prepStmtCacheSize", "250", + "prepStmtCacheSqlLimit", "2048", + "useServerPrepStmts", "true", + "useLocalSessionState", "true", + "useLocalTransactionState", "true" + )); + properties.putAll( + Map.of( + "rewriteBatchedStatements", "true", + "cacheResultSetMetadata", "true", + "cacheServerConfiguration", "true", + "elideSetAutoCommits", "true", + "maintainTimeStats", "false") + ); + dataSource.setDataSourceProperties(properties); // Prepare database schema; make tables if they don't exist try (Connection connection = dataSource.getConnection()) { @@ -107,20 +114,22 @@ public class MySqlDatabase extends Database { statement.execute(tableCreationStatement); } } catch (SQLException e) { - throw new IllegalStateException("Failed to create database tables. Please ensure you are running MySQL v8.0+ " + - "and that your connecting user account has privileges to create tables.", e); + 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); } } catch (SQLException | IOException e) { - throw new IllegalStateException("Failed to establish a connection to the MySQL database. " + - "Please check the supplied database credentials in the config file", e); + throw new IllegalStateException("Failed to establish a connection to the MySQL database. " + + "Please check the supplied database credentials in the config file", e); } } @Override protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) - VALUES (?,?,?,?,?,?,?,?);"""), + INSERT INTO `%positions_table%` + (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) + VALUES + (?,?,?,?,?,?,?,?);"""), Statement.RETURN_GENERATED_KEYS)) { statement.setDouble(1, position.getX()); @@ -142,7 +151,8 @@ public class MySqlDatabase extends Database { } @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(""" UPDATE `%positions_table%` SET `x`=?, @@ -168,10 +178,13 @@ public class MySqlDatabase extends Database { } @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(""" - INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `tags`, `timestamp`) - VALUES (?,?,?,?,?);"""), + INSERT INTO `%saved_positions_table%` + (`position_id`, `name`, `description`, `tags`, `timestamp`) + VALUES + (?,?,?,?,?);"""), Statement.RETURN_GENERATED_KEYS)) { statement.setInt(1, setPosition(position, connection)); @@ -190,7 +203,8 @@ public class MySqlDatabase extends Database { } @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(""" SELECT `position_id` FROM `%saved_positions_table%` @@ -220,7 +234,8 @@ public class MySqlDatabase extends Database { @Override public void ensureUser(@NotNull User onlineUser) { - getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUserData -> { + getUserData(onlineUser.getUuid()).ifPresentOrElse( + existingUserData -> { if (!existingUserData.getUsername().equals(onlineUser.getUsername())) { // Update a player's name if it has changed in the database try (Connection connection = getConnection()) { @@ -233,7 +248,9 @@ public class MySqlDatabase extends Database { statement.setString(2, existingUserData.getUserUuid().toString()); 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) { 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 - 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 (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) @@ -368,11 +386,15 @@ public class MySqlDatabase extends Database { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { 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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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`=? ORDER BY `name`;"""))) { @@ -408,10 +430,13 @@ public class MySqlDatabase extends Database { final List warps = new ArrayList<>(); try (Connection connection = getConnection()) { 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%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%saved_positions_table%` + 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`;"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -442,14 +467,18 @@ public class MySqlDatabase extends Database { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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 ORDER BY `name`;"""))) { - final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { userHomes.add(Home.from(resultSet.getDouble("x"), @@ -480,11 +509,16 @@ public class MySqlDatabase extends Database { public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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`=? AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); @@ -521,11 +555,16 @@ public class MySqlDatabase extends Database { public Optional getHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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`=?;"""))) { statement.setString(1, uuid.toString()); @@ -559,10 +598,13 @@ public class MySqlDatabase extends Database { public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { try (Connection connection = getConnection()) { 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%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%saved_positions_table%` + 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`=?))"""))) { statement.setBoolean(1, caseInsensitive); statement.setString(2, warpName); @@ -595,10 +637,13 @@ public class MySqlDatabase extends Database { public Optional getWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { 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%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%saved_positions_table%` + 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=?;"""))) { statement.setString(1, uuid.toString()); @@ -675,7 +720,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } 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); } } diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 9c4adc45..67c16263 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -39,23 +39,23 @@ import java.util.*; import java.util.logging.Level; /** - * An SQLite implementation of the plugin {@link Database} + * An SQLite implementation of the plugin {@link Database}. */ @SuppressWarnings("DuplicatedCode") public class SqLiteDatabase extends Database { /** - * Path to the SQLite HuskHomesData.db file + * Path to the SQLite HuskHomesData.db file. */ 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"; /** - * The persistent SQLite database connection + * The persistent SQLite database connection. */ private Connection connection; @@ -91,7 +91,9 @@ public class SqLiteDatabase extends Database { config.setSynchronous(SQLiteConfig.SynchronousMode.FULL); // Establish the connection - connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties()); + connection = DriverManager.getConnection( + "jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties() + ); } catch (IOException e) { plugin.log(Level.SEVERE, "An exception occurred creating the database file", e); } catch (SQLException e) { @@ -123,8 +125,10 @@ public class SqLiteDatabase extends Database { @Override protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) - VALUES (?,?,?,?,?,?,?,?);"""), + INSERT INTO `%positions_table%` + (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) + VALUES + (?,?,?,?,?,?,?,?);"""), Statement.RETURN_GENERATED_KEYS)) { statement.setDouble(1, position.getX()); @@ -148,7 +152,8 @@ public class SqLiteDatabase extends Database { } @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(""" UPDATE `%positions_table%` SET `x`=?, @@ -174,10 +179,13 @@ public class SqLiteDatabase extends Database { } @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(""" - INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `tags`, `timestamp`) - VALUES (?,?,?,?,?);"""), + INSERT INTO `%saved_positions_table%` + (`position_id`, `name`, `description`, `tags`, `timestamp`) + VALUES + (?,?,?,?,?);"""), Statement.RETURN_GENERATED_KEYS)) { statement.setInt(1, setPosition(position, connection)); @@ -198,7 +206,8 @@ public class SqLiteDatabase extends Database { } @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(""" SELECT `position_id` FROM `%saved_positions_table%` @@ -228,7 +237,8 @@ public class SqLiteDatabase extends Database { @Override public void ensureUser(@NotNull User onlineUser) { - getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUser -> { + getUserData(onlineUser.getUuid()).ifPresentOrElse( + existingUser -> { if (!existingUser.getUsername().equals(onlineUser.getUsername())) { // Update a player's name if it has changed in the database try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" @@ -239,7 +249,9 @@ public class SqLiteDatabase extends Database { statement.setString(1, onlineUser.getUsername()); statement.setString(2, existingUser.getUserUuid().toString()); 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) { 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 - 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(""" INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) VALUES (?,?,?,?);"""))) { @@ -361,11 +374,15 @@ public class SqLiteDatabase extends Database { public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); 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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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`=? ORDER BY `name`;"""))) { statement.setString(1, user.getUuid().toString()); @@ -399,12 +416,14 @@ public class SqLiteDatabase extends Database { public List getWarps() { final List warps = new ArrayList<>(); 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%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%saved_positions_table%` + 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`;"""))) { - final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { warps.add(Warp.from(resultSet.getDouble("x"), @@ -431,14 +450,18 @@ public class SqLiteDatabase extends Database { public List getPublicHomes() { final List userHomes = new ArrayList<>(); 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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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 ORDER BY `name`;"""))) { - final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { userHomes.add(Home.from(resultSet.getDouble("x"), @@ -468,11 +491,16 @@ public class SqLiteDatabase extends Database { @Override public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { 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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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`=? AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); @@ -507,11 +535,16 @@ public class SqLiteDatabase extends Database { @Override public Optional getHome(@NotNull UUID uuid) { 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%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - 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` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + 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`=?;"""))) { statement.setString(1, uuid.toString()); @@ -543,10 +576,13 @@ public class SqLiteDatabase extends Database { @Override public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { 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%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%saved_positions_table%` + 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`=?))"""))) { statement.setBoolean(1, caseInsensitive); statement.setString(2, warpName); @@ -577,10 +613,13 @@ public class SqLiteDatabase extends Database { @Override public Optional getWarp(@NotNull UUID uuid) { 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%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%saved_positions_table%` + 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=?;"""))) { statement.setString(1, uuid.toString()); @@ -652,7 +691,7 @@ public class SqLiteDatabase extends Database { statement.setString(3, savedUser.getUserUuid().toString()); statement.executeUpdate(); } 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); } } diff --git a/common/src/main/java/net/william278/huskhomes/event/Cancellable.java b/common/src/main/java/net/william278/huskhomes/event/Cancellable.java index 59a279d0..3f7b7239 100644 --- a/common/src/main/java/net/william278/huskhomes/event/Cancellable.java +++ b/common/src/main/java/net/william278/huskhomes/event/Cancellable.java @@ -20,21 +20,21 @@ package net.william278.huskhomes.event; /** - * Base interface for a cancellable event + * Base interface for a cancellable 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 */ 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(); diff --git a/common/src/main/java/net/william278/huskhomes/event/Event.java b/common/src/main/java/net/william278/huskhomes/event/Event.java index 15da15b9..e6fc8cd6 100644 --- a/common/src/main/java/net/william278/huskhomes/event/Event.java +++ b/common/src/main/java/net/william278/huskhomes/event/Event.java @@ -20,7 +20,7 @@ package net.william278.huskhomes.event; /** - * Interface for an event fired by HuskHomes + * Interface for an event fired by HuskHomes. */ public interface Event { } diff --git a/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java b/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java index d437edb8..a27a36a8 100644 --- a/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java +++ b/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java @@ -36,12 +36,12 @@ import java.util.List; import java.util.function.Consumer; /** - * An abstract dispatcher of events + * An abstract dispatcher of events. */ 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 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 The type of event to fire * @return Whether the event was canceled */ + boolean fireIsCancelled(@NotNull T event); + @NotNull ITeleportEvent getTeleportEvent(@NotNull Teleport teleport); + @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration); + @NotNull 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); + @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter); + @NotNull IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator); + @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor); + @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter); - IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, boolean publicHomeList); + @NotNull + IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, + boolean publicHomeList); + @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer); + @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter); + @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter); @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java index ec8890d8..792218f4 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java @@ -24,18 +24,23 @@ import net.william278.huskhomes.user.User; 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 { /** - * 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 */ @NotNull User getHomeOwner(); + /** + * Get the user who is deleting the homes. + * + * @return the {@link CommandUser} who is deleting the homes + */ @NotNull CommandUser getDeleter(); diff --git a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java index ccfdcbda..4eec4d89 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java @@ -23,10 +23,15 @@ import net.william278.huskhomes.user.CommandUser; 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 { + /** + * Get the user who is deleting the warps. + * + * @return the {@link CommandUser} who is deleting the warps + */ @NotNull CommandUser getDeleter(); diff --git a/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java b/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java index 7b63df92..c775c727 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java @@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser; 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 { /** - * Get the home being deleted + * Get the home being deleted. * * @return the {@link Home} being deleted */ @NotNull Home getHome(); + /** + * Get the user who is deleting the home. + * + * @return the {@link CommandUser} who is deleting the home + */ @NotNull CommandUser getDeleter(); diff --git a/common/src/main/java/net/william278/huskhomes/event/IHomeEditEvent.java b/common/src/main/java/net/william278/huskhomes/event/IHomeEditEvent.java index ef676cdb..edd8043d 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeEditEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeEditEvent.java @@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser; 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 { /** - * Get the home about to be saved + * Get the home about to be saved. * * @return the {@link Home} being saved */ @NotNull Home getHome(); + /** + * Get the user who is editing the home. + * + * @return the {@link CommandUser} who is editing the home + */ @NotNull CommandUser getEditor(); diff --git a/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java b/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java index 9d7e00ec..e382e25c 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java @@ -26,22 +26,27 @@ import org.jetbrains.annotations.NotNull; 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 { /** - * Get the list of homes to be displayed + * Get the list of homes to be displayed. * * @return the list of homes */ @NotNull List getHomes(); + /** + * Set the list of homes to be displayed. + * + * @param homes the list of homes + */ void setHomes(@NotNull List homes); /** - * Get the player viewing the home list + * Get the player viewing the home list. * * @return the player viewing the home list */ @@ -49,7 +54,7 @@ public interface IHomeListEvent extends Cancellable { 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 */ diff --git a/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java b/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java index bf0f5316..d333dd1b 100644 --- a/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java @@ -23,12 +23,12 @@ import net.william278.huskhomes.teleport.Teleport; 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 { /** - * Get the teleport being carried out + * Get the teleport being carried out. * * @return the {@link Teleport} being carried out */ diff --git a/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java b/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java index 3ad3c8d6..ea0f61b0 100644 --- a/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java @@ -23,19 +23,19 @@ import net.william278.huskhomes.teleport.TimedTeleport; 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 { /** - * 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 */ int getWarmupDuration(); /** - * The {@link TimedTeleport} being processed + * The {@link TimedTeleport} being processed. * * @return the timed teleport that has started */ diff --git a/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java b/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java index 77142cef..42ca76d9 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java @@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser; 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 { /** - * Get the warp being deleted + * Get the warp being deleted. * * @return the {@link Warp} being deleted */ @NotNull Warp getWarp(); + /** + * Get the user who is deleting the warp. + * + * @return the {@link CommandUser} who is deleting the warp + */ @NotNull CommandUser getDeleter(); diff --git a/common/src/main/java/net/william278/huskhomes/event/IWarpEditEvent.java b/common/src/main/java/net/william278/huskhomes/event/IWarpEditEvent.java index fb3e741b..0e9538f2 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpEditEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpEditEvent.java @@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser; 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 { /** - * Get the warp being created or updated + * Get the warp being created or updated. * * @return the {@link Warp} being saved */ @NotNull Warp getWarp(); + /** + * Get the user who is editing the warp. + * + * @return the {@link CommandUser} who is editing the warp + */ @NotNull CommandUser getEditor(); diff --git a/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java b/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java index 50710f2d..d0822301 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java @@ -26,22 +26,27 @@ import org.jetbrains.annotations.NotNull; 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 { /** - * Get the list of warps to be displayed + * Get the list of warps to be displayed. * * @return the list of warps */ @NotNull List getWarps(); + /** + * Set the list of warps to be displayed. + * + * @param warps the list of warps + */ void setWarps(@NotNull List warps); /** - * Get the user viewing the warp list + * Get the user viewing the warp list. * * @return the user viewing the warp list */ diff --git a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java index 048eaac5..4f55eb62 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java @@ -44,7 +44,7 @@ import java.util.Map; import java.util.logging.Level; /** - * Hook to display warps and public homes on BlueMap maps + * Hook to display warps and public homes on BlueMap maps. */ public class BlueMapHook extends MapHook { @@ -63,15 +63,15 @@ public class BlueMapHook extends MapHook { for (World world : plugin.getWorlds()) { 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(); for (BlueMapMap map : mapWorld.getMaps()) { - map.getMarkerSets().put(getPublicHomesKey(), publicHomeMarkers); + map.getMarkerSets().put(getPublicHomesKey(), homeMarkers); map.getMarkerSets().put(getWarpsKey(), warpsMarkers); } - publicHomesMarkerSets.put(world.getName(), publicHomeMarkers); + publicHomesMarkerSets.put(world.getName(), homeMarkers); warpsMarkerSets.put(world.getName(), warpsMarkers); })); } diff --git a/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java b/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java index 3c6364e8..4851162e 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java @@ -34,7 +34,7 @@ import org.jetbrains.annotations.Nullable; 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 { @@ -171,8 +171,12 @@ public class DynmapHook extends MapHook { return getDynmap().map(api -> { publicHomesMarkers = api.getMarkerAPI().getMarkerSet(getPublicHomesKey()); if (publicHomesMarkers == null) { - publicHomesMarkers = api.getMarkerAPI().createMarkerSet(getPublicHomesKey(), getPublicHomesMarkerSetName(), - api.getMarkerAPI().getMarkerIcons(), false); + publicHomesMarkers = api.getMarkerAPI().createMarkerSet( + getPublicHomesKey(), + getPublicHomesMarkerSetName(), + api.getMarkerAPI().getMarkerIcons(), + false + ); } else { publicHomesMarkers.setMarkerSetLabel(getPublicHomesMarkerSetName()); } diff --git a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java index 1003dfaf..a6561b8f 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java @@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Locale; /** - * A hook that provides economy features + * A hook that provides economy features. */ 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 * @return the balance of the player @@ -45,7 +45,7 @@ public abstract class EconomyHook extends Hook { 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 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); /** - * Format a balance to a string + * Format a balance to a string. * * @param amount the amount to format * @return the formatted string @@ -61,14 +61,14 @@ public abstract class EconomyHook extends Hook { public abstract String formatCurrency(final double amount); /** - * Send the player a message notifying them that they have been charged - * for performing an action + * Send the player a message notifying them that they have been charged for performing an action. * * @param user the user to notify * @param plugin the plugin instance * @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) .flatMap(cost -> plugin.getLocales().getLocale( "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 - * for performing an action + * Send the player a message notifying them that they have been charged for performing an action. * * @param user the user to notify * @param plugin the plugin instance * @param action the action that was performed - * @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead, - * using the new {@link TransactionResolver.Action} enum + * @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead */ @Deprecated(since = "4.4", forRemoval = true) 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 */ @@ -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 * @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} */ diff --git a/common/src/main/java/net/william278/huskhomes/hook/Hook.java b/common/src/main/java/net/william278/huskhomes/hook/Hook.java index 298bc679..5ae68b88 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/Hook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/Hook.java @@ -23,22 +23,22 @@ import net.william278.huskhomes.HuskHomes; 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 { /** - * The plugin that this hook is for + * The plugin that this hook is for. */ protected final HuskHomes plugin; /** - * The name of the hook + * The name of the hook. */ protected final String name; /** - * Construct a new {@link Hook} + * Construct a new {@link Hook}. * * @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 public String getName() { return name; } - } diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java index 02fd2509..76f3ff88 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java @@ -32,7 +32,7 @@ import java.util.HashMap; 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 { @@ -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() { 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 */ 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 */ 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 */ 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 */ 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 */ public abstract void removeWarp(@NotNull Warp warp); /** - * Clears all warps from the map + * Clears all warps from the map. */ 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 * @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 { @NotNull @@ -158,7 +158,8 @@ public abstract class MapHook extends Hook { } @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()) .thumbnail(thumbnail) .field("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60)) @@ -167,7 +168,8 @@ public abstract class MapHook extends Hook { } @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()) .thumbnail(thumbnail) .field("Owner", home.getOwner().getUsername()) diff --git a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java index 76c104ed..ca764c30 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java @@ -37,7 +37,7 @@ import java.util.UUID; 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 { @@ -66,12 +66,8 @@ public class PlanHook extends Hook { private void registerDataExtension() { try { ExtensionService.getInstance().register(new PlanDataExtension(plugin.getDatabase())); - } catch (IllegalStateException planIsNotEnabled) { - plugin.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled); - // 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 + } catch (IllegalStateException | IllegalArgumentException e) { + plugin.log(Level.SEVERE, "Failed to register HuskHomes Plan extension", e); } } diff --git a/common/src/main/java/net/william278/huskhomes/importer/Importer.java b/common/src/main/java/net/william278/huskhomes/importer/Importer.java index 29fc2b0c..98d17059 100644 --- a/common/src/main/java/net/william278/huskhomes/importer/Importer.java +++ b/common/src/main/java/net/william278/huskhomes/importer/Importer.java @@ -71,7 +71,8 @@ public abstract class Importer extends Hook { 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; if (user instanceof OnlineUser online) { 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 { USERS("User Data"), diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 0f216074..b9dac6ec 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -38,7 +38,7 @@ import java.util.Optional; import java.util.logging.Level; /** - * A handler for when events take place + * A handler for when events take place. */ 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} */ @@ -64,7 +64,9 @@ public class EventListener { this.handleInboundTeleport(onlineUser); // 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 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} */ @@ -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 */ @@ -135,7 +137,10 @@ public class EventListener { } try { - teleporter.teleportLocally((Position) teleport.getTarget(), plugin.getSettings().doAsynchronousTeleports()); + teleporter.teleportLocally( + (Position) teleport.getTarget(), + plugin.getSettings().doAsynchronousTeleports() + ); } catch (TeleportationException e) { 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 */ @@ -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 */ @@ -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} */ @@ -228,7 +233,7 @@ public class EventListener { // Display the return by death via /back notification final boolean canReturnByDeath = plugin.getCommand(BackCommand.class) .map(command -> onlineUser.hasPermission(command.getPermission()) - && onlineUser.hasPermission(command.getPermission("death"))) + && onlineUser.hasPermission(command.getPermission("death"))) .orElse(false); if (plugin.getSettings().doBackCommandReturnByDeath() && canReturnByDeath) { 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 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 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() { plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion()); } -} \ No newline at end of file +} diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index 6a5feabf..e42392a9 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -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 public Map> getUserHomes() { @@ -62,15 +64,20 @@ public class HomesManager { HashMap::putAll); } + /** + * Get a list of all cached set home identifiers. + * + * @return a list of all cached set home identifiers + */ @NotNull - public List getUserHomeNames() { + public List getUserHomeIdentifiers() { return userHomes.entrySet().stream() .flatMap(e -> e.getValue().stream().map(Home::getIdentifier)) .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 public Map> getPublicHomes() { @@ -79,17 +86,33 @@ public class HomesManager { HashMap::putAll); } + /** + * Get a list of all cached public home identifiers. + * + * @return a list of all cached public home identifiers + */ @NotNull - public List getPublicHomeNames() { + public List getPublicHomeIdentifiers() { return publicHomes.stream() .map(Home::getIdentifier) .toList(); } + /** + * Cache user homes for a given user. + * + * @param user the user to cache homes for + */ public void cacheUserHomes(@NotNull User 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) { userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> { 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). + * + *

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) { if (plugin.getSettings().doCrossServer()) { plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() @@ -196,7 +226,8 @@ public class HomesManager { 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); } @@ -226,7 +257,8 @@ public class HomesManager { 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 optionalHome = plugin.getDatabase().getHome(owner, name); if (optionalHome.isEmpty()) { throw new ValidationException(ValidationException.Type.NOT_FOUND); @@ -241,7 +273,8 @@ public class HomesManager { 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 optionalHome = plugin.getDatabase().getHome(owner, name); if (optionalHome.isEmpty()) { throw new ValidationException(ValidationException.Type.NOT_FOUND); @@ -260,7 +293,8 @@ public class HomesManager { 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 optionalHome = plugin.getDatabase().getHome(owner, name); if (optionalHome.isEmpty()) { throw new ValidationException(ValidationException.Type.NOT_FOUND); @@ -303,7 +337,8 @@ public class HomesManager { this.cacheHome(home, true); } - public void setHomeMetaTags(@NotNull User owner, @NotNull String name, @NotNull Map tags) throws ValidationException { + public void setHomeMetaTags(@NotNull User owner, @NotNull String name, + @NotNull Map tags) throws ValidationException { final Optional optionalHome = plugin.getDatabase().getHome(owner, name); if (optionalHome.isEmpty()) { throw new ValidationException(ValidationException.Type.NOT_FOUND); diff --git a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index 2280a6e5..f687121d 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -38,7 +38,7 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** - * Manages {@link TeleportRequest}s between players + * Manages {@link TeleportRequest}s between players. */ 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 * @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 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 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 * @return the last received request, if present @@ -200,7 +200,7 @@ public class RequestsManager { plugin.fireEvent(plugin.getReceiveTeleportRequestEvent(recipient, request), (event -> { addTeleportRequest(request, recipient); plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere") - + "_request_received", request.getRequesterName()) + + "_request_received", request.getRequesterName()) .ifPresent(recipient::sendMessage); plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName()) .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 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 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 recipient The recipient of the request * @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 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 request The {@link TeleportRequest} to handle diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java index 6a987601..b62c7e0f 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -94,7 +94,7 @@ public class WarpsManager { } /** - * Cached warp names + * Cached warp names. */ @NotNull public List getWarps() { @@ -112,7 +112,8 @@ public class WarpsManager { .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 existingWarp = plugin.getDatabase().getWarp(name); if (existingWarp.isPresent() && !overwrite) { throw new ValidationException(ValidationException.Type.NAME_TAKEN); diff --git a/common/src/main/java/net/william278/huskhomes/network/Broker.java b/common/src/main/java/net/william278/huskhomes/network/Broker.java index 16b0d2a1..6d2da6a1 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Broker.java +++ b/common/src/main/java/net/william278/huskhomes/network/Broker.java @@ -35,7 +35,7 @@ public abstract class Broker { protected final HuskHomes plugin; /** - * Create a new broker + * Create a new broker. * * @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 */ protected void handle(@NotNull OnlineUser receiver, @NotNull Message message) { @@ -117,18 +117,19 @@ public abstract class Broker { plugin.getManager().homes().updatePublicHomeCache(); 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 */ 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 sender the sender of the message @@ -136,7 +137,7 @@ public abstract class Broker { 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 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); /** - * Terminate the broker + * Terminate the broker. */ 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 { PLUGIN_MESSAGE("Plugin Messages"), diff --git a/common/src/main/java/net/william278/huskhomes/network/Message.java b/common/src/main/java/net/william278/huskhomes/network/Message.java index 7629303c..285599c9 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Message.java +++ b/common/src/main/java/net/william278/huskhomes/network/Message.java @@ -33,7 +33,7 @@ import java.util.UUID; public class Message { /** - * Message target indicating all players + * Message target indicating all players. */ 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 { 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 { TELEPORT_TO_POSITION, diff --git a/common/src/main/java/net/william278/huskhomes/network/Payload.java b/common/src/main/java/net/william278/huskhomes/network/Payload.java index 17d3dad0..21807785 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Payload.java +++ b/common/src/main/java/net/william278/huskhomes/network/Payload.java @@ -30,7 +30,7 @@ import java.util.List; 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 { @@ -53,7 +53,7 @@ public class Payload { private List stringList; /** - * Returns an empty cross-server message payload + * Returns an empty cross-server message 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 * @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 * @return a payload containing the teleport request @@ -89,7 +89,7 @@ public class Payload { } /** - * A string field + * A string field. */ @NotNull public static Payload withString(@NotNull String target) { @@ -99,7 +99,7 @@ public class Payload { } /** - * A string list field + * A string list field. */ @NotNull public static Payload withStringList(@NotNull List target) { @@ -112,7 +112,7 @@ public class Payload { } /** - * A position field + * A position field. */ public Optional getPosition() { return Optional.ofNullable(position); @@ -120,21 +120,21 @@ public class Payload { /** - * A teleport request field + * A teleport request field. */ public Optional getTeleportRequest() { return Optional.ofNullable(teleportRequest); } /** - * A string field + * A string field. */ public Optional getString() { return Optional.ofNullable(string); } /** - * A string list field + * A string list field. */ public Optional> getStringList() { return Optional.ofNullable(stringList); diff --git a/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java b/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java index 79349574..94d2c735 100644 --- a/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java +++ b/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java @@ -31,18 +31,15 @@ import java.util.logging.Level; /** * Plugin Messaging channel message - * broker implementation + * broker implementation. */ public class PluginMessageBroker extends Broker { /** * The name of BungeeCord's provided plugin channel. * - * @implNote Technically, the effective identifier of this channel is {@code bungeecord:main}, but Spigot remaps - * {@code BungeeCord} automatically to the new one (source). - * Spigot's official documentation - * 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. + *

Internally, this is {@code bungeecord:main}, + * but Spigot remaps {@code BungeeCord} automatically to the new one (hence BungeeCord is kept for back-compat). */ public static final String BUNGEE_CHANNEL_ID = "BungeeCord"; @@ -55,7 +52,6 @@ public class PluginMessageBroker extends Broker { plugin.initializePluginChannels(); } - @SuppressWarnings("UnstableApiUsage") public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) { if (!channel.equals(BUNGEE_CHANNEL_ID)) { return; @@ -79,7 +75,6 @@ public class PluginMessageBroker extends Broker { } @Override - @SuppressWarnings("UnstableApiUsage") protected void send(@NotNull Message message, @NotNull OnlineUser sender) { final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput(); messageWriter.writeUTF(message.getScope().getPluginMessageChannel()); @@ -102,7 +97,6 @@ public class PluginMessageBroker extends Broker { } @Override - @SuppressWarnings("UnstableApiUsage") public void changeServer(@NotNull OnlineUser user, @NotNull String server) { final ByteArrayDataOutput outputStream = ByteStreams.newDataOutput(); @@ -115,4 +109,5 @@ public class PluginMessageBroker extends Broker { @Override public void close() { } -} \ No newline at end of file + +} diff --git a/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java b/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java index 55407401..d335069e 100644 --- a/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java +++ b/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java @@ -30,7 +30,7 @@ import redis.clients.jedis.JedisPubSub; import java.util.logging.Level; /** - * Redis PubSub broker implementation + * Redis PubSub broker implementation. */ public class RedisBroker extends PluginMessageBroker { private JedisPool jedisPool; @@ -78,13 +78,13 @@ public class RedisBroker extends PluginMessageBroker { if (message.getScope() == Message.Scope.PLAYER) { plugin.getOnlineUsers().stream() .filter(online -> message.getTarget().equals(Message.TARGET_ALL) - || online.getUsername().equals(message.getTarget())) + || online.getUsername().equals(message.getTarget())) .forEach(receiver -> handle(receiver, message)); return; } if (message.getTarget().equals(plugin.getServerName()) - || message.getTarget().equals(Message.TARGET_ALL)) { + || message.getTarget().equals(Message.TARGET_ALL)) { plugin.getOnlineUsers().stream() .findAny() .ifPresent(receiver -> handle(receiver, message)); diff --git a/common/src/main/java/net/william278/huskhomes/position/Home.java b/common/src/main/java/net/william278/huskhomes/position/Home.java index cb8a47be..fc7dc6ba 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Home.java +++ b/common/src/main/java/net/william278/huskhomes/position/Home.java @@ -25,10 +25,13 @@ import org.jetbrains.annotations.NotNull; 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 { + /** + * The delimiter used to separate the owner's name from the home name in the home identifier. + */ public static final String IDENTIFIER_DELIMITER = "."; private final User owner; private boolean isPublic; @@ -46,19 +49,47 @@ public class Home extends SavedPosition { 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 - public static Home from(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server, - @NotNull PositionMeta positionMeta, @NotNull UUID uuid, @NotNull User owner, boolean isPublic) { + public static Home from(double x, double y, double z, float yaw, float pitch, @NotNull World world, + @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); } + /** + * 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 public static Home from(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User 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 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() { 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. + * + *

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 @Override public String getSafeIdentifier() { return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getSafeIdentifier(); } + /** + * Get the canonical home identifier string. + * + *

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 @Override public String getIdentifier() { diff --git a/common/src/main/java/net/william278/huskhomes/position/Location.java b/common/src/main/java/net/william278/huskhomes/position/Location.java index 3f54a390..37bf06f4 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Location.java +++ b/common/src/main/java/net/william278/huskhomes/position/Location.java @@ -23,9 +23,10 @@ import com.google.gson.annotations.Expose; import org.jetbrains.annotations.NotNull; /** - * Represents a local position on this server + * Represents a local position on this server. */ public class Location { + @Expose private double x; @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 */ @@ -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() { 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() { 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() { 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() { 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() { 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() { return world; @@ -140,4 +141,5 @@ public class Location { public void setWorld(World world) { this.world = world; } + } diff --git a/common/src/main/java/net/william278/huskhomes/position/Position.java b/common/src/main/java/net/william278/huskhomes/position/Position.java index e143cd86..288a5d19 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Position.java +++ b/common/src/main/java/net/william278/huskhomes/position/Position.java @@ -24,20 +24,22 @@ import net.william278.huskhomes.teleport.Target; 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 { @Expose 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); this.setServer(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); } @@ -46,12 +48,14 @@ public class Position extends Location implements Target { } @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); } @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); } @@ -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 public String getServer() { @@ -80,10 +84,10 @@ public class Position extends Location implements Target { @Override public String toString() { - return "x: " + (int) getX() + ", " + - "y: " + (int) getY() + ", " + - "z: " + (int) getZ() + " " + - "(" + getWorld().getName() + " / " + getServer() + ")"; + return "x: " + (int) getX() + ", " + + "y: " + (int) getY() + ", " + + "z: " + (int) getZ() + " " + + "(" + getWorld().getName() + " / " + getServer() + ")"; } } diff --git a/common/src/main/java/net/william278/huskhomes/position/PositionMeta.java b/common/src/main/java/net/william278/huskhomes/position/PositionMeta.java index 47363b2b..9100081c 100644 --- a/common/src/main/java/net/william278/huskhomes/position/PositionMeta.java +++ b/common/src/main/java/net/william278/huskhomes/position/PositionMeta.java @@ -29,7 +29,7 @@ import java.util.HashMap; 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 { @@ -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 * @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 */ @@ -96,7 +96,7 @@ public class PositionMeta { } /** - * The name of a position + * The name of a position. */ public String getName() { return name; @@ -107,7 +107,7 @@ public class PositionMeta { } /** - * A description of a position + * A description of a position. */ @NotNull 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 getTags() { return tags; @@ -130,7 +130,7 @@ public class PositionMeta { } /** - * The time the position was created + * The time the position was created. */ @NotNull public Instant getCreationTime() { diff --git a/common/src/main/java/net/william278/huskhomes/position/SavedPosition.java b/common/src/main/java/net/william278/huskhomes/position/SavedPosition.java index 19bd6d12..ad81e549 100644 --- a/common/src/main/java/net/william278/huskhomes/position/SavedPosition.java +++ b/common/src/main/java/net/william278/huskhomes/position/SavedPosition.java @@ -25,7 +25,7 @@ import org.jetbrains.annotations.NotNull; import java.util.UUID; /** - * Represents a persistently-saved {@link Position} + * Represents a persistently-saved {@link Position}. */ public abstract class SavedPosition extends Position implements Comparable { @@ -40,7 +40,7 @@ public abstract class SavedPosition extends Position implements Comparable - * Will return {@link Environment#OVERWORLD} if the environment is null + * or {@link Environment#CUSTOM}). + * + *

Will return {@link Environment#OVERWORLD} if the environment is null */ @NotNull 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 { OVERWORLD, diff --git a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java index 748be706..00f99b4c 100644 --- a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java @@ -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 * @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() { return (float) (Math.random() * 360); diff --git a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java index f7299754..37988614 100644 --- a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java @@ -28,7 +28,7 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; /** - * Represents an engine for generating random position targets + * Represents an engine for generating random position targets. */ public abstract class RandomTeleportEngine { @@ -37,7 +37,7 @@ public abstract class RandomTeleportEngine { public long maxAttempts = 12; /** - * Constructor for a random teleport engine + * Constructor for a random teleport engine. * * @param plugin The HuskHomes plugin instance * @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. + * + *

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 * @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 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 - * the configured number of attempts + * the configured number of attempts. * * @param world The world to find a random position in * @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 - * {@link #maxAttempts configured number of attempts} + * @return An Optional position, if one could be found in the {@link #maxAttempts max attempts} */ - public abstract CompletableFuture> getRandomPosition(@NotNull World world, @NotNull String[] args); + public abstract CompletableFuture> getRandomPosition(@NotNull World world, + @NotNull String[] args); } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Target.java b/common/src/main/java/net/william278/huskhomes/teleport/Target.java index 9cd7a031..06494970 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Target.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Target.java @@ -27,7 +27,7 @@ import org.jetbrains.annotations.NotNull; public interface Target { /** - * Create a {@link Target} from a player name + * Create a {@link Target} from a player name. * * @param target the player name * @return the target diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java index 333b46d0..eecb6e76 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -52,8 +52,8 @@ public class Teleport { protected final boolean updateLastPosition; protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target, - @NotNull Type type, boolean updateLastPosition, @NotNull List actions, - @NotNull HuskHomes plugin) { + @NotNull Type type, boolean updateLastPosition, + @NotNull List actions, @NotNull HuskHomes plugin) { this.plugin = plugin; this.executor = executor; this.teleporter = teleporter; @@ -62,10 +62,8 @@ public class Teleport { this.actions = actions; this.async = plugin.getSettings().doAsynchronousTeleports(); this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class) - .map(command -> - executor.hasPermission(command.getPermission()) && - executor.hasPermission(command.getPermission("previous")) - ) + .map(command -> executor.hasPermission(command.getPermission()) + && executor.hasPermission(command.getPermission("previous"))) .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 { TELEPORT(0), diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java index 68f445fe..9d05b1db 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java @@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull; 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 { @@ -50,7 +50,7 @@ public class TeleportRequest { private String recipientName; /** - * Create a teleport request + * Create a teleport 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 */ @@ -76,7 +76,7 @@ public class TeleportRequest { } /** - * The name of the request recipient + * The name of the request recipient. */ @NotNull public String getRecipientName() { @@ -88,7 +88,7 @@ public class TeleportRequest { } /** - * The user making the request + * The user making the request. */ @NotNull 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 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 public TeleportRequest.Type getType() { @@ -124,8 +124,7 @@ public class TeleportRequest { } /** - * The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} - * or {@link Status#DECLINED} + * The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} or {@link Status#DECLINED}. */ @NotNull 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 { /** - * The request is a {@code /tpa} request, where the requester is requesting to teleport to the recipient + * The request is a {@code /tpa} request, where the requester is requesting to teleport to the recipient. */ TPA, /** - * The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport to them + * The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport + * to them. */ TPA_HERE } /** - * The current status of a teleport request + * The current status of a teleport request. */ 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, /** - * 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, /** - * The recipient has declined the teleport request + * The recipient has declined the teleport request. */ DECLINED, /** * 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 } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java index 08ac95c9..e299221c 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java @@ -24,14 +24,14 @@ import org.jetbrains.annotations.NotNull; /** * Represents a teleporter; the person performing the teleport. - *

- * Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference + * + *

Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference * that needs to be resolved first. */ public interface Teleportable { /** - * Create a {@link Teleportable} from a player name + * Create a {@link Teleportable} from a player name. * * @param teleporter the player name * @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 */ diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java index 9d29e566..8ab4f1cb 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java @@ -54,6 +54,9 @@ public class TeleportationException extends IllegalStateException { case WORLD_NOT_FOUND -> plugin.getLocales() .getLocale("error_invalid_world") .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 { TELEPORTER_NOT_FOUND, diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index bd0c201b..292db107 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -119,9 +119,9 @@ public class TimedTeleport extends Teleport implements Runnable { } /** - * Ticks a timed teleport, decrementing the time left until the teleport is complete - *

- * A timed teleport will be canceled if certain criteria are met: + * Ticks a timed teleport, decrementing the time left until the teleport is complete. + * + *

A timed teleport will be canceled if certain criteria are met: *

    *
  • The player has left the server
  • *
  • The plugin is disabling
  • @@ -169,9 +169,9 @@ public class TimedTeleport extends Teleport implements Runnable { private boolean hasTeleporterMoved() { final double maxMovementDistance = 0.1d; - double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) + - Math.abs(startLocation.getY() - teleporter.getPosition().getY()) + - Math.abs(startLocation.getZ() - teleporter.getPosition().getZ()); + double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) + + Math.abs(startLocation.getY() - teleporter.getPosition().getY()) + + Math.abs(startLocation.getZ() - teleporter.getPosition().getZ()); return movementDistance > maxMovementDistance; } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Username.java b/common/src/main/java/net/william278/huskhomes/teleport/Username.java index 7f9308f2..95aad351 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Username.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Username.java @@ -36,14 +36,15 @@ public record Username(@NotNull String name) implements Teleportable, Target { /** * Search for a local {@link OnlineUser} by their name. * + *

    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. + * + *

    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} * @return An {@link Optional} containing the {@link OnlineUser} if 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. - *

    - * 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 public Optional 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 */ diff --git a/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java b/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java index e58aec7b..c6733979 100644 --- a/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java @@ -38,7 +38,7 @@ import org.jetbrains.annotations.NotNull; 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 { @@ -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} */ 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, - * otherwise an {@link Optional#empty()} + * @return the player's current respawn {@link Position} if it has been set, or {@link Optional#empty()} */ public abstract Optional getBedSpawnPosition(); /** - * Returns the health of this player + * Returns the health of this player. * * @return the player's health points */ 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 * @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); /** - * 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 */ @@ -85,7 +84,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs public abstract Map 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 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 */ @@ -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 */ @@ -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 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. + * + *

    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 - * @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") - @NotNull String translationKey) { + @NotNull String 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 * @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") - @NotNull String soundEffect) throws IllegalArgumentException { + @NotNull String soundEffect) throws IllegalArgumentException { try { getAudience().playSound( 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 */ @@ -176,16 +176,16 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs 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 asynchronous if the teleport should be asynchronous + * @param location the {@link Location} to teleport the player to + * @param async if the teleport should be asynchronous * @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 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); /** - * 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 */ 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 */ 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 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 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 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 * @return a list of numbers from the prefixed permission nodes, sorted by size diff --git a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java index 264ee0db..1e7909d1 100644 --- a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java @@ -27,7 +27,7 @@ import java.time.temporal.ChronoUnit; import java.util.UUID; /** - * Represents data about a player on the server + * Represents data about a player on the server. */ public class SavedUser { @@ -36,7 +36,7 @@ public class SavedUser { private boolean ignoringTeleports; /** - * Create a new SavedUser object + * Create a new SavedUser object. * * @param user The user to create the object for * @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 - *

    - * User RTP cooldowns are no longer stored in {@link SavedUser} objects, + * Create a new SavedUser object. + * + *

    Please note that User RTP cooldowns are no longer stored in {@link SavedUser} objects; * 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) + @SuppressWarnings("unused") public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) { 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 */ @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(since = "4.4", forRemoval = true) + @SuppressWarnings("unused") public void setRtpCooldown(@NotNull Instant rtpCooldown) { // Do nothing } diff --git a/common/src/main/java/net/william278/huskhomes/user/User.java b/common/src/main/java/net/william278/huskhomes/user/User.java index 75f30d54..42e9257b 100644 --- a/common/src/main/java/net/william278/huskhomes/user/User.java +++ b/common/src/main/java/net/william278/huskhomes/user/User.java @@ -24,7 +24,7 @@ import org.jetbrains.annotations.NotNull; 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 { @@ -35,7 +35,7 @@ public class User { 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 username Username of the player diff --git a/common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java b/common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java index 01b5cfec..d12a0642 100644 --- a/common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java +++ b/common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java @@ -31,16 +31,15 @@ public interface SafetyResolver { 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 - * @return a {@link CompletableFuture} that will complete with an optional of the safe ground position, if it is - * possible to find one + * @return a {@link CompletableFuture} with an optional safe ground position, if one could be found */ CompletableFuture> 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}) * @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}) - * @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) { return !getPlugin().getUnsafeBlocks().isUnsafeToOccupy(blockId); diff --git a/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java b/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java index 145bc514..02b7d5b9 100644 --- a/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java +++ b/common/src/main/java/net/william278/huskhomes/util/TransactionResolver.java @@ -30,15 +30,15 @@ import java.util.Optional; 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 { /** * 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. - *

    - * This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise + * + *

    This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise * {@code false}. * * @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 private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) { 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(hook -> { 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); 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 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) { getEconomyHook().ifPresent(hook -> 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)) .ifPresent(cost -> { hook.changePlayerBalance(player, -cost); hook.notifyDeducted(player, getPlugin(), action); @@ -131,16 +134,9 @@ public interface TransactionResolver { } /** - * @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()); - } - - /** - * @deprecated use {@link #performTransaction(OnlineUser, Action)} instead + * Execute an economy transaction if needed, updating the player's balance. + * + * @deprecated use {@link #performTransaction(OnlineUser, Action)} instead. */ @SuppressWarnings("removal") @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 */ @@ -162,7 +170,7 @@ public interface TransactionResolver { HuskHomes getPlugin(); /** - * Represents actions that can be the subject of a transaction + * Represents actions that can be the subject of a transaction. */ 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 */ @@ -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 */ diff --git a/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java b/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java index 2bbef5dd..eecffb53 100644 --- a/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java +++ b/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java @@ -39,6 +39,28 @@ public class UnsafeBlocks { @YamlKey("safe_occupation_blocks") public List 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) { if (!blockId.startsWith(Key.MINECRAFT_NAMESPACE + ":")) { blockId = Key.MINECRAFT_NAMESPACE + ":" + blockId; @@ -46,28 +68,6 @@ public class UnsafeBlocks { 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") public UnsafeBlocks() { } diff --git a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java index 006b8dac..9b889257 100644 --- a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java +++ b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java @@ -33,7 +33,8 @@ public class ValidationException extends IllegalArgumentException { 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) { case NOT_FOUND -> plugin.getLocales() .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) .ifPresent(viewer::sendMessage); 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))) .ifPresent(viewer::sendMessage); 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))) .ifPresent(viewer::sendMessage); + default -> { + // Do nothing (silently handle validation errors) + } } } @@ -72,6 +78,9 @@ public class ValidationException extends IllegalArgumentException { case DESCRIPTION_INVALID -> plugin.getLocales() .getLocale("error_warp_description_characters", args) .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 { NOT_FOUND, diff --git a/common/src/main/java/net/william278/huskhomes/util/Validator.java b/common/src/main/java/net/william278/huskhomes/util/Validator.java index 97a6be41..367625f8 100644 --- a/common/src/main/java/net/william278/huskhomes/util/Validator.java +++ b/common/src/main/java/net/william278/huskhomes/util/Validator.java @@ -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 * @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 * @return Whether the meta is valid against the plugin settings diff --git a/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java b/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java index aa307a57..9fb5adc0 100644 --- a/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java +++ b/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java @@ -37,7 +37,7 @@ import java.util.stream.Stream; @DisplayName("Message Serialization Tests") public class MessageSerializationTests { - private final static List TEST_MESSAGES = List.of( + private static final List TEST_MESSAGES = List.of( Message.builder() .type(Message.Type.REQUEST_PLAYER_LIST) .target("TestTarget") @@ -77,15 +77,27 @@ public class MessageSerializationTests { final Gson gson = createGson(); final String serializedMessage = gson.toJson(message); Assertions.assertNotNull(serializedMessage); - final Message deserializedMessage = gson.fromJson(serializedMessage, Message.class); - Assertions.assertNotNull(deserializedMessage); - Assertions.assertEquals(message.getType(), deserializedMessage.getType()); - Assertions.assertEquals(message.getScope(), deserializedMessage.getScope()); - Assertions.assertEquals(message.getTarget(), deserializedMessage.getTarget()); - Assertions.assertEquals(message.getPayload().getPosition().isPresent(), deserializedMessage.getPayload().getPosition().isPresent()); - Assertions.assertEquals(message.getPayload().getString().isPresent(), deserializedMessage.getPayload().getString().isPresent()); - Assertions.assertEquals(message.getPayload().getStringList().isPresent(), deserializedMessage.getPayload().getStringList().isPresent()); - Assertions.assertEquals(message.getPayload().getStringList().isPresent(), deserializedMessage.getPayload().getStringList().isPresent()); + final Message deserialized = gson.fromJson(serializedMessage, Message.class); + Assertions.assertNotNull(deserialized); + Assertions.assertEquals(message.getType(), deserialized.getType()); + Assertions.assertEquals(message.getScope(), deserialized.getScope()); + Assertions.assertEquals(message.getTarget(), deserialized.getTarget()); + Assertions.assertEquals( + message.getPayload().getPosition().isPresent(), + deserialized.getPayload().getPosition().isPresent() + ); + Assertions.assertEquals( + message.getPayload().getString().isPresent(), + deserialized.getPayload().getString().isPresent() + ); + Assertions.assertEquals( + message.getPayload().getStringList().isPresent(), + deserialized.getPayload().getStringList().isPresent()) + ; + Assertions.assertEquals( + message.getPayload().getStringList().isPresent(), + deserialized.getPayload().getStringList().isPresent() + ); } @NotNull @@ -97,4 +109,4 @@ public class MessageSerializationTests { return TEST_MESSAGES.stream().map(message -> Arguments.of(message, message.getType().name())); } -} \ No newline at end of file +} diff --git a/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java b/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java index a3f874fa..4582ecbc 100644 --- a/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java +++ b/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java @@ -49,7 +49,8 @@ public class SavedPositionTests { @DisplayName("Test Home Identifiers") @ParameterizedTest(name = "Home: \"{1}\" (Unsafe: {2})") @MethodSource("provideHomeData") - public void testHomeIdentifiers(@NotNull Home home, @NotNull @SuppressWarnings("unused") String name, boolean isUnsafeName) { + @SuppressWarnings("unused") + public void testHomeIdentifiers(@NotNull Home home, @NotNull String name, boolean isUnsafeName) { Assertions.assertEquals( home.getIdentifier(), home.getOwner().getUsername() + Home.IDENTIFIER_DELIMITER + home.getName() @@ -65,7 +66,8 @@ public class SavedPositionTests { @DisplayName("Test Warp Identifiers") @ParameterizedTest(name = "Warp: \"{1}\" (Unsafe: {2})") @MethodSource("provideWarpData") - public void testWarpIdentifiers(@NotNull Warp warp, @NotNull @SuppressWarnings("unused") String name, boolean isUnsafeName) { + @SuppressWarnings("unused") + public void testWarpIdentifiers(@NotNull Warp warp, @NotNull String name, boolean isUnsafeName) { Assertions.assertEquals( warp.getIdentifier(), warp.getName() diff --git a/common/src/test/java/net/william278/huskhomes/random/NormalDistributionTests.java b/common/src/test/java/net/william278/huskhomes/random/NormalDistributionTests.java index 115edf8b..570ce8ad 100644 --- a/common/src/test/java/net/william278/huskhomes/random/NormalDistributionTests.java +++ b/common/src/test/java/net/william278/huskhomes/random/NormalDistributionTests.java @@ -36,10 +36,10 @@ import java.util.UUID; @DisplayName("Normal Distribution Tests") public class NormalDistributionTests { - private final static float MEAN = 0.75f; - private final static float STANDARD_DEVIATION = 2f; - private final static float SPAWN_RADIUS = 500f; - private final static float MAX_RADIUS = 3000f; + private static final float MEAN = 0.75f; + private static final float STANDARD_DEVIATION = 2f; + private static final float SPAWN_RADIUS = 500f; + private static final float MAX_RADIUS = 3000f; @Test @DisplayName("Test Point Generation") @@ -59,14 +59,14 @@ public class NormalDistributionTests { } /** - * Plots location distribution to an image for testing + * Plots location distribution to an image for testing. */ public static class DistributionModeller { /** - * Plot a demo of the normal distribution algorithm + * Plot a demo of the normal distribution algorithm. * - * @param args file path to save image to + * @param args path to save image to */ @SuppressWarnings("unused") public static void main(String[] args) { @@ -95,7 +95,7 @@ public class NormalDistributionTests { plot.save(output.getAbsolutePath(), "png"); } catch (IOException e) { - e.printStackTrace(); + throw new RuntimeException(e); } } diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 00000000..b706511f --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,361 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/fabric/fabric-1.19.2/build.gradle b/fabric/fabric-1.19.2/build.gradle new file mode 100644 index 00000000..fb3e016e --- /dev/null +++ b/fabric/fabric-1.19.2/build.gradle @@ -0,0 +1,83 @@ +import org.apache.tools.ant.filters.ReplaceTokens + +plugins { + id 'fabric-loom' version "$fabric_loom_version" +} + +apply plugin: 'fabric-loom' +loom.serverOnlyMinecraftJar() + +// Get properties from local gradle.properties file +def properties = new Properties() +file("gradle.properties").withInputStream { properties.load(it) } + + +dependencies { + minecraft "com.mojang:minecraft:${fabric_minecraft_version}" + mappings "net.fabricmc:yarn:${fabric_yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}" + + // Fabric API modules + Set fabricApiModules = [ + 'fabric-api-base', + 'fabric-lifecycle-events-v1', + 'fabric-entity-events-v1', + 'fabric-command-api-v2', + 'fabric-networking-api-v1' + ] + fabricApiModules.forEach { + modImplementation(fabricApi.module(it, fabric_api_version)) + } + modImplementation include("net.kyori:adventure-platform-fabric:${adventure_platform_fabric_version}") + modImplementation include('me.lucko:fabric-permissions-api:0.2-SNAPSHOT') + + implementation include('redis.clients:jedis:' + jedis_version) + implementation include('com.mysql:mysql-connector-j:' + mysql_driver_version) + implementation include('org.xerial:sqlite-jdbc:' + sqlite_driver_version) + + compileOnly 'org.jetbrains:annotations:24.0.1' + + shadow project(path: ":common") +} + +shadowJar { + configurations = [project.configurations.shadow] + destinationDirectory.set(file("$projectDir/build/libs")) + + exclude('net.fabricmc:.*') + exclude('net.kyori:.*') + exclude '/mappings/*' + + relocate 'org.apache.commons.io', 'net.william278.huskhomes.libraries.commons.io' + relocate 'org.apache.commons.text', 'net.william278.huskhomes.libraries.commons.text' + relocate 'org.apache.commons.lang3', 'net.william278.huskhomes.libraries.commons.lang3' + relocate 'de.themoep', 'net.william278.huskhomes.libraries' + relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' + relocate 'org.intellij', 'net.william278.huskhomes.libraries' + relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' + relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml' + relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' + relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' + relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml' + relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' + relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' +} + +processResources { + filesMatching(['**/*.json', '**/*.yml']) { + filter ReplaceTokens as Class, beginToken: '${', endToken: '}', + tokens: properties + } +} + +remapJar { + dependsOn tasks.shadowJar + mustRunAfter tasks.shadowJar + inputFile = shadowJar.archiveFile.get() + addNestedDependencies = true + + destinationDirectory.set(file("$rootDir/target/")) + archiveClassifier.set('') +} + +shadowJar.finalizedBy(remapJar) \ No newline at end of file diff --git a/fabric/fabric-1.19.2/gradle.properties b/fabric/fabric-1.19.2/gradle.properties new file mode 100644 index 00000000..3eb8e059 --- /dev/null +++ b/fabric/fabric-1.19.2/gradle.properties @@ -0,0 +1,6 @@ +fabric_minecraft_version=1.19.2 +fabric_loader_version=0.14.17 +fabric_yarn_mappings=1.19.2+build.28 +fabric_api_version=0.76.0+1.19.2 + +adventure_platform_fabric_version=5.5.2 \ No newline at end of file diff --git a/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/FabricHuskHomes.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/FabricHuskHomes.java new file mode 100644 index 00000000..3aca2d0f --- /dev/null +++ b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/FabricHuskHomes.java @@ -0,0 +1,489 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes; + +import io.netty.buffer.ByteBufUtil; +import net.fabricmc.api.DedicatedServerModInitializer; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.kyori.adventure.platform.fabric.FabricServerAudiences; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerPlayNetworkHandler; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.william278.annotaml.Annotaml; +import net.william278.desertwell.util.Version; +import net.william278.huskhomes.command.Command; +import net.william278.huskhomes.command.FabricCommand; +import net.william278.huskhomes.config.Locales; +import net.william278.huskhomes.config.Server; +import net.william278.huskhomes.config.Settings; +import net.william278.huskhomes.config.Spawn; +import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.MySqlDatabase; +import net.william278.huskhomes.database.SqLiteDatabase; +import net.william278.huskhomes.event.FabricEventDispatcher; +import net.william278.huskhomes.hook.Hook; +import net.william278.huskhomes.listener.EventListener; +import net.william278.huskhomes.listener.FabricEventListener; +import net.william278.huskhomes.manager.Manager; +import net.william278.huskhomes.network.Broker; +import net.william278.huskhomes.network.PluginMessageBroker; +import net.william278.huskhomes.network.RedisBroker; +import net.william278.huskhomes.position.Location; +import net.william278.huskhomes.position.World; +import net.william278.huskhomes.random.NormalDistributionEngine; +import net.william278.huskhomes.random.RandomTeleportEngine; +import net.william278.huskhomes.user.ConsoleUser; +import net.william278.huskhomes.user.FabricUser; +import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.SavedUser; +import net.william278.huskhomes.util.FabricSafetyResolver; +import net.william278.huskhomes.util.FabricTask; +import net.william278.huskhomes.util.UnsafeBlocks; +import net.william278.huskhomes.util.Validator; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier, + FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler { + + public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes"); + private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes") + .orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); + + private MinecraftServer minecraftServer; + private Map permissions; + private Set savedUsers; + private Settings settings; + private Locales locales; + private Database database; + private Validator validator; + private Manager manager; + private EventListener eventListener; + private RandomTeleportEngine randomTeleportEngine; + private Spawn serverSpawn; + private UnsafeBlocks unsafeBlocks; + private List hooks; + private List commands; + private ConcurrentHashMap> globalPlayerList; + private Set currentlyOnWarmup; + private Server server; + @Nullable + private Broker broker; + private FabricServerAudiences audiences; + + @Override + public void onInitializeServer() { + // Get plugin version from mod container + this.permissions = new HashMap<>(); + this.savedUsers = new HashSet<>(); + this.globalPlayerList = new ConcurrentHashMap<>(); + this.currentlyOnWarmup = new HashSet<>(); + this.validator = new Validator(this); + + // Load settings and locales + initialize("plugin config & locale files", (plugin) -> { + if (!loadConfigs()) { + throw new IllegalStateException("Failed to load config files. Please check the console for errors"); + } + }); + + // Pre-register commands + initialize("commands", (plugin) -> this.commands = registerCommands()); + + ServerLifecycleEvents.SERVER_STARTING.register(server -> { + this.minecraftServer = server; + this.onEnable(); + }); + ServerLifecycleEvents.SERVER_STOPPING.register(server -> this.onDisable()); + } + + private void onEnable() { + // Create adventure audience + this.audiences = FabricServerAudiences.of(minecraftServer); + + // Initialize the database + initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { + this.database = switch (getSettings().getDatabaseType()) { + case MYSQL, MARIADB -> new MySqlDatabase(this); + case SQLITE -> new SqLiteDatabase(this); + }; + + database.initialize(); + }); + + // Initialize the manager + this.manager = new Manager(this); + + // Initialize the network messenger if proxy mode is enabled + if (getSettings().doCrossServer()) { + initialize(settings.getBrokerType().getDisplayName() + " message broker", (plugin) -> { + broker = switch (settings.getBrokerType()) { + case PLUGIN_MESSAGE -> new PluginMessageBroker(this); + case REDIS -> new RedisBroker(this); + }; + broker.initialize(); + }); + } + + setRandomTeleportEngine(new NormalDistributionEngine(this)); + + // Register plugin hooks (Economy, Maps, Plan) + initialize("hooks", (plugin) -> { + this.registerHooks(); + + if (hooks.size() > 0) { + hooks.forEach(hook -> { + try { + hook.initialize(); + } catch (Throwable e) { + log(Level.WARNING, "Failed to initialize " + hook.getName() + " hook", e); + } + }); + log(Level.INFO, "Registered " + hooks.size() + " mod hooks: " + hooks.stream() + .map(Hook::getName) + .collect(Collectors.joining(", "))); + } + }); + + // Register events + initialize("events", (plugin) -> this.eventListener = new FabricEventListener(this)); + + this.checkForUpdates(); + } + + private void onDisable() { + if (this.eventListener != null) { + this.eventListener.handlePluginDisable(); + } + if (database != null) { + database.terminate(); + } + if (broker != null) { + broker.close(); + } + if (audiences != null) { + audiences.close(); + audiences = null; + } + cancelTasks(); + } + + @Override + @NotNull + public ConsoleUser getConsole() { + return new ConsoleUser(audiences.console()); + } + + @Override + @NotNull + public List getOnlineUsers() { + return minecraftServer.getPlayerManager().getPlayerList() + .stream().map(user -> (OnlineUser) FabricUser.adapt(user, this)) + .toList(); + } + + @Override + @NotNull + public Set getSavedUsers() { + return savedUsers; + } + + @Override + @NotNull + public Settings getSettings() { + return settings; + } + + @Override + public void setSettings(@NotNull Settings settings) { + this.settings = settings; + } + + @Override + @NotNull + public Locales getLocales() { + return locales; + } + + @Override + public void setLocales(@NotNull Locales locales) { + this.locales = locales; + } + + @Override + public Optional getServerSpawn() { + return Optional.ofNullable(serverSpawn); + } + + @Override + public void setServerSpawn(@NotNull Spawn spawn) { + this.serverSpawn = spawn; + } + + @Override + public void setServerSpawn(@NotNull Location location) { + try { + // Create or update the spawn.yml file + final File spawnFile = new File(getDataFolder(), "spawn.yml"); + if (spawnFile.exists() && !spawnFile.delete()) { + log(Level.WARNING, "Failed to delete the existing spawn.yml file"); + } + this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get(); + + // Update the world spawn location, too + minecraftServer.getWorlds().forEach(world -> { + if (world.getRegistryKey().getValue().asString().equals(location.getWorld().getName())) { + world.setSpawnPos(new BlockPos(location.getX(), location.getY(), location.getZ()), 0); + } + }); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + log(Level.WARNING, "Failed to save the server spawn.yml file", e); + } + } + + @Override + @NotNull + public String getServerName() { + return server.getName(); + } + + @Override + public void setServer(@NotNull Server server) { + this.server = server; + } + + @Override + public void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks) { + this.unsafeBlocks = unsafeBlocks; + } + + @NotNull + @Override + public UnsafeBlocks getUnsafeBlocks() { + return unsafeBlocks; + } + + @Override + @NotNull + public Database getDatabase() { + return database; + } + + @Override + @NotNull + public Validator getValidator() { + return validator; + } + + @Override + @NotNull + public Manager getManager() { + return manager; + } + + @Override + @NotNull + public Broker getMessenger() { + if (broker == null) { + throw new IllegalStateException("Attempted to access message broker when it was not initialized"); + } + return broker; + } + + @Override + @NotNull + public RandomTeleportEngine getRandomTeleportEngine() { + return randomTeleportEngine; + } + + @Override + public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) { + this.randomTeleportEngine = randomTeleportEngine; + } + + @Override + @NotNull + public List getHooks() { + return hooks; + } + + @Override + public void setHooks(@NotNull List hooks) { + this.hooks = hooks; + } + + @Override + @Nullable + public InputStream getResource(@NotNull String name) { + return this.modContainer.findPath(name) + .map(path -> { + try { + return Files.newInputStream(path); + } catch (IOException e) { + log(Level.WARNING, "Failed to load resource: " + name, e); + } + return null; + }) + .orElse(this.getClass().getClassLoader().getResourceAsStream(name)); + } + + @Override + @NotNull + public File getDataFolder() { + return FabricLoader.getInstance().getConfigDir().resolve("huskhomes").toFile(); + } + + @Override + @NotNull + public List getWorlds() { + final List worlds = new ArrayList<>(); + minecraftServer.getWorlds().forEach(world -> worlds.add(World.from( + world.getRegistryKey().getValue().asString(), + UUID.nameUUIDFromBytes(world.getRegistryKey().getValue().asString().getBytes()) + ))); + return worlds; + } + + @Override + @NotNull + public Version getVersion() { + return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-"); + } + + @Override + @NotNull + public List getCommands() { + return commands; + } + + @NotNull + public List registerCommands() { + final List commands = FabricCommand.Type.getCommands(getPlugin()); + CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) -> + commands.forEach(command -> new FabricCommand(command, this).register(dispatcher))); + return commands; + } + + @Override + public boolean isDependencyLoaded(@NotNull String name) { + return FabricLoader.getInstance().isModLoaded(name); + } + + @Override + @NotNull + public Map> getGlobalPlayerList() { + return globalPlayerList; + } + + @Override + @NotNull + public Set getCurrentlyOnWarmup() { + return currentlyOnWarmup; + } + + @Override + public void registerMetrics(int metricsId) { + // No metrics for Fabric + } + + @Override + public void initializePluginChannels() { + ServerPlayNetworking.registerGlobalReceiver(new Identifier("bungeecord", "main"), this); + } + + // When the server receives a plugin message + @Override + public void receive(@NotNull MinecraftServer server, @NotNull ServerPlayerEntity player, + @NotNull ServerPlayNetworkHandler handler, @NotNull PacketByteBuf buf, + @NotNull PacketSender responseSender) { + if (broker instanceof PluginMessageBroker messenger + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + messenger.onReceive( + PluginMessageBroker.BUNGEE_CHANNEL_ID, + FabricUser.adapt(player, this), + ByteBufUtil.getBytes(buf) + ); + } + } + + @Override + public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... exceptions) { + switch (level.getName()) { + case "WARNING" -> { + if (exceptions.length >= 1) { + LOGGER.warn(message, exceptions[0]); + } else { + LOGGER.warn(message); + } + } + case "SEVERE" -> { + if (exceptions.length >= 1) { + LOGGER.error(message, exceptions[0]); + } else { + LOGGER.error(message); + } + } + default -> { + if (exceptions.length >= 1) { + LOGGER.info(message, exceptions[0]); + } else { + LOGGER.info(message); + } + } + } + } + + @NotNull + public Map getPermissions() { + return permissions; + } + + @NotNull + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + + @Override + @NotNull + public FabricHuskHomes getPlugin() { + return this; + } + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/command/FabricCommand.java similarity index 69% rename from fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/command/FabricCommand.java index 5fbb0bac..cb34e143 100644 --- a/fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java +++ b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/command/FabricCommand.java @@ -28,12 +28,17 @@ import net.fabricmc.fabric.api.util.TriState; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.FabricUser; import org.jetbrains.annotations.NotNull; +import java.util.Arrays; +import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.function.Function; import java.util.function.Predicate; import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; @@ -113,54 +118,64 @@ public class FabricCommand { private CommandUser resolveExecutor(@NotNull ServerCommandSource source) { if (source.getEntity() instanceof ServerPlayerEntity player) { - return FabricUser.adapt(plugin, player); + return FabricUser.adapt(player, plugin); } return plugin.getConsole(); } /** - * Commands available on the Fabric HuskHomes implementation + * Commands available on the Fabric HuskHomes implementation. */ public enum Type { - HOME_COMMAND(new PrivateHomeCommand(FabricHuskHomes.getInstance())), - SET_HOME_COMMAND(new SetHomeCommand(FabricHuskHomes.getInstance())), - HOME_LIST_COMMAND(new PrivateHomeListCommand(FabricHuskHomes.getInstance())), - DEL_HOME_COMMAND(new DelHomeCommand(FabricHuskHomes.getInstance())), - EDIT_HOME_COMMAND(new EditHomeCommand(FabricHuskHomes.getInstance())), - PUBLIC_HOME_COMMAND(new PublicHomeCommand(FabricHuskHomes.getInstance())), - PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(FabricHuskHomes.getInstance())), - WARP_COMMAND(new WarpCommand(FabricHuskHomes.getInstance())), - SET_WARP_COMMAND(new SetWarpCommand(FabricHuskHomes.getInstance())), - WARP_LIST_COMMAND(new WarpListCommand(FabricHuskHomes.getInstance())), - DEL_WARP_COMMAND(new DelWarpCommand(FabricHuskHomes.getInstance())), - EDIT_WARP_COMMAND(new EditWarpCommand(FabricHuskHomes.getInstance())), - TP_COMMAND(new TpCommand(FabricHuskHomes.getInstance())), - TP_HERE_COMMAND(new TpHereCommand(FabricHuskHomes.getInstance())), - TPA_COMMAND(new TeleportRequestCommand(FabricHuskHomes.getInstance(), TeleportRequest.Type.TPA)), - TPA_HERE_COMMAND(new TeleportRequestCommand(FabricHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)), - TPACCEPT_COMMAND(new TpRespondCommand(FabricHuskHomes.getInstance(), true)), - TPDECLINE_COMMAND(new TpRespondCommand(FabricHuskHomes.getInstance(), false)), - RTP_COMMAND(new RtpCommand(FabricHuskHomes.getInstance())), - TP_IGNORE_COMMAND(new TpIgnoreCommand(FabricHuskHomes.getInstance())), - TP_OFFLINE_COMMAND(new TpOfflineCommand(FabricHuskHomes.getInstance())), - TP_ALL_COMMAND(new TpAllCommand(FabricHuskHomes.getInstance())), - TPA_ALL_COMMAND(new TpaAllCommand(FabricHuskHomes.getInstance())), - SPAWN_COMMAND(new SpawnCommand(FabricHuskHomes.getInstance())), - SET_SPAWN_COMMAND(new SetSpawnCommand(FabricHuskHomes.getInstance())), - BACK_COMMAND(new BackCommand(FabricHuskHomes.getInstance())), - HUSKHOMES_COMMAND(new HuskHomesCommand(FabricHuskHomes.getInstance())); + HOME_COMMAND(PrivateHomeCommand::new), + SET_HOME_COMMAND(SetHomeCommand::new), + HOME_LIST_COMMAND(PrivateHomeListCommand::new), + DEL_HOME_COMMAND(DelHomeCommand::new), + EDIT_HOME_COMMAND(EditHomeCommand::new), + PUBLIC_HOME_COMMAND(PublicHomeCommand::new), + PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), + WARP_COMMAND(WarpCommand::new), + SET_WARP_COMMAND(SetWarpCommand::new), + WARP_LIST_COMMAND(WarpListCommand::new), + DEL_WARP_COMMAND(DelWarpCommand::new), + EDIT_WARP_COMMAND(EditWarpCommand::new), + TP_COMMAND(TpCommand::new), + TP_HERE_COMMAND(TpHereCommand::new), + TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), + TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), + TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), + TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), + RTP_COMMAND(RtpCommand::new), + TP_IGNORE_COMMAND(TpIgnoreCommand::new), + TP_OFFLINE_COMMAND(TpOfflineCommand::new), + TP_ALL_COMMAND(TpAllCommand::new), + TPA_ALL_COMMAND(TpaAllCommand::new), + SPAWN_COMMAND(SpawnCommand::new), + SET_SPAWN_COMMAND(SetSpawnCommand::new), + BACK_COMMAND(BackCommand::new), + HUSKHOMES_COMMAND(HuskHomesCommand::new); - private final Command command; + private final Function supplier; - Type(@NotNull Command command) { - this.command = command; + Type(@NotNull Function supplier) { + this.supplier = supplier; } @NotNull - public Command getCommand() { - return command; + public Command createCommand(@NotNull HuskHomes plugin) { + return supplier.apply(plugin); } + + @NotNull + public static List getCommands(@NotNull FabricHuskHomes plugin) { + return Arrays.stream(values()) + .map(type -> type.createCommand(plugin)) + .map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command) + .filter(Objects::nonNull) + .toList(); + } + } } diff --git a/fabric/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java similarity index 62% rename from fabric/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java index f377bb03..25b48705 100644 --- a/fabric/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java +++ b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java @@ -46,7 +46,8 @@ public interface FabricEventDispatcher extends EventDispatcher { final Method field = event.getClass().getDeclaredMethod("getEvent"); field.setAccessible(true); - net.fabricmc.fabric.api.event.Event fabricEvent = (net.fabricmc.fabric.api.event.Event) field.invoke(event); + net.fabricmc.fabric.api.event.Event fabricEvent = + (net.fabricmc.fabric.api.event.Event) field.invoke(event); final FabricEventCallback invoker = (FabricEventCallback) fabricEvent.invoker(); return invoker.invoke(event) == ActionResult.FAIL; @@ -57,77 +58,84 @@ public interface FabricEventDispatcher extends EventDispatcher { } @Override + @NotNull default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { return TeleportCallback.SUPPLIER.apply(teleport); } @Override - default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { + default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { return TeleportWarmupCallback.SUPPLIER.apply(teleport, duration); } @Override - default ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) { + default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, + @NotNull TeleportRequest request) { return SendTeleportRequestCallback.SUPPLIER.apply(sender, request); } @Override - default IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { + default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { return ReceiveTeleportRequestCallback.SUPPLIER.apply(recipient, request); } @Override - default IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { + default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { return ReplyTeleportRequestCallback.SUPPLIER.apply(recipient, request); } @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 HomeCreateCallback.SUPPLIER.apply(owner, name, position, creator); } @Override - default IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { + default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { return HomeEditCallback.SUPPLIER.apply(home, editor); } @Override - default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { + default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { return HomeDeleteCallback.SUPPLIER.apply(home, deleter); } @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 WarpCreateCallback.SUPPLIER.apply(name, position, creator); } @Override - default IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { + default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { return WarpEditCallback.SUPPLIER.apply(warp, editor); } @Override - default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { + default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { return WarpDeleteCallback.SUPPLIER.apply(warp, deleter); } @Override - default IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, boolean publicHomeList) { + default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, + boolean publicHomeList) { return HomeListCallback.SUPPLIER.apply(homes, listViewer, publicHomeList); } @Override - default IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { + default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { return WarpListCallback.SUPPLIER.apply(homes, listViewer); } @Override - default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { + default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { return DeleteAllHomesCallback.SUPPLIER.apply(user, deleter); } @Override - default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { + default @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { return DeleteAllWarpsCallback.SUPPLIER.apply(deleter); } diff --git a/fabric/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/HomeListCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeListCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/HomeListCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/HomeListCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/TeleportCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/TeleportCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/TeleportCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/TeleportCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/event/WarpListCallback.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpListCallback.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/event/WarpListCallback.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/event/WarpListCallback.java diff --git a/fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java similarity index 90% rename from fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java index 969d9d82..ba97ce55 100644 --- a/fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java +++ b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java @@ -40,24 +40,24 @@ public class FabricEventListener extends EventListener { private void registerEvents(@NotNull FabricHuskHomes plugin) { // Join event ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> handlePlayerJoin( - FabricUser.adapt(plugin, handler.player) + FabricUser.adapt(handler.player, plugin) )); // Quit event ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> handlePlayerLeave( - FabricUser.adapt(plugin, handler.player) + FabricUser.adapt(handler.player, plugin) )); // Death event ServerLivingEntityEvents.AFTER_DEATH.register((entity, source) -> { if (entity instanceof ServerPlayerEntity player) { - handlePlayerDeath(FabricUser.adapt(plugin, player)); + handlePlayerDeath(FabricUser.adapt(player, plugin)); } }); // Respawn event ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> handlePlayerRespawn( - FabricUser.adapt(plugin, newPlayer) + FabricUser.adapt(newPlayer, plugin) )); } diff --git a/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/user/FabricUser.java new file mode 100644 index 00000000..08984144 --- /dev/null +++ b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -0,0 +1,166 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.user; + +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; +import net.kyori.adventure.audience.Audience; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.position.Location; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.World; +import net.william278.huskhomes.teleport.TeleportationException; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public class FabricUser extends OnlineUser { + + private final FabricHuskHomes plugin; + private final ServerPlayerEntity player; + + private FabricUser(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { + super(player.getUuid(), player.getEntityName()); + this.player = player; + this.plugin = plugin; + } + + @NotNull + public static FabricUser adapt(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { + return new FabricUser(player, plugin); + } + + @Override + public Position getPosition() { + return Position.at( + player.getX(), player.getY(), player.getZ(), + player.getYaw(), player.getPitch(), + World.from( + player.getWorld().getRegistryKey().getValue().asString(), + UUID.nameUUIDFromBytes(player.getWorld().getRegistryKey().getValue().asString().getBytes()) + ), + plugin.getServerName() + ); + } + + @Override + public Optional getBedSpawnPosition() { + final BlockPos spawn = player.getSpawnPointPosition(); + if (spawn == null) { + return Optional.empty(); + } + + return Optional.of(Position.at( + spawn.getX(), spawn.getY(), spawn.getZ(), + player.getSpawnAngle(), 0, + World.from( + player.getSpawnPointDimension().getValue().asString(), + UUID.nameUUIDFromBytes(player.getSpawnPointDimension().getValue().asString().getBytes()) + ), + plugin.getServerName() + )); + } + + @Override + public double getHealth() { + return player.getHealth(); + } + + @Override + public boolean hasPermission(@NotNull String node) { + final boolean requiresOp = Boolean.TRUE.equals(plugin.getPermissions().getOrDefault(node, true)); + return Permissions.check(player, node, !requiresOp || player.hasPermissionLevel(3)); + } + + @Override + @NotNull + public Map getPermissions() { + return plugin.getPermissions().entrySet().stream() + .filter(entry -> Permissions.check(player, entry.getKey(), entry.getValue())) + .collect(HashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), HashMap::putAll); + } + + @Override + @NotNull + protected List getNumericalPermissions(@NotNull String nodePrefix) { + final List permissions = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + if (hasPermission(nodePrefix + i)) { + permissions.add(i); + } + } + return permissions.stream().sorted(Collections.reverseOrder()).toList(); + } + + @Override + @NotNull + public Audience getAudience() { + return player; + } + + @Override + public void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException { + final MinecraftServer server = player.getServer(); + assert server != null : "Server is null"; + final Identifier worldId = Identifier.tryParse(location.getWorld().getName()); + player.teleport( + server.getWorld(server.getWorldRegistryKeys().stream() + .filter(key -> key.getValue().equals(worldId)).findFirst().orElseThrow( + () -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND, plugin)) + ), + location.getX(), location.getY(), location.getZ(), + location.getYaw(), location.getPitch() + ); + } + + @Override + public void sendPluginMessage(@NotNull String channel, byte[] message) { + final PacketByteBuf buf = PacketByteBufs.create(); + buf.writeBytes(message); + final CustomPayloadS2CPacket packet = new CustomPayloadS2CPacket(parseIdentifier(channel), buf); + player.networkHandler.sendPacket(packet); + } + + @Override + public boolean isMoving() { + return player.isTouchingWater() || player.isFallFlying() || player.isSprinting() || player.isSneaking(); + } + + @Override + public boolean isVanished() { + return false; + } + + @NotNull + private static Identifier parseIdentifier(@NotNull String channel) { + if (channel.equals("BungeeCord")) { + return new Identifier("bungeecord", "main"); + } + return Optional.ofNullable(Identifier.tryParse(channel)) + .orElseThrow(() -> new IllegalArgumentException("Invalid channel name: " + channel)); + } + +} diff --git a/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java new file mode 100644 index 00000000..4d3b2d29 --- /dev/null +++ b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java @@ -0,0 +1,129 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.util; + +import net.minecraft.block.Block; +import net.minecraft.block.FireBlock; +import net.minecraft.block.FluidBlock; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; +import net.minecraft.util.registry.Registry; +import net.minecraft.world.BlockView; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.position.Location; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +public interface FabricSafetyResolver extends SafetyResolver { + + @Override + default CompletableFuture> findSafeGroundLocation(@NotNull Location location) { + final MinecraftServer server = ((FabricHuskHomes) getPlugin()).getMinecraftServer(); + final Identifier worldId = Identifier.tryParse(location.getWorld().getName()); + + // Ensure the location is on a valid world + final Optional locationWorld = server.getWorldRegistryKeys().stream() + .filter(key -> key.getValue().equals(worldId)).findFirst() + .map(server::getWorld); + if (locationWorld.isEmpty()) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + // Ensure the location is within the world border + final ServerWorld world = locationWorld.get(); + if (!world.getWorldBorder().contains(location.getX(), location.getZ())) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + return CompletableFuture.completedFuture(findSafeLocationNear(location, world)); + } + + /** + * Search for a safe ground location near the given location. + * + * @param location The location to search around + * @return An optional safe location, within 4 blocks of the given location + */ + private Optional findSafeLocationNear(@NotNull Location location, @NotNull ServerWorld world) { + final BlockPos.Mutable blockPos = new BlockPos.Mutable(location.getX(), location.getY(), location.getZ()); + for (int x = -SEARCH_RADIUS; x <= SEARCH_RADIUS; x++) { + for (int z = -SEARCH_RADIUS; z <= SEARCH_RADIUS; z++) { + blockPos.set(location.getX() + x, location.getY(), location.getZ() + z); + final int highestY = getHighestYAt(world, blockPos.getX(), blockPos.getY(), blockPos.getZ()) + 1; + + final Block block = world.getBlockState(blockPos.withY(highestY - 1)).getBlock(); + final Identifier id = Registry.BLOCK.getId(block); + + final Block bodyBlockType = world.getBlockState(blockPos.withY(highestY)).getBlock(); + final Identifier bodyBlockId = Registry.BLOCK.getId(bodyBlockType); + + final Block headBlockType = world.getBlockState(blockPos.withY(highestY + 1)).getBlock(); + final Identifier headBlockId = Registry.BLOCK.getId(headBlockType); + + if (!(block instanceof FluidBlock) && !(block instanceof FireBlock) + && isBlockSafeForStanding(id.toString()) && isBlockSafeForOccupation(bodyBlockId.toString()) + && isBlockSafeForOccupation(headBlockId.toString())) { + double locx = blockPos.getX(); + if (locx < 0) { + locx += 1.5d; + } else { + locx = locx + 0.5d; + } + double locz = blockPos.getZ(); + if (locz < 0) { + locz += 1.5d; + } else { + locz = locz + 0.5d; + } + return Optional.of(Location.at( + locx, + highestY, + locz, + location.getWorld() + )); + } + } + } + return Optional.empty(); + } + + /** + * Get the highest Y value at the given X and Z coordinates. + * + * @param blockView The block view to search + * @param x The X coordinate + * @param y The Y coordinate + * @param z The Z coordinate + * @return The highest Y value at the given X and Z coordinates + */ + private int getHighestYAt(@NotNull BlockView blockView, int x, int y, int z) { + final BlockPos.Mutable cursor = new BlockPos.Mutable(x, y, z); + while (blockView.getBlockState(cursor).isAir() && cursor.getY() > blockView.getBottomY()) { + cursor.move(Direction.DOWN); + } + return cursor.getY(); + } + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/util/FabricTask.java b/fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/util/FabricTask.java similarity index 100% rename from fabric/src/main/java/net/william278/huskhomes/util/FabricTask.java rename to fabric/fabric-1.19.2/src/main/java/net/william278/huskhomes/util/FabricTask.java diff --git a/fabric/src/main/resources/assets/huskhomes/icon.png b/fabric/fabric-1.19.2/src/main/resources/assets/huskhomes/icon.png similarity index 100% rename from fabric/src/main/resources/assets/huskhomes/icon.png rename to fabric/fabric-1.19.2/src/main/resources/assets/huskhomes/icon.png diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/fabric-1.19.2/src/main/resources/fabric.mod.json similarity index 100% rename from fabric/src/main/resources/fabric.mod.json rename to fabric/fabric-1.19.2/src/main/resources/fabric.mod.json diff --git a/fabric/build.gradle b/fabric/fabric-1.19.4/build.gradle similarity index 82% rename from fabric/build.gradle rename to fabric/fabric-1.19.4/build.gradle index 21edaad7..ceae8a02 100644 --- a/fabric/build.gradle +++ b/fabric/fabric-1.19.4/build.gradle @@ -1,10 +1,16 @@ +import org.apache.tools.ant.filters.ReplaceTokens + plugins { - id 'fabric-loom' version '1.2-SNAPSHOT' + id 'fabric-loom' version "$fabric_loom_version" } apply plugin: 'fabric-loom' loom.serverOnlyMinecraftJar() +// Get properties from local gradle.properties file +def properties = new Properties() +file("gradle.properties").withInputStream { properties.load(it) } + dependencies { minecraft "com.mojang:minecraft:${fabric_minecraft_version}" mappings "net.fabricmc:yarn:${fabric_yarn_mappings}:v2" @@ -21,7 +27,7 @@ dependencies { fabricApiModules.forEach { modImplementation(fabricApi.module(it, fabric_api_version)) } - modImplementation include('net.kyori:adventure-platform-fabric:5.9.0-SNAPSHOT') + modImplementation include("net.kyori:adventure-platform-fabric:${adventure_platform_fabric_version}") modImplementation include('me.lucko:fabric-permissions-api:0.2-SNAPSHOT') implementation include('redis.clients:jedis:' + jedis_version) @@ -56,6 +62,13 @@ shadowJar { relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' } +processResources { + filesMatching(['**/*.json', '**/*.yml']) { + filter ReplaceTokens as Class, beginToken: '${', endToken: '}', + tokens: properties + } +} + remapJar { dependsOn tasks.shadowJar mustRunAfter tasks.shadowJar diff --git a/fabric/fabric-1.19.4/gradle.properties b/fabric/fabric-1.19.4/gradle.properties new file mode 100644 index 00000000..fb8648a1 --- /dev/null +++ b/fabric/fabric-1.19.4/gradle.properties @@ -0,0 +1,6 @@ +fabric_minecraft_version=1.20.1 +fabric_loader_version=0.14.21 +fabric_yarn_mappings=1.19.4+build.2 +fabric_api_version=0.84.0+1.19.4 + +adventure_platform_fabric_version=5.8.0 \ No newline at end of file diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/FabricHuskHomes.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/FabricHuskHomes.java new file mode 100644 index 00000000..13fd5bbd --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/FabricHuskHomes.java @@ -0,0 +1,478 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes; + +import io.netty.buffer.ByteBufUtil; +import net.fabricmc.api.DedicatedServerModInitializer; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.kyori.adventure.platform.fabric.FabricServerAudiences; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerPlayNetworkHandler; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.william278.annotaml.Annotaml; +import net.william278.desertwell.util.Version; +import net.william278.huskhomes.command.Command; +import net.william278.huskhomes.command.FabricCommand; +import net.william278.huskhomes.config.Locales; +import net.william278.huskhomes.config.Server; +import net.william278.huskhomes.config.Settings; +import net.william278.huskhomes.config.Spawn; +import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.MySqlDatabase; +import net.william278.huskhomes.database.SqLiteDatabase; +import net.william278.huskhomes.event.FabricEventDispatcher; +import net.william278.huskhomes.hook.Hook; +import net.william278.huskhomes.listener.EventListener; +import net.william278.huskhomes.listener.FabricEventListener; +import net.william278.huskhomes.manager.Manager; +import net.william278.huskhomes.network.Broker; +import net.william278.huskhomes.network.PluginMessageBroker; +import net.william278.huskhomes.network.RedisBroker; +import net.william278.huskhomes.position.Location; +import net.william278.huskhomes.position.World; +import net.william278.huskhomes.random.NormalDistributionEngine; +import net.william278.huskhomes.random.RandomTeleportEngine; +import net.william278.huskhomes.user.ConsoleUser; +import net.william278.huskhomes.user.FabricUser; +import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.SavedUser; +import net.william278.huskhomes.util.FabricSafetyResolver; +import net.william278.huskhomes.util.FabricTask; +import net.william278.huskhomes.util.UnsafeBlocks; +import net.william278.huskhomes.util.Validator; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggingEventBuilder; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier, + FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler { + + public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes"); + private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes") + .orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); + + private MinecraftServer minecraftServer; + private Map permissions; + private Set savedUsers; + private Settings settings; + private Locales locales; + private Database database; + private Validator validator; + private Manager manager; + private EventListener eventListener; + private RandomTeleportEngine randomTeleportEngine; + private Spawn serverSpawn; + private UnsafeBlocks unsafeBlocks; + private List hooks; + private List commands; + private ConcurrentHashMap> globalPlayerList; + private Set currentlyOnWarmup; + private Server server; + @Nullable + private Broker broker; + private FabricServerAudiences audiences; + + @Override + public void onInitializeServer() { + // Get plugin version from mod container + this.permissions = new HashMap<>(); + this.savedUsers = new HashSet<>(); + this.globalPlayerList = new ConcurrentHashMap<>(); + this.currentlyOnWarmup = new HashSet<>(); + this.validator = new Validator(this); + + // Load settings and locales + initialize("plugin config & locale files", (plugin) -> { + if (!loadConfigs()) { + throw new IllegalStateException("Failed to load config files. Please check the console for errors"); + } + }); + + // Pre-register commands + initialize("commands", (plugin) -> this.commands = registerCommands()); + + ServerLifecycleEvents.SERVER_STARTING.register(server -> { + this.minecraftServer = server; + this.onEnable(); + }); + ServerLifecycleEvents.SERVER_STOPPING.register(server -> this.onDisable()); + } + + private void onEnable() { + // Create adventure audience + this.audiences = FabricServerAudiences.of(minecraftServer); + + // Initialize the database + initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { + this.database = switch (getSettings().getDatabaseType()) { + case MYSQL, MARIADB -> new MySqlDatabase(this); + case SQLITE -> new SqLiteDatabase(this); + }; + + database.initialize(); + }); + + // Initialize the manager + this.manager = new Manager(this); + + // Initialize the network messenger if proxy mode is enabled + if (getSettings().doCrossServer()) { + initialize(settings.getBrokerType().getDisplayName() + " message broker", (plugin) -> { + broker = switch (settings.getBrokerType()) { + case PLUGIN_MESSAGE -> new PluginMessageBroker(this); + case REDIS -> new RedisBroker(this); + }; + broker.initialize(); + }); + } + + setRandomTeleportEngine(new NormalDistributionEngine(this)); + + // Register plugin hooks (Economy, Maps, Plan) + initialize("hooks", (plugin) -> { + this.registerHooks(); + + if (hooks.size() > 0) { + hooks.forEach(hook -> { + try { + hook.initialize(); + } catch (Throwable e) { + log(Level.WARNING, "Failed to initialize " + hook.getName() + " hook", e); + } + }); + log(Level.INFO, "Registered " + hooks.size() + " mod hooks: " + hooks.stream() + .map(Hook::getName) + .collect(Collectors.joining(", "))); + } + }); + + // Register events + initialize("events", (plugin) -> this.eventListener = new FabricEventListener(this)); + + this.checkForUpdates(); + } + + private void onDisable() { + if (this.eventListener != null) { + this.eventListener.handlePluginDisable(); + } + if (database != null) { + database.terminate(); + } + if (broker != null) { + broker.close(); + } + if (audiences != null) { + audiences.close(); + audiences = null; + } + cancelTasks(); + } + + @Override + @NotNull + public ConsoleUser getConsole() { + return new ConsoleUser(audiences.console()); + } + + @Override + @NotNull + public List getOnlineUsers() { + return minecraftServer.getPlayerManager().getPlayerList() + .stream().map(user -> (OnlineUser) FabricUser.adapt(user, this)) + .toList(); + } + + @Override + @NotNull + public Set getSavedUsers() { + return savedUsers; + } + + @Override + @NotNull + public Settings getSettings() { + return settings; + } + + @Override + public void setSettings(@NotNull Settings settings) { + this.settings = settings; + } + + @Override + @NotNull + public Locales getLocales() { + return locales; + } + + @Override + public void setLocales(@NotNull Locales locales) { + this.locales = locales; + } + + @Override + public Optional getServerSpawn() { + return Optional.ofNullable(serverSpawn); + } + + @Override + public void setServerSpawn(@NotNull Spawn spawn) { + this.serverSpawn = spawn; + } + + @Override + public void setServerSpawn(@NotNull Location location) { + try { + // Create or update the spawn.yml file + final File spawnFile = new File(getDataFolder(), "spawn.yml"); + if (spawnFile.exists() && !spawnFile.delete()) { + log(Level.WARNING, "Failed to delete the existing spawn.yml file"); + } + this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get(); + + // Update the world spawn location, too + minecraftServer.getWorlds().forEach(world -> { + if (world.getRegistryKey().getValue().asString().equals(location.getWorld().getName())) { + world.setSpawnPos(BlockPos.ofFloored(location.getX(), location.getY(), location.getZ()), 0); + } + }); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + log(Level.WARNING, "Failed to save the server spawn.yml file", e); + } + } + + @Override + @NotNull + public String getServerName() { + return server.getName(); + } + + @Override + public void setServer(@NotNull Server server) { + this.server = server; + } + + @Override + public void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks) { + this.unsafeBlocks = unsafeBlocks; + } + + @NotNull + @Override + public UnsafeBlocks getUnsafeBlocks() { + return unsafeBlocks; + } + + @Override + @NotNull + public Database getDatabase() { + return database; + } + + @Override + @NotNull + public Validator getValidator() { + return validator; + } + + @Override + @NotNull + public Manager getManager() { + return manager; + } + + @Override + @NotNull + public Broker getMessenger() { + if (broker == null) { + throw new IllegalStateException("Attempted to access message broker when it was not initialized"); + } + return broker; + } + + @Override + @NotNull + public RandomTeleportEngine getRandomTeleportEngine() { + return randomTeleportEngine; + } + + @Override + public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) { + this.randomTeleportEngine = randomTeleportEngine; + } + + @Override + @NotNull + public List getHooks() { + return hooks; + } + + @Override + public void setHooks(@NotNull List hooks) { + this.hooks = hooks; + } + + @Override + @Nullable + public InputStream getResource(@NotNull String name) { + return this.modContainer.findPath(name) + .map(path -> { + try { + return Files.newInputStream(path); + } catch (IOException e) { + log(Level.WARNING, "Failed to load resource: " + name, e); + } + return null; + }) + .orElse(this.getClass().getClassLoader().getResourceAsStream(name)); + } + + @Override + @NotNull + public File getDataFolder() { + return FabricLoader.getInstance().getConfigDir().resolve("huskhomes").toFile(); + } + + @Override + @NotNull + public List getWorlds() { + final List worlds = new ArrayList<>(); + minecraftServer.getWorlds().forEach(world -> worlds.add(World.from( + world.getRegistryKey().getValue().asString(), + UUID.nameUUIDFromBytes(world.getRegistryKey().getValue().asString().getBytes()) + ))); + return worlds; + } + + @Override + @NotNull + public Version getVersion() { + return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-"); + } + + @Override + @NotNull + public List getCommands() { + return commands; + } + + @NotNull + public List registerCommands() { + final List commands = FabricCommand.Type.getCommands(getPlugin()); + CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) -> + commands.forEach(command -> new FabricCommand(command, this).register(dispatcher))); + return commands; + } + + @Override + public boolean isDependencyLoaded(@NotNull String name) { + return FabricLoader.getInstance().isModLoaded(name); + } + + @Override + @NotNull + public Map> getGlobalPlayerList() { + return globalPlayerList; + } + + @Override + @NotNull + public Set getCurrentlyOnWarmup() { + return currentlyOnWarmup; + } + + @Override + public void registerMetrics(int metricsId) { + // No metrics for Fabric + } + + @Override + public void initializePluginChannels() { + ServerPlayNetworking.registerGlobalReceiver(new Identifier("bungeecord", "main"), this); + } + + // When the server receives a plugin message + @Override + public void receive(@NotNull MinecraftServer server, @NotNull ServerPlayerEntity player, + @NotNull ServerPlayNetworkHandler handler, @NotNull PacketByteBuf buf, + @NotNull PacketSender responseSender) { + if (broker instanceof PluginMessageBroker messenger + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + messenger.onReceive( + PluginMessageBroker.BUNGEE_CHANNEL_ID, + FabricUser.adapt(player, this), + ByteBufUtil.getBytes(buf) + ); + } + } + + @Override + public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... exceptions) { + LoggingEventBuilder logEvent = LOGGER.makeLoggingEventBuilder( + switch (level.getName()) { + case "WARNING" -> org.slf4j.event.Level.WARN; + case "SEVERE" -> org.slf4j.event.Level.ERROR; + default -> org.slf4j.event.Level.INFO; + } + ); + if (exceptions.length >= 1) { + logEvent = logEvent.setCause(exceptions[0]); + } + logEvent.log(message); + } + + @NotNull + public Map getPermissions() { + return permissions; + } + + @NotNull + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + + @Override + @NotNull + public FabricHuskHomes getPlugin() { + return this; + } + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/command/FabricCommand.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/command/FabricCommand.java new file mode 100644 index 00000000..cb34e143 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/command/FabricCommand.java @@ -0,0 +1,181 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.command; + +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.tree.LiteralCommandNode; +import me.lucko.fabric.api.permissions.v0.PermissionCheckEvent; +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.network.ServerPlayerEntity; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.FabricUser; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; + +import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; +import static net.minecraft.server.command.CommandManager.argument; +import static net.minecraft.server.command.CommandManager.literal; + +public class FabricCommand { + + private final FabricHuskHomes plugin; + private final Command command; + + public FabricCommand(@NotNull Command command, @NotNull FabricHuskHomes plugin) { + this.command = command; + this.plugin = plugin; + } + + public void register(@NotNull CommandDispatcher dispatcher) { + // Register brigadier command + final Predicate predicate = Permissions + .require(command.getPermission(), command.isOperatorCommand() ? 3 : 0); + final LiteralArgumentBuilder builder = literal(command.getName()) + .requires(predicate).executes(getBrigadierExecutor()); + plugin.getPermissions().put(command.getPermission(), command.isOperatorCommand()); + if (!command.getRawUsage().isBlank()) { + builder.then(argument(command.getRawUsage().replaceAll("[<>\\[\\]]", ""), greedyString()) + .executes(getBrigadierExecutor()) + .suggests(getBrigadierSuggester())); + } + + // Register additional permissions + final Map permissions = command.getAdditionalPermissions(); + permissions.forEach((permission, isOp) -> plugin.getPermissions().put(permission, isOp)); + PermissionCheckEvent.EVENT.register((player, node) -> { + if (permissions.containsKey(node) && permissions.get(node) && player.hasPermissionLevel(3)) { + return TriState.TRUE; + } + return TriState.DEFAULT; + }); + + // Register aliases + final LiteralCommandNode node = dispatcher.register(builder); + dispatcher.register(literal("huskhomes:" + command.getName()) + .requires(predicate).executes(getBrigadierExecutor()).redirect(node)); + command.getAliases().forEach(alias -> dispatcher.register(literal(alias) + .requires(predicate).executes(getBrigadierExecutor()).redirect(node))); + } + + private com.mojang.brigadier.Command getBrigadierExecutor() { + return (context) -> { + command.onExecuted( + resolveExecutor(context.getSource()), + command.removeFirstArg(context.getInput().split(" ")) + ); + return 1; + }; + } + + private com.mojang.brigadier.suggestion.SuggestionProvider getBrigadierSuggester() { + if (!(command instanceof TabProvider provider)) { + return (context, builder) -> com.mojang.brigadier.suggestion.Suggestions.empty(); + } + return (context, builder) -> { + final String[] args = command.removeFirstArg(context.getInput().split(" ")); + provider.getSuggestions(resolveExecutor(context.getSource()), args).stream() + .map(suggestion -> { + final String completedArgs = String.join(" ", args); + int lastIndex = completedArgs.lastIndexOf(" "); + if (lastIndex == -1) { + return suggestion; + } + return completedArgs.substring(0, lastIndex + 1) + suggestion; + }) + .forEach(builder::suggest); + return builder.buildFuture(); + }; + } + + private CommandUser resolveExecutor(@NotNull ServerCommandSource source) { + if (source.getEntity() instanceof ServerPlayerEntity player) { + return FabricUser.adapt(player, plugin); + } + return plugin.getConsole(); + } + + + /** + * Commands available on the Fabric HuskHomes implementation. + */ + public enum Type { + HOME_COMMAND(PrivateHomeCommand::new), + SET_HOME_COMMAND(SetHomeCommand::new), + HOME_LIST_COMMAND(PrivateHomeListCommand::new), + DEL_HOME_COMMAND(DelHomeCommand::new), + EDIT_HOME_COMMAND(EditHomeCommand::new), + PUBLIC_HOME_COMMAND(PublicHomeCommand::new), + PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), + WARP_COMMAND(WarpCommand::new), + SET_WARP_COMMAND(SetWarpCommand::new), + WARP_LIST_COMMAND(WarpListCommand::new), + DEL_WARP_COMMAND(DelWarpCommand::new), + EDIT_WARP_COMMAND(EditWarpCommand::new), + TP_COMMAND(TpCommand::new), + TP_HERE_COMMAND(TpHereCommand::new), + TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), + TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), + TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), + TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), + RTP_COMMAND(RtpCommand::new), + TP_IGNORE_COMMAND(TpIgnoreCommand::new), + TP_OFFLINE_COMMAND(TpOfflineCommand::new), + TP_ALL_COMMAND(TpAllCommand::new), + TPA_ALL_COMMAND(TpaAllCommand::new), + SPAWN_COMMAND(SpawnCommand::new), + SET_SPAWN_COMMAND(SetSpawnCommand::new), + BACK_COMMAND(BackCommand::new), + HUSKHOMES_COMMAND(HuskHomesCommand::new); + + private final Function supplier; + + Type(@NotNull Function supplier) { + this.supplier = supplier; + } + + @NotNull + public Command createCommand(@NotNull HuskHomes plugin) { + return supplier.apply(plugin); + } + + @NotNull + public static List getCommands(@NotNull FabricHuskHomes plugin) { + return Arrays.stream(values()) + .map(type -> type.createCommand(plugin)) + .map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command) + .filter(Objects::nonNull) + .toList(); + } + + } + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java new file mode 100644 index 00000000..f84f238d --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java @@ -0,0 +1,82 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface DeleteAllHomesCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(DeleteAllHomesCallback.class, + (listeners) -> (event) -> { + for (DeleteAllHomesCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (owner, deleter) -> + new IDeleteAllHomesEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public User getHomeOwner() { + return owner; + } + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java new file mode 100644 index 00000000..78945be9 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java @@ -0,0 +1,75 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public interface DeleteAllWarpsCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(DeleteAllWarpsCallback.class, + (listeners) -> (event) -> { + for (DeleteAllWarpsCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + Function SUPPLIER = (deleter) -> + new IDeleteAllWarpsEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java new file mode 100644 index 00000000..ef0c3a7f --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java @@ -0,0 +1,31 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.minecraft.util.ActionResult; +import org.jetbrains.annotations.NotNull; + +public interface FabricEventCallback { + + @NotNull + ActionResult invoke(@NotNull E event); + + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java new file mode 100644 index 00000000..25b48705 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java @@ -0,0 +1,146 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.teleport.TimedTeleport; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.logging.Level; + +public interface FabricEventDispatcher extends EventDispatcher { + + @SuppressWarnings("unchecked") + @Override + default boolean fireIsCancelled(@NotNull T event) { + try { + final Method field = event.getClass().getDeclaredMethod("getEvent"); + field.setAccessible(true); + + net.fabricmc.fabric.api.event.Event fabricEvent = + (net.fabricmc.fabric.api.event.Event) field.invoke(event); + + final FabricEventCallback invoker = (FabricEventCallback) fabricEvent.invoker(); + return invoker.invoke(event) == ActionResult.FAIL; + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { + getPlugin().log(Level.WARNING, "Failed to fire event (" + event.getClass().getName() + ")", e); + return false; + } + } + + @Override + @NotNull + default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { + return TeleportCallback.SUPPLIER.apply(teleport); + } + + @Override + default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { + return TeleportWarmupCallback.SUPPLIER.apply(teleport, duration); + } + + @Override + default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, + @NotNull TeleportRequest request) { + return SendTeleportRequestCallback.SUPPLIER.apply(sender, request); + } + + @Override + default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { + return ReceiveTeleportRequestCallback.SUPPLIER.apply(recipient, request); + } + + @Override + default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { + return ReplyTeleportRequestCallback.SUPPLIER.apply(recipient, request); + } + + @Override + default @NotNull IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, + @NotNull Position position, @NotNull CommandUser creator) { + return HomeCreateCallback.SUPPLIER.apply(owner, name, position, creator); + } + + @Override + default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { + return HomeEditCallback.SUPPLIER.apply(home, editor); + } + + @Override + default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { + return HomeDeleteCallback.SUPPLIER.apply(home, deleter); + } + + @Override + default @NotNull IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, + @NotNull CommandUser creator) { + return WarpCreateCallback.SUPPLIER.apply(name, position, creator); + } + + @Override + default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { + return WarpEditCallback.SUPPLIER.apply(warp, editor); + } + + @Override + default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { + return WarpDeleteCallback.SUPPLIER.apply(warp, deleter); + } + + @Override + default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, + boolean publicHomeList) { + return HomeListCallback.SUPPLIER.apply(homes, listViewer, publicHomeList); + } + + @Override + default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { + return WarpListCallback.SUPPLIER.apply(homes, listViewer); + } + + @Override + default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { + return DeleteAllHomesCallback.SUPPLIER.apply(user, deleter); + } + + @Override + default @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { + return DeleteAllWarpsCallback.SUPPLIER.apply(deleter); + } + + @Override + @NotNull + FabricHuskHomes getPlugin(); + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java new file mode 100644 index 00000000..026ad4b3 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java @@ -0,0 +1,103 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.data.client.BlockStateVariantMap.QuadFunction; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; + +public interface HomeCreateCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeCreateCallback.class, + (listeners) -> (event) -> { + for (HomeCreateCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + QuadFunction SUPPLIER = (user, name, position, creator) -> + new IHomeCreateEvent() { + private boolean cancelled = false; + private String homeName = name; + + @Override + @NotNull + public User getOwner() { + return user; + } + + @Override + @NotNull + public String getName() { + return homeName; + } + + @Override + public void setName(@NotNull String name) { + this.homeName = name; + } + + @Override + @NotNull + public Position getPosition() { + return position; + } + + @Override + public void setPosition(@NotNull Position position) { + } + + @Override + public @NotNull CommandUser getCreator() { + return creator; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java new file mode 100644 index 00000000..0f479589 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface HomeDeleteCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeDeleteCallback.class, + (listeners) -> (event) -> { + for (HomeDeleteCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (home, deleter) -> + new IHomeDeleteEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Home getHome() { + return home; + } + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java new file mode 100644 index 00000000..3b28f749 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface HomeEditCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeEditCallback.class, + (listeners) -> (event) -> { + for (HomeEditCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (home, editor) -> + new IHomeEditEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Home getHome() { + return home; + } + + @Override + @NotNull + public CommandUser getEditor() { + return editor; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeListCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeListCallback.java new file mode 100644 index 00000000..e89d5cb6 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/HomeListCallback.java @@ -0,0 +1,95 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; +import org.apache.commons.lang3.function.TriFunction; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public interface HomeListCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeListCallback.class, + (listeners) -> (event) -> { + for (HomeListCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + TriFunction, CommandUser, Boolean, IHomeListEvent> SUPPLIER = (homes, viewer, publicHomes) -> + new IHomeListEvent() { + private boolean cancelled = false; + private List listHomes = homes; + + @Override + @NotNull + public List getHomes() { + return listHomes; + } + + @Override + public void setHomes(@NotNull List homes) { + this.listHomes = homes; + } + + @Override + @NotNull + public CommandUser getListViewer() { + return viewer; + } + + @Override + public boolean getIsPublicHomeList() { + return publicHomes; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java new file mode 100644 index 00000000..a0b4da5a --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface ReceiveTeleportRequestCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(ReceiveTeleportRequestCallback.class, + (listeners) -> (event) -> { + for (ReceiveTeleportRequestCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (recipient, request) -> + new IReceiveTeleportRequestEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public OnlineUser getRecipient() { + return recipient; + } + + @Override + @NotNull + public TeleportRequest getRequest() { + return request; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java new file mode 100644 index 00000000..85dcddb8 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface ReplyTeleportRequestCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(ReplyTeleportRequestCallback.class, + (listeners) -> (event) -> { + for (ReplyTeleportRequestCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (recipient, request) -> + new IReplyTeleportRequestEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public OnlineUser getRecipient() { + return recipient; + } + + @Override + @NotNull + public TeleportRequest getRequest() { + return request; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java new file mode 100644 index 00000000..d7fd6505 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface SendTeleportRequestCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(SendTeleportRequestCallback.class, + (listeners) -> (event) -> { + for (SendTeleportRequestCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (sender, request) -> + new ISendTeleportRequestEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public OnlineUser getSender() { + return sender; + } + + @Override + @NotNull + public TeleportRequest getRequest() { + return request; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java new file mode 100644 index 00000000..90a153c6 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.teleport.Teleport; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public interface TeleportBackCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(TeleportBackCallback.class, + (listeners) -> (event) -> { + for (TeleportBackCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.FAIL; + } else if (result == ActionResult.FAIL) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + Function SUPPLIER = (teleport) -> + new ITeleportBackEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Position getLastPosition() { + return (Position) getTeleport().getTarget(); + } + + @Override + @NotNull + public Teleport getTeleport() { + return teleport; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportCallback.java new file mode 100644 index 00000000..99a7cc6b --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportCallback.java @@ -0,0 +1,76 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.Teleport; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public interface TeleportCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(TeleportCallback.class, + (listeners) -> (event) -> { + for (TeleportCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.FAIL; + } else if (result == ActionResult.FAIL) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + Function SUPPLIER = (teleport) -> + new ITeleportEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Teleport getTeleport() { + return teleport; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java new file mode 100644 index 00000000..c9d6961c --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java @@ -0,0 +1,79 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TimedTeleport; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface TeleportWarmupCallback extends FabricEventCallback { + @NotNull + Event EVENT = EventFactory.createArrayBacked(TeleportWarmupCallback.class, + (listeners) -> (event) -> { + for (TeleportWarmupCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.FAIL; + } else if (result == ActionResult.FAIL) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (timedTeleport, duration) -> + new ITeleportWarmupEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public TimedTeleport getTimedTeleport() { + return timedTeleport; + } + + @Override + public int getWarmupDuration() { + return duration; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java new file mode 100644 index 00000000..78b69dc9 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java @@ -0,0 +1,98 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.user.CommandUser; +import org.apache.commons.lang3.function.TriFunction; +import org.jetbrains.annotations.NotNull; + +public interface WarpCreateCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpCreateCallback.class, + (listeners) -> (event) -> { + for (WarpCreateCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + TriFunction SUPPLIER = (name, position, creator) -> + new IWarpCreateEvent() { + private boolean cancelled = false; + private String homeName = name; + + @Override + @NotNull + public String getName() { + return homeName; + } + + @Override + public void setName(@NotNull String name) { + this.homeName = name; + } + + @Override + @NotNull + public Position getPosition() { + return position; + } + + @Override + public void setPosition(@NotNull Position position) { + } + + @Override + @NotNull + public CommandUser getCreator() { + return creator; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java new file mode 100644 index 00000000..cbba72ea --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface WarpDeleteCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpDeleteCallback.class, + (listeners) -> (event) -> { + for (WarpDeleteCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (warp, deleter) -> + new IWarpDeleteEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Warp getWarp() { + return warp; + } + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java new file mode 100644 index 00000000..d3291d91 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface WarpEditCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpEditCallback.class, + (listeners) -> (event) -> { + for (WarpEditCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (warp, editor) -> + new IWarpEditEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Warp getWarp() { + return warp; + } + + @Override + @NotNull + public CommandUser getEditor() { + return editor; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpListCallback.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpListCallback.java new file mode 100644 index 00000000..21f2a55f --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/event/WarpListCallback.java @@ -0,0 +1,90 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.function.BiFunction; + +public interface WarpListCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpListCallback.class, + (listeners) -> (event) -> { + for (WarpListCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction, CommandUser, IWarpListEvent> SUPPLIER = (warps, viewer) -> + new IWarpListEvent() { + private boolean cancelled = false; + private List listWarps = warps; + + @Override + @NotNull + public List getWarps() { + return listWarps; + } + + @Override + public void setWarps(@NotNull List homes) { + this.listWarps = homes; + } + + @Override + @NotNull + public CommandUser getListViewer() { + return viewer; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java new file mode 100644 index 00000000..ba97ce55 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java @@ -0,0 +1,64 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.listener; + +import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; +import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents; +import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; +import net.minecraft.server.network.ServerPlayerEntity; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.user.FabricUser; +import org.jetbrains.annotations.NotNull; + +// Note that the teleport event and update player respawn position events are not handled on Fabric. +// The "update last position on teleport event" and "global respawn" features are not supported on Fabric. +public class FabricEventListener extends EventListener { + + public FabricEventListener(@NotNull FabricHuskHomes plugin) { + super(plugin); + this.registerEvents(plugin); + } + + // Register fabric event callback listeners to internal handlers + private void registerEvents(@NotNull FabricHuskHomes plugin) { + // Join event + ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> handlePlayerJoin( + FabricUser.adapt(handler.player, plugin) + )); + + // Quit event + ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> handlePlayerLeave( + FabricUser.adapt(handler.player, plugin) + )); + + // Death event + ServerLivingEntityEvents.AFTER_DEATH.register((entity, source) -> { + if (entity instanceof ServerPlayerEntity player) { + handlePlayerDeath(FabricUser.adapt(player, plugin)); + } + }); + + // Respawn event + ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> handlePlayerRespawn( + FabricUser.adapt(newPlayer, plugin) + )); + } + +} diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/user/FabricUser.java new file mode 100644 index 00000000..08984144 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -0,0 +1,166 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.user; + +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; +import net.kyori.adventure.audience.Audience; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.position.Location; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.World; +import net.william278.huskhomes.teleport.TeleportationException; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public class FabricUser extends OnlineUser { + + private final FabricHuskHomes plugin; + private final ServerPlayerEntity player; + + private FabricUser(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { + super(player.getUuid(), player.getEntityName()); + this.player = player; + this.plugin = plugin; + } + + @NotNull + public static FabricUser adapt(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { + return new FabricUser(player, plugin); + } + + @Override + public Position getPosition() { + return Position.at( + player.getX(), player.getY(), player.getZ(), + player.getYaw(), player.getPitch(), + World.from( + player.getWorld().getRegistryKey().getValue().asString(), + UUID.nameUUIDFromBytes(player.getWorld().getRegistryKey().getValue().asString().getBytes()) + ), + plugin.getServerName() + ); + } + + @Override + public Optional getBedSpawnPosition() { + final BlockPos spawn = player.getSpawnPointPosition(); + if (spawn == null) { + return Optional.empty(); + } + + return Optional.of(Position.at( + spawn.getX(), spawn.getY(), spawn.getZ(), + player.getSpawnAngle(), 0, + World.from( + player.getSpawnPointDimension().getValue().asString(), + UUID.nameUUIDFromBytes(player.getSpawnPointDimension().getValue().asString().getBytes()) + ), + plugin.getServerName() + )); + } + + @Override + public double getHealth() { + return player.getHealth(); + } + + @Override + public boolean hasPermission(@NotNull String node) { + final boolean requiresOp = Boolean.TRUE.equals(plugin.getPermissions().getOrDefault(node, true)); + return Permissions.check(player, node, !requiresOp || player.hasPermissionLevel(3)); + } + + @Override + @NotNull + public Map getPermissions() { + return plugin.getPermissions().entrySet().stream() + .filter(entry -> Permissions.check(player, entry.getKey(), entry.getValue())) + .collect(HashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), HashMap::putAll); + } + + @Override + @NotNull + protected List getNumericalPermissions(@NotNull String nodePrefix) { + final List permissions = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + if (hasPermission(nodePrefix + i)) { + permissions.add(i); + } + } + return permissions.stream().sorted(Collections.reverseOrder()).toList(); + } + + @Override + @NotNull + public Audience getAudience() { + return player; + } + + @Override + public void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException { + final MinecraftServer server = player.getServer(); + assert server != null : "Server is null"; + final Identifier worldId = Identifier.tryParse(location.getWorld().getName()); + player.teleport( + server.getWorld(server.getWorldRegistryKeys().stream() + .filter(key -> key.getValue().equals(worldId)).findFirst().orElseThrow( + () -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND, plugin)) + ), + location.getX(), location.getY(), location.getZ(), + location.getYaw(), location.getPitch() + ); + } + + @Override + public void sendPluginMessage(@NotNull String channel, byte[] message) { + final PacketByteBuf buf = PacketByteBufs.create(); + buf.writeBytes(message); + final CustomPayloadS2CPacket packet = new CustomPayloadS2CPacket(parseIdentifier(channel), buf); + player.networkHandler.sendPacket(packet); + } + + @Override + public boolean isMoving() { + return player.isTouchingWater() || player.isFallFlying() || player.isSprinting() || player.isSneaking(); + } + + @Override + public boolean isVanished() { + return false; + } + + @NotNull + private static Identifier parseIdentifier(@NotNull String channel) { + if (channel.equals("BungeeCord")) { + return new Identifier("bungeecord", "main"); + } + return Optional.ofNullable(Identifier.tryParse(channel)) + .orElseThrow(() -> new IllegalArgumentException("Invalid channel name: " + channel)); + } + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java similarity index 92% rename from fabric/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java rename to fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java index 66848b87..15eb62ef 100644 --- a/fabric/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java @@ -61,7 +61,7 @@ public interface FabricSafetyResolver 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 * @return An optional safe location, within 4 blocks of the given location @@ -82,16 +82,16 @@ public interface FabricSafetyResolver extends SafetyResolver { final Block headBlockType = world.getBlockState(blockPos.withY(highestY + 1)).getBlock(); final Identifier headBlockId = Registries.BLOCK.getId(headBlockType); - if (!(block instanceof FluidBlock) && !(block instanceof FireBlock) && isBlockSafeForStanding(id.toString()) - && isBlockSafeForOccupation(bodyBlockId.toString()) - && isBlockSafeForOccupation(headBlockId.toString())) { - double locx = Math.floor(blockPos.getX()); + if (!(block instanceof FluidBlock) && !(block instanceof FireBlock) + && isBlockSafeForStanding(id.toString()) && isBlockSafeForOccupation(bodyBlockId.toString()) + && isBlockSafeForOccupation(headBlockId.toString())) { + double locx = blockPos.getX(); if (locx < 0) { locx += 1.5d; } else { locx = locx + 0.5d; } - double locz = Math.floor(blockPos.getZ()); + double locz = blockPos.getZ(); if (locz < 0) { locz += 1.5d; } else { @@ -110,7 +110,7 @@ public interface FabricSafetyResolver extends SafetyResolver { } /** - * Get the highest Y value at the given X and Z coordinates + * Get the highest Y value at the given X and Z coordinates. * * @param blockView The block view to search * @param x The X coordinate diff --git a/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/util/FabricTask.java b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/util/FabricTask.java new file mode 100644 index 00000000..70b9efe8 --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/java/net/william278/huskhomes/util/FabricTask.java @@ -0,0 +1,142 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.util; + +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public interface FabricTask extends Task { + + class Sync extends Task.Sync implements FabricTask { + + protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + if (delayTicks > 0) { + CompletableFuture.runAsync(() -> { + + try { + Thread.sleep(delayTicks * 50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + ((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable); + + }, ((FabricHuskHomes) getPlugin()).getMinecraftServer()); + } else { + ((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable); + } + } + } + } + + class Async extends Task.Async implements FabricTask { + private CompletableFuture task; + + protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + super(plugin, runnable); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(true); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = CompletableFuture.runAsync(runnable, ((FabricHuskHomes) getPlugin()).getMinecraftServer()); + } + } + } + + class Repeating extends Task.Repeating implements FabricTask { + + private ScheduledFuture task; + + protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable, repeatingTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(true); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate( + runnable, 0, repeatingTicks * 50, TimeUnit.MILLISECONDS + ); + } + } + } + + interface Supplier extends Task.Supplier { + + @NotNull + @Override + default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Sync(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Async getAsyncTask(@NotNull Runnable runnable) { + return new Async(getPlugin(), runnable); + } + + @NotNull + @Override + default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { + return new Repeating(getPlugin(), runnable, repeatingTicks); + } + + @Override + default void cancelTasks() { + // Do nothing + } + + } + +} diff --git a/fabric/fabric-1.19.4/src/main/resources/assets/huskhomes/icon.png b/fabric/fabric-1.19.4/src/main/resources/assets/huskhomes/icon.png new file mode 100644 index 00000000..7c79c219 Binary files /dev/null and b/fabric/fabric-1.19.4/src/main/resources/assets/huskhomes/icon.png differ diff --git a/fabric/fabric-1.19.4/src/main/resources/fabric.mod.json b/fabric/fabric-1.19.4/src/main/resources/fabric.mod.json new file mode 100644 index 00000000..5c57dfef --- /dev/null +++ b/fabric/fabric-1.19.4/src/main/resources/fabric.mod.json @@ -0,0 +1,37 @@ +{ + "schemaVersion": 1, + "id": "huskhomes", + "version": "${version}", + "name": "HuskHomes", + "icon": "assets/huskhomes/icon.png", + "description": "${description}", + "authors": [ + { + "name": "William278", + "contact": { + "sources": "https://github.com/WiIIiam278/", + "homepage": "https://william278.net/" + } + } + ], + "license": "Apache-2.0", + "contact": { + "homepage": "https://william278.net/project/huskhomes/", + "repo": "https://github.com/WiIIiam278/HuskHomes", + "issues": "https://github.com/WiIIiam278/HuskHomes/issues" + }, + "environment": "server", + "entrypoints": { + "server": [ + "net.william278.huskhomes.FabricHuskHomes" + ] + }, + "depends": { + "fabricloader": ">=${fabric_loader_version}", + "minecraft": ">=${fabric_minecraft_version}", + "fabric-api": "*" + }, + "custom": { + "modmenu:api": true + } +} \ No newline at end of file diff --git a/fabric/fabric-1.20.1/build.gradle b/fabric/fabric-1.20.1/build.gradle new file mode 100644 index 00000000..ceae8a02 --- /dev/null +++ b/fabric/fabric-1.20.1/build.gradle @@ -0,0 +1,82 @@ +import org.apache.tools.ant.filters.ReplaceTokens + +plugins { + id 'fabric-loom' version "$fabric_loom_version" +} + +apply plugin: 'fabric-loom' +loom.serverOnlyMinecraftJar() + +// Get properties from local gradle.properties file +def properties = new Properties() +file("gradle.properties").withInputStream { properties.load(it) } + +dependencies { + minecraft "com.mojang:minecraft:${fabric_minecraft_version}" + mappings "net.fabricmc:yarn:${fabric_yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}" + + // Fabric API modules + Set fabricApiModules = [ + 'fabric-api-base', + 'fabric-lifecycle-events-v1', + 'fabric-entity-events-v1', + 'fabric-command-api-v2', + 'fabric-networking-api-v1' + ] + fabricApiModules.forEach { + modImplementation(fabricApi.module(it, fabric_api_version)) + } + modImplementation include("net.kyori:adventure-platform-fabric:${adventure_platform_fabric_version}") + modImplementation include('me.lucko:fabric-permissions-api:0.2-SNAPSHOT') + + implementation include('redis.clients:jedis:' + jedis_version) + implementation include('com.mysql:mysql-connector-j:' + mysql_driver_version) + implementation include('org.xerial:sqlite-jdbc:' + sqlite_driver_version) + + compileOnly 'org.jetbrains:annotations:24.0.1' + + shadow project(path: ":common") +} + +shadowJar { + configurations = [project.configurations.shadow] + destinationDirectory.set(file("$projectDir/build/libs")) + + exclude('net.fabricmc:.*') + exclude('net.kyori:.*') + exclude '/mappings/*' + + relocate 'org.apache.commons.io', 'net.william278.huskhomes.libraries.commons.io' + relocate 'org.apache.commons.text', 'net.william278.huskhomes.libraries.commons.text' + relocate 'org.apache.commons.lang3', 'net.william278.huskhomes.libraries.commons.lang3' + relocate 'de.themoep', 'net.william278.huskhomes.libraries' + relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' + relocate 'org.intellij', 'net.william278.huskhomes.libraries' + relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' + relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml' + relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' + relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' + relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml' + relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' + relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' +} + +processResources { + filesMatching(['**/*.json', '**/*.yml']) { + filter ReplaceTokens as Class, beginToken: '${', endToken: '}', + tokens: properties + } +} + +remapJar { + dependsOn tasks.shadowJar + mustRunAfter tasks.shadowJar + inputFile = shadowJar.archiveFile.get() + addNestedDependencies = true + + destinationDirectory.set(file("$rootDir/target/")) + archiveClassifier.set('') +} + +shadowJar.finalizedBy(remapJar) \ No newline at end of file diff --git a/fabric/fabric-1.20.1/gradle.properties b/fabric/fabric-1.20.1/gradle.properties new file mode 100644 index 00000000..32f6e0ce --- /dev/null +++ b/fabric/fabric-1.20.1/gradle.properties @@ -0,0 +1,6 @@ +fabric_minecraft_version=1.20.1 +fabric_loader_version=0.14.21 +fabric_yarn_mappings=1.20.1+build.2 +fabric_api_version=0.83.1+1.20.1 + +adventure_platform_fabric_version=5.9.0-SNAPSHOT \ No newline at end of file diff --git a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/FabricHuskHomes.java similarity index 94% rename from fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java rename to fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/FabricHuskHomes.java index 4e2ede8f..232a7903 100644 --- a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/FabricHuskHomes.java @@ -77,6 +77,7 @@ import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.stream.Collectors; @@ -84,15 +85,9 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler { public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes"); - private static FabricHuskHomes instance; - - @NotNull - public static FabricHuskHomes getInstance() { - return instance; - } - private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes") .orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); + private MinecraftServer minecraftServer; private Map permissions; private Set savedUsers; @@ -107,7 +102,7 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes private UnsafeBlocks unsafeBlocks; private List hooks; private List commands; - private Map> globalPlayerList; + private ConcurrentHashMap> globalPlayerList; private Set currentlyOnWarmup; private Server server; @Nullable @@ -116,13 +111,10 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes @Override public void onInitializeServer() { - // Set instance - instance = this; - // Get plugin version from mod container this.permissions = new HashMap<>(); this.savedUsers = new HashSet<>(); - this.globalPlayerList = new HashMap<>(); + this.globalPlayerList = new ConcurrentHashMap<>(); this.currentlyOnWarmup = new HashSet<>(); this.validator = new Validator(this); @@ -149,15 +141,14 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes // Temporarily log about sounds being disabled - todo: Remove when adventure-platform-fabric is updated if (getSettings().doPlaySoundEffects()) { - log(Level.WARNING, "Sound effects are currently disabled for HuskHomes v" + - getVersion() + " on Fabric servers running Minecraft " + - getMinecraftServer().getVersion()); + log(Level.WARNING, "Sound effects are currently disabled for HuskHomes v" + getVersion() + + " on Fabric servers running Minecraft " + getMinecraftServer().getVersion()); } // Initialize the database initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { this.database = switch (getSettings().getDatabaseType()) { - case MYSQL -> new MySqlDatabase(this); + case MYSQL, MARIADB -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); }; @@ -231,7 +222,7 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes @NotNull public List getOnlineUsers() { return minecraftServer.getPlayerManager().getPlayerList() - .stream().map(user -> (OnlineUser) FabricUser.adapt(this, user)) + .stream().map(user -> (OnlineUser) FabricUser.adapt(user, this)) .toList(); } @@ -273,6 +264,27 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes this.serverSpawn = spawn; } + @Override + public void setServerSpawn(@NotNull Location location) { + try { + // Create or update the spawn.yml file + final File spawnFile = new File(getDataFolder(), "spawn.yml"); + if (spawnFile.exists() && !spawnFile.delete()) { + log(Level.WARNING, "Failed to delete the existing spawn.yml file"); + } + this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get(); + + // Update the world spawn location, too + minecraftServer.getWorlds().forEach(world -> { + if (world.getRegistryKey().getValue().asString().equals(location.getWorld().getName())) { + world.setSpawnPos(BlockPos.ofFloored(location.getX(), location.getY(), location.getZ()), 0); + } + }); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + log(Level.WARNING, "Failed to save the server spawn.yml file", e); + } + } + @Override @NotNull public String getServerName() { @@ -333,27 +345,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes this.randomTeleportEngine = randomTeleportEngine; } - @Override - public void setServerSpawn(@NotNull Location location) { - try { - // Create or update the spawn.yml file - final File spawnFile = new File(getDataFolder(), "spawn.yml"); - if (spawnFile.exists() && !spawnFile.delete()) { - log(Level.WARNING, "Failed to delete the existing spawn.yml file"); - } - this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get(); - - // Update the world spawn location, too - minecraftServer.getWorlds().forEach(world -> { - if (world.getRegistryKey().getValue().asString().equals(location.getWorld().getName())) { - world.setSpawnPos(BlockPos.ofFloored(location.getX(), location.getY(), location.getZ()), 0); - } - }); - } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { - log(Level.WARNING, "Failed to save the server spawn.yml file", e); - } - } - @Override @NotNull public List getHooks() { @@ -411,14 +402,9 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes @NotNull public List registerCommands() { - final List commands = Arrays.stream(FabricCommand.Type.values()) - .map(FabricCommand.Type::getCommand) - .filter(command -> !settings.isCommandDisabled(command)) - .toList(); - + final List commands = FabricCommand.Type.getCommands(getPlugin()); CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) -> commands.forEach(command -> new FabricCommand(command, this).register(dispatcher))); - return commands; } @@ -454,10 +440,11 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes public void receive(@NotNull MinecraftServer server, @NotNull ServerPlayerEntity player, @NotNull ServerPlayNetworkHandler handler, @NotNull PacketByteBuf buf, @NotNull PacketSender responseSender) { - if (broker instanceof PluginMessageBroker messenger && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + if (broker instanceof PluginMessageBroker messenger + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { messenger.onReceive( PluginMessageBroker.BUNGEE_CHANNEL_ID, - FabricUser.adapt(this, player), + FabricUser.adapt(player, this), ByteBufUtil.getBytes(buf) ); } diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/command/FabricCommand.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/command/FabricCommand.java new file mode 100644 index 00000000..cb34e143 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/command/FabricCommand.java @@ -0,0 +1,181 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.command; + +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.tree.LiteralCommandNode; +import me.lucko.fabric.api.permissions.v0.PermissionCheckEvent; +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.network.ServerPlayerEntity; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.FabricUser; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; + +import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; +import static net.minecraft.server.command.CommandManager.argument; +import static net.minecraft.server.command.CommandManager.literal; + +public class FabricCommand { + + private final FabricHuskHomes plugin; + private final Command command; + + public FabricCommand(@NotNull Command command, @NotNull FabricHuskHomes plugin) { + this.command = command; + this.plugin = plugin; + } + + public void register(@NotNull CommandDispatcher dispatcher) { + // Register brigadier command + final Predicate predicate = Permissions + .require(command.getPermission(), command.isOperatorCommand() ? 3 : 0); + final LiteralArgumentBuilder builder = literal(command.getName()) + .requires(predicate).executes(getBrigadierExecutor()); + plugin.getPermissions().put(command.getPermission(), command.isOperatorCommand()); + if (!command.getRawUsage().isBlank()) { + builder.then(argument(command.getRawUsage().replaceAll("[<>\\[\\]]", ""), greedyString()) + .executes(getBrigadierExecutor()) + .suggests(getBrigadierSuggester())); + } + + // Register additional permissions + final Map permissions = command.getAdditionalPermissions(); + permissions.forEach((permission, isOp) -> plugin.getPermissions().put(permission, isOp)); + PermissionCheckEvent.EVENT.register((player, node) -> { + if (permissions.containsKey(node) && permissions.get(node) && player.hasPermissionLevel(3)) { + return TriState.TRUE; + } + return TriState.DEFAULT; + }); + + // Register aliases + final LiteralCommandNode node = dispatcher.register(builder); + dispatcher.register(literal("huskhomes:" + command.getName()) + .requires(predicate).executes(getBrigadierExecutor()).redirect(node)); + command.getAliases().forEach(alias -> dispatcher.register(literal(alias) + .requires(predicate).executes(getBrigadierExecutor()).redirect(node))); + } + + private com.mojang.brigadier.Command getBrigadierExecutor() { + return (context) -> { + command.onExecuted( + resolveExecutor(context.getSource()), + command.removeFirstArg(context.getInput().split(" ")) + ); + return 1; + }; + } + + private com.mojang.brigadier.suggestion.SuggestionProvider getBrigadierSuggester() { + if (!(command instanceof TabProvider provider)) { + return (context, builder) -> com.mojang.brigadier.suggestion.Suggestions.empty(); + } + return (context, builder) -> { + final String[] args = command.removeFirstArg(context.getInput().split(" ")); + provider.getSuggestions(resolveExecutor(context.getSource()), args).stream() + .map(suggestion -> { + final String completedArgs = String.join(" ", args); + int lastIndex = completedArgs.lastIndexOf(" "); + if (lastIndex == -1) { + return suggestion; + } + return completedArgs.substring(0, lastIndex + 1) + suggestion; + }) + .forEach(builder::suggest); + return builder.buildFuture(); + }; + } + + private CommandUser resolveExecutor(@NotNull ServerCommandSource source) { + if (source.getEntity() instanceof ServerPlayerEntity player) { + return FabricUser.adapt(player, plugin); + } + return plugin.getConsole(); + } + + + /** + * Commands available on the Fabric HuskHomes implementation. + */ + public enum Type { + HOME_COMMAND(PrivateHomeCommand::new), + SET_HOME_COMMAND(SetHomeCommand::new), + HOME_LIST_COMMAND(PrivateHomeListCommand::new), + DEL_HOME_COMMAND(DelHomeCommand::new), + EDIT_HOME_COMMAND(EditHomeCommand::new), + PUBLIC_HOME_COMMAND(PublicHomeCommand::new), + PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), + WARP_COMMAND(WarpCommand::new), + SET_WARP_COMMAND(SetWarpCommand::new), + WARP_LIST_COMMAND(WarpListCommand::new), + DEL_WARP_COMMAND(DelWarpCommand::new), + EDIT_WARP_COMMAND(EditWarpCommand::new), + TP_COMMAND(TpCommand::new), + TP_HERE_COMMAND(TpHereCommand::new), + TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), + TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), + TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), + TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), + RTP_COMMAND(RtpCommand::new), + TP_IGNORE_COMMAND(TpIgnoreCommand::new), + TP_OFFLINE_COMMAND(TpOfflineCommand::new), + TP_ALL_COMMAND(TpAllCommand::new), + TPA_ALL_COMMAND(TpaAllCommand::new), + SPAWN_COMMAND(SpawnCommand::new), + SET_SPAWN_COMMAND(SetSpawnCommand::new), + BACK_COMMAND(BackCommand::new), + HUSKHOMES_COMMAND(HuskHomesCommand::new); + + private final Function supplier; + + Type(@NotNull Function supplier) { + this.supplier = supplier; + } + + @NotNull + public Command createCommand(@NotNull HuskHomes plugin) { + return supplier.apply(plugin); + } + + @NotNull + public static List getCommands(@NotNull FabricHuskHomes plugin) { + return Arrays.stream(values()) + .map(type -> type.createCommand(plugin)) + .map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command) + .filter(Objects::nonNull) + .toList(); + } + + } + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java new file mode 100644 index 00000000..f84f238d --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/DeleteAllHomesCallback.java @@ -0,0 +1,82 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface DeleteAllHomesCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(DeleteAllHomesCallback.class, + (listeners) -> (event) -> { + for (DeleteAllHomesCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (owner, deleter) -> + new IDeleteAllHomesEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public User getHomeOwner() { + return owner; + } + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java new file mode 100644 index 00000000..78945be9 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsCallback.java @@ -0,0 +1,75 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public interface DeleteAllWarpsCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(DeleteAllWarpsCallback.class, + (listeners) -> (event) -> { + for (DeleteAllWarpsCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + Function SUPPLIER = (deleter) -> + new IDeleteAllWarpsEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java new file mode 100644 index 00000000..ef0c3a7f --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/FabricEventCallback.java @@ -0,0 +1,31 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.minecraft.util.ActionResult; +import org.jetbrains.annotations.NotNull; + +public interface FabricEventCallback { + + @NotNull + ActionResult invoke(@NotNull E event); + + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java new file mode 100644 index 00000000..21300067 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/FabricEventDispatcher.java @@ -0,0 +1,146 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.teleport.TimedTeleport; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.logging.Level; + +public interface FabricEventDispatcher extends EventDispatcher { + + @SuppressWarnings("unchecked") + @Override + default boolean fireIsCancelled(@NotNull T event) { + try { + final Method field = event.getClass().getDeclaredMethod("getEvent"); + field.setAccessible(true); + + net.fabricmc.fabric.api.event.Event fabricEvent = + (net.fabricmc.fabric.api.event.Event) field.invoke(event); + + final FabricEventCallback invoker = (FabricEventCallback) fabricEvent.invoker(); + return invoker.invoke(event) == ActionResult.FAIL; + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { + getPlugin().log(Level.WARNING, "Failed to fire event (" + event.getClass().getName() + ")", e); + return false; + } + } + + @Override + @NotNull + default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { + return TeleportCallback.SUPPLIER.apply(teleport); + } + + @Override + default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { + return TeleportWarmupCallback.SUPPLIER.apply(teleport, duration); + } + + @Override + default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, + @NotNull TeleportRequest request) { + return SendTeleportRequestCallback.SUPPLIER.apply(sender, request); + } + + @Override + default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { + return ReceiveTeleportRequestCallback.SUPPLIER.apply(recipient, request); + } + + @Override + default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { + return ReplyTeleportRequestCallback.SUPPLIER.apply(recipient, request); + } + + @Override + default @NotNull IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, + @NotNull Position position, @NotNull CommandUser creator) { + return HomeCreateCallback.SUPPLIER.apply(owner, name, position, creator); + } + + @Override + default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { + return HomeEditCallback.SUPPLIER.apply(home, editor); + } + + @Override + default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { + return HomeDeleteCallback.SUPPLIER.apply(home, deleter); + } + + @Override + default @NotNull IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, + @NotNull CommandUser creator) { + return WarpCreateCallback.SUPPLIER.apply(name, position, creator); + } + + @Override + default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { + return WarpEditCallback.SUPPLIER.apply(warp, editor); + } + + @Override + default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { + return WarpDeleteCallback.SUPPLIER.apply(warp, deleter); + } + + @Override + default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, + boolean publicHomeList) { + return HomeListCallback.SUPPLIER.apply(homes, listViewer, publicHomeList); + } + + @Override + default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { + return WarpListCallback.SUPPLIER.apply(homes, listViewer); + } + + @Override + default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { + return DeleteAllHomesCallback.SUPPLIER.apply(user, deleter); + } + + @Override + default @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { + return DeleteAllWarpsCallback.SUPPLIER.apply(deleter); + } + + @Override + @NotNull + FabricHuskHomes getPlugin(); + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java new file mode 100644 index 00000000..026ad4b3 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeCreateCallback.java @@ -0,0 +1,103 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.data.client.BlockStateVariantMap.QuadFunction; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; + +public interface HomeCreateCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeCreateCallback.class, + (listeners) -> (event) -> { + for (HomeCreateCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + QuadFunction SUPPLIER = (user, name, position, creator) -> + new IHomeCreateEvent() { + private boolean cancelled = false; + private String homeName = name; + + @Override + @NotNull + public User getOwner() { + return user; + } + + @Override + @NotNull + public String getName() { + return homeName; + } + + @Override + public void setName(@NotNull String name) { + this.homeName = name; + } + + @Override + @NotNull + public Position getPosition() { + return position; + } + + @Override + public void setPosition(@NotNull Position position) { + } + + @Override + public @NotNull CommandUser getCreator() { + return creator; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java new file mode 100644 index 00000000..0f479589 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeDeleteCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface HomeDeleteCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeDeleteCallback.class, + (listeners) -> (event) -> { + for (HomeDeleteCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (home, deleter) -> + new IHomeDeleteEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Home getHome() { + return home; + } + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java new file mode 100644 index 00000000..3b28f749 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeEditCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface HomeEditCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeEditCallback.class, + (listeners) -> (event) -> { + for (HomeEditCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (home, editor) -> + new IHomeEditEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Home getHome() { + return home; + } + + @Override + @NotNull + public CommandUser getEditor() { + return editor; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeListCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeListCallback.java new file mode 100644 index 00000000..e89d5cb6 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/HomeListCallback.java @@ -0,0 +1,95 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; +import org.apache.commons.lang3.function.TriFunction; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public interface HomeListCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(HomeListCallback.class, + (listeners) -> (event) -> { + for (HomeListCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + TriFunction, CommandUser, Boolean, IHomeListEvent> SUPPLIER = (homes, viewer, publicHomes) -> + new IHomeListEvent() { + private boolean cancelled = false; + private List listHomes = homes; + + @Override + @NotNull + public List getHomes() { + return listHomes; + } + + @Override + public void setHomes(@NotNull List homes) { + this.listHomes = homes; + } + + @Override + @NotNull + public CommandUser getListViewer() { + return viewer; + } + + @Override + public boolean getIsPublicHomeList() { + return publicHomes; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java new file mode 100644 index 00000000..a0b4da5a --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/ReceiveTeleportRequestCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface ReceiveTeleportRequestCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(ReceiveTeleportRequestCallback.class, + (listeners) -> (event) -> { + for (ReceiveTeleportRequestCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (recipient, request) -> + new IReceiveTeleportRequestEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public OnlineUser getRecipient() { + return recipient; + } + + @Override + @NotNull + public TeleportRequest getRequest() { + return request; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java new file mode 100644 index 00000000..85dcddb8 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/ReplyTeleportRequestCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface ReplyTeleportRequestCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(ReplyTeleportRequestCallback.class, + (listeners) -> (event) -> { + for (ReplyTeleportRequestCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (recipient, request) -> + new IReplyTeleportRequestEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public OnlineUser getRecipient() { + return recipient; + } + + @Override + @NotNull + public TeleportRequest getRequest() { + return request; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java new file mode 100644 index 00000000..d7fd6505 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/SendTeleportRequestCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface SendTeleportRequestCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(SendTeleportRequestCallback.class, + (listeners) -> (event) -> { + for (SendTeleportRequestCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (sender, request) -> + new ISendTeleportRequestEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public OnlineUser getSender() { + return sender; + } + + @Override + @NotNull + public TeleportRequest getRequest() { + return request; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java new file mode 100644 index 00000000..90a153c6 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportBackCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.teleport.Teleport; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public interface TeleportBackCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(TeleportBackCallback.class, + (listeners) -> (event) -> { + for (TeleportBackCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.FAIL; + } else if (result == ActionResult.FAIL) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + Function SUPPLIER = (teleport) -> + new ITeleportBackEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Position getLastPosition() { + return (Position) getTeleport().getTarget(); + } + + @Override + @NotNull + public Teleport getTeleport() { + return teleport; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportCallback.java new file mode 100644 index 00000000..99a7cc6b --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportCallback.java @@ -0,0 +1,76 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.Teleport; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public interface TeleportCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(TeleportCallback.class, + (listeners) -> (event) -> { + for (TeleportCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.FAIL; + } else if (result == ActionResult.FAIL) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + Function SUPPLIER = (teleport) -> + new ITeleportEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Teleport getTeleport() { + return teleport; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java new file mode 100644 index 00000000..c9d6961c --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/TeleportWarmupCallback.java @@ -0,0 +1,79 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.teleport.TimedTeleport; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface TeleportWarmupCallback extends FabricEventCallback { + @NotNull + Event EVENT = EventFactory.createArrayBacked(TeleportWarmupCallback.class, + (listeners) -> (event) -> { + for (TeleportWarmupCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.FAIL; + } else if (result == ActionResult.FAIL) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (timedTeleport, duration) -> + new ITeleportWarmupEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public TimedTeleport getTimedTeleport() { + return timedTeleport; + } + + @Override + public int getWarmupDuration() { + return duration; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java new file mode 100644 index 00000000..78b69dc9 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpCreateCallback.java @@ -0,0 +1,98 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.user.CommandUser; +import org.apache.commons.lang3.function.TriFunction; +import org.jetbrains.annotations.NotNull; + +public interface WarpCreateCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpCreateCallback.class, + (listeners) -> (event) -> { + for (WarpCreateCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + TriFunction SUPPLIER = (name, position, creator) -> + new IWarpCreateEvent() { + private boolean cancelled = false; + private String homeName = name; + + @Override + @NotNull + public String getName() { + return homeName; + } + + @Override + public void setName(@NotNull String name) { + this.homeName = name; + } + + @Override + @NotNull + public Position getPosition() { + return position; + } + + @Override + public void setPosition(@NotNull Position position) { + } + + @Override + @NotNull + public CommandUser getCreator() { + return creator; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java new file mode 100644 index 00000000..cbba72ea --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpDeleteCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface WarpDeleteCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpDeleteCallback.class, + (listeners) -> (event) -> { + for (WarpDeleteCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (warp, deleter) -> + new IWarpDeleteEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Warp getWarp() { + return warp; + } + + @Override + @NotNull + public CommandUser getDeleter() { + return deleter; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java new file mode 100644 index 00000000..d3291d91 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpEditCallback.java @@ -0,0 +1,83 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.function.BiFunction; + +public interface WarpEditCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpEditCallback.class, + (listeners) -> (event) -> { + for (WarpEditCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction SUPPLIER = (warp, editor) -> + new IWarpEditEvent() { + private boolean cancelled = false; + + @Override + @NotNull + public Warp getWarp() { + return warp; + } + + @Override + @NotNull + public CommandUser getEditor() { + return editor; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpListCallback.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpListCallback.java new file mode 100644 index 00000000..21f2a55f --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/event/WarpListCallback.java @@ -0,0 +1,90 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.util.ActionResult; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.function.BiFunction; + +public interface WarpListCallback extends FabricEventCallback { + + @NotNull + Event EVENT = EventFactory.createArrayBacked(WarpListCallback.class, + (listeners) -> (event) -> { + for (WarpListCallback listener : listeners) { + final ActionResult result = listener.invoke(event); + if (event.isCancelled()) { + return ActionResult.CONSUME; + } else if (result != ActionResult.PASS) { + event.setCancelled(true); + return result; + } + } + + return ActionResult.PASS; + }); + + @NotNull + BiFunction, CommandUser, IWarpListEvent> SUPPLIER = (warps, viewer) -> + new IWarpListEvent() { + private boolean cancelled = false; + private List listWarps = warps; + + @Override + @NotNull + public List getWarps() { + return listWarps; + } + + @Override + public void setWarps(@NotNull List homes) { + this.listWarps = homes; + } + + @Override + @NotNull + public CommandUser getListViewer() { + return viewer; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @NotNull + public Event getEvent() { + return EVENT; + } + + }; + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java new file mode 100644 index 00000000..ba97ce55 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java @@ -0,0 +1,64 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.listener; + +import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; +import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents; +import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; +import net.minecraft.server.network.ServerPlayerEntity; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.user.FabricUser; +import org.jetbrains.annotations.NotNull; + +// Note that the teleport event and update player respawn position events are not handled on Fabric. +// The "update last position on teleport event" and "global respawn" features are not supported on Fabric. +public class FabricEventListener extends EventListener { + + public FabricEventListener(@NotNull FabricHuskHomes plugin) { + super(plugin); + this.registerEvents(plugin); + } + + // Register fabric event callback listeners to internal handlers + private void registerEvents(@NotNull FabricHuskHomes plugin) { + // Join event + ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> handlePlayerJoin( + FabricUser.adapt(handler.player, plugin) + )); + + // Quit event + ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> handlePlayerLeave( + FabricUser.adapt(handler.player, plugin) + )); + + // Death event + ServerLivingEntityEvents.AFTER_DEATH.register((entity, source) -> { + if (entity instanceof ServerPlayerEntity player) { + handlePlayerDeath(FabricUser.adapt(player, plugin)); + } + }); + + // Respawn event + ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> handlePlayerRespawn( + FabricUser.adapt(newPlayer, plugin) + )); + } + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/user/FabricUser.java similarity index 93% rename from fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java rename to fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/user/FabricUser.java index 668f2419..4e772256 100644 --- a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -38,18 +38,19 @@ import org.jetbrains.annotations.NotNull; import java.util.*; public class FabricUser extends OnlineUser { + private final FabricHuskHomes plugin; private final ServerPlayerEntity player; - private FabricUser(@NotNull FabricHuskHomes plugin, @NotNull ServerPlayerEntity player) { + private FabricUser(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { super(player.getUuid(), player.getEntityName()); - this.plugin = plugin; this.player = player; + this.plugin = plugin; } @NotNull - public static FabricUser adapt(@NotNull FabricHuskHomes plugin, @NotNull ServerPlayerEntity player) { - return new FabricUser(plugin, player); + public static FabricUser adapt(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { + return new FabricUser(player, plugin); } @Override @@ -126,14 +127,14 @@ public class FabricUser extends OnlineUser { } @Override - public void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException { + public void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException { final MinecraftServer server = player.getServer(); assert server != null : "Server is null"; final Identifier worldId = Identifier.tryParse(location.getWorld().getName()); player.teleport( server.getWorld(server.getWorldRegistryKeys().stream() - .filter(key -> key.getValue().equals(worldId)).findFirst() - .orElseThrow(() -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND, plugin)) + .filter(key -> key.getValue().equals(worldId)).findFirst().orElseThrow( + () -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND, plugin)) ), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch() diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java new file mode 100644 index 00000000..15eb62ef --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java @@ -0,0 +1,129 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.util; + +import net.minecraft.block.Block; +import net.minecraft.block.FireBlock; +import net.minecraft.block.FluidBlock; +import net.minecraft.registry.Registries; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; +import net.minecraft.world.BlockView; +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.position.Location; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +public interface FabricSafetyResolver extends SafetyResolver { + + @Override + default CompletableFuture> findSafeGroundLocation(@NotNull Location location) { + final MinecraftServer server = ((FabricHuskHomes) getPlugin()).getMinecraftServer(); + final Identifier worldId = Identifier.tryParse(location.getWorld().getName()); + + // Ensure the location is on a valid world + final Optional locationWorld = server.getWorldRegistryKeys().stream() + .filter(key -> key.getValue().equals(worldId)).findFirst() + .map(server::getWorld); + if (locationWorld.isEmpty()) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + // Ensure the location is within the world border + final ServerWorld world = locationWorld.get(); + if (!world.getWorldBorder().contains(location.getX(), location.getZ())) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + return CompletableFuture.completedFuture(findSafeLocationNear(location, world)); + } + + /** + * Search for a safe ground location near the given location. + * + * @param location The location to search around + * @return An optional safe location, within 4 blocks of the given location + */ + private Optional findSafeLocationNear(@NotNull Location location, @NotNull ServerWorld world) { + final BlockPos.Mutable blockPos = new BlockPos.Mutable(location.getX(), location.getY(), location.getZ()); + for (int x = -SEARCH_RADIUS; x <= SEARCH_RADIUS; x++) { + for (int z = -SEARCH_RADIUS; z <= SEARCH_RADIUS; z++) { + blockPos.set(location.getX() + x, location.getY(), location.getZ() + z); + final int highestY = getHighestYAt(world, blockPos.getX(), blockPos.getY(), blockPos.getZ()) + 1; + + final Block block = world.getBlockState(blockPos.withY(highestY - 1)).getBlock(); + final Identifier id = Registries.BLOCK.getId(block); + + final Block bodyBlockType = world.getBlockState(blockPos.withY(highestY)).getBlock(); + final Identifier bodyBlockId = Registries.BLOCK.getId(bodyBlockType); + + final Block headBlockType = world.getBlockState(blockPos.withY(highestY + 1)).getBlock(); + final Identifier headBlockId = Registries.BLOCK.getId(headBlockType); + + if (!(block instanceof FluidBlock) && !(block instanceof FireBlock) + && isBlockSafeForStanding(id.toString()) && isBlockSafeForOccupation(bodyBlockId.toString()) + && isBlockSafeForOccupation(headBlockId.toString())) { + double locx = blockPos.getX(); + if (locx < 0) { + locx += 1.5d; + } else { + locx = locx + 0.5d; + } + double locz = blockPos.getZ(); + if (locz < 0) { + locz += 1.5d; + } else { + locz = locz + 0.5d; + } + return Optional.of(Location.at( + locx, + highestY, + locz, + location.getWorld() + )); + } + } + } + return Optional.empty(); + } + + /** + * Get the highest Y value at the given X and Z coordinates. + * + * @param blockView The block view to search + * @param x The X coordinate + * @param y The Y coordinate + * @param z The Z coordinate + * @return The highest Y value at the given X and Z coordinates + */ + private int getHighestYAt(@NotNull BlockView blockView, int x, int y, int z) { + final BlockPos.Mutable cursor = new BlockPos.Mutable(x, y, z); + while (blockView.getBlockState(cursor).isAir() && cursor.getY() > blockView.getBottomY()) { + cursor.move(Direction.DOWN); + } + return cursor.getY(); + } + +} diff --git a/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/util/FabricTask.java b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/util/FabricTask.java new file mode 100644 index 00000000..70b9efe8 --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/java/net/william278/huskhomes/util/FabricTask.java @@ -0,0 +1,142 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.util; + +import net.william278.huskhomes.FabricHuskHomes; +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public interface FabricTask extends Task { + + class Sync extends Task.Sync implements FabricTask { + + protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + if (delayTicks > 0) { + CompletableFuture.runAsync(() -> { + + try { + Thread.sleep(delayTicks * 50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + ((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable); + + }, ((FabricHuskHomes) getPlugin()).getMinecraftServer()); + } else { + ((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable); + } + } + } + } + + class Async extends Task.Async implements FabricTask { + private CompletableFuture task; + + protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + super(plugin, runnable); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(true); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = CompletableFuture.runAsync(runnable, ((FabricHuskHomes) getPlugin()).getMinecraftServer()); + } + } + } + + class Repeating extends Task.Repeating implements FabricTask { + + private ScheduledFuture task; + + protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable, repeatingTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(true); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate( + runnable, 0, repeatingTicks * 50, TimeUnit.MILLISECONDS + ); + } + } + } + + interface Supplier extends Task.Supplier { + + @NotNull + @Override + default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Sync(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Async getAsyncTask(@NotNull Runnable runnable) { + return new Async(getPlugin(), runnable); + } + + @NotNull + @Override + default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { + return new Repeating(getPlugin(), runnable, repeatingTicks); + } + + @Override + default void cancelTasks() { + // Do nothing + } + + } + +} diff --git a/fabric/fabric-1.20.1/src/main/resources/assets/huskhomes/icon.png b/fabric/fabric-1.20.1/src/main/resources/assets/huskhomes/icon.png new file mode 100644 index 00000000..7c79c219 Binary files /dev/null and b/fabric/fabric-1.20.1/src/main/resources/assets/huskhomes/icon.png differ diff --git a/fabric/fabric-1.20.1/src/main/resources/fabric.mod.json b/fabric/fabric-1.20.1/src/main/resources/fabric.mod.json new file mode 100644 index 00000000..5c57dfef --- /dev/null +++ b/fabric/fabric-1.20.1/src/main/resources/fabric.mod.json @@ -0,0 +1,37 @@ +{ + "schemaVersion": 1, + "id": "huskhomes", + "version": "${version}", + "name": "HuskHomes", + "icon": "assets/huskhomes/icon.png", + "description": "${description}", + "authors": [ + { + "name": "William278", + "contact": { + "sources": "https://github.com/WiIIiam278/", + "homepage": "https://william278.net/" + } + } + ], + "license": "Apache-2.0", + "contact": { + "homepage": "https://william278.net/project/huskhomes/", + "repo": "https://github.com/WiIIiam278/HuskHomes", + "issues": "https://github.com/WiIIiam278/HuskHomes/issues" + }, + "environment": "server", + "entrypoints": { + "server": [ + "net.william278.huskhomes.FabricHuskHomes" + ] + }, + "depends": { + "fabricloader": ">=${fabric_loader_version}", + "minecraft": ">=${fabric_minecraft_version}", + "fabric-api": "*" + }, + "custom": { + "modmenu:api": true + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index b350cace..8084dcf9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ javaVersion=16 org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.daemon=true -plugin_version=4.4.1 +plugin_version=4.4.2 plugin_archive=huskhomes plugin_description=The powerful and intuitive homes, warps, and teleports plugin/mod @@ -11,7 +11,4 @@ jedis_version=4.4.2 sqlite_driver_version=3.42.0.0 mysql_driver_version=8.0.33 -fabric_minecraft_version=1.20.1 -fabric_loader_version=0.14.21 -fabric_yarn_mappings=1.20.1+build.2 -fabric_api_version=0.83.1+1.20.1 \ No newline at end of file +fabric_loom_version=1.3-SNAPSHOT \ No newline at end of file diff --git a/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java b/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java index c0471c2e..318ad74d 100644 --- a/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java +++ b/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java @@ -21,14 +21,13 @@ package net.william278.huskhomes; import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.Command; +import net.william278.huskhomes.command.DisabledCommand; import net.william278.huskhomes.command.PaperCommand; import net.william278.huskhomes.hook.Pl3xMapHook; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; public class PaperHuskHomes extends BukkitHuskHomes { @@ -45,16 +44,16 @@ public class PaperHuskHomes extends BukkitHuskHomes { @Override public List registerCommands() { return Arrays.stream(BukkitCommand.Type.values()) - .map(type -> { - final Command command = type.getCommand(); - if (!getSettings().isCommandDisabled(command)) { - new PaperCommand(command, this).register(); - return command; + .map((type) -> { + Command command = type.createCommand(this); + if (this.getSettings().isCommandDisabled(command)) { + command = new DisabledCommand(command.getName(), this); } - return null; + new PaperCommand(command, this).register(); + return command; }) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + .filter((command) -> !(command instanceof DisabledCommand)) + .toList(); } } diff --git a/paper/src/main/java/net/william278/huskhomes/PaperHuskHomesLoader.java b/paper/src/main/java/net/william278/huskhomes/PaperHuskHomesLoader.java index 94b9557c..e0c40930 100644 --- a/paper/src/main/java/net/william278/huskhomes/PaperHuskHomesLoader.java +++ b/paper/src/main/java/net/william278/huskhomes/PaperHuskHomesLoader.java @@ -29,6 +29,7 @@ import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.repository.RemoteRepository; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.InputStream; import java.util.List; @@ -53,7 +54,7 @@ public class PaperHuskHomesLoader implements PluginLoader { @NotNull private static List resolveLibraries(@NotNull PluginClasspathBuilder classpathBuilder) { - try (InputStream input = PaperHuskHomesLoader.class.getClassLoader().getResourceAsStream("paper-libraries.yml")) { + try (InputStream input = getLibraryListFile()) { return Annotaml.create(PaperLibraries.class, Objects.requireNonNull(input)).get().libraries; } catch (Exception e) { e.printStackTrace(); @@ -61,6 +62,11 @@ public class PaperHuskHomesLoader implements PluginLoader { return List.of(); } + @Nullable + private static InputStream getLibraryListFile() { + return PaperHuskHomesLoader.class.getClassLoader().getResourceAsStream("paper-libraries.yml"); + } + @YamlFile(header = "Dependencies for HuskHomes on Paper") public static class PaperLibraries { diff --git a/paper/src/main/java/net/william278/huskhomes/command/PaperCommand.java b/paper/src/main/java/net/william278/huskhomes/command/PaperCommand.java index e7006f98..afa1a727 100644 --- a/paper/src/main/java/net/william278/huskhomes/command/PaperCommand.java +++ b/paper/src/main/java/net/william278/huskhomes/command/PaperCommand.java @@ -45,17 +45,18 @@ public class PaperCommand extends org.bukkit.command.Command { @Override public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @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; } @NotNull @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { + public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, + @NotNull String[] args) throws IllegalArgumentException { if (!(this.command instanceof TabProvider provider)) { 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); } @@ -64,15 +65,30 @@ public class PaperCommand extends org.bukkit.command.Command { plugin.getServer().getCommandMap().register("huskhomes", this); // Register permissions - BukkitCommand.addPermission(plugin, command.getPermission(), command.getUsage(), BukkitCommand.getPermissionDefault(command.isOperatorCommand())); + BukkitCommand.addPermission( + plugin, + command.getPermission(), + command.getUsage(), + BukkitCommand.getPermissionDefault(command.isOperatorCommand()) + ); final List childNodes = command.getAdditionalPermissions() .entrySet().stream() - .map((entry) -> BukkitCommand.addPermission(plugin, entry.getKey(), "", BukkitCommand.getPermissionDefault(entry.getValue()))) + .map((entry) -> BukkitCommand.addPermission( + plugin, + entry.getKey(), + "", + BukkitCommand.getPermissionDefault(entry.getValue())) + ) .filter(Objects::nonNull) .toList(); if (!childNodes.isEmpty()) { - BukkitCommand.addPermission(plugin, command.getPermission("*"), command.getUsage(), PermissionDefault.FALSE, - childNodes.toArray(new Permission[0])); + BukkitCommand.addPermission( + plugin, + command.getPermission("*"), + command.getUsage(), + PermissionDefault.FALSE, + childNodes.toArray(new Permission[0]) + ); } // Register commodore TAB completion diff --git a/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java b/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java index 20eaf26a..a55fb51b 100644 --- a/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java +++ b/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java @@ -32,23 +32,27 @@ import org.jetbrains.annotations.NotNull; public class PaperEventListener extends BukkitEventListener implements Listener { - public PaperEventListener(@NotNull PaperHuskHomes huskHomes) { - super(huskHomes); + public PaperEventListener(@NotNull PaperHuskHomes plugin) { + super(plugin); this.checkForBed = false; - huskHomes.getServer().getPluginManager().registerEvents(this, huskHomes); + plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerUpdateRespawnLocation(PlayerSetSpawnEvent event) { - if (!(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) return; + if (!(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) { + return; + } // Ensure the updated location is correct final Location location = event.getLocation(); - if (location == null) return; + if (location == null) { + return; + } // Update the player's respawn location BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> super.handlePlayerUpdateSpawnPoint( - BukkitUser.adapt(event.getPlayer()), + BukkitUser.adapt(event.getPlayer(), (PaperHuskHomes) plugin), Position.at(adaptedLocation, plugin.getServerName())) ); } diff --git a/settings.gradle b/settings.gradle index 13701c52..75b5cbe0 100644 --- a/settings.gradle +++ b/settings.gradle @@ -8,9 +8,17 @@ pluginManagement { rootProject.name = 'HuskHomes' include( 'common', + + // Paper/Spigot 'bukkit', 'paper', 'plugin', - 'fabric', - 'sponge' + + // Fabric + 'fabric:fabric-1.19.2', + 'fabric:fabric-1.19.4', + 'fabric:fabric-1.20.1', + + // Sponge + 'sponge:sponge-api8' ) \ No newline at end of file diff --git a/sponge/build.gradle b/sponge/sponge-api8/build.gradle similarity index 100% rename from sponge/build.gradle rename to sponge/sponge-api8/build.gradle diff --git a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java similarity index 92% rename from sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java index f5b85568..47260588 100644 --- a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java @@ -93,13 +93,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa private static final int METRICS_ID = 18423; private static final ResourceKey PLUGIN_MESSAGE_CHANNEL_KEY = ResourceKey.of("bungeecord", "main"); - // Instance of the plugin - private static SpongeHuskHomes instance; - - public static SpongeHuskHomes getInstance() { - return instance; - } - @Inject @ConfigDir(sharedRoot = false) private Path pluginDirectory; @@ -130,8 +123,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa @Listener public void onConstructPlugin(final ConstructPluginEvent event) { - instance = this; - // Get plugin version from mod container this.savedUsers = new HashSet<>(); this.globalPlayerList = new HashMap<>(); @@ -148,7 +139,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa // Initialize the database initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { this.database = switch (getSettings().getDatabaseType()) { - case MYSQL -> new MySqlDatabase(this); + case MYSQL, MARIADB -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); }; @@ -232,7 +223,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa @Override public List getOnlineUsers() { return game.server().onlinePlayers().stream() - .map(SpongeUser::adapt) + .map(user -> SpongeUser.adapt(user, this)) .collect(Collectors.toList()); } @@ -274,6 +265,29 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa this.serverSpawn = spawn; } + @Override + public void setServerSpawn(@NotNull Location location) { + try { + // Create or update the spawn.yml file + final File spawnFile = new File(getDataFolder(), "spawn.yml"); + if (spawnFile.exists() && !spawnFile.delete()) { + log(Level.WARNING, "Failed to delete the existing spawn.yml file"); + } + this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get(); + + // Update the world spawn location, too + game.server().worldManager().worlds().forEach(world -> { + if (world.properties().key().asString().equals(location.getWorld().getName())) { + world.properties().setSpawnPosition(Vector3i.from( + (int) location.getX(), (int) location.getY(), (int) location.getZ()) + ); + } + }); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + log(Level.WARNING, "Failed to save the server spawn.yml file", e); + } + } + @NotNull @Override public String getServerName() { @@ -334,29 +348,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa this.randomTeleportEngine = randomTeleportEngine; } - @Override - public void setServerSpawn(@NotNull Location location) { - try { - // Create or update the spawn.yml file - final File spawnFile = new File(getDataFolder(), "spawn.yml"); - if (spawnFile.exists() && !spawnFile.delete()) { - log(Level.WARNING, "Failed to delete the existing spawn.yml file"); - } - this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get(); - - // Update the world spawn location, too - game.server().worldManager().worlds().forEach(world -> { - if (world.properties().key().asString().equals(location.getWorld().getName())) { - world.properties().setSpawnPosition(Vector3i.from( - (int) location.getX(), (int) location.getY(), (int) location.getZ()) - ); - } - }); - } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { - log(Level.WARNING, "Failed to save the server spawn.yml file", e); - } - } - @NotNull @Override public List getHooks() { @@ -414,13 +405,10 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa @NotNull public List registerCommands(@NotNull RegisterCommandEvent event) { - final List commands = new ArrayList<>(); - for (SpongeCommand.Type type : SpongeCommand.Type.values()) { - final SpongeCommand command = new SpongeCommand(type.getCommand(), this); - commands.add(command); - command.registerCommand(event); - } - return commands; + return SpongeCommand.Type.getCommands(getPlugin()).stream() + .map(command -> new SpongeCommand(command, this)) + .peek(command -> command.registerCommand(event)) + .toList(); } public void registerPermissions() { @@ -452,14 +440,20 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa try { final Metrics metrics = metricsFactory.make(METRICS_ID); - metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().doCrossServer()))); + metrics.addCustomChart(new SimplePie("bungee_mode", + () -> Boolean.toString(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("using_economy", () -> Boolean.toString(getSettings().doEconomy()))); - metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook()))); + metrics.addCustomChart(new SimplePie("language", + () -> getSettings().getLanguage().toLowerCase())); + 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))); } catch (Throwable e) { log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); @@ -487,7 +481,8 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa // Read the message and handle final SpongeUser user = (SpongeUser) playerConnection.get(); final String channel = pluginMessage.readUTF(); - if (broker instanceof PluginMessageBroker messenger && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + if (broker instanceof PluginMessageBroker messenger + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { messenger.onReceive(channel, user, pluginMessage.readBytes(pluginMessage.available())); } } diff --git a/sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/command/SpongeCommand.java similarity index 68% rename from sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/command/SpongeCommand.java index 7f29afe4..cf533796 100644 --- a/sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/command/SpongeCommand.java @@ -20,6 +20,7 @@ package net.william278.huskhomes.command; import net.kyori.adventure.text.Component; +import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.SpongeHuskHomes; import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.user.CommandUser; @@ -35,10 +36,8 @@ import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; import org.spongepowered.api.service.permission.PermissionDescription; import org.spongepowered.api.util.Tristate; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; +import java.util.function.Function; public class SpongeCommand implements Raw { @@ -109,13 +108,13 @@ public class SpongeCommand implements Raw { @NotNull private CommandUser resolveExecutor(@NotNull CommandCause cause) { if (cause.root() instanceof ServerPlayer player) { - return SpongeUser.adapt(player); + return SpongeUser.adapt(player, plugin); } return plugin.getConsole(); } /** - * Assimilate the arguments from a {@link ArgumentReader} into a spaced {@link String} array + * Assimilate the arguments from a {@link ArgumentReader} into a spaced {@link String} array. * * @param arguments the {@link ArgumentReader} to assimilate * @return the assimilated {@link String} array @@ -153,46 +152,55 @@ public class SpongeCommand implements Raw { } /** - * Commands available on the Sponge HuskHomes implementation + * Commands available on the Sponge HuskHomes implementation. */ public enum Type { - HOME_COMMAND(new PrivateHomeCommand(SpongeHuskHomes.getInstance())), - SET_HOME_COMMAND(new SetHomeCommand(SpongeHuskHomes.getInstance())), - HOME_LIST_COMMAND(new PrivateHomeListCommand(SpongeHuskHomes.getInstance())), - DEL_HOME_COMMAND(new DelHomeCommand(SpongeHuskHomes.getInstance())), - EDIT_HOME_COMMAND(new EditHomeCommand(SpongeHuskHomes.getInstance())), - PUBLIC_HOME_COMMAND(new PublicHomeCommand(SpongeHuskHomes.getInstance())), - PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(SpongeHuskHomes.getInstance())), - WARP_COMMAND(new WarpCommand(SpongeHuskHomes.getInstance())), - SET_WARP_COMMAND(new SetWarpCommand(SpongeHuskHomes.getInstance())), - WARP_LIST_COMMAND(new WarpListCommand(SpongeHuskHomes.getInstance())), - DEL_WARP_COMMAND(new DelWarpCommand(SpongeHuskHomes.getInstance())), - EDIT_WARP_COMMAND(new EditWarpCommand(SpongeHuskHomes.getInstance())), - TP_COMMAND(new TpCommand(SpongeHuskHomes.getInstance())), - TP_HERE_COMMAND(new TpHereCommand(SpongeHuskHomes.getInstance())), - TPA_COMMAND(new TeleportRequestCommand(SpongeHuskHomes.getInstance(), TeleportRequest.Type.TPA)), - TPA_HERE_COMMAND(new TeleportRequestCommand(SpongeHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)), - TPACCEPT_COMMAND(new TpRespondCommand(SpongeHuskHomes.getInstance(), true)), - TPDECLINE_COMMAND(new TpRespondCommand(SpongeHuskHomes.getInstance(), false)), - RTP_COMMAND(new RtpCommand(SpongeHuskHomes.getInstance())), - TP_IGNORE_COMMAND(new TpIgnoreCommand(SpongeHuskHomes.getInstance())), - TP_OFFLINE_COMMAND(new TpOfflineCommand(SpongeHuskHomes.getInstance())), - TP_ALL_COMMAND(new TpAllCommand(SpongeHuskHomes.getInstance())), - TPA_ALL_COMMAND(new TpaAllCommand(SpongeHuskHomes.getInstance())), - SPAWN_COMMAND(new SpawnCommand(SpongeHuskHomes.getInstance())), - SET_SPAWN_COMMAND(new SetSpawnCommand(SpongeHuskHomes.getInstance())), - BACK_COMMAND(new BackCommand(SpongeHuskHomes.getInstance())), - HUSKHOMES_COMMAND(new HuskHomesCommand(SpongeHuskHomes.getInstance())); + HOME_COMMAND(PrivateHomeCommand::new), + SET_HOME_COMMAND(SetHomeCommand::new), + HOME_LIST_COMMAND(PrivateHomeListCommand::new), + DEL_HOME_COMMAND(DelHomeCommand::new), + EDIT_HOME_COMMAND(EditHomeCommand::new), + PUBLIC_HOME_COMMAND(PublicHomeCommand::new), + PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), + WARP_COMMAND(WarpCommand::new), + SET_WARP_COMMAND(SetWarpCommand::new), + WARP_LIST_COMMAND(WarpListCommand::new), + DEL_WARP_COMMAND(DelWarpCommand::new), + EDIT_WARP_COMMAND(EditWarpCommand::new), + TP_COMMAND(TpCommand::new), + TP_HERE_COMMAND(TpHereCommand::new), + TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), + TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), + TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), + TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), + RTP_COMMAND(RtpCommand::new), + TP_IGNORE_COMMAND(TpIgnoreCommand::new), + TP_OFFLINE_COMMAND(TpOfflineCommand::new), + TP_ALL_COMMAND(TpAllCommand::new), + TPA_ALL_COMMAND(TpaAllCommand::new), + SPAWN_COMMAND(SpawnCommand::new), + SET_SPAWN_COMMAND(SetSpawnCommand::new), + BACK_COMMAND(BackCommand::new), + HUSKHOMES_COMMAND(HuskHomesCommand::new); - private final Command command; + private final Function supplier; - Type(@NotNull Command command) { - this.command = command; + Type(@NotNull Function supplier) { + this.supplier = supplier; } @NotNull - public Command getCommand() { - return command; + public Command createCommand(@NotNull HuskHomes plugin) { + return supplier.apply(plugin); + } + + @NotNull + public static List getCommands(@NotNull SpongeHuskHomes plugin) { + return Arrays.stream(values()) + .map(type -> type.createCommand(plugin)) + .map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command) + .filter(Objects::nonNull) + .toList(); } } diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java similarity index 60% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java index 554e56dd..cc4e33d0 100644 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java @@ -42,75 +42,83 @@ public interface SpongeEventDispatcher extends EventDispatcher { } @Override + @NotNull default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { return new SpongeTeleportEvent(teleport); } @Override - default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { + default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { return new SpongeTeleportWarmupEvent(teleport, duration); } @Override - default ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) { + default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, + @NotNull TeleportRequest request) { return new SpongeSendTeleportRequestEvent(sender, request); } @Override - default IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { + default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { return new SpongeReceiveTeleportRequestEvent(recipient, request); } @Override - default IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { + default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, + @NotNull TeleportRequest request) { return new SpongeReplyTeleportRequestEvent(recipient, request); } @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 SpongeHomeCreateEvent(owner, name, position, creator); } @Override - default IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { + default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) { return new SpongeHomeEditEvent(home, editor); } @Override - default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { + default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { return new SpongeHomeDeleteEvent(home, deleter); } @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 SpongeWarpCreateEvent(name, position, creator); } @Override - default IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { + default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) { return new SpongeWarpEditEvent(warp, editor); } @Override - default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { + default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { return new SpongeWarpDeleteEvent(warp, deleter); } @Override - default IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, boolean publicHomeList) { + default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, + boolean publicHomeList) { return new SpongeHomeListEvent(homes, listViewer, publicHomeList); } @Override - default IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { + default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { return new SpongeWarpListEvent(homes, listViewer); } @Override - default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { + default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { return new SpongeDeleteAllHomesEvent(user, deleter); } + @NotNull @Override default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { return new SpongeDeleteAllWarpsEvent(deleter); diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java similarity index 95% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java index 6b6277a8..afb5d61c 100644 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java @@ -35,7 +35,8 @@ public class SpongeHomeCreateEvent implements IHomeCreateEvent, Event, Cancellab private Position position; private final CommandUser creator; - public SpongeHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) { + public SpongeHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, + @NotNull CommandUser creator) { this.owner = owner; this.name = name; this.position = position; diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java similarity index 99% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java index 0539b5fe..448bec54 100644 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java @@ -45,6 +45,7 @@ public class SpongeTeleportWarmupEvent implements ITeleportWarmupEvent, Event, C public boolean isCancelled() { return cancelled; } + @Override public Cause cause() { return Cause.builder() @@ -62,4 +63,5 @@ public class SpongeTeleportWarmupEvent implements ITeleportWarmupEvent, Event, C public TimedTeleport getTimedTeleport() { return teleport; } + } diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java diff --git a/sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java similarity index 86% rename from sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java index f6ab5029..c7831aec 100644 --- a/sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java @@ -54,9 +54,17 @@ public class SpongeEconomyHook extends EconomyHook { final double currentBalance = getPlayerBalance(player); final double amountToChange = Math.abs(currentBalance - Math.max(0d, currentBalance + amount)); if (amount < 0d) { - account.withdraw(currency, BigDecimal.valueOf(amountToChange), getServer().causeStackManager().currentCause()); + account.withdraw( + currency, + BigDecimal.valueOf(amountToChange), + getServer().causeStackManager().currentCause() + ); } else { - account.deposit(currency, BigDecimal.valueOf(amountToChange), getServer().causeStackManager().currentCause()); + account.deposit( + currency, + BigDecimal.valueOf(amountToChange), + getServer().causeStackManager().currentCause() + ); } } } diff --git a/sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java similarity index 85% rename from sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java index 32cebc59..cab98667 100644 --- a/sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java @@ -51,18 +51,18 @@ public class SpongeEventListener extends EventListener { @Listener public void onPlayerJoin(final ServerSideConnectionEvent.Join event) { - super.handlePlayerJoin(SpongeUser.adapt(event.player())); + super.handlePlayerJoin(SpongeUser.adapt(event.player(), (SpongeHuskHomes) plugin)); } @Listener public void onPlayerLeave(final ServerSideConnectionEvent.Disconnect event) { - super.handlePlayerJoin(SpongeUser.adapt(event.player())); + super.handlePlayerJoin(SpongeUser.adapt(event.player(), (SpongeHuskHomes) plugin)); } @Listener public void onPlayerDeath(final DestructEntityEvent.Death event) { if (event.entity() instanceof ServerPlayer player) { - super.handlePlayerJoin(SpongeUser.adapt(player)); + super.handlePlayerJoin(SpongeUser.adapt(player, (SpongeHuskHomes) plugin)); } } @@ -72,7 +72,7 @@ public class SpongeEventListener extends EventListener { if (type.isPresent() && type.get().type().equals(PortalTypes.END.get())) { return; } - super.handlePlayerJoin(SpongeUser.adapt(event.entity())); + super.handlePlayerJoin(SpongeUser.adapt(event.entity(), (SpongeHuskHomes) plugin)); } @Listener @@ -81,8 +81,10 @@ public class SpongeEventListener extends EventListener { final Optional type = event.context().get(EventContextKeys.MOVEMENT_TYPE); if (type.isPresent() && type.get().equals(MovementTypes.ENTITY_TELEPORT.get())) { SpongeAdapter.adaptLocation(ServerLocation.of(player.world(), event.originalPosition())) - .ifPresent(location -> super.handlePlayerTeleport(SpongeUser.adapt(player), - Position.at(location, plugin.getServerName()))); + .ifPresent(location -> super.handlePlayerTeleport( + SpongeUser.adapt(player, (SpongeHuskHomes) plugin), + Position.at(location, plugin.getServerName()) + )); } } } @@ -100,10 +102,11 @@ public class SpongeEventListener extends EventListener { BlockTypes.PURPLE_BED, BlockTypes.RED_BED, BlockTypes.WHITE_BED, BlockTypes.YELLOW_BED, BlockTypes.RESPAWN_ANCHOR)) { - super.handlePlayerUpdateSpawnPoint(SpongeUser.adapt(player), Position.at( - SpongeAdapter.adaptLocation(player.serverLocation()).orElseThrow(), - plugin.getServerName() - )); + super.handlePlayerUpdateSpawnPoint(SpongeUser.adapt(player, (SpongeHuskHomes) plugin), + Position.at( + SpongeAdapter.adaptLocation(player.serverLocation()).orElseThrow(), + plugin.getServerName() + )); } } } diff --git a/sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/user/SpongeUser.java similarity index 89% rename from sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/user/SpongeUser.java index f2eb3ed6..0ef3f7e5 100644 --- a/sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/user/SpongeUser.java @@ -39,21 +39,31 @@ public class SpongeUser extends OnlineUser { private final ServerPlayer player; private final SpongeHuskHomes plugin; - private SpongeUser(@NotNull ServerPlayer player) { + private SpongeUser(@NotNull ServerPlayer player, @NotNull SpongeHuskHomes plugin) { super(player.uniqueId(), player.name()); this.player = player; - this.plugin = SpongeHuskHomes.getInstance(); + this.plugin = plugin; } /** - * Adapt a {@link ServerPlayer} to a {@link OnlineUser} + * Adapt a {@link ServerPlayer} to a {@link OnlineUser}. * * @param player the online {@link ServerPlayer} to adapt * @return the adapted {@link OnlineUser} */ @NotNull - public static SpongeUser adapt(@NotNull ServerPlayer player) { - return new SpongeUser(player); + public static SpongeUser adapt(@NotNull ServerPlayer player, @NotNull SpongeHuskHomes plugin) { + return new SpongeUser(player, plugin); + } + + /** + * Get the {@link ServerPlayer} associated with this {@link OnlineUser}. + * + * @return the {@link ServerPlayer} + */ + @NotNull + public ServerPlayer getPlayer() { + return player; } @Override @@ -97,7 +107,7 @@ public class SpongeUser extends OnlineUser { } @Override - public void teleportLocally(@NotNull Location location, boolean asynchronous) { + public void teleportLocally(@NotNull Location location, boolean async) { plugin.runSync(() -> { final Optional serverLocation = SpongeAdapter.adaptLocation(location); if (serverLocation.isEmpty()) { @@ -122,9 +132,4 @@ public class SpongeUser extends OnlineUser { return false; } - @NotNull - public ServerPlayer getPlayer() { - return player; - } - } diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeAdapter.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeAdapter.java similarity index 99% rename from sponge/src/main/java/net/william278/huskhomes/util/SpongeAdapter.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeAdapter.java index 60952222..d1cea578 100644 --- a/sponge/src/main/java/net/william278/huskhomes/util/SpongeAdapter.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeAdapter.java @@ -35,7 +35,7 @@ import java.util.Optional; public final class SpongeAdapter { /** - * Adapt a Sponge {@link ServerLocation} to a HuskHomes {@link Location} + * Adapt a Sponge {@link ServerLocation} to a HuskHomes {@link Location}. * * @param location the Sponge {@link ServerLocation} to adapt * @return the adapted {@link Location} @@ -53,7 +53,7 @@ public final class SpongeAdapter { } /** - * Adapt a HuskHomes {@link Location} to a Sponge {@link ServerLocation} + * Adapt a HuskHomes {@link Location} to a Sponge {@link ServerLocation}. * * @param location the HuskHomes {@link Location} to adapt * @return the adapted {@link ServerLocation} @@ -66,7 +66,7 @@ public final class SpongeAdapter { } /** - * Adapt a Sponge {@link ServerWorld} to a HuskHomes {@link World} + * Adapt a Sponge {@link ServerWorld} to a HuskHomes {@link World}. * * @param world the Sponge {@link ServerWorld} to adapt * @return the adapted {@link World} diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java similarity index 92% rename from sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java index 9c12cb9a..77ee1af3 100644 --- a/sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java +++ b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java @@ -51,7 +51,7 @@ public interface SpongeSafetyResolver 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 world The world to search in @@ -67,15 +67,15 @@ public interface SpongeSafetyResolver extends SafetyResolver { final BlockState bodyBlockState = location.world().block(cursorBody); final BlockState headBlockState = location.world().block(cursorHead); if (isBlockSafeForStanding(blockState.type().key(RegistryTypes.BLOCK_TYPE).asString()) - && isBlockSafeForOccupation(bodyBlockState.type().key(RegistryTypes.BLOCK_TYPE).asString()) - && isBlockSafeForOccupation(headBlockState.type().key(RegistryTypes.BLOCK_TYPE).asString())) { - double locx = Math.floor(cursor.x()); + && isBlockSafeForOccupation(bodyBlockState.type().key(RegistryTypes.BLOCK_TYPE).asString()) + && isBlockSafeForOccupation(headBlockState.type().key(RegistryTypes.BLOCK_TYPE).asString())) { + double locx = cursor.x(); if (locx < 0) { locx += 1.5d; } else { locx = locx + 0.5d; } - double locz = Math.floor(cursor.z()); + double locz = cursor.z(); if (locz < 0) { locz += 1.5d; } else { diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java b/sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeTask.java similarity index 100% rename from sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java rename to sponge/sponge-api8/src/main/java/net/william278/huskhomes/util/SpongeTask.java