refactor: Move to ConfigLib, use lombok (#563)

* refactor: move to configlib, adjust config structure

* fix: huskclaims typos

* fix: don't generate `server.yml` in local mode

* fix: NPE with server name
This commit is contained in:
William authored and GitHub committed 2024-02-12 16:54:23 +00:00
1 parent c55631a30d
commit 1723aa44fc
84 files changed
+4334 -4832

No files matched your search

@@ -23,22 +23,19 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.ThrowingConsumer;
import net.william278.desertwell.util.UpdateChecker;
import net.william278.desertwell.util.Version;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.ConfigProvider;
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.event.EventDispatcher;
import net.william278.huskhomes.hook.*;
import net.william278.huskhomes.importer.Importer;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.RandomTeleportEngine;
@@ -51,10 +48,7 @@ import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
@@ -64,7 +58,7 @@ import java.util.stream.Stream;
/**
* Represents a cross-platform instance of the plugin.
*/
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver {
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver, ConfigProvider {
/**
* The spigot resource ID, used for update checking.
@@ -155,56 +149,15 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
log(Level.INFO, "Successfully initialized " + name);
}
/**
* The plugin {@link Settings} loaded from file.
*
* @return the plugin {@link Settings}
*/
@NotNull
Settings getSettings();
void setSettings(@NotNull Settings settings);
/**
* The plugin messages loaded from file.
*
* @return The plugin {@link Locales}
*/
@NotNull
Locales getLocales();
void setLocales(@NotNull Locales locales);
/**
* 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<Spawn> getServerSpawn();
/**
* Update the local {@link Spawn} config file.
*
* @param spawn the new {@link Spawn} data
*/
void setServerSpawn(@NotNull Spawn spawn);
/**
* 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
*/
default Optional<Position> getSpawn() {
return getSettings().doCrossServer() && getSettings().isGlobalSpawn()
? getDatabase().getWarp(getSettings().getGlobalSpawnName()).map(warp -> (Position) warp)
final Settings.CrossServerSettings crossServer = getSettings().getCrossServer();
return crossServer.isEnabled() && crossServer.getGlobalSpawn().isEnabled()
? getDatabase().getWarp(crossServer.getGlobalSpawn().getWarpName()).map(warp -> (Position) warp)
: getServerSpawn().map(spawn -> spawn.getPosition(getServerName()));
}
@@ -308,14 +261,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
@Nullable
InputStream getResource(@NotNull String name);
/**
* Returns the plugin data folder containing the plugin config, etc.
*
* @return the plugin data folder
*/
@NotNull
File getDataFolder();
/**
* Returns a list of worlds on the server.
*
@@ -350,7 +295,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
default void registerHooks() {
setHooks(new ArrayList<>());
if (getSettings().doMapHook()) {
if (getSettings().getMapHook().isEnabled()) {
if (isDependencyLoaded("Dynmap")) {
getHooks().add(new DynmapHook(this));
} else if (isDependencyLoaded("BlueMap")) {
@@ -418,51 +363,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
return this.getCurrentlyOnWarmup().contains(userUuid);
}
/**
* Reloads the {@link Settings} and {@link Locales} from their respective config files.
*
* @return {@code true} if the reload was successful, {@code false} otherwise
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
default boolean loadConfigs() {
try {
// Load settings
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());
// Load server from file
if (getSettings().doCrossServer()) {
setServer(Annotaml.create(new File(getDataFolder(), "server.yml"), Server.class).get());
} else {
setServer(new Server(Server.getDefaultServerName()));
}
// Load spawn location from file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists()) {
setServerSpawn(Annotaml.create(spawnFile, Spawn.class).get());
}
// Load unsafe blocks from resources
final InputStream blocksResource = getResource("safety/unsafe_blocks.yml");
setUnsafeBlocks(Annotaml.create(new UnsafeBlocks(), Objects.requireNonNull(blocksResource)).get());
return true;
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.SEVERE, "Failed to reload HuskHomes config or messages file", e);
}
return false;
}
@NotNull
default UpdateChecker getUpdateChecker() {
return UpdateChecker.builder()
@@ -473,7 +373,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
}
default void checkForUpdates() {
if (getSettings().doCheckForUpdates()) {
if (getSettings().isCheckForUpdates()) {
getUpdateChecker().check().thenAccept(checked -> {
if (!checked.isUpToDate()) {
log(Level.WARNING, "A new version of HuskHomes is available: v"
@@ -22,6 +22,7 @@ package net.william278.huskhomes.api;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Warp;
@@ -192,7 +193,8 @@ public class BaseHuskHomesAPI {
* @since 3.0
*/
public CompletableFuture<Optional<Position>> getUserRespawnPosition(@NotNull User user) {
if (!plugin.getSettings().doCrossServer() || plugin.getSettings().isGlobalRespawning()) {
final Settings.CrossServerSettings settings = plugin.getSettings().getCrossServer();
if (!settings.isEnabled() || settings.isGlobalRespawning()) {
return CompletableFuture.completedFuture(Optional.empty());
}
return plugin.supplyAsync(() -> plugin.getDatabase().getRespawnPosition(user));
@@ -44,7 +44,8 @@ public class DelWarpCommand extends SavedPositionCommand<Warp> {
@Override
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
if (plugin.getSettings().doPermissionRestrictWarps() && !executor.hasPermission(warp.getPermission())
if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()
&& !executor.hasPermission(warp.getPermission())
&& !executor.hasPermission(Warp.getWildcardPermission())) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
@@ -256,11 +256,11 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
if (!home.getMeta().getDescription().isEmpty()) {
plugin.getLocales().getLocale("edit_home_menu_description",
plugin.getLocales().truncateText(home.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))
home.getMeta().getDescription())
.ifPresent(messages::add);
}
if (!plugin.getSettings().doCrossServer()) {
if (!plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(messages::add);
} else {
@@ -157,11 +157,11 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
if (!warp.getMeta().getDescription().isEmpty()) {
plugin.getLocales().getLocale("edit_warp_menu_description",
plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40))
warp.getMeta().getDescription())
.ifPresent(messages::add);
}
if (!plugin.getSettings().doCrossServer()) {
if (!plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getLocales().getLocale("edit_warp_menu_world",
warp.getWorld().getName()).ifPresent(messages::add);
} else {
@@ -35,6 +35,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -104,12 +105,16 @@ public class HuskHomesCommand extends Command implements TabProvider {
case "help" -> executor.sendMessage(getCommandList(executor)
.getNearestValidPage(parseIntArg(args, 1).orElse(1)));
case "reload" -> {
if (!plugin.loadConfigs()) {
try {
plugin.loadConfigs();
} catch (Throwable e) {
plugin.log(Level.SEVERE, "Failed to reload config files", e);
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)\n"
+ "[ℹ If you have modified the database or cross-server message broker settings,"
@@ -297,12 +302,12 @@ public class HuskHomesCommand extends Command implements TabProvider {
plugin.getLocales().truncateText(command.getDescription(), 50)
),
Locales.escapeText(String.format("%s\n\n%s",
plugin.getLocales().wrapText(command.getUsage(), 50),
plugin.getLocales().wrapText(command.getDescription(), 50)
)))
command.getUsage(),
command.getDescription())
))
.orElse(command.getName()))
.collect(Collectors.toList()),
plugin.getLocales().getBaseList(Math.min(plugin.getSettings().getListItemsPerPage(), 6))
plugin.getLocales().getBaseList(Math.min(plugin.getSettings().getGeneral().getListItemsPerPage(), 6))
.setHeaderFormat(plugin.getLocales().getRawLocale("command_list_title").orElse(""))
.setItemSeparator("\n").setCommand("/huskhomes:huskhomes help")
.build());
@@ -318,7 +323,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
.collect(Collectors.joining(", "))))
.orElse(importer.getName()))
.collect(Collectors.toList()),
plugin.getLocales().getBaseList(Math.min(plugin.getSettings().getListItemsPerPage(), 6))
plugin.getLocales().getBaseList(Math.min(plugin.getSettings().getGeneral().getListItemsPerPage(), 6))
.setHeaderFormat(plugin.getLocales().getRawLocale("importer_list_title").orElse(""))
.setItemSeparator("\n").setCommand("/huskhomes:huskhomes import list")
.build());
@@ -19,6 +19,8 @@
package net.william278.huskhomes.command;
import lombok.Getter;
import lombok.Setter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
@@ -39,6 +41,9 @@ public abstract class Node implements Executable {
protected final HuskHomes plugin;
private final String name;
private final List<String> aliases;
@Setter
@Getter
private boolean operatorCommand = false;
protected Node(@NotNull String name, @NotNull List<String> aliases, @NotNull HuskHomes plugin) {
@@ -71,14 +76,6 @@ public abstract class Node implements Executable {
return joiner.toString().trim();
}
public boolean isOperatorCommand() {
return operatorCommand;
}
public void setOperatorCommand(boolean operatorCommand) {
this.operatorCommand = operatorCommand;
}
protected Optional<Integer> parseIntArg(@NotNull String[] args, int index) {
try {
if (args.length > index) {
@@ -151,6 +148,7 @@ public abstract class Node implements Executable {
return Optional.empty();
}
@NotNull
protected Position getBasePosition(@NotNull CommandUser executor) {
return executor instanceof OnlineUser user ? user.getPosition() : plugin.getSpawn()
.orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName()));
@@ -110,13 +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(home.getMeta().getDescription()))
.orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage())
.getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("home_list_page_title",
user.getUsername(), "%first_item_on_page_index%",
"%last_item_on_page_index%", "%total_items%")
@@ -71,13 +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(home.getMeta().getDescription()))
.orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage())
.getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("public_home_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%")
.orElse(""))
@@ -73,7 +73,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
case 0, 1 -> user.hasPermission("other") ? UserListTabProvider.super.suggestLocal(args)
: user instanceof OnlineUser online ? List.of(online.getUsername()) : List.of();
case 2 -> user.hasPermission("world") ? plugin.getWorlds().stream()
.filter(w -> !plugin.getSettings().isWorldRtpRestricted(w))
.filter(world -> !plugin.getSettings().getRtp().isWorldRtpRestricted(world))
.map(World::getName).toList() : List.of();
default -> null;
};
@@ -118,7 +118,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
.ifPresent(executor::sendMessage);
return Optional.empty();
}
if (plugin.getSettings().isWorldRtpRestricted(world)) {
if (plugin.getSettings().getRtp().isWorldRtpRestricted(world)) {
plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(executor::sendMessage);
return Optional.empty();
@@ -137,7 +137,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
.ifPresent(executor::sendMessage);
return Optional.empty();
}
if (executor instanceof OnlineUser user && plugin.getSettings().doPermissionRestrictWarps()
if (executor instanceof OnlineUser user && plugin.getSettings().getGeneral().isPermissionRestrictWarps()
&& !user.hasPermission(Warp.getWildcardPermission())
&& !user.hasPermission(Warp.getPermission(warpName))) {
plugin.getLocales().getLocale("error_warp_invalid", warpName)
@@ -59,9 +59,9 @@ public class SetHomeCommand extends SetPositionCommand {
private boolean createDefaultHome(@NotNull OnlineUser user) {
final List<Home> homes = plugin.getDatabase().getHomes(user);
final Optional<String> name = homes.isEmpty() ? Optional.of("home") :
(homes.size() == 1 && plugin.getSettings().doOverwriteExistingHomesWarps())
? Optional.of(homes.get(0).getName()) : Optional.empty();
final Optional<String> name = homes.isEmpty() ? Optional.of("home")
: (homes.size() == 1 && plugin.getSettings().getGeneral().getNames().isOverwriteExisting())
? Optional.of(homes.get(0).getName()) : Optional.empty();
if (name.isPresent()) {
this.execute(user, "home");
return true;
@@ -27,6 +27,8 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
import static net.william278.huskhomes.config.Settings.CrossServerSettings.GlobalSpawnSettings;
public class SetSpawnCommand extends InGameCommand {
protected SetSpawnCommand(@NotNull HuskHomes plugin) {
@@ -37,9 +39,10 @@ public class SetSpawnCommand extends InGameCommand {
@Override
public void execute(@NotNull OnlineUser executor, @NotNull String[] args) {
final Position position = executor.getPosition();
final GlobalSpawnSettings global = plugin.getSettings().getCrossServer().getGlobalSpawn();
try {
if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalSpawn()) {
final String warpName = plugin.getSettings().getGlobalSpawnName();
if (plugin.getSettings().getCrossServer().isEnabled() && global.isEnabled()) {
final String warpName = global.getWarpName();
plugin.getManager().warps().createWarp(warpName, position, true);
plugin.getLocales().getRawLocale("spawn_warp_default_description").ifPresent(
description -> plugin.getManager().warps().setWarpDescription(warpName, description)
@@ -48,7 +51,7 @@ public class SetSpawnCommand extends InGameCommand {
plugin.setServerSpawn(position);
}
} catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, plugin.getSettings().getGlobalSpawnName());
e.dispatchWarpError(executor, plugin, global.getWarpName());
return;
}
@@ -58,7 +58,7 @@ public class TpAllCommand extends InGameCommand {
return;
}
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder()
.target(Message.TARGET_ALL)
.type(Message.Type.TELEPORT_TO_POSITION)
@@ -47,7 +47,7 @@ public class WarpCommand extends SavedPositionCommand<Warp> {
@Override
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
if (plugin.getSettings().doPermissionRestrictWarps()) {
if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()) {
if (!executor.hasPermission(warp.getPermission())
&& !executor.hasPermission(Warp.getWildcardPermission())) {
plugin.getLocales().getLocale("error_no_permission")
@@ -70,13 +70,11 @@ 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(warp.getMeta().getDescription())
)
.orElse(warp.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage())
.getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("warp_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%")
.orElse(""))
@@ -87,7 +85,8 @@ public class WarpListCommand extends ListCommand {
@NotNull
private List<Warp> getItems(@NotNull CommandUser executor) {
List<Warp> warps = plugin.getDatabase().getWarps();
if (plugin.getSettings().doPermissionRestrictWarps() && !executor.hasPermission(Warp.getWildcardPermission())) {
if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()
&& !executor.hasPermission(Warp.getWildcardPermission())) {
warps = warps.stream().filter(warp -> executor.hasPermission(warp.getPermission())).toList();
}
return warps;
@@ -0,0 +1,220 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* 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.config;
import de.exlll.configlib.NameFormatters;
import de.exlll.configlib.YamlConfigurationProperties;
import de.exlll.configlib.YamlConfigurationStore;
import de.exlll.configlib.YamlConfigurations;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.util.UnsafeBlocks;
import org.jetbrains.annotations.NotNull;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
public interface ConfigProvider {
@NotNull
YamlConfigurationProperties.Builder<?> YAML_CONFIGURATION_PROPERTIES = YamlConfigurationProperties.newBuilder()
.charset(StandardCharsets.UTF_8)
.setNameFormatter(NameFormatters.LOWER_UNDERSCORE);
default void loadConfigs() throws IllegalStateException {
loadSettings();
loadLocales();
loadServer();
loadServerSpawn();
loadUnsafeBlocks();
}
/**
* Get the plugin settings, read from the config file.
*
* @return the plugin settings
*/
@NotNull
Settings getSettings();
/**
* Set the plugin settings.
*
* @param settings The settings to set
*/
void setSettings(@NotNull Settings settings);
/**
* Load the plugin settings from the config file.
*/
default void loadSettings() {
setSettings(YamlConfigurations.update(
getConfigDirectory().resolve("config.yml"),
Settings.class,
YAML_CONFIGURATION_PROPERTIES.header(Settings.CONFIG_HEADER).build()
));
}
/**
* Get the locales for the plugin.
*
* @return the locales for the plugin
*/
@NotNull
Locales getLocales();
/**
* Set the locales for the plugin.
*
* @param locales The locales to set
*/
void setLocales(@NotNull Locales locales);
/**
* Load the locales from the config file.
*/
default void loadLocales() {
final YamlConfigurationStore<Locales> store = new YamlConfigurationStore<>(
Locales.class, YAML_CONFIGURATION_PROPERTIES.header(Locales.CONFIG_HEADER).build()
);
// Read existing locales if present
final Path path = getConfigDirectory().resolve(String.format("messages-%s.yml", getSettings().getLanguage()));
if (Files.exists(path)) {
setLocales(store.load(path));
return;
}
// Otherwise, save and read the default locales
try (InputStream input = getResource(String.format("locales/%s.yml", getSettings().getLanguage()))) {
final Locales locales = store.read(input);
store.save(locales, path);
setLocales(locales);
} catch (Throwable e) {
throw new IllegalStateException("An error occurred loading the locales (invalid lang code?)", e);
}
}
@NotNull
String getServerName();
void setServerName(@NotNull Server server);
default void loadServer() {
if (getSettings().getCrossServer().isEnabled()) {
setServerName(YamlConfigurations.update(
getConfigDirectory().resolve("server.yml"),
Server.class,
YAML_CONFIGURATION_PROPERTIES.header(Server.CONFIG_HEADER).build()
));
}
}
Optional<Spawn> getServerSpawn();
void setServerSpawn(@NotNull Spawn spawn);
/**
* Update the {@link Spawn} position to a location on the server.
*
* @param location the new {@link Spawn} location
*/
default void setServerSpawn(@NotNull Location location) {
final Spawn spawn = new Spawn(location);
setServerSpawn(spawn);
saveServerSpawn(spawn);
}
default void saveServerSpawn(@NotNull Spawn spawn) {
YamlConfigurations.save(
getConfigDirectory().resolve("spawn.yml"),
Spawn.class,
spawn,
YAML_CONFIGURATION_PROPERTIES.header(Spawn.CONFIG_HEADER).build()
);
}
/**
* Load the spawn location from the config file.
*/
default void loadServerSpawn() {
final Path spawn = getConfigDirectory().resolve("spawn.yml");
if (Files.exists(spawn)) {
setServerSpawn(YamlConfigurations.update(
getConfigDirectory().resolve("spawn.yml"),
Spawn.class,
YAML_CONFIGURATION_PROPERTIES.header(Spawn.CONFIG_HEADER).build()
));
}
}
/**
* Get the unsafe blocks for the plugin.
*
* @return the unsafe blocks for the plugin
*/
@NotNull
UnsafeBlocks getUnsafeBlocks();
/**
* Set the unsafe blocks for the plugin.
*
* @param unsafeBlocks The unsafe blocks to set
*/
void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks);
/**
* Load the unsafe blocks from the internal resource file.
*/
default void loadUnsafeBlocks() {
try (InputStream input = getResource("safety/unsafe_blocks.yml")) {
setUnsafeBlocks(YamlConfigurations.read(
input,
UnsafeBlocks.class,
YAML_CONFIGURATION_PROPERTIES.build()
));
} catch (Throwable e) {
throw new IllegalStateException("An error occurred loading the unsafe blocks", e);
}
}
/**
* Get a plugin resource.
*
* @param name The name of the resource
* @return the resource, if found
*/
InputStream getResource(@NotNull String name);
/**
* Get the plugin config directory.
*
* @return the plugin config directory
*/
@NotNull
Path getConfigDirectory();
@NotNull
HuskHomes getPlugin();
}
@@ -19,57 +19,65 @@
package net.william278.huskhomes.config;
import com.google.common.collect.Maps;
import de.exlll.configlib.Configuration;
import de.themoep.minedown.adventure.MineDown;
import net.william278.annotaml.YamlFile;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.william278.paginedown.ListOptions;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.text.WordUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Loaded locales used by the plugin to display styled messages.
*/
@YamlFile(rootedMap = true, header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Locales ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits
┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""")
@SuppressWarnings("FieldMayBeFinal")
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Locales {
/**
* The raw set of locales loaded from yaml.
*/
public Map<String, String> rawLocales = new HashMap<>();
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Locales ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits
┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""";
@SuppressWarnings("unused")
private Locales() {
protected static final String DEFAULT_LOCALE = "en-gb";
// The raw set of locales loaded from yaml
private Map<String, String> locales = Maps.newTreeMap();
@TestOnly
@NotNull
public Map<String, String> getRawLocales() {
return locales;
}
/**
* Returns a raw, unformatted locale loaded from the locale file.
* Returns a raw, unformatted locale loaded from the locales file.
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the locale corresponding to the id, if it exists
*/
public Optional<String> getRawLocale(@NotNull String localeId) {
return Optional.ofNullable(rawLocales.get(localeId)).map(StringEscapeUtils::unescapeJava);
return Optional.ofNullable(locales.get(localeId)).map(StringEscapeUtils::unescapeJava);
}
/**
* Returns a raw, unformatted locale loaded from the locale file, with replacements applied.
* Returns a raw, un-formatted locale loaded from the locales file, with replacements applied.
*
* <p>Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements An ordered array of replacement strings to fill in placeholders with
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists
*/
public Optional<String> getRawLocale(@NotNull String localeId, @NotNull String... replacements) {
@@ -77,34 +85,45 @@ public class Locales {
}
/**
* Returns a MineDown-formatted locale from the locale file.
* Returns a MineDown-formatted locale from the locales file.
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists
*/
public Optional<MineDown> getLocale(@NotNull String localeId) {
return getRawLocale(localeId).map(MineDown::new);
return getRawLocale(localeId).map(this::format);
}
/**
* Returns a MineDown-formatted locale from the locale file, with replacements applied.
* Returns a MineDown-formatted locale from the locales file, with replacements applied.
*
* <p>Note that replacements will be MineDown-escaped before application
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param 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
* @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
*/
public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) {
return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText)
.toArray(String[]::new)).map(MineDown::new);
.toArray(String[]::new)).map(this::format);
}
/**
* Returns a MineDown-formatted string.
*
* @param text The text to format
* @return A {@link MineDown} object containing the formatted text
*/
@NotNull
public MineDown format(@NotNull String text) {
return new MineDown(text);
}
/**
* Apply placeholder replacements to a raw locale.
*
* @param rawLocale The raw, unparsed locale
* @param replacements An ordered array of replacement strings to fill in placeholders with
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return the raw locale, with inserted placeholders
*/
@NotNull
@@ -138,7 +157,7 @@ public class Locales {
value.append(c);
}
return value.toString();
return value.toString().replace("__", "_\\_");
}
@NotNull
@@ -149,18 +168,19 @@ public class Locales {
return string.length() > truncateAfter ? string.substring(0, truncateAfter) + "…" : string;
}
/**
* 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
*/
@NotNull
public String wrapText(@NotNull String string, int wrapAfter) {
if (string.isBlank()) {
return this.getRawLocale("item_no_description").orElse("N/A");
}
return WordUtils.wrap(string, wrapAfter, "\n", true);
public String getNotApplicable() {
return getRawLocale("not_applicable").orElse("N/A");
}
@NotNull
public String getListJoiner() {
return getRawLocale("list_separator").orElse(", ");
}
@NotNull
public String getNone() {
return getRawLocale("none").orElse("(none)");
}
@NotNull
@@ -19,64 +19,33 @@
package net.william278.huskhomes.config;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import de.exlll.configlib.Configuration;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Path;
/**
* Represents a server on a proxied network.
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Server ID config ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ This file should contain the ID of this server as defined in your proxy config.
┣╸ If you join it using /server alpha, then set it to 'alpha' (case-sensitive)
┗╸ You only need to touch this if you're using cross-server mode.""")
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Server {
/**
* Default server identifier.
*/
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes - Server ID ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ This file should contain the ID of this server as defined in your proxy config.
┣╸ If you join it using /server alpha, then set it to 'alpha' (case-sensitive)
┗╸ You only need to touch this if you're using cross-server mode.""";
private String name = "server";
@NotNull
public static String getDefaultServerName() {
try {
final Path serverDirectory = Path.of(System.getProperty("user.dir"));
return serverDirectory.getFileName().toString().trim();
} catch (Exception e) {
return "server";
}
public static Server of(@NotNull String name) {
return new Server(name);
}
@YamlKey("name")
private String serverName = getDefaultServerName();
public Server(@NotNull String serverName) {
this.serverName = serverName;
}
@SuppressWarnings("unused")
private Server() {
}
@Override
public boolean equals(@NotNull Object other) {
// If the name of this server matches another, the servers are the same.
if (other instanceof Server server) {
return server.getName().equalsIgnoreCase(this.getName());
}
return super.equals(other);
}
/**
* Proxy-defined name of this server.
*/
@NotNull
public String getName() {
return serverName;
}
}
}
@@ -19,9 +19,12 @@
package net.william278.huskhomes.config;
import net.william278.annotaml.YamlComment;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import com.google.common.collect.Lists;
import de.exlll.configlib.Comment;
import de.exlll.configlib.Configuration;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.network.Broker;
@@ -35,582 +38,371 @@ import java.util.stream.Collectors;
/**
* Plugin settings, read from config.yml
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Config ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ Information: https://william278.net/project/huskhomes/
┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/
┗╸ Documentation: https://william278.net/docs/huskhomes/""")
public class Settings {
@SuppressWarnings("FieldMayBeFinal")
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Settings {
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Config ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ Information: https://william278.net/project/huskhomes/
┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/
┗╸ Documentation: https://william278.net/docs/huskhomes/""";
// Top-level settings
@YamlComment("Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations")
@YamlKey("language")
private String language = "en-gb";
@Comment("Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations")
private String language = Locales.DEFAULT_LOCALE;
@YamlComment("Whether to automatically check for plugin updates on startup")
@YamlKey("check_for_updates")
@Comment("Whether to automatically check for plugin updates on startup")
private boolean checkForUpdates = true;
// Database settings
@YamlComment("Type of database to use (SQLITE, H2, MYSQL or MARIADB)")
@YamlKey("database.type")
private Database.Type databaseType = Database.Type.SQLITE;
@Comment("Database settings")
private DatabaseSettings database = new DatabaseSettings();
@YamlComment("Specify credentials here if you are using MYSQL or MARIADB as your database type")
@YamlKey("database.mysql.credentials.host")
private String mySqlHost = "localhost";
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class DatabaseSettings {
@YamlKey("database.mysql.credentials.port")
private int mySqlPort = 3306;
@Comment("Type of database to use (SQLITE, H2, MYSQL, or MARIADB)")
private Database.Type type = Database.Type.SQLITE;
@YamlKey("database.mysql.credentials.database")
private String mySqlDatabase = "HuskHomes";
@Comment("Specify credentials here if you are using MYSQL or MARIADB")
private DatabaseCredentials credentials = new DatabaseCredentials();
@YamlKey("database.mysql.credentials.username")
private String mySqlUsername = "root";
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class DatabaseCredentials {
private String host = "localhost";
private int port = 3306;
private String database = "huskhomes";
private String username = "root";
private String password = "pa55w0rd";
private String parameters = String.join("&",
"?autoReconnect=true", "useSSL=false",
"useUnicode=true", "characterEncoding=UTF-8");
}
@YamlKey("database.mysql.credentials.password")
private String mySqlPassword = "pa55w0rd";
@Comment({"MYSQL / MARIADB database Hikari connection pool properties",
"Don't modify this unless you know what you're doing!"})
private PoolOptions poolOptions = new PoolOptions();
@YamlKey("database.mysql.credentials.parameters")
private String mySqlConnectionParameters = "?autoReconnect=true"
+ "&useSSL=false"
+ "&useUnicode=true"
+ "&characterEncoding=UTF-8";
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class PoolOptions {
private int size = 12;
private int idle = 12;
private long lifetime = 1800000;
private long keepAlive = 30000;
private long timeout = 20000;
}
@YamlComment("MYSQL / MARIADB 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;
@Comment("Names of tables to use on your database. Don't modify this unless you know what you're doing!")
private Map<Database.Table, String> tableNames = Database.Table.getConfigMap();
@YamlKey("database.mysql.connection_pool.idle")
private int mySqlConnectionPoolIdle = 12;
@NotNull
public String getTableName(@NotNull Database.Table tableName) {
return Optional.ofNullable(tableNames.get(tableName)).orElse(tableName.getDefaultName());
}
}
@YamlKey("database.mysql.connection_pool.lifetime")
private long mySqlConnectionPoolLifetime = 1800000;
@Comment("General settings")
private GeneralSettings general = new GeneralSettings();
@YamlKey("database.mysql.connection_pool.keepalive")
private long mySqlConnectionPoolKeepAlive = 30000;
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class GeneralSettings {
@Comment("The maximum homes a user can create. Override with the huskhomes.max_homes.<number> permission.")
private int maxHomes = 10;
@YamlKey("database.mysql.connection_pool.timeout")
private long mySqlConnectionPoolTimeout = 20000;
@Comment("The maximum public homes a user can create. "
+ "Override with the huskhomes.max_public_homes.<number> permission.")
private int maxPublicHomes = 10;
@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 TreeMap<String, String> tableNames = new TreeMap<>(Database.Table.getConfigMap());
@Comment("Whether permission limits (i.e. huskhomes.max_homes.<number>) should stack "
+ "if the user inherits multiple nodes.")
private boolean stackPermissionLimits = false;
@Comment("Whether users require a permission (huskhomes.command.warp.<warp_name>) to use warps")
private boolean permissionRestrictWarps = false;
// General settings
@YamlComment("The maximum homes a user can create. Override with the huskhomes.max_homes.<number> permission.")
@YamlKey("general.max_homes")
private int maxHomes = 10;
@Comment("How long a player has to stand still and not take damage for when teleporting (in seconds) ")
private int teleportWarmupTime = 5;
@YamlComment("The maximum public homes a user can create. "
+ "Override with the huskhomes.max_public_homes.<number> permission.")
@YamlKey("general.max_public_homes")
private int maxPublicHomes = 10;
@Comment("Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE)")
private Locales.DisplaySlot teleportWarmupDisplay = Locales.DisplaySlot.ACTION_BAR;
@YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>) "
+ "should stack if the user inherits multiple nodes.")
@YamlKey("general.stack_permission_limits")
private boolean stackPermissionLimits = false;
@Comment("How long before received teleport requests expire (in seconds)")
private int teleportRequestExpiryTime = 60;
@YamlComment("Whether users require a permission (huskhomes.command.warp.<warp_name>) to use warps")
@YamlKey("general.permission_restrict_warps")
private boolean permissionRestrictWarps = false;
@Comment("Whether /tpahere should use the location of the sender when sent. "
+ "Docs: https://william278.net/docs/huskhomes/strict-tpahere/")
private boolean strictTpaHereRequests = true;
@YamlComment("Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite.")
@YamlKey("general.overwrite_existing_homes_warps")
private boolean overwriteExistingHomesWarps = true;
@Comment("How many items should be displayed per-page in chat menu lists")
private int listItemsPerPage = 12;
@YamlComment("How long a player has to stand still and not take damage for when teleporting (in seconds) ")
@YamlKey("general.teleport_warmup_time")
private int teleportWarmupTime = 5;
@Comment("Whether to provide modern, rich TAB suggestions for commands (if available)")
private boolean brigadierTabCompletion = true;
@YamlComment("Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE)")
@YamlKey("general.teleport_warmup_display")
private Locales.DisplaySlot teleportWarmupDisplay = Locales.DisplaySlot.ACTION_BAR;
@Comment("Whether the user should always be put back at the /spawn point when they die "
+ "(ignores beds/respawn anchors)")
private boolean alwaysRespawnAtSpawn = false;
@YamlComment("How long before received teleport requests expire (in seconds)")
@YamlKey("general.teleport_request_expiry_time")
private int teleportRequestExpiryTime = 60;
@Comment("Whether teleportation should be carried out async (ensuring chunks load before teleporting)")
private boolean teleportAsync = true;
@YamlComment("Whether /tpahere should use the location of the sender when sent. Docs: https://william278.net/docs/huskhomes/strict-tpahere/")
@YamlKey("general.strict_tpa_here_requests")
private boolean strictTpaHereRequests = true;
@Comment("Settings for home and warp names")
private NameSettings names = new NameSettings();
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class NameSettings {
@Comment("Whether running /sethome <name> or /setwarp <name> when one already exists should overwrite.")
private boolean overwriteExisting = true;
// Name & description settings
@YamlComment("Whether home or warp names should be case insensitive (i.e. allow /home HomeOne and /home homeone)")
@YamlKey("general.case_insensitive_names")
private boolean caseInsensitiveNames = false;
@Comment("Whether home or warp names should be case insensitive (i.e. allow /home HomeOne & /home homeone)")
private boolean caseInsensitive = false;
@YamlComment("Whether home and warp names should be restricted by a regex."
+ "Set this to false to allow full UTF-8 names (i.e. allow /home 你好).")
@YamlKey("general.restrict_names")
private boolean restrictNames = true;
@Comment("Whether home and warp names should be restricted to a regex filter."
+ "Set this to false to allow full UTF-8 names (i.e. allow /home 你好).")
private boolean restrict = true;
@YamlComment("Regex which home and warp names must match. Names have a max length of 16 characters")
@YamlKey("general.name_regex")
private String nameRegex = "[a-zA-Z0-9-_]*";
@Comment("Regex which home and warp names must match. Names have a max length of 16 characters")
private String regex = "[a-zA-Z0-9-_]*";
}
@YamlComment("Whether home/warp descriptions should be restricted. Set this to true to restrict UTF-8 usage.")
@YamlKey("general.restrict_descriptions")
private boolean restrictDescriptions = false;
@Comment("Settings for home and warp descriptions")
private DescriptionSettings descriptions = new DescriptionSettings();
@YamlComment("Regex which home and warp descriptions must match. A hard max length of 256 characters is enforced")
@YamlKey("general.description_regex")
private String descriptionRegex = "\\A\\p{ASCII}*\\z";
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class DescriptionSettings {
@Comment("Whether home/warp descriptions should be restricted to a regex filter. "
+ "Set this to true to restrict UTF-8 usage.")
private boolean restrict = false;
@YamlComment("Whether the user should back to spawn when they die")
@YamlKey("general.always_respawn_at_spawn")
private boolean alwaysRespawnAtSpawn = false;
@Comment("Regex which home and warp descriptions must match. "
+ "A hard max length of 256 characters is enforced")
private String regex = "\\A\\p{ASCII}*\\z";
}
// Back command settings
@YamlComment("Whether /back should work to teleport the user to where they died")
@YamlKey("general.back_command_return_by_death")
private boolean backCommandReturnByDeath = true;
@Comment("Settings for the /back command")
private BackCommandSettings backCommand = new BackCommandSettings();
@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;
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class BackCommandSettings {
@Comment("Whether /back should work to teleport the user to where they died")
private boolean returnByDeath = true;
@YamlComment("How many items should be displayed per-page in chat menu lists")
@YamlKey("general.list_items_per_page")
private int listItemsPerPage = 12;
@Comment("Whether /back should work with other plugins that use the PlayerTeleportEvent (can conflict)")
private boolean saveOnTeleportEvent = false;
}
@YamlComment("Whether teleportation should be carried out asynchronously (ensuring chunks load before teleporting)")
@YamlKey("general.asynchronous_teleports")
private boolean asynchronousTeleports = true;
@Comment("Settings for sound effects")
private SoundEffectSettings soundEffects = new SoundEffectSettings();
@YamlComment("Whether to play sound effects")
@YamlKey("general.play_sound_effects")
private boolean playSoundEffects = true;
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class SoundEffectSettings {
@Comment("Whether to play sound effects")
private boolean enabled = true;
@YamlComment("Which sound effects to play for various actions")
@YamlKey("general.sound_effects")
private TreeMap<String, String> soundEffects = new TreeMap<>(SoundEffectAction.getConfigMap());
@Comment("Map of sound effect actions to types")
private Map<SoundEffectAction, String> types = SoundEffectAction.getDefaults();
@YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)")
@YamlKey("general.brigadier_tab_completion")
private boolean brigadierTabCompletion = true;
@NotNull
public Optional<String> get(@NotNull SoundEffectAction action) {
if (!enabled) {
return Optional.empty();
}
return Optional.ofNullable(types.get(action));
}
}
}
@Comment("Cross-server settings")
private CrossServerSettings crossServer = new CrossServerSettings();
// Cross-server settings
@YamlComment("Enable teleporting across your proxy network. Requires database type to be MYSQL")
@YamlKey("cross_server.enabled")
private boolean crossServer = false;
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class CrossServerSettings {
@Comment("Whether to enable cross-server mode for teleporting across your proxy network.")
private boolean enabled = false;
@YamlComment("The type of message broker to use for cross-server communication. Options: PLUGIN_MESSAGE, REDIS")
@YamlKey("cross_server.messenger_type")
private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE;
@Comment({"The cluster ID, for if you're networking multiple separate groups of HuskHomes-enabled servers.",
"Do not change unless you know what you're doing"})
private String clusterId = "main";
@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 = "";
@Comment("Type of network message broker to ues for data synchronization (PLUGIN_MESSAGE or REDIS)")
private Broker.Type brokerType = Broker.Type.PLUGIN_MESSAGE;
@YamlComment("Define a single global /spawn for your network via a warp. Docs: https://william278.net/docs/huskhomes/global-spawn/")
@YamlKey("cross_server.global_spawn.enabled")
private boolean globalSpawn = false;
@Comment("Settings for if you're using REDIS as your message broker")
private RedisSettings redis = new RedisSettings();
@YamlComment("The name of the warp to use as the global spawn.")
@YamlKey("cross_server.global_spawn.warp_name")
private String globalSpawnName = "Spawn";
@Getter
@Configuration
@NoArgsConstructor
public static class RedisSettings {
private String host = "localhost";
private int port = 6379;
@Comment("Password for your Redis server. Leave blank if you're not using a password.")
private String password = "";
private boolean useSsl = false;
@YamlComment("Whether player respawn positions should work cross-server. Docs: https://william278.net/docs/huskhomes/global-respawning/")
@YamlKey("cross_server.global_respawning")
private boolean globalRespawning = false;
@Comment({"Settings for if you're using Redis Sentinels.",
"If you're not sure what this is, please ignore this section."})
private SentinelSettings sentinel = new SentinelSettings();
@YamlComment("Specify credentials here if you are using REDIS as your messenger_type. Docs: https://william278.net/docs/huskhomes/redis-support/")
@YamlKey("cross_server.redis_credentials.host")
private String redisHost = "localhost";
@Getter
@Configuration
@NoArgsConstructor
public static class SentinelSettings {
private String masterName = "";
@Comment("List of host:port pairs")
private List<String> nodes = Lists.newArrayList();
private String password = "";
}
}
@YamlKey("cross_server.redis_credentials.port")
private int redisPort = 6379;
@Comment("Define a single global /spawn for your network via a warp. "
+ "Docs: https://william278.net/docs/huskhomes/global-spawn/")
private GlobalSpawnSettings globalSpawn = new GlobalSpawnSettings();
@YamlKey("cross_server.redis_credentials.password")
private String redisPassword = "";
@Getter
@Configuration
@NoArgsConstructor
public static class GlobalSpawnSettings {
@Comment("Whether to define a single global /spawn for your network via a warp.")
private boolean enabled = false;
@Comment("The name of the warp to use as the global spawn.")
private String warpName = "Spawn";
}
@YamlKey("cross_server.redis_credentials.use_ssl")
private boolean redisUseSsl = false;
@Comment("Whether player respawn positions should work cross-server. "
+ "Docs: https://william278.net/docs/huskhomes/global-respawning/")
private boolean globalRespawning = false;
}
@Comment("Random teleport (/rtp) settings.")
private RtpSettings rtp = new RtpSettings();
// Rtp command settings
@YamlComment("Radius around the /spawn position where players CAN be randomly teleported")
@YamlKey("rtp.radius")
private int rtpRadius = 5000;
@Getter
@Configuration
@NoArgsConstructor
public static class RtpSettings {
@YamlComment("Radius around the /spawn position where players CANNOT be randomly teleported")
@YamlKey("rtp.spawn_radius")
private int rtpSpawnRadius = 500;
@Comment({"Radial region around the /spawn position where players CAN be randomly teleported.",
"If no /spawn has been set, (0, 0) will be used instead."})
private RtpRadius region = new RtpRadius();
@YamlComment("Mean of the normal distribution used to calculate the distance from the center of the world")
@YamlKey("rtp.distribution_mean")
private float rtpDistributionMean = 0.75f;
@Getter
@Configuration
@NoArgsConstructor
public static class RtpRadius {
private int min = 500;
private int max = 5000;
}
@YamlComment("Standard deviation of the normal distribution for distributing players randomly")
@YamlKey("rtp.distribution_deviation")
private float rtpDistributionStandardDeviation = 2f;
@Comment("Mean of the normal distribution used to calculate the distance from the center of the world")
private float distributionMean = 0.75f;
@YamlComment("List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether.")
@YamlKey("rtp.restricted_worlds")
private List<String> rtpRestrictedWorlds = List.of("world_nether", "world_the_end");
@Comment("Standard deviation of the normal distribution for distributing players randomly")
private float distributionStandardDeviation = 2.0f;
@Comment("List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether.")
private List<String> restrictedWorlds = List.of("world_nether", "world_the_end");
// Cooldown settings
@YamlComment("Whether to apply a cooldown between performing certain actions")
@YamlKey("cooldowns.enabled")
private boolean cooldowns = true;
public boolean isWorldRtpRestricted(@NotNull World world) {
final String name = world.getName();
final String filteredName = name.startsWith("minecraft:") ? name.substring(10) : name;
return restrictedWorlds.stream()
.map(n -> n.startsWith("minecraft:") ? n.substring(10) : n)
.anyMatch(n -> n.equalsIgnoreCase(filteredName));
}
}
@YamlComment("Set a cooldown between performing actions (in seconds). Docs: https://william278.net/docs/huskhomes/cooldowns/")
@YamlKey("cooldowns.cooldown_times")
private TreeMap<String, Integer> cooldownTimes = new TreeMap<>(TransactionResolver.Action.getCooldownsConfigMap());
@Comment("Action cooldown settings. Docs: https://william278.net/docs/huskhomes/cooldowns")
private CooldownSettings cooldowns = new CooldownSettings();
@Getter
@Configuration
@NoArgsConstructor
public static class CooldownSettings {
@Comment("Whether to apply a cooldown between performing certain actions")
private boolean enabled = true;
@Comment("Map of cooldown times to actions")
private Map<TransactionResolver.Action, Long> cooldownTimes = TransactionResolver.Action.getCooldownTimes();
public long getCooldown(@NotNull TransactionResolver.Action action) {
return enabled ? cooldownTimes.getOrDefault(action, 0L) : 0L;
}
}
// Economy settings
@YamlComment("Enable economy plugin integration (requires Vault)")
@YamlKey("economy.enabled")
private boolean economy = false;
@Comment("Economy settings. Docs: https://william278.net/docs/huskhomes/economy-hook")
private EconomySettings economy = new EconomySettings();
@YamlComment("Specify how many homes players can set for free, before they need to pay for more slots")
@YamlKey("economy.free_home_slots")
private int freeHomeSlots = 5;
@Getter
@Configuration
@NoArgsConstructor
public static class EconomySettings {
@YamlComment("Charge money for perform certain actions. Docs: https://william278.net/docs/huskhomes/economy-hook/")
@YamlKey("economy.costs")
private TreeMap<String, Double> economyCosts = new TreeMap<>(TransactionResolver.Action.getEconomyCostsConfigMap());
@Comment("Enable economy plugin integration (requires Vault and a compatible Economy plugin)")
private boolean enabled = true;
// Mapping plugins
@YamlComment("Display public homes/warps on your Dynmap, BlueMap or Pl3xMap. Docs: https://william278.net/docs/huskhomes/map-hooks")
@YamlKey("map_hook.enabled")
private boolean doMapHook = true;
@Comment("Map of economy actions to costs.")
private Map<TransactionResolver.Action, Double> economyCosts = TransactionResolver.Action.getEconomyCosts();
@YamlComment("Show public homes on the web map")
@YamlKey("map_hook.show_public_homes")
private boolean publicHomesOnMap = true;
@Comment("Specify how many homes players can set for free, before they need to pay for more slots")
private int freeHomeSlots = 5;
@YamlComment("Show warps on the web map")
@YamlKey("map_hook.show_warps")
private boolean warpsOnMap = true;
// Disabled commands
@YamlComment("List of commands to disable (e.g. ['/home', '/warp'] to disable /home and /warp)")
@YamlKey("disabled_commands")
private List<String> disabledCommands = Collections.emptyList();
@SuppressWarnings("unused")
private Settings() {
}
@NotNull
public String getLanguage() {
return language;
}
public boolean doCheckForUpdates() {
return checkForUpdates;
}
@NotNull
public Database.Type getDatabaseType() {
return databaseType;
}
@NotNull
public String getMySqlHost() {
return mySqlHost;
}
public int getMySqlPort() {
return mySqlPort;
}
@NotNull
public String getMySqlDatabase() {
return mySqlDatabase;
}
@NotNull
public String getMySqlUsername() {
return mySqlUsername;
}
@NotNull
public String getMySqlPassword() {
return mySqlPassword;
}
@NotNull
public String getMySqlConnectionParameters() {
return mySqlConnectionParameters;
}
public int getMySqlConnectionPoolSize() {
return mySqlConnectionPoolSize;
}
public int getMySqlConnectionPoolIdle() {
return mySqlConnectionPoolIdle;
}
public long getMySqlConnectionPoolLifetime() {
return mySqlConnectionPoolLifetime;
}
public long getMySqlConnectionPoolKeepAlive() {
return mySqlConnectionPoolKeepAlive;
}
public long getMySqlConnectionPoolTimeout() {
return mySqlConnectionPoolTimeout;
}
@NotNull
public TreeMap<String, String> getTableNames() {
final TreeMap<String, String> tableNames = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
tableNames.putAll(this.tableNames);
return tableNames;
}
@NotNull
public String getTableName(@NotNull Database.Table table) {
return Optional.ofNullable(getTableNames().get(table.name())).orElse(table.getDefaultName());
}
public int getMaxHomes() {
return maxHomes;
}
public int getMaxPublicHomes() {
return maxPublicHomes;
}
public boolean doStackPermissionLimits() {
return stackPermissionLimits;
}
public boolean doPermissionRestrictWarps() {
return permissionRestrictWarps;
}
public boolean doOverwriteExistingHomesWarps() {
return overwriteExistingHomesWarps;
}
public int getTeleportWarmupTime() {
return teleportWarmupTime;
}
@NotNull
public Locales.DisplaySlot getTeleportWarmupDisplay() {
return teleportWarmupDisplay;
}
public int getTeleportRequestExpiryTime() {
return teleportRequestExpiryTime;
}
public boolean doStrictTpaHereRequests() {
return strictTpaHereRequests;
}
public boolean caseInsensitiveNames() {
return caseInsensitiveNames;
}
public boolean doRestrictNames() {
return restrictNames;
}
@NotNull
public String getNameRegex() {
return nameRegex;
}
public boolean doRestrictDescriptions() {
return restrictDescriptions;
}
@NotNull
public String getDescriptionRegex() {
return descriptionRegex;
}
public boolean doAlwaysRespawnAtSpawn() {
return alwaysRespawnAtSpawn;
}
public boolean doBackCommandReturnByDeath() {
return backCommandReturnByDeath;
}
public boolean doBackCommandSaveOnTeleportEvent() {
return backCommandSaveOnTeleportEvent;
}
public int getListItemsPerPage() {
return listItemsPerPage;
}
public boolean doAsynchronousTeleports() {
return asynchronousTeleports;
}
public boolean doPlaySoundEffects() {
return playSoundEffects;
}
@NotNull
public TreeMap<String, String> getSoundEffects() {
final TreeMap<String, String> soundEffects = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
soundEffects.putAll(this.soundEffects);
return soundEffects;
}
public Optional<String> getSoundEffect(@NotNull SoundEffectAction action) {
if (!doPlaySoundEffects()) {
return Optional.empty();
public Optional<Double> getCost(@NotNull TransactionResolver.Action action) {
if (!enabled) {
return Optional.empty();
}
return economyCosts.containsKey(action) ? Optional.of(economyCosts.get(action)) : Optional.empty();
}
return Optional.ofNullable(getSoundEffects().get(action.name()));
}
public boolean doCrossServer() {
return crossServer;
@Comment("Web map hook settings. Docs: https://william278.net/docs/huskhomes/map-hooks")
private MapHookSettings mapHook = new MapHookSettings();
@Getter
@Configuration
@NoArgsConstructor
public static class MapHookSettings {
@Comment("Display public homes/warps on your Dynmap, BlueMap or Pl3xMap")
private boolean enabled = true;
@Comment("Show public homes on the web map")
private boolean showPublicHomes = true;
@Comment("Show warps on the web map")
private boolean showWarps = true;
}
@NotNull
public Broker.Type getBrokerType() {
return messageBrokerType;
}
@Comment("List of commands to disable (e.g. ['/home', '/warp'] to disable /home and /warp)")
private List<String> disabledCommands = Lists.newArrayList();
@NotNull
public String getClusterId() {
return clusterId;
}
public boolean isGlobalSpawn() {
return globalSpawn;
}
@NotNull
public String getGlobalSpawnName() {
return globalSpawnName;
}
public boolean isGlobalRespawning() {
return globalRespawning;
}
@NotNull
public String getRedisHost() {
return redisHost;
}
public int getRedisPort() {
return redisPort;
}
@NotNull
public String getRedisPassword() {
return redisPassword;
}
public boolean useRedisSsl() {
return redisUseSsl;
}
public int getRtpRadius() {
return rtpRadius;
}
public int getRtpSpawnRadius() {
return rtpSpawnRadius;
}
public float getRtpDistributionMean() {
return rtpDistributionMean;
}
public float getRtpDistributionStandardDeviation() {
return rtpDistributionStandardDeviation;
}
public boolean isWorldRtpRestricted(@NotNull World world) {
final String worldName = world.getName();
final String filteredName = worldName.startsWith("minecraft:") ? worldName.substring(10) : worldName;
return rtpRestrictedWorlds.stream()
.map(name -> name.startsWith("minecraft:") ? name.substring(10) : name)
.anyMatch(name -> name.equalsIgnoreCase(filteredName));
}
public boolean doCooldowns() {
return cooldowns;
}
@NotNull
public TreeMap<String, Integer> getCooldownTimes() {
final TreeMap<String, Integer> cooldownTimes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
cooldownTimes.putAll(this.cooldownTimes);
return cooldownTimes;
}
public long getCooldown(@NotNull TransactionResolver.Action action) {
if (!doCooldowns()) {
return 0;
}
final Integer cooldown = getCooldownTimes().get(action.name());
if (cooldown != null && cooldown > 0) {
return cooldown;
}
return 0;
}
public boolean doEconomy() {
return economy;
}
public int getFreeHomeSlots() {
return freeHomeSlots;
}
@NotNull
public TreeMap<String, Double> getEconomyCosts() {
final TreeMap<String, Double> economyCosts = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
economyCosts.putAll(this.economyCosts);
return economyCosts;
}
public Optional<Double> getEconomyCost(@NotNull TransactionResolver.Action action) {
if (!doEconomy()) {
return Optional.empty();
}
final Double cost = getEconomyCosts().get(action.name());
if (cost != null && cost > 0d) {
return Optional.of(cost);
}
return Optional.empty();
}
public boolean doMapHook() {
return doMapHook;
}
public boolean doPublicHomesOnMap() {
return publicHomesOnMap;
}
public boolean doWarpsOnMap() {
return warpsOnMap;
}
public boolean isCommandDisabled(Command type) {
public boolean isCommandDisabled(@NotNull Command type) {
return disabledCommands.stream()
.anyMatch(disabled -> {
final String command = (disabled.startsWith("/") ? disabled.substring(1) : disabled);
@@ -619,10 +411,6 @@ public class Settings {
});
}
public boolean doBrigadierTabCompletion() {
return brigadierTabCompletion;
}
/**
* Represents actions that have a sound effect associated with performing them.
*/
@@ -639,13 +427,14 @@ public class Settings {
}
@NotNull
public static Map<String, String> getConfigMap() {
public static Map<SoundEffectAction, String> getDefaults() {
return Arrays.stream(values()).collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH),
action -> action.defaultEffect
action -> action,
action -> action.defaultEffect,
(a, b) -> a,
TreeMap::new
));
}
}
}
@@ -19,8 +19,11 @@
package net.william278.huskhomes.config;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import de.exlll.configlib.Configuration;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
@@ -31,22 +34,25 @@ import java.util.UUID;
/**
* Used to store the server spawn location.
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server /spawn location ┃
┃ Edit in-game using /setspawn ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Spawn {
public double x;
public double y;
public double z;
public float yaw;
public float pitch;
@YamlKey("world_name")
public String worldName;
@YamlKey("world_uuid")
public String worldUuid;
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server /spawn location ┃
┃ Edit in-game using /setspawn ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""";
private double x;
private double y;
private double z;
private float yaw;
private float pitch;
private String worldName;
private String worldUuid;
/**
* Returns the {@link Position} of the spawn.
@@ -65,16 +71,9 @@ public class Spawn {
* @param location The {@link Location} of the spawn
*/
public Spawn(@NotNull Location location) {
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
this.yaw = location.getYaw();
this.pitch = location.getPitch();
this.worldName = location.getWorld().getName();
this.worldUuid = location.getWorld().getUuid().toString();
}
@SuppressWarnings("unused")
public Spawn() {
this(
location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(),
location.getWorld().getName(), location.getWorld().getUuid().toString()
);
}
}
@@ -19,8 +19,11 @@
package net.william278.huskhomes.database;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.SavedPosition;
@@ -72,20 +75,21 @@ public abstract class Database {
* @return the formatted statement, with table placeholders replaced with the correct names
*/
protected final String formatStatementTables(@NotNull String sql) {
final Settings.DatabaseSettings settings = plugin.getSettings().getDatabase();
return sql
.replaceAll("%positions_table%", plugin.getSettings()
.replaceAll("%positions_table%", settings
.getTableName(Table.POSITION_DATA))
.replaceAll("%players_table%", plugin.getSettings()
.replaceAll("%players_table%", settings
.getTableName(Table.PLAYER_DATA))
.replaceAll("%cooldowns_table%", plugin.getSettings()
.replaceAll("%cooldowns_table%", settings
.getTableName(Table.PLAYER_COOLDOWNS_DATA))
.replaceAll("%teleports_table%", plugin.getSettings()
.replaceAll("%teleports_table%", settings
.getTableName(Table.TELEPORT_DATA))
.replaceAll("%saved_positions_table%", plugin.getSettings()
.replaceAll("%saved_positions_table%", settings
.getTableName(Table.SAVED_POSITION_DATA))
.replaceAll("%homes_table%", plugin.getSettings()
.replaceAll("%homes_table%", settings
.getTableName(Table.HOME_DATA))
.replaceAll("%warps_table%", plugin.getSettings()
.replaceAll("%warps_table%", settings
.getTableName(Table.WARP_DATA));
}
@@ -261,7 +265,7 @@ public abstract class Database {
* @apiNote Whether lookup is case-sensitive is determined by the {@code general.case_insensitive_names} setting
*/
public final Optional<Home> getHome(@NotNull User user, @NotNull String homeName) {
return this.getHome(user, homeName, plugin.getSettings().caseInsensitiveNames());
return this.getHome(user, homeName, plugin.getSettings().getGeneral().getNames().isCaseInsensitive());
}
/**
@@ -290,7 +294,7 @@ public abstract class Database {
* @apiNote Whether lookup is case-insensitive is determined by the {@code general.case_insensitive_names} setting
*/
public final Optional<Warp> getWarp(@NotNull String warpName) {
return getWarp(warpName, plugin.getSettings().caseInsensitiveNames());
return getWarp(warpName, plugin.getSettings().getGeneral().getNames().isCaseInsensitive());
}
/**
@@ -462,27 +466,23 @@ public abstract class Database {
/**
* Identifies types of databases.
*/
@Getter
@AllArgsConstructor
public enum Type {
MYSQL("MySQL"),
MARIADB("MariaDB"),
SQLITE("SQLite"),
H2("H2");
MYSQL("MySQL", "mysql"),
MARIADB("MariaDB", "mariadb"),
SQLITE("SQLite", "sqlite"),
H2("H2", "h2");
private final String displayName;
Type(@NotNull String displayName) {
this.displayName = displayName;
}
@NotNull
public String getDisplayName() {
return displayName;
}
private final String protocol;
}
/**
* Represents the names of tables in the database.
*/
@Getter
@AllArgsConstructor
public enum Table {
PLAYER_DATA("huskhomes_users"),
PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"),
@@ -494,21 +494,11 @@ public abstract class Database {
private final String defaultName;
Table(@NotNull String defaultName) {
this.defaultName = defaultName;
}
@NotNull
public String getDefaultName() {
return defaultName;
}
@NotNull
public static Map<String, String> getConfigMap() {
return Arrays.stream(values()).collect(Collectors.toMap(
table -> table.name().toLowerCase(Locale.ENGLISH),
Table::getDefaultName
));
public static Map<Table, String> getConfigMap() {
return Arrays.stream(values()).collect(
Collectors.toMap(t -> t, Table::getDefaultName, (a, b) -> b, TreeMap::new)
);
}
}
@@ -58,7 +58,7 @@ public class H2Database extends Database {
public H2Database(@NotNull HuskHomes plugin) {
super(plugin);
this.databaseFile = new File(plugin.getDataFolder(), DATABASE_FILE_NAME);
this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile();
}
/**
@@ -28,6 +28,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.Blocking;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -37,6 +38,8 @@ import java.time.Instant;
import java.util.*;
import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.DatabaseSettings;
/**
* A MySQL / MariaDB implementation of the plugin {@link Database}.
*/
@@ -50,10 +53,10 @@ public class MySqlDatabase extends Database {
public MySqlDatabase(@NotNull HuskHomes plugin) {
super(plugin);
this.flavor = plugin.getSettings().getDatabaseType() == Type.MARIADB
? "mariadb" : "mysql";
this.driverClass = plugin.getSettings().getDatabaseType() == Type.MARIADB
? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver";
final Type type = plugin.getSettings().getDatabase().getType();
this.flavor = type.getProtocol();
this.driverClass = type == Type.MARIADB ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver";
}
/**
@@ -62,33 +65,41 @@ public class MySqlDatabase extends Database {
* @return The {@link Connection} to the MySQL database
* @throws SQLException if the connection fails for some reason
*/
@Blocking
@NotNull
private Connection getConnection() throws SQLException {
if (dataSource == null) {
throw new IllegalStateException("The database has not been initialized");
}
return dataSource.getConnection();
}
@Blocking
@Override
public void initialize() throws IllegalStateException {
// Initialize the Hikari pooled connection
final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials();
dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s",
flavor,
plugin.getSettings().getMySqlHost(),
plugin.getSettings().getMySqlPort(),
plugin.getSettings().getMySqlDatabase(),
plugin.getSettings().getMySqlConnectionParameters()
credentials.getHost(),
credentials.getPort(),
credentials.getDatabase(),
credentials.getParameters()
));
// Authenticate with the database
dataSource.setUsername(plugin.getSettings().getMySqlUsername());
dataSource.setPassword(plugin.getSettings().getMySqlPassword());
dataSource.setUsername(credentials.getUsername());
dataSource.setPassword(credentials.getPassword());
// Set connection pool options
dataSource.setMaximumPoolSize(plugin.getSettings().getMySqlConnectionPoolSize());
dataSource.setMinimumIdle(plugin.getSettings().getMySqlConnectionPoolIdle());
dataSource.setMaxLifetime(plugin.getSettings().getMySqlConnectionPoolLifetime());
dataSource.setKeepaliveTime(plugin.getSettings().getMySqlConnectionPoolKeepAlive());
dataSource.setConnectionTimeout(plugin.getSettings().getMySqlConnectionPoolTimeout());
final DatabaseSettings.PoolOptions pool = plugin.getSettings().getDatabase().getPoolOptions();
dataSource.setMaximumPoolSize(pool.getSize());
dataSource.setMinimumIdle(pool.getIdle());
dataSource.setMaxLifetime(pool.getLifetime());
dataSource.setKeepaliveTime(pool.getKeepAlive());
dataSource.setConnectionTimeout(pool.getTimeout());
dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties
@@ -119,8 +130,8 @@ public class MySqlDatabase extends Database {
statement.execute(tableCreationStatement);
}
} catch (SQLException 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);
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);
}
} catch (SQLException | IOException e) {
throw new IllegalStateException("Failed to establish a connection to the MySQL database. "
@@ -332,26 +343,31 @@ public class MySqlDatabase extends Database {
@Override
public void deleteUserData(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
// Delete Position
PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `id`
IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""));
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
statement.executeUpdate();
statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
WHERE `uuid`=?;"""));
statement.setString(1, uuid.toString());
statement.executeUpdate();
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `id`
IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""))) {
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete player positions from the database", e);
return;
}
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
plugin.log(Level.SEVERE, "Failed to delete user data", e);
}
}
@@ -62,7 +62,7 @@ public class SqLiteDatabase extends Database {
public SqLiteDatabase(@NotNull HuskHomes plugin) {
super(plugin);
this.databaseFile = new File(plugin.getDataFolder(), DATABASE_FILE_NAME);
this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile();
}
private Connection getConnection() throws SQLException {
@@ -126,11 +126,11 @@ 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
(?,?,?,?,?,?,?,?)
RETURNING `id`;"""))) {
INSERT INTO `%positions_table%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?)
RETURNING `id`;"""))) {
statement.setDouble(1, position.getX());
statement.setDouble(2, position.getY());
@@ -182,11 +182,11 @@ public class SqLiteDatabase extends Database {
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
(?,?,?,?,?)
RETURNING `id`;"""))) {
INSERT INTO `%saved_positions_table%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?)
RETURNING `id`;"""))) {
statement.setInt(1, setPosition(position, connection));
statement.setString(2, position.getName());
@@ -321,25 +321,26 @@ public class SqLiteDatabase extends Database {
@Override
public void deleteUserData(@NotNull UUID uuid) {
try {
// Delete Position
PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `id`
IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""));
(SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""))) {
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete player positions from the database", e);
return;
}
statement = getConnection().prepareStatement(formatStatementTables("""
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
WHERE `uuid`=?;"""));
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
}
@@ -971,9 +972,7 @@ public class SqLiteDatabase extends Database {
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
plugin.log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().getUsername(), e);
plugin.log(Level.SEVERE, "Failed to set home for " + home.getOwner().getUsername(), e);
}
});
}
@@ -20,6 +20,7 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.User;
@@ -57,12 +58,13 @@ public class DynmapHook extends MapHook {
public void apiEnabled(@NotNull DynmapCommonAPI dynmapCommonAPI) {
dynmapApi = dynmapCommonAPI;
if (plugin.getSettings().doPublicHomesOnMap()) {
final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowPublicHomes()) {
getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME).orElseThrow();
dynmapApi.getMarkerAPI().createMarkerSet(getPublicHomesKey(),
getPublicHomesMarkerSetName(), dynmapApi.getMarkerAPI().getMarkerIcons(), false);
}
if (plugin.getSettings().doWarpsOnMap()) {
if (settings.isShowWarps()) {
getMarkerIcon(WARP_MARKER_IMAGE_NAME).orElseThrow();
dynmapApi.getMarkerAPI().createMarkerSet(getWarpsKey(),
getWarpsMarkerSetName(), dynmapApi.getMarkerAPI().getMarkerIcons(), false);
@@ -89,7 +91,7 @@ public class DynmapHook extends MapHook {
home.getX(), home.getY(), home.getZ(),
getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME).orElseThrow(), false)
.setDescription(MarkerInformationPopup.publicHome(
home, ICON_PATH + PUBLIC_HOME_MARKER_IMAGE_NAME, plugin
home, ICON_PATH + PUBLIC_HOME_MARKER_IMAGE_NAME
).toHtml());
});
});
@@ -135,7 +137,7 @@ public class DynmapHook extends MapHook {
warp.getX(), warp.getY(), warp.getZ(),
getMarkerIcon(WARP_MARKER_IMAGE_NAME).orElseThrow(), false)
.setDescription(MarkerInformationPopup.warp(
warp, ICON_PATH + WARP_MARKER_IMAGE_NAME, plugin
warp, ICON_PATH + WARP_MARKER_IMAGE_NAME
).toHtml());
});
});
@@ -69,7 +69,7 @@ public abstract class EconomyHook extends Hook {
*/
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin,
@NotNull TransactionResolver.Action action) {
plugin.getSettings().getEconomyCost(action)
plugin.getSettings().getEconomy().getCost(action)
.flatMap(cost -> plugin.getLocales().getLocale(
"economy_transaction_complete",
formatCurrency(cost),
@@ -125,7 +125,7 @@ public abstract class EconomyHook extends Hook {
* Create an action with a default cost.
*
* @return the default cost
* @deprecated Use the new {@link TransactionResolver.Action#getDefaultCost()} instead
* @deprecated Use the new {@code TransactionResolver.Action#getDefaultCost()} instead
*/
@Deprecated(since = "4.4", forRemoval = true)
public double getDefaultCost() {
@@ -20,6 +20,7 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
@@ -47,12 +48,13 @@ public abstract class MapHook extends Hook {
* Populate the map with public homes and warps.
*/
protected void populateMap() {
if (plugin.getSettings().doPublicHomesOnMap()) {
final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowPublicHomes()) {
plugin.getDatabase()
.getLocalPublicHomes(plugin)
.forEach(this::updateHome);
}
if (plugin.getSettings().doWarpsOnMap()) {
if (settings.isShowWarps()) {
plugin.getDatabase()
.getLocalWarps(plugin)
.forEach(this::updateWarp);
@@ -121,14 +123,16 @@ public abstract class MapHook extends Hook {
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected final boolean isValidPosition(@NotNull SavedPosition position) {
if (position instanceof Warp && !plugin.getSettings().doWarpsOnMap()) {
final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (position instanceof Warp && !settings.isShowWarps()) {
return false;
}
if (position instanceof Home && !plugin.getSettings().doPublicHomesOnMap()) {
if (position instanceof Home && !settings.isShowPublicHomes()) {
return false;
}
return !plugin.getSettings().doCrossServer() || position.getServer().equals(plugin.getServerName());
return !plugin.getSettings().getCrossServer().isEnabled()
|| position.getServer().equals(plugin.getServerName());
}
@NotNull
@@ -172,22 +176,20 @@ 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) {
return MarkerInformationPopup.create(warp.getName())
.thumbnail(thumbnail)
.field("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60))
.field("Description", warp.getMeta().getDescription())
.field("Location", warp.toString())
.field("Command", "/warp " + warp.getSafeIdentifier());
}
@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) {
return MarkerInformationPopup.create(home.getName())
.thumbnail(thumbnail)
.field("Owner", home.getOwner().getUsername())
.field("Description", plugin.getLocales().wrapText(home.getMeta().getDescription(), 60))
.field("Description", home.getMeta().getDescription())
.field("Location", home.toString())
.field("Command", "/phome " + home.getSafeIdentifier());
}
@@ -35,6 +35,7 @@ import net.pl3x.map.core.markers.option.Popup;
import net.pl3x.map.core.markers.option.Tooltip;
import net.pl3x.map.core.world.World;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
@@ -126,11 +127,12 @@ public class Pl3xMapHook extends MapHook implements EventListener {
}
private void registerLayers(@NotNull World world) {
if (plugin.getSettings().doWarpsOnMap()) {
final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowWarps()) {
WarpsLayer layer = new WarpsLayer(this, world);
world.getLayerRegistry().register(layer);
}
if (plugin.getSettings().doPublicHomesOnMap()) {
if (settings.isShowPublicHomes()) {
PublicHomesLayer layer = new PublicHomesLayer(this, world);
world.getLayerRegistry().register(layer);
}
@@ -139,10 +141,11 @@ public class Pl3xMapHook extends MapHook implements EventListener {
@EventHandler
public void onPl3xMapEnabled(@NotNull Pl3xMapEnabledEvent event) {
// Register icons
if (plugin.getSettings().doWarpsOnMap()) {
final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowWarps()) {
this.registerIcon(WARPS_LAYER, "markers/16x/warp.png");
}
if (plugin.getSettings().doPublicHomesOnMap()) {
if (settings.isShowPublicHomes()) {
this.registerIcon(PUBLIC_HOMES_LAYER, "markers/16x/public-home.png");
}
@@ -172,9 +175,9 @@ public class Pl3xMapHook extends MapHook implements EventListener {
return Options.builder()
.tooltip(new Tooltip(position.getIdentifier()))
.popup(new Popup(position instanceof Home home ? MarkerInformationPopup.publicHome(
home, ICON_PATH + WARPS_LAYER, plugin
home, ICON_PATH + WARPS_LAYER
).toHtml() : position instanceof Warp warp ? MarkerInformationPopup.warp(
warp, ICON_PATH + PUBLIC_HOMES_LAYER, plugin
warp, ICON_PATH + PUBLIC_HOMES_LAYER
).toHtml() : ""))
.build();
}
@@ -26,6 +26,9 @@ import com.djrapitops.plan.extension.ExtensionService;
import com.djrapitops.plan.extension.annotation.*;
import com.djrapitops.plan.extension.icon.Color;
import com.djrapitops.plan.extension.icon.Family;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.position.Home;
@@ -87,18 +90,13 @@ public class PlanHook extends Hook {
color = Color.LIGHT_BLUE
)
@SuppressWarnings("unused")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
protected static class PlanDataExtension implements DataExtension {
private static final String UNKNOWN_STRING = "N/A";
private Database database;
protected PlanDataExtension(@NotNull Database database) {
this.database = database;
}
protected PlanDataExtension() {
}
@Override
public CallEvents[] callExtensionMethodsOn() {
return new CallEvents[]{
@@ -23,6 +23,7 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BackCommand;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
@@ -60,7 +61,7 @@ public class EventListener {
plugin.getDatabase().ensureUser(onlineUser);
// Handle cross-server checks
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
this.handleInboundTeleport(onlineUser);
// Synchronize the global player list
@@ -106,12 +107,12 @@ public class EventListener {
plugin.getManager().homes().removeUserHomes(onlineUser);
// Update global lists
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
final List<String> localPlayerList = plugin.getLocalPlayerList().stream()
.filter(player -> !player.equals(onlineUser.getUsername()))
.toList();
if (plugin.getSettings().getBrokerType() == Broker.Type.REDIS) {
if (plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
this.synchronizeGlobalPlayerList(onlineUser, localPlayerList);
return;
}
@@ -139,7 +140,7 @@ public class EventListener {
try {
teleporter.teleportLocally(
(Position) teleport.getTarget(),
plugin.getSettings().doAsynchronousTeleports()
plugin.getSettings().getGeneral().isTeleportAsync()
);
} catch (TeleportationException e) {
e.displayMessage(teleporter);
@@ -158,7 +159,8 @@ public class EventListener {
final Optional<Position> bedPosition = teleporter.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getSpawn().ifPresent(spawn -> {
if (plugin.getSettings().doCrossServer() && !spawn.getServer().equals(plugin.getServerName())) {
if (plugin.getSettings().getCrossServer().isEnabled()
&& !spawn.getServer().equals(plugin.getServerName())) {
plugin.runSyncDelayed(() -> {
try {
Teleport.builder(plugin)
@@ -172,7 +174,7 @@ public class EventListener {
}, 40L);
} else {
try {
teleporter.teleportLocally(spawn, plugin.getSettings().doAsynchronousTeleports());
teleporter.teleportLocally(spawn, plugin.getSettings().getGeneral().isTeleportAsync());
} catch (TeleportationException e) {
e.displayMessage(teleporter);
}
@@ -181,7 +183,7 @@ public class EventListener {
});
} else {
try {
teleporter.teleportLocally(bedPosition.get(), plugin.getSettings().doAsynchronousTeleports());
teleporter.teleportLocally(bedPosition.get(), plugin.getSettings().getGeneral().isTeleportAsync());
} catch (TeleportationException e) {
e.displayMessage(teleporter);
}
@@ -217,7 +219,7 @@ public class EventListener {
* @param onlineUser the {@link OnlineUser} who died
*/
protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) {
if (plugin.getSettings().doBackCommandReturnByDeath() && plugin.getCommand(BackCommand.class)
if (plugin.getSettings().getGeneral().getBackCommand().isReturnByDeath() && plugin.getCommand(BackCommand.class)
.map(Command::getPermission).map(onlineUser::hasPermission).orElse(false)) {
plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
}
@@ -235,13 +237,14 @@ public class EventListener {
.map(command -> onlineUser.hasPermission(command.getPermission())
&& onlineUser.hasPermission(command.getPermission("death")))
.orElse(false);
if (plugin.getSettings().doBackCommandReturnByDeath() && canReturnByDeath) {
if (plugin.getSettings().getGeneral().getBackCommand().isReturnByDeath() && canReturnByDeath) {
plugin.getLocales().getLocale("return_by_death_notification")
.ifPresent(onlineUser::sendMessage);
}
// Respawn the player via the global respawn system
if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning()) {
final Settings.CrossServerSettings crossServer = plugin.getSettings().getCrossServer();
if (crossServer.isEnabled() && crossServer.isGlobalRespawning()) {
this.respawnGlobally(onlineUser);
}
});
@@ -283,7 +286,7 @@ public class EventListener {
* @param sourcePosition the source {@link Position} they came from
*/
protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) {
if (!plugin.getSettings().doBackCommandSaveOnTeleportEvent()) {
if (!plugin.getSettings().getGeneral().getBackCommand().isSaveOnTeleportEvent()) {
return;
}
@@ -298,9 +301,9 @@ public class EventListener {
* @param position the new spawn point
*/
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (!plugin.getSettings().doAlwaysRespawnAtSpawn()
&& plugin.getSettings().doCrossServer()
&& plugin.getSettings().isGlobalRespawning()) {
if (!plugin.getSettings().getGeneral().isAlwaysRespawnAtSpawn()
&& plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().getCrossServer().isGlobalRespawning()) {
plugin.getDatabase().setRespawnPosition(onlineUser, position);
}
}
@@ -163,7 +163,7 @@ public class HomesManager {
* @param homeId the UUID of the home/warp to update
*/
private void propagateCacheUpdate(@NotNull UUID homeId) {
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_HOME)
.scope(Message.Scope.SERVER)
@@ -203,7 +203,8 @@ public class HomesManager {
final SavedUser savedOwner = plugin.getSavedUser(owner)
.or(() -> plugin.getDatabase().getUserData(owner.getUuid()))
.orElseThrow(() -> new IllegalStateException("User data not found for " + owner.getUuid()));
if (plugin.getSettings().doEconomy() && homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) {
if (plugin.getSettings().getEconomy().isEnabled()
&& homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) {
if (!buyAdditionalSlots || plugin.getEconomyHook().isEmpty() || !(owner instanceof OnlineUser online)) {
throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS);
}
@@ -230,7 +231,10 @@ public class HomesManager {
public void createHome(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position)
throws ValidationException {
this.createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true, false);
this.createHome(
owner, name, position, plugin.getSettings().getGeneral().getNames().isOverwriteExisting(),
true, false
);
}
public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException {
@@ -269,7 +273,7 @@ public class HomesManager {
h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName)
));
publicHomes.removeIf(h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName));
if (plugin.getSettings().doCrossServer() && serverName.equals(plugin.getServerName())) {
if (plugin.getSettings().getCrossServer().isEnabled() && serverName.equals(plugin.getServerName())) {
plugin.getMapHook().ifPresent(hook -> hook.clearHomes(worldName));
}
plugin.getCommands().stream()
@@ -374,23 +378,23 @@ public class HomesManager {
public int getMaxHomes(@Nullable User user) {
return user instanceof OnlineUser online ? online.getMaxHomes(
plugin.getSettings().getMaxHomes(),
plugin.getSettings().doStackPermissionLimits()
) : plugin.getSettings().getMaxHomes();
plugin.getSettings().getGeneral().getMaxHomes(),
plugin.getSettings().getGeneral().isStackPermissionLimits()
) : plugin.getSettings().getGeneral().getMaxHomes();
}
public int getMaxPublicHomes(@Nullable User user) {
return user instanceof OnlineUser online ? online.getMaxPublicHomes(
plugin.getSettings().getMaxPublicHomes(),
plugin.getSettings().doStackPermissionLimits()
) : plugin.getSettings().getMaxPublicHomes();
plugin.getSettings().getGeneral().getMaxPublicHomes(),
plugin.getSettings().getGeneral().isStackPermissionLimits()
) : plugin.getSettings().getGeneral().getMaxPublicHomes();
}
public int getFreeHomes(@Nullable User user) {
return user instanceof OnlineUser online ? online.getFreeHomes(
plugin.getSettings().getFreeHomeSlots(),
plugin.getSettings().doStackPermissionLimits()
) : plugin.getSettings().getFreeHomeSlots();
plugin.getSettings().getEconomy().getFreeHomeSlots(),
plugin.getSettings().getGeneral().isStackPermissionLimits()
) : plugin.getSettings().getEconomy().getFreeHomeSlots();
}
}
@@ -54,7 +54,7 @@ public class Manager {
// Update caches on all servers
protected void propagateCacheUpdate() {
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_CACHES)
.scope(Message.Scope.SERVER)
@@ -117,7 +117,8 @@ public class RequestsManager {
}
public void sendTeleportAllRequest(@NotNull OnlineUser requester) {
final long expiry = Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime();
final long expiry = Instant.now().getEpochSecond()
+ plugin.getSettings().getGeneral().getTeleportRequestExpiryTime();
final TeleportRequest request = new TeleportRequest(requester, TeleportRequest.Type.TPA_HERE, expiry);
for (OnlineUser onlineUser : plugin.getOnlineUsers()) {
if (onlineUser.equals(requester)) {
@@ -127,7 +128,7 @@ public class RequestsManager {
sendLocalTeleportRequest(request, onlineUser);
}
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request))
@@ -145,7 +146,8 @@ public class RequestsManager {
*/
public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser,
@NotNull TeleportRequest.Type type) throws IllegalArgumentException {
final long expiry = Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime();
final long expiry = Instant.now().getEpochSecond()
+ plugin.getSettings().getGeneral().getTeleportRequestExpiryTime();
final TeleportRequest request = new TeleportRequest(requester, type, expiry);
final Optional<OnlineUser> localTarget = plugin.getOnlineUser(targetUser);
if (localTarget.isPresent()) {
@@ -161,7 +163,7 @@ public class RequestsManager {
}
// If the player couldn't be found locally, send the request cross-server
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
request.setRecipientName(targetUser);
plugin.fireEvent(plugin.getSendTeleportRequestEvent(requester, request), (event -> Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
@@ -204,7 +206,8 @@ public class RequestsManager {
.ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
.ifPresent(recipient::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORT_REQUEST_RECEIVED)
plugin.getSettings().getGeneral().getSoundEffects()
.get(Settings.SoundEffectAction.TELEPORT_REQUEST_RECEIVED)
.ifPresent(recipient::playSound);
}));
}
@@ -286,15 +289,16 @@ public class RequestsManager {
// Fire event and send request response confirmation to the recipient
plugin.fireEvent(plugin.getReplyTeleportRequestEvent(recipient, request), (event -> {
plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation",
request.getRequesterName())
.ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale(
"teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation",
request.getRequesterName()
).ifPresent(recipient::sendMessage);
// Find the requester and inform them of the response
final Optional<OnlineUser> localRequester = plugin.getOnlineUserExact(request.getRequesterName());
if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().doCrossServer()) {
} else if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder()
.type(Message.Type.TELEPORT_REQUEST_RESPONSE)
.payload(Payload.withTeleportRequest(request))
@@ -314,7 +318,7 @@ public class RequestsManager {
.teleporter(recipient);
// Strict /tpahere requests will teleport to where the sender was when typing the command
if (plugin.getSettings().doStrictTpaHereRequests()) {
if (plugin.getSettings().getGeneral().isStrictTpaHereRequests()) {
builder.target(request.getRequesterPosition());
} else {
builder.target(request.getRequesterName());
@@ -79,7 +79,7 @@ public class WarpsManager {
}
private void propagateCacheUpdate(@NotNull UUID warpId) {
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_WARP)
.scope(Message.Scope.SERVER)
@@ -103,7 +103,8 @@ public class WarpsManager {
@NotNull
public List<String> getUsableWarps(@NotNull CommandUser user) {
if (!plugin.getSettings().doPermissionRestrictWarps() || user.hasPermission(Warp.getWildcardPermission())) {
if (!plugin.getSettings().getGeneral().isPermissionRestrictWarps()
|| user.hasPermission(Warp.getWildcardPermission())) {
return getWarps();
}
return warps.stream()
@@ -137,7 +138,7 @@ public class WarpsManager {
@NotNull
public Warp createWarp(@NotNull String name, @NotNull Position position) throws ValidationException {
return this.createWarp(name, position, plugin.getSettings().doOverwriteExistingHomesWarps());
return this.createWarp(name, position, plugin.getSettings().getGeneral().getNames().isOverwriteExisting());
}
public void deleteWarp(@NotNull String name) throws ValidationException {
@@ -169,7 +170,7 @@ public class WarpsManager {
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
final int deleted = plugin.getDatabase().deleteAllWarps(worldName, serverName);
warps.removeIf(warp -> warp.getServer().equals(serverName) && warp.getWorld().getName().equals(worldName));
if (plugin.getSettings().doCrossServer() && plugin.getServerName().equals(serverName)) {
if (plugin.getSettings().getCrossServer().isEnabled() && plugin.getServerName().equals(serverName)) {
plugin.getMapHook().ifPresent(hook -> hook.clearWarps(worldName));
}
plugin.getCommands().stream()
@@ -157,7 +157,10 @@ public abstract class Broker {
protected String getSubChannelId() {
final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor());
try {
return plugin.getKey(plugin.getSettings().getClusterId().toLowerCase(Locale.ENGLISH), version).asString();
return plugin.getKey(
plugin.getSettings().getCrossServer().getClusterId().toLowerCase(Locale.ENGLISH),
version
).asString();
} catch (InvalidKeyException e) {
plugin.log(Level.SEVERE, "Cluster ID specified in config contains invalid characters");
}
@@ -19,96 +19,197 @@
package net.william278.huskhomes.network;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.util.Pool;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.CrossServerSettings.RedisSettings;
/**
* Redis PubSub broker implementation.
*/
public class RedisBroker extends PluginMessageBroker {
private JedisPool jedisPool;
private final Subscriber subscriber;
public RedisBroker(@NotNull HuskHomes plugin) {
super(plugin);
this.subscriber = new Subscriber(this, getSubChannelId());
}
@Blocking
@Override
public void initialize() throws IllegalStateException {
super.initialize();
// Establish a connection with the Redis server
final Pool<Jedis> jedisPool = getJedisPool(plugin.getSettings().getCrossServer().getRedis());
try {
jedisPool.getResource().ping();
} catch (JedisException e) {
throw new IllegalStateException("Failed to establish connection with Redis. "
+ "Please check the supplied credentials in the config file", e);
}
final String password = plugin.getSettings().getRedisPassword();
final String host = plugin.getSettings().getRedisHost();
final int port = plugin.getSettings().getRedisPort();
final boolean useSSL = plugin.getSettings().useRedisSsl();
this.jedisPool = password.isEmpty() ? new JedisPool(new JedisPoolConfig(), host, port, 0, useSSL)
: new JedisPool(new JedisPoolConfig(), host, port, 0, password, useSSL);
new Thread(getSubscriber(), plugin.getKey("redis_subscriber").toString()).start();
plugin.log(Level.INFO, "Initialized Redis connection pool");
// Subscribe using a thread (rather than a task)
subscriber.enable(jedisPool);
new Thread(subscriber::subscribe, "huskhomes:redis_subscriber").start();
}
@NotNull
private Runnable getSubscriber() {
return () -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(@NotNull String channel, @NotNull String encodedMessage) {
if (!channel.equals(getSubChannelId())) {
return;
}
private static Pool<Jedis> getJedisPool(@NotNull RedisSettings settings) {
// Get the Redis connection settings
final String password = settings.getPassword();
final String host = settings.getHost();
final int port = settings.getPort();
final boolean useSSL = settings.isUseSsl();
final Message message;
try {
message = plugin.getGson().fromJson(encodedMessage, Message.class);
} catch (Exception e) {
plugin.log(Level.WARNING, "Failed to decode message from Redis: " + e.getMessage());
return;
}
// Create the jedis pool
final JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(0);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
if (message.getScope() == Message.Scope.PLAYER) {
plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> handle(receiver, message));
return;
}
// Check if sentinels are to be used
final RedisSettings.SentinelSettings sentinel = settings.getSentinel();
Set<String> redisSentinelNodes = new HashSet<>(sentinel.getNodes());
if (!redisSentinelNodes.isEmpty()) {
final String sentinelPassword = sentinel.getPassword();
return new JedisSentinelPool(sentinel.getMasterName(), redisSentinelNodes, password.isEmpty()
? null : password, sentinelPassword.isEmpty() ? null : sentinelPassword);
}
if (message.getTarget().equals(plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) {
plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> handle(receiver, message));
}
}
}, getSubChannelId());
}
};
// Otherwise, use the standard Jedis pool
return password.isEmpty()
? new JedisPool(config, host, port, 0, useSSL)
: new JedisPool(config, host, port, 0, password, useSSL);
}
@Override
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
plugin.runAsync(() -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(getSubChannelId(), plugin.getGson().toJson(message));
}
});
plugin.runAsync(() -> subscriber.send(message));
}
@Override
@Blocking
public void close() {
super.close();
if (jedisPool != null) {
jedisPool.close();
subscriber.disable();
}
@AllArgsConstructor
private static class Subscriber extends JedisPubSub {
private static final int RECONNECTION_TIME = 8000;
private final RedisBroker broker;
private final String channel;
private Pool<Jedis> jedisPool;
private boolean enabled;
private boolean reconnected;
private Subscriber(@NotNull RedisBroker broker, @NotNull String channel) {
this.broker = broker;
this.channel = channel;
}
private void enable(@NotNull Pool<Jedis> jedisPool) {
this.jedisPool = jedisPool;
this.enabled = true;
}
@Blocking
private void disable() {
this.enabled = false;
if (jedisPool != null && !jedisPool.isClosed()) {
jedisPool.close();
}
this.unsubscribe();
}
@Blocking
public void send(@NotNull Message message) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(channel, broker.plugin.getGson().toJson(message));
}
}
@Blocking
private void subscribe() {
while (enabled && !Thread.interrupted() && jedisPool != null && !jedisPool.isClosed()) {
try (Jedis jedis = jedisPool.getResource()) {
if (reconnected) {
broker.plugin.log(Level.INFO, "Redis connection is alive again");
}
// Subscribe to channel and lock the thread
jedis.subscribe(this, channel);
} catch (Throwable t) {
// Thread was unlocked due error
onThreadUnlock(t);
}
}
}
private void onThreadUnlock(@NotNull Throwable t) {
if (!enabled) {
return;
}
if (reconnected) {
broker.plugin.log(Level.WARNING, "Redis Server connection lost. Attempting reconnect in %ss..."
.formatted(RECONNECTION_TIME / 1000), t);
}
try {
this.unsubscribe();
} catch (Throwable ignored) {
// empty catch
}
// Make an instant subscribe if occurs any error on initialization
if (!reconnected) {
reconnected = true;
} else {
try {
Thread.sleep(RECONNECTION_TIME);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Override
public void onMessage(@NotNull String channel, @NotNull String encoded) {
final Message message;
try {
message = broker.plugin.getGson().fromJson(encoded, Message.class);
} catch (Exception e) {
broker.plugin.log(Level.WARNING, "Failed to decode message from Redis: " + e.getMessage());
return;
}
if (message.getScope() == Message.Scope.PLAYER) {
broker.plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> broker.handle(receiver, message));
return;
}
if (message.getTarget().equals(broker.plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) {
broker.plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> broker.handle(receiver, message));
}
}
}
@@ -20,38 +20,36 @@
package net.william278.huskhomes.position;
import com.google.gson.annotations.Expose;
import lombok.*;
import org.jetbrains.annotations.NotNull;
/**
* Represents a local position on this server.
*/
@Setter
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class Location {
@Expose
private double x;
@Expose
private double y;
@Expose
private double z;
@Expose
private float yaw;
@Expose
private float pitch;
@Expose
private World world;
protected Location(double x, double y, double z, float yaw, float pitch, @NotNull World world) {
this.setX(x);
this.setY(y);
this.setZ(z);
this.setYaw(yaw);
this.setPitch(pitch);
this.setWorld(world);
}
public Location() {
}
@NotNull
public static Location at(double x, double y, double z, float yaw, float pitch, @NotNull World world) {
return new Location(x, y, z, yaw, pitch, world);
@@ -76,70 +74,4 @@ public class Location {
this.setWorld(position.getWorld());
}
/**
* The double-precision defined x coordinate of the location.
*/
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
/**
* The double-precision defined y coordinate of the location.
*/
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
/**
* The double-precision defined z coordinate of the location.
*/
public double getZ() {
return z;
}
public void setZ(double z) {
this.z = z;
}
/**
* The float-precision defined yaw facing of the location.
*/
public float getYaw() {
return yaw;
}
public void setYaw(float yaw) {
this.yaw = yaw;
}
/**
* The float-precision defined pitch facing of the location.
*/
public float getPitch() {
return pitch;
}
public void setPitch(float pitch) {
this.pitch = pitch;
}
/**
* The {@link World} the location is on.
*/
public World getWorld() {
return world;
}
public void setWorld(World world) {
this.world = world;
}
}
@@ -20,12 +20,15 @@
package net.william278.huskhomes.position;
import com.google.gson.annotations.Expose;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.teleport.Target;
import org.jetbrains.annotations.NotNull;
/**
* Represents a position - a {@link Location} somewhere on the proxy network or server.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Position extends Location implements Target {
@Expose
@@ -43,10 +46,6 @@ public class Position extends Location implements Target {
this.setServer(server);
}
@SuppressWarnings("unused")
private Position() {
}
@NotNull
public static Position at(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull String server) {
@@ -19,6 +19,7 @@
package net.william278.huskhomes.position;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -28,6 +29,7 @@ import java.util.UUID;
/**
* Represents a world on a server.
*/
@NoArgsConstructor
public class World {
private String name;
@@ -41,10 +43,6 @@ public class World {
this.setEnvironment(environment);
}
@SuppressWarnings("unused")
public World() {
}
@NotNull
public static World from(@NotNull String name, @NotNull UUID uuid, @NotNull Environment environment) {
return new World(name, uuid, environment);
@@ -20,6 +20,7 @@
package net.william278.huskhomes.random;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
@@ -35,17 +36,15 @@ import java.util.logging.Level;
*/
public final class NormalDistributionEngine extends RandomTeleportEngine {
private final int radius;
private final int spawnRadius;
private final Settings.RtpSettings.RtpRadius radius;
private final float mean;
private final float standardDeviation;
public NormalDistributionEngine(@NotNull HuskHomes plugin) {
super(plugin, "Normal Distribution");
this.radius = plugin.getSettings().getRtpRadius();
this.spawnRadius = determineSpawnRadius(radius, plugin.getSettings().getRtpSpawnRadius(), plugin);
this.mean = plugin.getSettings().getRtpDistributionMean();
this.standardDeviation = plugin.getSettings().getRtpDistributionStandardDeviation();
this.radius = plugin.getSettings().getRtp().getRegion();
this.mean = plugin.getSettings().getRtp().getDistributionMean();
this.standardDeviation = plugin.getSettings().getRtp().getDistributionStandardDeviation();
}
// Utility for determining a valid spawn radius
@@ -93,7 +92,8 @@ public final class NormalDistributionEngine extends RandomTeleportEngine {
*/
private CompletableFuture<Optional<Location>> generateSafeLocation(@NotNull World world) {
return plugin.findSafeGroundLocation(generateLocation(
getCenterPoint(world), mean, standardDeviation, spawnRadius, radius
getCenterPoint(world), mean, standardDeviation,
radius.getMin(), radius.getMax()
));
}
@@ -19,6 +19,8 @@
package net.william278.huskhomes.teleport;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.william278.desertwell.util.ThrowingConsumer;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BackCommand;
@@ -60,7 +62,7 @@ public class Teleport {
this.target = target;
this.type = type;
this.actions = actions;
this.async = plugin.getSettings().doAsynchronousTeleports();
this.async = plugin.getSettings().getGeneral().isTeleportAsync();
this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class)
.map(command -> executor.hasPermission(command.getPermission())
&& executor.hasPermission(command.getPermission("previous")))
@@ -81,7 +83,7 @@ public class Teleport {
// Teleport a user on another server
if (localTeleporter.isEmpty()) {
final Username teleporter = (Username) this.teleporter;
if (!plugin.getSettings().doCrossServer()) {
if (!plugin.getSettings().getCrossServer().isEnabled()) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin);
}
@@ -128,7 +130,7 @@ public class Teleport {
return;
}
if (plugin.getSettings().doCrossServer()) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
fireEvent((event) -> {
performTransactions();
Message.builder()
@@ -149,7 +151,8 @@ public class Teleport {
}
final Position target = (Position) this.target;
if (!plugin.getSettings().doCrossServer() || target.getServer().equals(plugin.getServerName())) {
if (!plugin.getSettings().getCrossServer().isEnabled()
|| target.getServer().equals(plugin.getServerName())) {
try {
teleporter.teleportLocally(target, async);
} catch (TeleportationException e) {
@@ -176,7 +179,7 @@ public class Teleport {
public void displayTeleportingComplete(@NotNull OnlineUser teleporter) {
plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(teleporter::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(teleporter::playSound);
}
@@ -217,6 +220,8 @@ public class Teleport {
/**
* Represents the type of teleport being used.
*/
@Getter
@AllArgsConstructor
public enum Type {
TELEPORT(0),
RESPAWN(1),
@@ -224,10 +229,6 @@ public class Teleport {
private final int typeId;
Type(final int typeId) {
this.typeId = typeId;
}
/**
* Returns a {@link Type} by its type id.
*
@@ -240,8 +241,5 @@ public class Teleport {
.findFirst();
}
public int getTypeId() {
return typeId;
}
}
}
@@ -19,6 +19,8 @@
package net.william278.huskhomes.teleport;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
@@ -31,12 +33,17 @@ import java.util.List;
/**
* A builder for {@link Teleport} and {@link TimedTeleport} objects.
*/
@Accessors(fluent = true, chain = true)
public class TeleportBuilder {
private final HuskHomes plugin;
@Setter
private OnlineUser executor;
private Teleportable teleporter;
private Target target;
@Setter
private boolean updateLastPosition = true;
@Setter
private Teleport.Type type = Teleport.Type.TELEPORT;
private List<TransactionResolver.Action> actions = List.of();
@@ -52,12 +59,16 @@ public class TeleportBuilder {
@NotNull
public TimedTeleport toTimedTeleport() throws IllegalStateException {
validateTeleport();
this.validateTeleport();
if (!(teleporter instanceof OnlineUser onlineTeleporter)) {
throw new IllegalStateException("Teleporter must be an OnlineUser for timed teleportation");
}
return new TimedTeleport(executor, onlineTeleporter, target, type,
plugin.getSettings().getTeleportWarmupTime(), updateLastPosition, actions, plugin);
return new TimedTeleport(
executor, onlineTeleporter, target, type,
plugin.getSettings().getGeneral().getTeleportWarmupTime(),
updateLastPosition, actions, plugin
);
}
private void validateTeleport() throws TeleportationException {
@@ -77,12 +88,6 @@ public class TeleportBuilder {
}
}
@NotNull
public TeleportBuilder executor(@NotNull OnlineUser executor) {
this.executor = executor;
return this;
}
@NotNull
public TeleportBuilder teleporter(@NotNull Teleportable teleporter) {
this.teleporter = teleporter;
@@ -91,8 +96,7 @@ public class TeleportBuilder {
@NotNull
public TeleportBuilder teleporter(@NotNull String teleporter) {
this.teleporter = Teleportable.username(teleporter);
return this;
return teleporter(Teleportable.username(teleporter));
}
@NotNull
@@ -103,14 +107,7 @@ public class TeleportBuilder {
@NotNull
public TeleportBuilder target(@NotNull String target) {
this.target = Target.username(target);
return this;
}
@NotNull
public TeleportBuilder updateLastPosition(boolean updateLastPosition) {
this.updateLastPosition = updateLastPosition;
return this;
return target(Target.username(target));
}
@SuppressWarnings("removal")
@@ -126,10 +123,4 @@ public class TeleportBuilder {
this.actions = List.of(actions);
return this;
}
@NotNull
public TeleportBuilder type(@NotNull Teleport.Type type) {
this.type = type;
return this;
}
}
@@ -21,6 +21,10 @@ package net.william278.huskhomes.teleport;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
@@ -30,6 +34,9 @@ import java.time.Instant;
/**
* Represents a request between players for one user to teleport to another, or vice versa.
*/
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TeleportRequest {
@Expose
@@ -40,6 +47,8 @@ public class TeleportRequest {
private Position requesterPosition;
@Expose
@SerializedName("expiry_time")
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private long expiryTime;
@Expose
private Type type;
@@ -62,10 +71,6 @@ public class TeleportRequest {
this.expiryTime = expiryTime;
}
@SuppressWarnings("unused")
private TeleportRequest() {
}
/**
* Returns if the request has now expired.
*
@@ -75,65 +80,6 @@ public class TeleportRequest {
return Instant.now().isAfter(Instant.ofEpochSecond(expiryTime));
}
/**
* The name of the request recipient.
*/
@NotNull
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(@NotNull String recipientName) {
this.recipientName = recipientName;
}
/**
* The user making the request.
*/
@NotNull
public String getRequesterName() {
return requesterName;
}
public void setRequesterName(String requesterName) {
this.requesterName = requesterName;
}
/**
* The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request.
*/
@NotNull
public Position getRequesterPosition() {
return requesterPosition;
}
public void setRequesterPosition(Position requesterPosition) {
this.requesterPosition = requesterPosition;
}
/**
* The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE}.
*/
@NotNull
public TeleportRequest.Type getType() {
return type;
}
public void setType(@NotNull TeleportRequest.Type type) {
this.type = type;
}
/**
* The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} or {@link Status#DECLINED}.
*/
@NotNull
public TeleportRequest.Status getStatus() {
return status;
}
public void setStatus(@NotNull TeleportRequest.Status status) {
this.status = status;
}
/**
* Types of teleport requests ({@code /tpa} or {@code /tpahere}).
@@ -97,7 +97,7 @@ public class TimedTeleport extends Teleport implements Runnable {
public void run() {
// Display a countdown action bar message
if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
.ifPresent(teleporter::playSound);
plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft))
.ifPresent(this::sendStatusMessage);
@@ -142,7 +142,7 @@ public class TimedTeleport extends Teleport implements Runnable {
.ifPresent(teleporter::sendMessage);
plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
return true;
}
@@ -153,7 +153,7 @@ public class TimedTeleport extends Teleport implements Runnable {
.ifPresent(teleporter::sendMessage);
plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound);
return true;
}
@@ -164,7 +164,7 @@ public class TimedTeleport extends Teleport implements Runnable {
}
private void sendStatusMessage(@NotNull MineDown message) {
teleporter.sendMessage(message, plugin.getSettings().getTeleportWarmupDisplay());
teleporter.sendMessage(message, plugin.getSettings().getGeneral().getTeleportWarmupDisplay());
}
private boolean hasTeleporterMoved() {
@@ -131,14 +131,11 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
* @param slot the {@link Locales.DisplaySlot} to send the message to
*/
public void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) {
if (slot == Locales.DisplaySlot.CHAT) {
sendMessage(mineDown);
} else if (slot == Locales.DisplaySlot.ACTION_BAR) {
sendActionBar(mineDown);
} else if (slot == Locales.DisplaySlot.TITLE) {
sendTitle(mineDown, false);
} else if (slot == Locales.DisplaySlot.SUBTITLE) {
sendTitle(mineDown, true);
switch (slot) {
case ACTION_BAR -> sendActionBar(mineDown);
case TITLE -> sendTitle(mineDown, false);
case SUBTITLE -> sendTitle(mineDown, true);
default -> sendMessage(mineDown);
}
}
@@ -19,6 +19,9 @@
package net.william278.huskhomes.user;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import java.time.Duration;
@@ -29,32 +32,23 @@ import java.util.UUID;
/**
* Represents data about a player on the server.
*/
@Getter
@AllArgsConstructor
public class SavedUser {
private final User user;
@Setter
private int homeSlots;
@Setter
private boolean ignoringTeleports;
/**
* Create a new SavedUser object.
*
* @param user The user to create the object for
* @param homeSlots The number of home slots the user has
* @param ignoringTeleports Whether the user is ignoring teleports or not
*/
public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports) {
this.user = user;
this.homeSlots = homeSlots;
this.ignoringTeleports = ignoringTeleports;
}
/**
* Create a new SavedUser object.
*
* <p>Please note that User RTP cooldowns are no longer stored in {@link SavedUser} objects;
* please use the new API methods for getting/setting cooldowns
*
* @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object.
* @deprecated See {@code #SavedUser(User, int, boolean)} to create a SavedUser object.
*/
@Deprecated(since = "4.4", forRemoval = true)
@SuppressWarnings("unused")
@@ -62,36 +56,16 @@ public class SavedUser {
this(user, homeSlots, ignoringTeleports);
}
@NotNull
public User getUser() {
return user;
}
@NotNull
public UUID getUserUuid() {
return user.getUuid();
return getUser().getUuid();
}
@NotNull
public String getUsername() {
return user.getUsername();
return getUser().getUsername();
}
public int getHomeSlots() {
return homeSlots;
}
public void setHomeSlots(int homeSlots) {
this.homeSlots = homeSlots;
}
public boolean isIgnoringTeleports() {
return ignoringTeleports;
}
public void setIgnoringTeleports(boolean ignoringTeleports) {
this.ignoringTeleports = ignoringTeleports;
}
/**
* Get the user's RTP cooldown. This method will always return 5 seconds before the current time since v4.4.
@@ -19,6 +19,9 @@
package net.william278.huskhomes.user;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@@ -26,7 +29,9 @@ import java.util.UUID;
/**
* Represents a user who has data saved in the database.
*/
public class User {
@Getter
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class User implements Comparable<User> {
@NotNull
private final UUID uuid;
@@ -34,17 +39,6 @@ public class User {
@NotNull
private final String 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
*/
protected User(@NotNull UUID uuid, @NotNull String username) {
this.uuid = uuid;
this.username = username;
}
@NotNull
public static User of(@NotNull UUID uuid, @NotNull String username) {
return new User(uuid, username);
@@ -58,13 +52,9 @@ public class User {
return super.equals(obj);
}
@NotNull
public UUID getUuid() {
return uuid;
@Override
public int compareTo(@NotNull User o) {
return getUsername().compareTo(o.getUsername());
}
@NotNull
public String getUsername() {
return username;
}
}
@@ -19,6 +19,8 @@
package net.william278.huskhomes.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
@@ -51,7 +53,7 @@ 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)
return getPlugin().getSettings().getEconomy().getCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c))
.map(c -> getEconomyHook()
@@ -70,7 +72,7 @@ public interface TransactionResolver {
// Validates if the user is on cooldown for an action
private boolean isNotOnCooldown(@NotNull OnlineUser player, @NotNull Action action) {
final long configCooldown = getPlugin().getSettings().getCooldown(action);
final long configCooldown = getPlugin().getSettings().getCooldowns().getCooldown(action);
if (configCooldown <= 0 || player.hasPermission(Action.BYPASS_COOLDOWNS_PERMISSION)) {
return true;
}
@@ -118,8 +120,8 @@ public interface TransactionResolver {
* @param action the {@link Action action} to deduct the cost from if needed
*/
default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) {
getEconomyHook().ifPresent(hook -> getPlugin().getSettings()
.getEconomyCost(action).map(Math::abs)
getEconomyHook().ifPresent(hook -> getPlugin().getSettings().getEconomy()
.getCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c))
.ifPresent(cost -> {
@@ -127,7 +129,7 @@ public interface TransactionResolver {
hook.notifyDeducted(player, getPlugin(), action);
}));
final long configCooldown = getPlugin().getSettings().getCooldown(action);
final long configCooldown = getPlugin().getSettings().getCooldowns().getCooldown(action);
if (configCooldown > 0 && !player.hasPermission(Action.BYPASS_COOLDOWNS_PERMISSION)) {
getPlugin().getDatabase().setCooldown(action, player, Instant.now().plusSeconds(configCooldown));
}
@@ -172,6 +174,8 @@ public interface TransactionResolver {
/**
* Represents actions that can be the subject of a transaction.
*/
@Getter
@AllArgsConstructor
enum Action {
/*
@@ -200,54 +204,35 @@ public interface TransactionResolver {
public static final String BYPASS_COOLDOWNS_PERMISSION = "huskhomes.bypass_cooldowns";
private final double defaultCost;
private final int defaultCooldown;
Action(double defaultCost, int defaultCooldown) {
this.defaultCost = defaultCost;
this.defaultCooldown = defaultCooldown;
}
private final long defaultCooldown;
Action() {
this(0d, 0);
}
/**
* Create an action with a default cost.
*
* @return the default cost
*/
public double getDefaultCost() {
return defaultCost;
}
/**
* Get the default cooldown for this action (in seconds).
*
* @return the default cooldown in seconds
*/
public int getDefaultCooldown() {
return defaultCooldown;
this(0, 0);
}
// Get the default economy action cost map for the config
@NotNull
public static Map<String, Double> getEconomyCostsConfigMap() {
public static Map<Action, Double> getEconomyCosts() {
return Arrays.stream(values())
.filter(action -> action.getDefaultCost() > 0)
.collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH),
Action::getDefaultCost
action -> action,
Action::getDefaultCost,
(a, b) -> a,
TreeMap::new
));
}
// Get the default cooldown action time map for the config
@NotNull
public static Map<String, Integer> getCooldownsConfigMap() {
public static Map<Action, Long> getCooldownTimes() {
return Arrays.stream(values())
.filter(action -> action.getDefaultCooldown() > 0)
.collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH),
Action::getDefaultCooldown
action -> action,
Action::getDefaultCooldown,
(a, b) -> a,
TreeMap::new
));
}
@@ -19,24 +19,19 @@
package net.william278.huskhomes.util;
import de.exlll.configlib.Configuration;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.kyori.adventure.key.Key;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Unsafe /rtp Blocks ┃
┃ Developed by William278 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UnsafeBlocks {
@YamlKey("unsafe_blocks")
public List<String> unsafeBlocks;
@YamlKey("safe_occupation_blocks")
public List<String> safeOccupationBlocks;
/**
@@ -68,8 +63,4 @@ public class UnsafeBlocks {
return blockId;
}
@SuppressWarnings("unused")
public UnsafeBlocks() {
}
}
@@ -19,11 +19,13 @@
package net.william278.huskhomes.util;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
@Getter
public class ValidationException extends IllegalArgumentException {
private final Type type;
@@ -96,12 +98,6 @@ public class ValidationException extends IllegalArgumentException {
}
}
@NotNull
@SuppressWarnings("unused")
public Type getType() {
return type;
}
/**
* The type of validation error.
*/
@@ -19,22 +19,20 @@
package net.william278.huskhomes.util;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import org.jetbrains.annotations.NotNull;
@AllArgsConstructor
public class Validator {
public static final int MAX_NAME_LENGTH = 16;
public static final int MIN_NAME_LENGTH = 1;
public static final int MAX_DESCRIPTION_LENGTH = 256;
private final HuskHomes plugin;
public Validator(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/**
* Validate home and warp names.
*
@@ -67,7 +65,8 @@ public class Validator {
// Check a home/warp name contains only valid characters
private boolean isValidNameCharacters(@NotNull String name) {
return (name.matches(plugin.getSettings().getNameRegex()) || !plugin.getSettings().doRestrictNames())
final Settings.GeneralSettings.NameSettings config = plugin.getSettings().getGeneral().getNames();
return (name.matches(config.getRegex()) || !config.isRestrict())
&& !name.contains("\u0000")
&& !containsWhitespace(name)
&& !name.contains(Home.IDENTIFIER_DELIMITER);
@@ -75,13 +74,13 @@ public class Validator {
// Check a home/warp name is of a valid length
private boolean isValidNameLength(@NotNull String name) {
return name.length() <= MAX_NAME_LENGTH && name.length() >= MIN_NAME_LENGTH;
return name.length() <= MAX_NAME_LENGTH && !name.isEmpty();
}
// Check a home/warp description contains only valid characters
private boolean isValidDescriptionCharacters(@NotNull String description) {
return (description.matches(plugin.getSettings().getDescriptionRegex())
|| !plugin.getSettings().doRestrictDescriptions())
final Settings.GeneralSettings.DescriptionSettings config = plugin.getSettings().getGeneral().getDescriptions();
return (description.matches(config.getRegex()) || !config.isRestrict())
&& !description.contains("\u0000");
}