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
+1408 -1906

No files matched your search

+2
View File
@@ -93,6 +93,8 @@ allprojects {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.2' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.2'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.2' testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.2'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.10.2' testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.10.2'
testCompileOnly 'org.jetbrains:annotations:24.1.0'
} }
license { license {
+4 -3
View File
@@ -10,13 +10,13 @@ dependencies {
compileOnly 'org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT' compileOnly 'org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT'
compileOnly 'org.jetbrains:annotations:24.1.0' compileOnly 'org.jetbrains:annotations:24.1.0'
compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
compileOnly 'net.william278:annotaml:2.0.5'
compileOnly 'net.william278:DesertWell:2.0.4' compileOnly 'net.william278:DesertWell:2.0.4'
compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1' compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1'
compileOnly 'me.clip:placeholderapi:2.11.5' compileOnly 'me.clip:placeholderapi:2.11.5'
compileOnly('net.essentialsx:EssentialsX:2.20.1') { compileOnly('net.essentialsx:EssentialsX:2.20.1') {
exclude group: 'org.spigotmc', module: 'spigot-api' exclude group: 'org.spigotmc', module: 'spigot-api'
} }
compileOnly 'org.projectlombok:lombok:1.18.30'
testImplementation 'com.github.seeseemelk:MockBukkit-v1.17:1.13.0' testImplementation 'com.github.seeseemelk:MockBukkit-v1.17:1.13.0'
testImplementation 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' testImplementation 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
@@ -25,6 +25,8 @@ dependencies {
testImplementation "redis.clients:jedis:${jedis_version}" testImplementation "redis.clients:jedis:${jedis_version}"
testImplementation "org.xerial:sqlite-jdbc:${sqlite_driver_version}" testImplementation "org.xerial:sqlite-jdbc:${sqlite_driver_version}"
testImplementation "com.mysql:mysql-connector-j:${mysql_driver_version}" testImplementation "com.mysql:mysql-connector-j:${mysql_driver_version}"
annotationProcessor 'org.projectlombok:lombok:1.18.30'
} }
shadowJar { shadowJar {
@@ -39,11 +41,10 @@ shadowJar {
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown'
relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell'
relocate 'de.exlll', 'net.william278.huskhomes.libraries'
relocate 'org.json', 'net.william278.huskhomes.libraries.json' relocate 'org.json', 'net.william278.huskhomes.libraries.json'
relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml'
relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats' relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats'
@@ -19,10 +19,14 @@
package net.william278.huskhomes; package net.william278.huskhomes;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.platform.bukkit.BukkitAudiences; import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.Version; import net.william278.desertwell.util.Version;
import net.william278.huskhomes.api.HuskHomesAPI; import net.william278.huskhomes.api.HuskHomesAPI;
import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.BukkitCommand;
@@ -46,7 +50,6 @@ import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.PluginMessageBroker; import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker; import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RandomTeleportEngine; import net.william278.huskhomes.random.RandomTeleportEngine;
@@ -71,12 +74,14 @@ import space.arim.morepaperlib.commands.CommandRegistration;
import space.arim.morepaperlib.scheduling.GracefulScheduling; import space.arim.morepaperlib.scheduling.GracefulScheduling;
import java.io.File; import java.io.File;
import java.io.IOException; import java.nio.file.Path;
import java.lang.reflect.InvocationTargetException;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Getter
@Setter
@NoArgsConstructor
public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask.Supplier, BukkitEventDispatcher, public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask.Supplier, BukkitEventDispatcher,
PluginMessageListener, BukkitSafetyResolver { PluginMessageListener, BukkitSafetyResolver {
@@ -85,7 +90,10 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
*/ */
private static final int METRICS_ID = 8430; private static final int METRICS_ID = 8430;
private Set<SavedUser> savedUsers; private final Set<SavedUser> savedUsers = Sets.newHashSet();
private final Map<String, List<String>> globalPlayerList = Maps.newConcurrentMap();
private final Set<UUID> currentlyOnWarmup = Sets.newConcurrentHashSet();
private Settings settings; private Settings settings;
private Locales locales; private Locales locales;
private Database database; private Database database;
@@ -97,19 +105,15 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
private UnsafeBlocks unsafeBlocks; private UnsafeBlocks unsafeBlocks;
private List<Hook> hooks; private List<Hook> hooks;
private List<Command> commands; private List<Command> commands;
private Map<String, List<String>> globalPlayerList; @Getter(AccessLevel.NONE)
private Set<UUID> currentlyOnWarmup;
private Server server; private Server server;
@Getter(AccessLevel.NONE)
private BukkitAudiences audiences; private BukkitAudiences audiences;
@Getter(AccessLevel.NONE)
private MorePaperLib paperLib; private MorePaperLib paperLib;
@Nullable @Nullable
private Broker broker; private Broker broker;
// Default public constructor
public BukkitHuskHomes() {
super();
}
// Super constructor for unit testing // Super constructor for unit testing
@TestOnly @TestOnly
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description,
@@ -122,21 +126,15 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Create adventure audience // Create adventure audience
this.audiences = BukkitAudiences.create(this); this.audiences = BukkitAudiences.create(this);
this.paperLib = new MorePaperLib(this); this.paperLib = new MorePaperLib(this);
this.savedUsers = new HashSet<>();
this.globalPlayerList = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.validator = new Validator(this); this.validator = new Validator(this);
// Load settings and locales // Load settings and locales
initialize("plugin config & locale files", (plugin) -> { initialize("plugin config & locale files", (plugin) -> loadConfigs());
if (!loadConfigs()) {
throw new IllegalStateException("Failed to load config files. Please check the console for errors");
}
});
// Initialize the database // Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { final Database.Type type = getSettings().getDatabase().getType();
this.database = switch (getSettings().getDatabaseType()) { initialize(type.getDisplayName() + " database connection", (plugin) -> {
this.database = switch (type) {
case MYSQL, MARIADB -> new MySqlDatabase(this); case MYSQL, MARIADB -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this); case SQLITE -> new SqLiteDatabase(this);
case H2 -> new H2Database(this); case H2 -> new H2Database(this);
@@ -149,9 +147,10 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
this.manager = new Manager(this); this.manager = new Manager(this);
// Initialize the network messenger if proxy mode is enabled // Initialize the network messenger if proxy mode is enabled
if (getSettings().doCrossServer()) { final Settings.CrossServerSettings crossServer = getSettings().getCrossServer();
initialize(settings.getBrokerType().getDisplayName() + " message broker", (plugin) -> { if (crossServer.isEnabled()) {
broker = switch (settings.getBrokerType()) { initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> {
broker = switch (crossServer.getBrokerType()) {
case PLUGIN_MESSAGE -> new PluginMessageBroker(this); case PLUGIN_MESSAGE -> new PluginMessageBroker(this);
case REDIS -> new RedisBroker(this); case REDIS -> new RedisBroker(this);
}; };
@@ -205,7 +204,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
HuskHomes.super.registerHooks(); HuskHomes.super.registerHooks();
// Hooks // Hooks
if (getSettings().doEconomy() && isDependencyLoaded("Vault")) { if (getSettings().getEconomy().isEnabled() && isDependencyLoaded("Vault")) {
getHooks().add(new VaultEconomyHook(this)); getHooks().add(new VaultEconomyHook(this));
} }
if (isDependencyLoaded("PlaceholderAPI")) { if (isDependencyLoaded("PlaceholderAPI")) {
@@ -267,52 +266,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
return audiences.player(user); return audiences.player(user);
} }
@NotNull
@Override
public Set<SavedUser> getSavedUsers() {
return savedUsers;
}
@NotNull
@Override
public Settings getSettings() {
return settings;
}
@Override
public void setSettings(@NotNull Settings settings) {
this.settings = settings;
}
@NotNull
@Override
public Locales getLocales() {
return locales;
}
@Override
public void setLocales(@NotNull Locales locales) {
this.locales = locales;
}
@Override
@NotNull
public Database getDatabase() {
return database;
}
@Override
@NotNull
public Validator getValidator() {
return validator;
}
@NotNull
@Override
public Manager getManager() {
return manager;
}
@NotNull @NotNull
@Override @Override
public Broker getMessenger() { public Broker getMessenger() {
@@ -322,17 +275,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
return broker; return broker;
} }
@NotNull
@Override
public RandomTeleportEngine getRandomTeleportEngine() {
return randomTeleportEngine;
}
@Override
public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) {
this.randomTeleportEngine = randomTeleportEngine;
}
@Override @Override
public Optional<Spawn> getServerSpawn() { public Optional<Spawn> getServerSpawn() {
return Optional.ofNullable(serverSpawn); return Optional.ofNullable(serverSpawn);
@@ -343,81 +285,27 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
this.serverSpawn = spawn; this.serverSpawn = spawn;
} }
@Override
public void setServerSpawn(@NotNull Location location) {
try {
// Create or update the spawn.yml file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists() && !spawnFile.delete()) {
log(Level.WARNING, "Failed to delete the existing spawn.yml file");
}
this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get();
// Update the world spawn location, too
BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> {
assert bukkitLocation.getWorld() != null : "World was null when setting server spawn";
bukkitLocation.getWorld().setSpawnLocation(bukkitLocation);
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.WARNING, "Failed to save the server spawn.yml file", e);
}
}
@Override
@NotNull
public List<Hook> getHooks() {
return hooks;
}
@Override
public void setHooks(@NotNull List<Hook> hooks) {
this.hooks = hooks;
}
@Override @Override
@NotNull @NotNull
public Version getVersion() { public Version getVersion() {
return Version.fromString(getDescription().getVersion(), "-"); return Version.fromString(getDescription().getVersion(), "-");
} }
@Override
@NotNull
public List<Command> getCommands() {
return commands;
}
@Override
@NotNull
public Map<String, List<String>> getGlobalPlayerList() {
return globalPlayerList;
}
@Override
@NotNull
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
@Override @Override
@NotNull @NotNull
public String getServerName() { public String getServerName() {
return server.getName(); return server != null ? server.getName() : "server";
} }
@Override @Override
public void setServer(@NotNull Server server) { public void setServerName(@NotNull Server server) {
this.server = server; this.server = server;
} }
@Override
public void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks) {
this.unsafeBlocks = unsafeBlocks;
}
@Override @Override
@NotNull @NotNull
public UnsafeBlocks getUnsafeBlocks() { public Path getConfigDirectory() {
return unsafeBlocks; return getDataFolder().toPath();
} }
@Override @Override
@@ -438,21 +326,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
try { try {
final Metrics metrics = new Metrics(this, metricsId); final Metrics metrics = new Metrics(this, metricsId);
metrics.addCustomChart(new SimplePie("bungee_mode", metrics.addCustomChart(new SimplePie("bungee_mode",
() -> Boolean.toString(getSettings().doCrossServer()))); () -> Boolean.toString(getSettings().getCrossServer().isEnabled())
));
if (getSettings().doCrossServer()) { if (getSettings().getCrossServer().isEnabled()) {
metrics.addCustomChart(new SimplePie("messenger_type", metrics.addCustomChart(new SimplePie("messenger_type",
() -> getSettings().getBrokerType().getDisplayName())); () -> getSettings().getCrossServer().getBrokerType().getDisplayName())
);
} }
metrics.addCustomChart(new SimplePie("language", metrics.addCustomChart(new SimplePie("language",
() -> getSettings().getLanguage().toLowerCase())); () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", metrics.addCustomChart(new SimplePie("database_type",
() -> getSettings().getDatabaseType().getDisplayName())); () -> getSettings().getDatabase().getType().getDisplayName()));
metrics.addCustomChart(new SimplePie("using_economy", metrics.addCustomChart(new SimplePie("using_economy",
() -> Boolean.toString(getSettings().doEconomy()))); () -> Boolean.toString(getSettings().getEconomy().isEnabled())));
metrics.addCustomChart(new SimplePie("using_map", metrics.addCustomChart(new SimplePie("using_map",
() -> Boolean.toString(getSettings().doMapHook()))); () -> Boolean.toString(getSettings().getMapHook().isEnabled())));
getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName))); getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName)));
} catch (Throwable e) { } catch (Throwable e) {
@@ -479,7 +369,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override @Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) {
if (broker != null && broker instanceof PluginMessageBroker pluginMessenger if (broker != null && broker instanceof PluginMessageBroker pluginMessenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
pluginMessenger.onReceive(channel, BukkitUser.adapt(player, this), message); pluginMessenger.onReceive(channel, BukkitUser.adapt(player, this), message);
} }
} }
@@ -96,7 +96,7 @@ public class BukkitCommand extends org.bukkit.command.Command {
} }
// Register commodore TAB completion // Register commodore TAB completion
if (CommodoreProvider.isSupported() && plugin.getSettings().doBrigadierTabCompletion()) { if (CommodoreProvider.isSupported() && plugin.getSettings().getGeneral().isBrigadierTabCompletion()) {
BrigadierUtil.registerCommodore(plugin, this, command); BrigadierUtil.registerCommodore(plugin, this, command);
} }
} }
@@ -114,8 +114,8 @@ public class EssentialsXImporter extends Importer {
name = name.replaceAll(" ", "_"); name = name.replaceAll(" ", "_");
// Remove unicode characters // Remove unicode characters
if (plugin.getSettings().doRestrictNames()) { if (plugin.getSettings().getGeneral().getNames().isRestrict()) {
name = name.replaceAll("[^A-Za-z0-9_-]", ""); name = name.replaceAll(plugin.getSettings().getGeneral().getNames().getRegex(), "");
} }
// Ensure the name is not blank // Ensure the name is not blank
@@ -20,6 +20,7 @@
package net.william278.huskhomes.listener; package net.william278.huskhomes.listener;
import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.util.BukkitAdapter; import net.william278.huskhomes.util.BukkitAdapter;
@@ -91,7 +92,8 @@ public class BukkitEventListener extends EventListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) { public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) {
if (usePaperEvents || !(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) { final Settings.CrossServerSettings crossServer = plugin.getSettings().getCrossServer();
if (usePaperEvents || !(crossServer.isEnabled()) && crossServer.isGlobalRespawning()) {
return; return;
} }
if (event.getClickedBlock() == null || !(event.getClickedBlock().getBlockData() instanceof Bed if (event.getClickedBlock() == null || !(event.getClickedBlock().getBlockData() instanceof Bed
@@ -131,7 +131,7 @@ public class BukkitPluginTests {
@Test @Test
@DisplayName("Test Locale Loading") @DisplayName("Test Locale Loading")
public void testLocalesLoading() { public void testLocalesLoading() {
final Map<String, String> rawLocales = plugin.getLocales().rawLocales; final Map<String, String> rawLocales = plugin.getLocales().getRawLocales();
Assertions.assertFalse(rawLocales.isEmpty()); Assertions.assertFalse(rawLocales.isEmpty());
rawLocales.forEach((key, value) -> Assertions.assertNotNull(value)); rawLocales.forEach((key, value) -> Assertions.assertNotNull(value));
} }
@@ -139,7 +139,7 @@ public class BukkitPluginTests {
@Test @Test
@DisplayName("Test Locale Parsing") @DisplayName("Test Locale Parsing")
public void testLocaleParsing() { public void testLocaleParsing() {
final Map<String, String> rawLocales = plugin.getLocales().rawLocales; final Map<String, String> rawLocales = plugin.getLocales().getRawLocales();
BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin); BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin);
rawLocales.forEach((key, value) -> { rawLocales.forEach((key, value) -> {
Optional<MineDown> locale = plugin.getLocales().getLocale(key); Optional<MineDown> locale = plugin.getLocales().getLocale(key);
@@ -457,8 +457,6 @@ public class BukkitPluginTests {
private static final List<String> HOME_NAMES = List.of( private static final List<String> HOME_NAMES = List.of(
"mr_home", "mr_home",
"homble", "homble",
"seaside",
"hovel",
"tokyo-3", "tokyo-3",
"testington", "testington",
"h" "h"
+10 -7
View File
@@ -7,20 +7,19 @@ dependencies {
api 'org.apache.commons:commons-text:1.11.0' api 'org.apache.commons:commons-text:1.11.0'
api 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' api 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
api 'com.google.code.gson:gson:2.10.1' api 'com.google.code.gson:gson:2.10.1'
api 'net.william278:annotaml:2.0.5'
api 'net.william278:PagineDown:1.1' api 'net.william278:PagineDown:1.1'
api 'net.william278:DesertWell:2.0.4' api 'net.william278:DesertWell:2.0.4'
api 'dev.dejvokep:boosted-yaml:1.3.1' api 'com.github.Exlll.ConfigLib:configlib-yaml:v4.4.0'
api('com.zaxxer:HikariCP:5.1.0') { api('com.zaxxer:HikariCP:5.1.0') {
exclude module: 'slf4j-api' exclude module: 'slf4j-api'
} }
compileOnly 'net.kyori:adventure-api:4.15.0' compileOnly 'net.kyori:adventure-api:4.15.0'
compileOnly "redis.clients:jedis:$jedis_version" compileOnly "redis.clients:jedis:${jedis_version}"
compileOnly "org.xerial:sqlite-jdbc:$sqlite_driver_version" compileOnly "org.xerial:sqlite-jdbc:${sqlite_driver_version}"
compileOnly "com.mysql:mysql-connector-j:$mysql_driver_version" compileOnly "com.mysql:mysql-connector-j:${mysql_driver_version}"
compileOnly "org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version" compileOnly "org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}"
compileOnly "com.h2database:h2:$h2_driver_version" compileOnly "com.h2database:h2:${h2_driver_version}"
compileOnly 'org.jetbrains:annotations:24.1.0' compileOnly 'org.jetbrains:annotations:24.1.0'
compileOnly 'com.google.guava:guava:33.0.0-jre' compileOnly 'com.google.guava:guava:33.0.0-jre'
@@ -28,7 +27,11 @@ dependencies {
compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.6.0' compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.6.0'
compileOnly 'us.dynmap:DynmapCoreAPI:3.4' compileOnly 'us.dynmap:DynmapCoreAPI:3.4'
compileOnly 'maven.modrinth:pl3xmap:1.20.2-475' compileOnly 'maven.modrinth:pl3xmap:1.20.2-475'
compileOnly 'org.projectlombok:lombok:1.18.30'
testImplementation 'com.github.plan-player-analytics:Plan:5.5.2391' testImplementation 'com.github.plan-player-analytics:Plan:5.5.2391'
testImplementation 'com.github.yuriy-g:simple-java-plot:5c502c2e98' testImplementation 'com.github.yuriy-g:simple-java-plot:5c502c2e98'
testImplementation 'com.google.guava:guava:33.0.0-jre'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
} }
@@ -23,22 +23,19 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.ThrowingConsumer; import net.william278.desertwell.util.ThrowingConsumer;
import net.william278.desertwell.util.UpdateChecker; import net.william278.desertwell.util.UpdateChecker;
import net.william278.desertwell.util.Version; import net.william278.desertwell.util.Version;
import net.william278.huskhomes.command.Command; 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.Server;
import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.Spawn;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.EventDispatcher; import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.hook.*; import net.william278.huskhomes.hook.*;
import net.william278.huskhomes.importer.Importer; import net.william278.huskhomes.importer.Importer;
import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.RandomTeleportEngine; 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.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.logging.Level; import java.util.logging.Level;
@@ -64,7 +58,7 @@ import java.util.stream.Stream;
/** /**
* Represents a cross-platform instance of the plugin. * Represents a cross-platform instance of the plugin.
*/ */
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver { public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver, ConfigProvider {
/** /**
* The spigot resource ID, used for update checking. * 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); 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. * The canonical spawn {@link Position} of this server, if it has been set.
* *
* @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set * @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set
*/ */
default Optional<Position> getSpawn() { default Optional<Position> getSpawn() {
return getSettings().doCrossServer() && getSettings().isGlobalSpawn() final Settings.CrossServerSettings crossServer = getSettings().getCrossServer();
? getDatabase().getWarp(getSettings().getGlobalSpawnName()).map(warp -> (Position) warp) return crossServer.isEnabled() && crossServer.getGlobalSpawn().isEnabled()
? getDatabase().getWarp(crossServer.getGlobalSpawn().getWarpName()).map(warp -> (Position) warp)
: getServerSpawn().map(spawn -> spawn.getPosition(getServerName())); : getServerSpawn().map(spawn -> spawn.getPosition(getServerName()));
} }
@@ -308,14 +261,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
@Nullable @Nullable
InputStream getResource(@NotNull String name); 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. * Returns a list of worlds on the server.
* *
@@ -350,7 +295,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
default void registerHooks() { default void registerHooks() {
setHooks(new ArrayList<>()); setHooks(new ArrayList<>());
if (getSettings().doMapHook()) { if (getSettings().getMapHook().isEnabled()) {
if (isDependencyLoaded("Dynmap")) { if (isDependencyLoaded("Dynmap")) {
getHooks().add(new DynmapHook(this)); getHooks().add(new DynmapHook(this));
} else if (isDependencyLoaded("BlueMap")) { } else if (isDependencyLoaded("BlueMap")) {
@@ -418,51 +363,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
return this.getCurrentlyOnWarmup().contains(userUuid); 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 @NotNull
default UpdateChecker getUpdateChecker() { default UpdateChecker getUpdateChecker() {
return UpdateChecker.builder() return UpdateChecker.builder()
@@ -473,7 +373,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
} }
default void checkForUpdates() { default void checkForUpdates() {
if (getSettings().doCheckForUpdates()) { if (getSettings().isCheckForUpdates()) {
getUpdateChecker().check().thenAccept(checked -> { getUpdateChecker().check().thenAccept(checked -> {
if (!checked.isUpToDate()) { if (!checked.isUpToDate()) {
log(Level.WARNING, "A new version of HuskHomes is available: v" log(Level.WARNING, "A new version of HuskHomes is available: v"
@@ -22,6 +22,7 @@ package net.william278.huskhomes.api;
import de.themoep.minedown.adventure.MineDown; import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
@@ -192,7 +193,8 @@ public class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public CompletableFuture<Optional<Position>> getUserRespawnPosition(@NotNull User user) { 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 CompletableFuture.completedFuture(Optional.empty());
} }
return plugin.supplyAsync(() -> plugin.getDatabase().getRespawnPosition(user)); return plugin.supplyAsync(() -> plugin.getDatabase().getRespawnPosition(user));
@@ -44,7 +44,8 @@ public class DelWarpCommand extends SavedPositionCommand<Warp> {
@Override @Override
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) { public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
if (plugin.getSettings().doPermissionRestrictWarps() && !executor.hasPermission(warp.getPermission()) if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()
&& !executor.hasPermission(warp.getPermission())
&& !executor.hasPermission(Warp.getWildcardPermission())) { && !executor.hasPermission(Warp.getWildcardPermission())) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
@@ -256,11 +256,11 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
if (!home.getMeta().getDescription().isEmpty()) { if (!home.getMeta().getDescription().isEmpty()) {
plugin.getLocales().getLocale("edit_home_menu_description", plugin.getLocales().getLocale("edit_home_menu_description",
plugin.getLocales().truncateText(home.getMeta().getDescription(), 50), plugin.getLocales().truncateText(home.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(home.getMeta().getDescription(), 40)) home.getMeta().getDescription())
.ifPresent(messages::add); .ifPresent(messages::add);
} }
if (!plugin.getSettings().doCrossServer()) { if (!plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName()) plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(messages::add); .ifPresent(messages::add);
} else { } else {
@@ -157,11 +157,11 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
if (!warp.getMeta().getDescription().isEmpty()) { if (!warp.getMeta().getDescription().isEmpty()) {
plugin.getLocales().getLocale("edit_warp_menu_description", plugin.getLocales().getLocale("edit_warp_menu_description",
plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50), plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40)) warp.getMeta().getDescription())
.ifPresent(messages::add); .ifPresent(messages::add);
} }
if (!plugin.getSettings().doCrossServer()) { if (!plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getLocales().getLocale("edit_warp_menu_world", plugin.getLocales().getLocale("edit_warp_menu_world",
warp.getWorld().getName()).ifPresent(messages::add); warp.getWorld().getName()).ifPresent(messages::add);
} else { } else {
@@ -35,6 +35,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@@ -104,12 +105,16 @@ public class HuskHomesCommand extends Command implements TabProvider {
case "help" -> executor.sendMessage(getCommandList(executor) case "help" -> executor.sendMessage(getCommandList(executor)
.getNearestValidPage(parseIntArg(args, 1).orElse(1))); .getNearestValidPage(parseIntArg(args, 1).orElse(1)));
case "reload" -> { 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( executor.sendMessage(new MineDown(
"[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)" "[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"
)); ));
return; return;
} }
executor.sendMessage(new MineDown( executor.sendMessage(new MineDown(
"[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)\n" "[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)\n"
+ "[ℹ If you have modified the database or cross-server message broker settings," + "[ℹ 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) plugin.getLocales().truncateText(command.getDescription(), 50)
), ),
Locales.escapeText(String.format("%s\n\n%s", Locales.escapeText(String.format("%s\n\n%s",
plugin.getLocales().wrapText(command.getUsage(), 50), command.getUsage(),
plugin.getLocales().wrapText(command.getDescription(), 50) command.getDescription())
))) ))
.orElse(command.getName())) .orElse(command.getName()))
.collect(Collectors.toList()), .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("")) .setHeaderFormat(plugin.getLocales().getRawLocale("command_list_title").orElse(""))
.setItemSeparator("\n").setCommand("/huskhomes:huskhomes help") .setItemSeparator("\n").setCommand("/huskhomes:huskhomes help")
.build()); .build());
@@ -318,7 +323,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
.collect(Collectors.joining(", ")))) .collect(Collectors.joining(", "))))
.orElse(importer.getName())) .orElse(importer.getName()))
.collect(Collectors.toList()), .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("")) .setHeaderFormat(plugin.getLocales().getRawLocale("importer_list_title").orElse(""))
.setItemSeparator("\n").setCommand("/huskhomes:huskhomes import list") .setItemSeparator("\n").setCommand("/huskhomes:huskhomes import list")
.build()); .build());
@@ -19,6 +19,8 @@
package net.william278.huskhomes.command; package net.william278.huskhomes.command;
import lombok.Getter;
import lombok.Setter;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
@@ -39,6 +41,9 @@ public abstract class Node implements Executable {
protected final HuskHomes plugin; protected final HuskHomes plugin;
private final String name; private final String name;
private final List<String> aliases; private final List<String> aliases;
@Setter
@Getter
private boolean operatorCommand = false; private boolean operatorCommand = false;
protected Node(@NotNull String name, @NotNull List<String> aliases, @NotNull HuskHomes plugin) { 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(); 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) { protected Optional<Integer> parseIntArg(@NotNull String[] args, int index) {
try { try {
if (args.length > index) { if (args.length > index) {
@@ -151,6 +148,7 @@ public abstract class Node implements Executable {
return Optional.empty(); return Optional.empty();
} }
@NotNull
protected Position getBasePosition(@NotNull CommandUser executor) { protected Position getBasePosition(@NotNull CommandUser executor) {
return executor instanceof OnlineUser user ? user.getPosition() : plugin.getSpawn() return executor instanceof OnlineUser user ? user.getPosition() : plugin.getSpawn()
.orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName())); .orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName()));
@@ -110,13 +110,10 @@ public class PrivateHomeListCommand extends ListCommand {
plugin.getLocales() plugin.getLocales()
.getRawLocale("home_list_item", .getRawLocale("home_list_item",
Locales.escapeText(home.getName()), home.getSafeIdentifier(), Locales.escapeText(home.getName()), home.getSafeIdentifier(),
Locales.escapeText(plugin.getLocales().wrapText( Locales.escapeText(home.getMeta().getDescription()))
home.getMeta().getDescription(),
40
)))
.orElse(home.getName())).sorted().collect(Collectors.toList()), .orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales() plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage()) .getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("home_list_page_title", .setHeaderFormat(plugin.getLocales().getRawLocale("home_list_page_title",
user.getUsername(), "%first_item_on_page_index%", user.getUsername(), "%first_item_on_page_index%",
"%last_item_on_page_index%", "%total_items%") "%last_item_on_page_index%", "%total_items%")
@@ -71,13 +71,10 @@ public class PublicHomeListCommand extends ListCommand {
.getRawLocale("public_home_list_item", .getRawLocale("public_home_list_item",
Locales.escapeText(home.getName()), home.getSafeIdentifier(), Locales.escapeText(home.getName()), home.getSafeIdentifier(),
Locales.escapeText(home.getOwner().getUsername()), Locales.escapeText(home.getOwner().getUsername()),
Locales.escapeText(plugin.getLocales().wrapText( Locales.escapeText(home.getMeta().getDescription()))
home.getMeta().getDescription(),
40
)))
.orElse(home.getName())).sorted().collect(Collectors.toList()), .orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales() plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage()) .getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("public_home_list_page_title", .setHeaderFormat(plugin.getLocales().getRawLocale("public_home_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%") "%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%")
.orElse("")) .orElse(""))
@@ -73,7 +73,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
case 0, 1 -> user.hasPermission("other") ? UserListTabProvider.super.suggestLocal(args) case 0, 1 -> user.hasPermission("other") ? UserListTabProvider.super.suggestLocal(args)
: user instanceof OnlineUser online ? List.of(online.getUsername()) : List.of(); : user instanceof OnlineUser online ? List.of(online.getUsername()) : List.of();
case 2 -> user.hasPermission("world") ? plugin.getWorlds().stream() 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(); .map(World::getName).toList() : List.of();
default -> null; default -> null;
}; };
@@ -118,7 +118,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
} }
if (plugin.getSettings().isWorldRtpRestricted(world)) { if (plugin.getSettings().getRtp().isWorldRtpRestricted(world)) {
plugin.getLocales().getLocale("error_rtp_restricted_world") plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
@@ -137,7 +137,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); 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.getWildcardPermission())
&& !user.hasPermission(Warp.getPermission(warpName))) { && !user.hasPermission(Warp.getPermission(warpName))) {
plugin.getLocales().getLocale("error_warp_invalid", warpName) plugin.getLocales().getLocale("error_warp_invalid", warpName)
@@ -59,8 +59,8 @@ public class SetHomeCommand extends SetPositionCommand {
private boolean createDefaultHome(@NotNull OnlineUser user) { private boolean createDefaultHome(@NotNull OnlineUser user) {
final List<Home> homes = plugin.getDatabase().getHomes(user); final List<Home> homes = plugin.getDatabase().getHomes(user);
final Optional<String> name = homes.isEmpty() ? Optional.of("home") : final Optional<String> name = homes.isEmpty() ? Optional.of("home")
(homes.size() == 1 && plugin.getSettings().doOverwriteExistingHomesWarps()) : (homes.size() == 1 && plugin.getSettings().getGeneral().getNames().isOverwriteExisting())
? Optional.of(homes.get(0).getName()) : Optional.empty(); ? Optional.of(homes.get(0).getName()) : Optional.empty();
if (name.isPresent()) { if (name.isPresent()) {
this.execute(user, "home"); this.execute(user, "home");
@@ -27,6 +27,8 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import static net.william278.huskhomes.config.Settings.CrossServerSettings.GlobalSpawnSettings;
public class SetSpawnCommand extends InGameCommand { public class SetSpawnCommand extends InGameCommand {
protected SetSpawnCommand(@NotNull HuskHomes plugin) { protected SetSpawnCommand(@NotNull HuskHomes plugin) {
@@ -37,9 +39,10 @@ public class SetSpawnCommand extends InGameCommand {
@Override @Override
public void execute(@NotNull OnlineUser executor, @NotNull String[] args) { public void execute(@NotNull OnlineUser executor, @NotNull String[] args) {
final Position position = executor.getPosition(); final Position position = executor.getPosition();
final GlobalSpawnSettings global = plugin.getSettings().getCrossServer().getGlobalSpawn();
try { try {
if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalSpawn()) { if (plugin.getSettings().getCrossServer().isEnabled() && global.isEnabled()) {
final String warpName = plugin.getSettings().getGlobalSpawnName(); final String warpName = global.getWarpName();
plugin.getManager().warps().createWarp(warpName, position, true); plugin.getManager().warps().createWarp(warpName, position, true);
plugin.getLocales().getRawLocale("spawn_warp_default_description").ifPresent( plugin.getLocales().getRawLocale("spawn_warp_default_description").ifPresent(
description -> plugin.getManager().warps().setWarpDescription(warpName, description) description -> plugin.getManager().warps().setWarpDescription(warpName, description)
@@ -48,7 +51,7 @@ public class SetSpawnCommand extends InGameCommand {
plugin.setServerSpawn(position); plugin.setServerSpawn(position);
} }
} catch (ValidationException e) { } catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, plugin.getSettings().getGlobalSpawnName()); e.dispatchWarpError(executor, plugin, global.getWarpName());
return; return;
} }
@@ -58,7 +58,7 @@ public class TpAllCommand extends InGameCommand {
return; return;
} }
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder() Message.builder()
.target(Message.TARGET_ALL) .target(Message.TARGET_ALL)
.type(Message.Type.TELEPORT_TO_POSITION) .type(Message.Type.TELEPORT_TO_POSITION)
@@ -47,7 +47,7 @@ public class WarpCommand extends SavedPositionCommand<Warp> {
@Override @Override
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) { public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
if (plugin.getSettings().doPermissionRestrictWarps()) { if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()) {
if (!executor.hasPermission(warp.getPermission()) if (!executor.hasPermission(warp.getPermission())
&& !executor.hasPermission(Warp.getWildcardPermission())) { && !executor.hasPermission(Warp.getWildcardPermission())) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
@@ -70,13 +70,11 @@ public class WarpListCommand extends ListCommand {
plugin.getLocales() plugin.getLocales()
.getRawLocale("warp_list_item", .getRawLocale("warp_list_item",
Locales.escapeText(warp.getName()), warp.getSafeIdentifier(), Locales.escapeText(warp.getName()), warp.getSafeIdentifier(),
Locales.escapeText(plugin.getLocales().wrapText( Locales.escapeText(warp.getMeta().getDescription())
warp.getMeta().getDescription(), )
40
)))
.orElse(warp.getName())).sorted().collect(Collectors.toList()), .orElse(warp.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales() plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage()) .getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("warp_list_page_title", .setHeaderFormat(plugin.getLocales().getRawLocale("warp_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%") "%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%")
.orElse("")) .orElse(""))
@@ -87,7 +85,8 @@ public class WarpListCommand extends ListCommand {
@NotNull @NotNull
private List<Warp> getItems(@NotNull CommandUser executor) { private List<Warp> getItems(@NotNull CommandUser executor) {
List<Warp> warps = plugin.getDatabase().getWarps(); 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(); warps = warps.stream().filter(warp -> executor.hasPermission(warp.getPermission())).toList();
} }
return warps; 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; package net.william278.huskhomes.config;
import com.google.common.collect.Maps;
import de.exlll.configlib.Configuration;
import de.themoep.minedown.adventure.MineDown; import de.themoep.minedown.adventure.MineDown;
import net.william278.annotaml.YamlFile; import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.william278.paginedown.ListOptions; import net.william278.paginedown.ListOptions;
import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.text.WordUtils;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
/** /**
* Loaded locales used by the plugin to display styled messages. * Loaded locales used by the plugin to display styled messages.
*/ */
@YamlFile(rootedMap = true, header = """ @SuppressWarnings("FieldMayBeFinal")
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Locales {
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Locales ┃ ┃ HuskHomes Locales ┃
┃ Developed by William278 ┃ ┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits ┣╸ See plugin about menu for international locale credits
┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown ┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""") ┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""";
public class Locales {
/** protected static final String DEFAULT_LOCALE = "en-gb";
* The raw set of locales loaded from yaml.
*/
public Map<String, String> rawLocales = new HashMap<>();
@SuppressWarnings("unused") // The raw set of locales loaded from yaml
private Locales() { 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 * @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the locale corresponding to the id, if it exists * @return An {@link Optional} containing the locale corresponding to the id, if it exists
*/ */
public Optional<String> getRawLocale(@NotNull String localeId) { 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 * <p>Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements
* *
* @param localeId String identifier of the locale, corresponding to a key in the file * @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements 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 * @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists
*/ */
public Optional<String> getRawLocale(@NotNull String localeId, @NotNull String... replacements) { public Optional<String> getRawLocale(@NotNull String localeId, @NotNull String... replacements) {
@@ -77,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 * @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists * @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists
*/ */
public Optional<MineDown> getLocale(@NotNull String localeId) { 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 * <p>Note that replacements will be MineDown-escaped before application
* *
* @param localeId String identifier of the locale, corresponding to a key in the file * @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements 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} with the replacement-applied, formatted locale corresponding to the id, if it exists * @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id
*/ */
public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) { public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) {
return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText) return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText)
.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. * Apply placeholder replacements to a raw locale.
* *
* @param rawLocale The raw, unparsed 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 * @return the raw locale, with inserted placeholders
*/ */
@NotNull @NotNull
@@ -138,7 +157,7 @@ public class Locales {
value.append(c); value.append(c);
} }
return value.toString(); return value.toString().replace("__", "_\\_");
} }
@NotNull @NotNull
@@ -149,18 +168,19 @@ public class Locales {
return string.length() > truncateAfter ? string.substring(0, truncateAfter) + "…" : string; 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 @NotNull
public String wrapText(@NotNull String string, int wrapAfter) { public String getNotApplicable() {
if (string.isBlank()) { return getRawLocale("not_applicable").orElse("N/A");
return this.getRawLocale("item_no_description").orElse("N/A");
} }
return WordUtils.wrap(string, wrapAfter, "\n", true);
@NotNull
public String getListJoiner() {
return getRawLocale("list_separator").orElse(", ");
}
@NotNull
public String getNone() {
return getRawLocale("none").orElse("(none)");
} }
@NotNull @NotNull
@@ -19,64 +19,33 @@
package net.william278.huskhomes.config; package net.william278.huskhomes.config;
import net.william278.annotaml.YamlFile; import de.exlll.configlib.Configuration;
import net.william278.annotaml.YamlKey; import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.nio.file.Path; @Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Server {
/** static final String CONFIG_HEADER = """
* Represents a server on a proxied network.
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Server ID config ┃ ┃ HuskHomes - Server ID ┃
┃ Developed by William278 ┃ ┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ This file should contain the ID of this server as defined in your proxy config. ┣╸ 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) ┣╸ 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.""") ┗╸ You only need to touch this if you're using cross-server mode.""";
public class Server {
private String name = "server";
/**
* Default server identifier.
*/
@NotNull @NotNull
public static String getDefaultServerName() { public static Server of(@NotNull String name) {
try { return new Server(name);
final Path serverDirectory = Path.of(System.getProperty("user.dir"));
return serverDirectory.getFileName().toString().trim();
} catch (Exception e) {
return "server";
}
}
@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; package net.william278.huskhomes.config;
import net.william278.annotaml.YamlComment; import com.google.common.collect.Lists;
import net.william278.annotaml.YamlFile; import de.exlll.configlib.Comment;
import net.william278.annotaml.YamlKey; import de.exlll.configlib.Configuration;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.command.Command; import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Broker;
@@ -35,582 +38,371 @@ import java.util.stream.Collectors;
/** /**
* Plugin settings, read from config.yml * Plugin settings, read from config.yml
*/ */
@YamlFile(header = """ @SuppressWarnings("FieldMayBeFinal")
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Settings {
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Config ┃ ┃ HuskHomes Config ┃
┃ Developed by William278 ┃ ┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ Information: https://william278.net/project/huskhomes/ ┣╸ Information: https://william278.net/project/huskhomes/
┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/ ┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/
┗╸ Documentation: https://william278.net/docs/huskhomes/""") ┗╸ Documentation: https://william278.net/docs/huskhomes/""";
public class Settings {
// Top-level settings // Top-level settings
@YamlComment("Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations") @Comment("Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations")
@YamlKey("language") private String language = Locales.DEFAULT_LOCALE;
private String language = "en-gb";
@YamlComment("Whether to automatically check for plugin updates on startup") @Comment("Whether to automatically check for plugin updates on startup")
@YamlKey("check_for_updates")
private boolean checkForUpdates = true; private boolean checkForUpdates = true;
// Database settings // Database settings
@YamlComment("Type of database to use (SQLITE, H2, MYSQL or MARIADB)") @Comment("Database settings")
@YamlKey("database.type") private DatabaseSettings database = new DatabaseSettings();
private Database.Type databaseType = Database.Type.SQLITE;
@YamlComment("Specify credentials here if you are using MYSQL or MARIADB as your database type") @Getter
@YamlKey("database.mysql.credentials.host") @Configuration
private String mySqlHost = "localhost"; @NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class DatabaseSettings {
@YamlKey("database.mysql.credentials.port") @Comment("Type of database to use (SQLITE, H2, MYSQL, or MARIADB)")
private int mySqlPort = 3306; private Database.Type type = Database.Type.SQLITE;
@YamlKey("database.mysql.credentials.database") @Comment("Specify credentials here if you are using MYSQL or MARIADB")
private String mySqlDatabase = "HuskHomes"; private DatabaseCredentials credentials = new DatabaseCredentials();
@YamlKey("database.mysql.credentials.username") @Getter
private String mySqlUsername = "root"; @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") @Comment({"MYSQL / MARIADB database Hikari connection pool properties",
private String mySqlPassword = "pa55w0rd"; "Don't modify this unless you know what you're doing!"})
private PoolOptions poolOptions = new PoolOptions();
@YamlKey("database.mysql.credentials.parameters") @Getter
private String mySqlConnectionParameters = "?autoReconnect=true" @Configuration
+ "&useSSL=false" @NoArgsConstructor(access = AccessLevel.PRIVATE)
+ "&useUnicode=true" public static class PoolOptions {
+ "&characterEncoding=UTF-8"; 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. " @Comment("Names of tables to use on your database. Don't modify this unless you know what you're doing!")
+ "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.size")
private int mySqlConnectionPoolSize = 12;
@YamlKey("database.mysql.connection_pool.idle") @NotNull
private int mySqlConnectionPoolIdle = 12; public String getTableName(@NotNull Database.Table tableName) {
return Optional.ofNullable(tableNames.get(tableName)).orElse(tableName.getDefaultName());
}
}
@YamlKey("database.mysql.connection_pool.lifetime") @Comment("General settings")
private long mySqlConnectionPoolLifetime = 1800000; private GeneralSettings general = new GeneralSettings();
@YamlKey("database.mysql.connection_pool.keepalive") @Getter
private long mySqlConnectionPoolKeepAlive = 30000; @Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@YamlKey("database.mysql.connection_pool.timeout") public static class GeneralSettings {
private long mySqlConnectionPoolTimeout = 20000; @Comment("The maximum homes a user can create. Override with the huskhomes.max_homes.<number> permission.")
@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());
// 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; private int maxHomes = 10;
@YamlComment("The maximum public homes a user can create. " @Comment("The maximum public homes a user can create. "
+ "Override with the huskhomes.max_public_homes.<number> permission.") + "Override with the huskhomes.max_public_homes.<number> permission.")
@YamlKey("general.max_public_homes")
private int maxPublicHomes = 10; private int maxPublicHomes = 10;
@YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>) " @Comment("Whether permission limits (i.e. huskhomes.max_homes.<number>) should stack "
+ "should stack if the user inherits multiple nodes.") + "if the user inherits multiple nodes.")
@YamlKey("general.stack_permission_limits")
private boolean stackPermissionLimits = false; private boolean stackPermissionLimits = false;
@YamlComment("Whether users require a permission (huskhomes.command.warp.<warp_name>) to use warps") @Comment("Whether users require a permission (huskhomes.command.warp.<warp_name>) to use warps")
@YamlKey("general.permission_restrict_warps")
private boolean permissionRestrictWarps = false; private boolean permissionRestrictWarps = false;
@YamlComment("Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite.") @Comment("How long a player has to stand still and not take damage for when teleporting (in seconds) ")
@YamlKey("general.overwrite_existing_homes_warps")
private boolean overwriteExistingHomesWarps = true;
@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; private int teleportWarmupTime = 5;
@YamlComment("Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE)") @Comment("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; private Locales.DisplaySlot teleportWarmupDisplay = Locales.DisplaySlot.ACTION_BAR;
@YamlComment("How long before received teleport requests expire (in seconds)") @Comment("How long before received teleport requests expire (in seconds)")
@YamlKey("general.teleport_request_expiry_time")
private int teleportRequestExpiryTime = 60; private int teleportRequestExpiryTime = 60;
@YamlComment("Whether /tpahere should use the location of the sender when sent. Docs: https://william278.net/docs/huskhomes/strict-tpahere/") @Comment("Whether /tpahere should use the location of the sender when sent. "
@YamlKey("general.strict_tpa_here_requests") + "Docs: https://william278.net/docs/huskhomes/strict-tpahere/")
private boolean strictTpaHereRequests = true; private boolean strictTpaHereRequests = true;
@Comment("How many items should be displayed per-page in chat menu lists")
// 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;
@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;
@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-_]*";
@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;
@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";
@YamlComment("Whether the user should back to spawn when they die")
@YamlKey("general.always_respawn_at_spawn")
private boolean alwaysRespawnAtSpawn = false;
// 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;
@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;
@YamlComment("How many items should be displayed per-page in chat menu lists")
@YamlKey("general.list_items_per_page")
private int listItemsPerPage = 12; private int listItemsPerPage = 12;
@YamlComment("Whether teleportation should be carried out asynchronously (ensuring chunks load before teleporting)") @Comment("Whether to provide modern, rich TAB suggestions for commands (if available)")
@YamlKey("general.asynchronous_teleports")
private boolean asynchronousTeleports = true;
@YamlComment("Whether to play sound effects")
@YamlKey("general.play_sound_effects")
private boolean playSoundEffects = true;
@YamlComment("Which sound effects to play for various actions")
@YamlKey("general.sound_effects")
private TreeMap<String, String> soundEffects = new TreeMap<>(SoundEffectAction.getConfigMap());
@YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)")
@YamlKey("general.brigadier_tab_completion")
private boolean brigadierTabCompletion = true; private boolean brigadierTabCompletion = true;
@Comment("Whether the user should always be put back at the /spawn point when they die "
+ "(ignores beds/respawn anchors)")
private boolean alwaysRespawnAtSpawn = false;
// Cross-server settings @Comment("Whether teleportation should be carried out async (ensuring chunks load before teleporting)")
@YamlComment("Enable teleporting across your proxy network. Requires database type to be MYSQL") private boolean teleportAsync = true;
@YamlKey("cross_server.enabled")
private boolean crossServer = false;
@YamlComment("The type of message broker to use for cross-server communication. Options: PLUGIN_MESSAGE, REDIS") @Comment("Settings for home and warp names")
@YamlKey("cross_server.messenger_type") private NameSettings names = new NameSettings();
private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE;
@YamlComment("Specify a common ID for grouping servers running HuskHomes on your proxy. " @Getter
+ "Don't modify this unless you know what you're doing!") @Configuration
@YamlKey("cross_server.cluster_id") @NoArgsConstructor(access = AccessLevel.PRIVATE)
private String clusterId = ""; public static class NameSettings {
@Comment("Whether running /sethome <name> or /setwarp <name> when one already exists should overwrite.")
private boolean overwriteExisting = true;
@YamlComment("Define a single global /spawn for your network via a warp. Docs: https://william278.net/docs/huskhomes/global-spawn/") @Comment("Whether home or warp names should be case insensitive (i.e. allow /home HomeOne & /home homeone)")
@YamlKey("cross_server.global_spawn.enabled") private boolean caseInsensitive = false;
private boolean globalSpawn = false;
@YamlComment("The name of the warp to use as the global spawn.") @Comment("Whether home and warp names should be restricted to a regex filter."
@YamlKey("cross_server.global_spawn.warp_name") + "Set this to false to allow full UTF-8 names (i.e. allow /home 你好).")
private String globalSpawnName = "Spawn"; private boolean restrict = true;
@YamlComment("Whether player respawn positions should work cross-server. Docs: https://william278.net/docs/huskhomes/global-respawning/") @Comment("Regex which home and warp names must match. Names have a max length of 16 characters")
@YamlKey("cross_server.global_respawning") private String regex = "[a-zA-Z0-9-_]*";
private boolean globalRespawning = false;
@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";
@YamlKey("cross_server.redis_credentials.port")
private int redisPort = 6379;
@YamlKey("cross_server.redis_credentials.password")
private String redisPassword = "";
@YamlKey("cross_server.redis_credentials.use_ssl")
private boolean redisUseSsl = false;
// Rtp command settings
@YamlComment("Radius around the /spawn position where players CAN be randomly teleported")
@YamlKey("rtp.radius")
private int rtpRadius = 5000;
@YamlComment("Radius around the /spawn position where players CANNOT be randomly teleported")
@YamlKey("rtp.spawn_radius")
private int rtpSpawnRadius = 500;
@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;
@YamlComment("Standard deviation of the normal distribution for distributing players randomly")
@YamlKey("rtp.distribution_deviation")
private float rtpDistributionStandardDeviation = 2f;
@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");
// Cooldown settings
@YamlComment("Whether to apply a cooldown between performing certain actions")
@YamlKey("cooldowns.enabled")
private boolean cooldowns = true;
@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());
// Economy settings
@YamlComment("Enable economy plugin integration (requires Vault)")
@YamlKey("economy.enabled")
private boolean economy = false;
@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;
@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());
// 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;
@YamlComment("Show public homes on the web map")
@YamlKey("map_hook.show_public_homes")
private boolean publicHomesOnMap = true;
@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() {
} }
@Comment("Settings for home and warp descriptions")
private DescriptionSettings descriptions = new DescriptionSettings();
@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;
@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";
}
@Comment("Settings for the /back command")
private BackCommandSettings backCommand = new BackCommandSettings();
@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;
@Comment("Whether /back should work with other plugins that use the PlayerTeleportEvent (can conflict)")
private boolean saveOnTeleportEvent = false;
}
@Comment("Settings for sound effects")
private SoundEffectSettings soundEffects = new SoundEffectSettings();
@Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class SoundEffectSettings {
@Comment("Whether to play sound effects")
private boolean enabled = true;
@Comment("Map of sound effect actions to types")
private Map<SoundEffectAction, String> types = SoundEffectAction.getDefaults();
@NotNull @NotNull
public String getLanguage() { public Optional<String> get(@NotNull SoundEffectAction action) {
return language; if (!enabled) {
}
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(); return Optional.empty();
} }
return Optional.ofNullable(getSoundEffects().get(action.name())); return Optional.ofNullable(types.get(action));
}
}
} }
public boolean doCrossServer() { @Comment("Cross-server settings")
return crossServer; private CrossServerSettings crossServer = new CrossServerSettings();
@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;
@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";
@Comment("Type of network message broker to ues for data synchronization (PLUGIN_MESSAGE or REDIS)")
private Broker.Type brokerType = Broker.Type.PLUGIN_MESSAGE;
@Comment("Settings for if you're using REDIS as your message broker")
private RedisSettings redis = new RedisSettings();
@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;
@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();
@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 = "";
}
} }
@NotNull @Comment("Define a single global /spawn for your network via a warp. "
public Broker.Type getBrokerType() { + "Docs: https://william278.net/docs/huskhomes/global-spawn/")
return messageBrokerType; private GlobalSpawnSettings globalSpawn = new GlobalSpawnSettings();
@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";
} }
@NotNull @Comment("Whether player respawn positions should work cross-server. "
public String getClusterId() { + "Docs: https://william278.net/docs/huskhomes/global-respawning/")
return clusterId; private boolean globalRespawning = false;
} }
public boolean isGlobalSpawn() { @Comment("Random teleport (/rtp) settings.")
return globalSpawn; private RtpSettings rtp = new RtpSettings();
@Getter
@Configuration
@NoArgsConstructor
public static class RtpSettings {
@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();
@Getter
@Configuration
@NoArgsConstructor
public static class RtpRadius {
private int min = 500;
private int max = 5000;
} }
@NotNull @Comment("Mean of the normal distribution used to calculate the distance from the center of the world")
public String getGlobalSpawnName() { private float distributionMean = 0.75f;
return globalSpawnName;
}
public boolean isGlobalRespawning() { @Comment("Standard deviation of the normal distribution for distributing players randomly")
return globalRespawning; private float distributionStandardDeviation = 2.0f;
}
@NotNull @Comment("List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether.")
public String getRedisHost() { private List<String> restrictedWorlds = List.of("world_nether", "world_the_end");
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) { public boolean isWorldRtpRestricted(@NotNull World world) {
final String worldName = world.getName(); final String name = world.getName();
final String filteredName = worldName.startsWith("minecraft:") ? worldName.substring(10) : worldName; final String filteredName = name.startsWith("minecraft:") ? name.substring(10) : name;
return rtpRestrictedWorlds.stream() return restrictedWorlds.stream()
.map(name -> name.startsWith("minecraft:") ? name.substring(10) : name) .map(n -> n.startsWith("minecraft:") ? n.substring(10) : n)
.anyMatch(name -> name.equalsIgnoreCase(filteredName)); .anyMatch(n -> n.equalsIgnoreCase(filteredName));
}
} }
public boolean doCooldowns() { @Comment("Action cooldown settings. Docs: https://william278.net/docs/huskhomes/cooldowns")
return cooldowns; private CooldownSettings cooldowns = new CooldownSettings();
}
@NotNull @Getter
public TreeMap<String, Integer> getCooldownTimes() { @Configuration
final TreeMap<String, Integer> cooldownTimes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); @NoArgsConstructor
cooldownTimes.putAll(this.cooldownTimes); public static class CooldownSettings {
return cooldownTimes;
} @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) { public long getCooldown(@NotNull TransactionResolver.Action action) {
if (!doCooldowns()) { return enabled ? cooldownTimes.getOrDefault(action, 0L) : 0L;
return 0;
} }
final Integer cooldown = getCooldownTimes().get(action.name());
if (cooldown != null && cooldown > 0) {
return cooldown;
}
return 0;
} }
public boolean doEconomy() { // Economy settings
return economy; @Comment("Economy settings. Docs: https://william278.net/docs/huskhomes/economy-hook")
} private EconomySettings economy = new EconomySettings();
public int getFreeHomeSlots() { @Getter
return freeHomeSlots; @Configuration
} @NoArgsConstructor
public static class EconomySettings {
@NotNull @Comment("Enable economy plugin integration (requires Vault and a compatible Economy plugin)")
public TreeMap<String, Double> getEconomyCosts() { private boolean enabled = true;
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) { @Comment("Map of economy actions to costs.")
if (!doEconomy()) { private Map<TransactionResolver.Action, Double> economyCosts = TransactionResolver.Action.getEconomyCosts();
@Comment("Specify how many homes players can set for free, before they need to pay for more slots")
private int freeHomeSlots = 5;
public Optional<Double> getCost(@NotNull TransactionResolver.Action action) {
if (!enabled) {
return Optional.empty(); return Optional.empty();
} }
final Double cost = getEconomyCosts().get(action.name()); return economyCosts.containsKey(action) ? Optional.of(economyCosts.get(action)) : Optional.empty();
if (cost != null && cost > 0d) {
return Optional.of(cost);
} }
return Optional.empty();
} }
public boolean doMapHook() { @Comment("Web map hook settings. Docs: https://william278.net/docs/huskhomes/map-hooks")
return doMapHook; 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;
} }
public boolean doPublicHomesOnMap() { @Comment("List of commands to disable (e.g. ['/home', '/warp'] to disable /home and /warp)")
return publicHomesOnMap; private List<String> disabledCommands = Lists.newArrayList();
}
public boolean doWarpsOnMap() { public boolean isCommandDisabled(@NotNull Command type) {
return warpsOnMap;
}
public boolean isCommandDisabled(Command type) {
return disabledCommands.stream() return disabledCommands.stream()
.anyMatch(disabled -> { .anyMatch(disabled -> {
final String command = (disabled.startsWith("/") ? disabled.substring(1) : 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. * Represents actions that have a sound effect associated with performing them.
*/ */
@@ -639,13 +427,14 @@ public class Settings {
} }
@NotNull @NotNull
public static Map<String, String> getConfigMap() { public static Map<SoundEffectAction, String> getDefaults() {
return Arrays.stream(values()).collect(Collectors.toMap( return Arrays.stream(values()).collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH), action -> action,
action -> action.defaultEffect action -> action.defaultEffect,
(a, b) -> a,
TreeMap::new
)); ));
} }
} }
} }
@@ -19,8 +19,11 @@
package net.william278.huskhomes.config; package net.william278.huskhomes.config;
import net.william278.annotaml.YamlFile; import de.exlll.configlib.Configuration;
import net.william278.annotaml.YamlKey; import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
@@ -31,22 +34,25 @@ import java.util.UUID;
/** /**
* Used to store the server spawn location. * Used to store the server spawn location.
*/ */
@YamlFile(header = """ @Getter
@Configuration
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Spawn {
static final String CONFIG_HEADER = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server /spawn location ┃ ┃ Server /spawn location ┃
┃ Edit in-game using /setspawn ┃ ┃ Edit in-game using /setspawn ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""") ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""";
public class Spawn {
public double x; private double x;
public double y; private double y;
public double z; private double z;
public float yaw; private float yaw;
public float pitch; private float pitch;
@YamlKey("world_name") private String worldName;
public String worldName; private String worldUuid;
@YamlKey("world_uuid")
public String worldUuid;
/** /**
* Returns the {@link Position} of the spawn. * Returns the {@link Position} of the spawn.
@@ -65,16 +71,9 @@ public class Spawn {
* @param location The {@link Location} of the spawn * @param location The {@link Location} of the spawn
*/ */
public Spawn(@NotNull Location location) { public Spawn(@NotNull Location location) {
this.x = location.getX(); this(
this.y = location.getY(); location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(),
this.z = location.getZ(); location.getWorld().getName(), location.getWorld().getUuid().toString()
this.yaw = location.getYaw(); );
this.pitch = location.getPitch();
this.worldName = location.getWorld().getName();
this.worldUuid = location.getWorld().getUuid().toString();
}
@SuppressWarnings("unused")
public Spawn() {
} }
} }
@@ -19,8 +19,11 @@
package net.william278.huskhomes.database; package net.william278.huskhomes.database;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.SavedPosition; 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 * @return the formatted statement, with table placeholders replaced with the correct names
*/ */
protected final String formatStatementTables(@NotNull String sql) { protected final String formatStatementTables(@NotNull String sql) {
final Settings.DatabaseSettings settings = plugin.getSettings().getDatabase();
return sql return sql
.replaceAll("%positions_table%", plugin.getSettings() .replaceAll("%positions_table%", settings
.getTableName(Table.POSITION_DATA)) .getTableName(Table.POSITION_DATA))
.replaceAll("%players_table%", plugin.getSettings() .replaceAll("%players_table%", settings
.getTableName(Table.PLAYER_DATA)) .getTableName(Table.PLAYER_DATA))
.replaceAll("%cooldowns_table%", plugin.getSettings() .replaceAll("%cooldowns_table%", settings
.getTableName(Table.PLAYER_COOLDOWNS_DATA)) .getTableName(Table.PLAYER_COOLDOWNS_DATA))
.replaceAll("%teleports_table%", plugin.getSettings() .replaceAll("%teleports_table%", settings
.getTableName(Table.TELEPORT_DATA)) .getTableName(Table.TELEPORT_DATA))
.replaceAll("%saved_positions_table%", plugin.getSettings() .replaceAll("%saved_positions_table%", settings
.getTableName(Table.SAVED_POSITION_DATA)) .getTableName(Table.SAVED_POSITION_DATA))
.replaceAll("%homes_table%", plugin.getSettings() .replaceAll("%homes_table%", settings
.getTableName(Table.HOME_DATA)) .getTableName(Table.HOME_DATA))
.replaceAll("%warps_table%", plugin.getSettings() .replaceAll("%warps_table%", settings
.getTableName(Table.WARP_DATA)); .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 * @apiNote Whether lookup is case-sensitive is determined by the {@code general.case_insensitive_names} setting
*/ */
public final Optional<Home> getHome(@NotNull User user, @NotNull String homeName) { public final Optional<Home> getHome(@NotNull User user, @NotNull String homeName) {
return this.getHome(user, homeName, plugin.getSettings().caseInsensitiveNames()); return this.getHome(user, homeName, plugin.getSettings().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 * @apiNote Whether lookup is case-insensitive is determined by the {@code general.case_insensitive_names} setting
*/ */
public final Optional<Warp> getWarp(@NotNull String warpName) { public final Optional<Warp> getWarp(@NotNull String warpName) {
return getWarp(warpName, plugin.getSettings().caseInsensitiveNames()); return getWarp(warpName, plugin.getSettings().getGeneral().getNames().isCaseInsensitive());
} }
/** /**
@@ -462,27 +466,23 @@ public abstract class Database {
/** /**
* Identifies types of databases. * Identifies types of databases.
*/ */
@Getter
@AllArgsConstructor
public enum Type { public enum Type {
MYSQL("MySQL"), MYSQL("MySQL", "mysql"),
MARIADB("MariaDB"), MARIADB("MariaDB", "mariadb"),
SQLITE("SQLite"), SQLITE("SQLite", "sqlite"),
H2("H2"); H2("H2", "h2");
private final String displayName; private final String displayName;
private final String protocol;
Type(@NotNull String displayName) {
this.displayName = displayName;
}
@NotNull
public String getDisplayName() {
return displayName;
}
} }
/** /**
* Represents the names of tables in the database. * Represents the names of tables in the database.
*/ */
@Getter
@AllArgsConstructor
public enum Table { public enum Table {
PLAYER_DATA("huskhomes_users"), PLAYER_DATA("huskhomes_users"),
PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"), PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"),
@@ -494,21 +494,11 @@ public abstract class Database {
private final String defaultName; private final String defaultName;
Table(@NotNull String defaultName) {
this.defaultName = defaultName;
}
@NotNull @NotNull
public String getDefaultName() { public static Map<Table, String> getConfigMap() {
return defaultName; return Arrays.stream(values()).collect(
} Collectors.toMap(t -> t, Table::getDefaultName, (a, b) -> b, TreeMap::new)
);
@NotNull
public static Map<String, String> getConfigMap() {
return Arrays.stream(values()).collect(Collectors.toMap(
table -> table.name().toLowerCase(Locale.ENGLISH),
Table::getDefaultName
));
} }
} }
@@ -58,7 +58,7 @@ public class H2Database extends Database {
public H2Database(@NotNull HuskHomes plugin) { public H2Database(@NotNull HuskHomes plugin) {
super(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.SavedUser;
import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver; import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -37,6 +38,8 @@ import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.DatabaseSettings;
/** /**
* A MySQL / MariaDB implementation of the plugin {@link Database}. * A MySQL / MariaDB implementation of the plugin {@link Database}.
*/ */
@@ -50,10 +53,10 @@ public class MySqlDatabase extends Database {
public MySqlDatabase(@NotNull HuskHomes plugin) { public MySqlDatabase(@NotNull HuskHomes plugin) {
super(plugin); super(plugin);
this.flavor = plugin.getSettings().getDatabaseType() == Type.MARIADB
? "mariadb" : "mysql"; final Type type = plugin.getSettings().getDatabase().getType();
this.driverClass = plugin.getSettings().getDatabaseType() == Type.MARIADB this.flavor = type.getProtocol();
? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver"; 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 * @return The {@link Connection} to the MySQL database
* @throws SQLException if the connection fails for some reason * @throws SQLException if the connection fails for some reason
*/ */
@Blocking
@NotNull
private Connection getConnection() throws SQLException { private Connection getConnection() throws SQLException {
if (dataSource == null) {
throw new IllegalStateException("The database has not been initialized");
}
return dataSource.getConnection(); return dataSource.getConnection();
} }
@Blocking
@Override @Override
public void initialize() throws IllegalStateException { public void initialize() throws IllegalStateException {
// Initialize the Hikari pooled connection // Initialize the Hikari pooled connection
final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials();
dataSource = new HikariDataSource(); dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass); dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s", dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s",
flavor, flavor,
plugin.getSettings().getMySqlHost(), credentials.getHost(),
plugin.getSettings().getMySqlPort(), credentials.getPort(),
plugin.getSettings().getMySqlDatabase(), credentials.getDatabase(),
plugin.getSettings().getMySqlConnectionParameters() credentials.getParameters()
)); ));
// Authenticate with the database // Authenticate with the database
dataSource.setUsername(plugin.getSettings().getMySqlUsername()); dataSource.setUsername(credentials.getUsername());
dataSource.setPassword(plugin.getSettings().getMySqlPassword()); dataSource.setPassword(credentials.getPassword());
// Set connection pool options // Set connection pool options
dataSource.setMaximumPoolSize(plugin.getSettings().getMySqlConnectionPoolSize()); final DatabaseSettings.PoolOptions pool = plugin.getSettings().getDatabase().getPoolOptions();
dataSource.setMinimumIdle(plugin.getSettings().getMySqlConnectionPoolIdle()); dataSource.setMaximumPoolSize(pool.getSize());
dataSource.setMaxLifetime(plugin.getSettings().getMySqlConnectionPoolLifetime()); dataSource.setMinimumIdle(pool.getIdle());
dataSource.setKeepaliveTime(plugin.getSettings().getMySqlConnectionPoolKeepAlive()); dataSource.setMaxLifetime(pool.getLifetime());
dataSource.setConnectionTimeout(plugin.getSettings().getMySqlConnectionPoolTimeout()); dataSource.setKeepaliveTime(pool.getKeepAlive());
dataSource.setConnectionTimeout(pool.getTimeout());
dataSource.setPoolName(DATA_POOL_NAME); dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties // Set additional connection pool properties
@@ -119,8 +130,8 @@ public class MySqlDatabase extends Database {
statement.execute(tableCreationStatement); statement.execute(tableCreationStatement);
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IllegalStateException("Failed to create database tables. Make sure you're running MySQL v8.0+" throw new IllegalStateException("Failed to create database tables. Please ensure you are running "
+ "and that your connecting user account has privileges to create tables.", e); + "MySQL v8.0+ and that your connecting user account has privileges to create tables.", e);
} }
} catch (SQLException | IOException e) { } catch (SQLException | IOException e) {
throw new IllegalStateException("Failed to establish a connection to the MySQL database. " throw new IllegalStateException("Failed to establish a connection to the MySQL database. "
@@ -332,27 +343,32 @@ public class MySqlDatabase extends Database {
@Override @Override
public void deleteUserData(@NotNull UUID uuid) { public void deleteUserData(@NotNull UUID uuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
// Delete Position try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
WHERE `id` WHERE `id`
IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?), IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `offline_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(1, uuid.toString());
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString()); statement.setString(3, uuid.toString());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete player positions from the database", e);
return;
}
statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%` DELETE FROM `%players_table%`
WHERE `uuid`=?;""")); WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e); plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
} }
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete user data", e);
}
} }
@Override @Override
@@ -62,7 +62,7 @@ public class SqLiteDatabase extends Database {
public SqLiteDatabase(@NotNull HuskHomes plugin) { public SqLiteDatabase(@NotNull HuskHomes plugin) {
super(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 { private Connection getConnection() throws SQLException {
@@ -321,25 +321,26 @@ public class SqLiteDatabase extends Database {
@Override @Override
public void deleteUserData(@NotNull UUID uuid) { public void deleteUserData(@NotNull UUID uuid) {
try { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
// Delete Position
PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
WHERE `id` WHERE `id`
IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?), IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `offline_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(1, uuid.toString());
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString()); statement.setString(3, uuid.toString());
statement.executeUpdate(); 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%` DELETE FROM `%players_table%`
WHERE `uuid`=?;""")); WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", 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(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); plugin.log(Level.SEVERE, "Failed to set home for " + home.getOwner().getUsername(), e);
plugin.log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().getUsername(), e);
} }
}); });
} }
@@ -20,6 +20,7 @@
package net.william278.huskhomes.hook; package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.User;
@@ -57,12 +58,13 @@ public class DynmapHook extends MapHook {
public void apiEnabled(@NotNull DynmapCommonAPI dynmapCommonAPI) { public void apiEnabled(@NotNull DynmapCommonAPI dynmapCommonAPI) {
dynmapApi = dynmapCommonAPI; dynmapApi = dynmapCommonAPI;
if (plugin.getSettings().doPublicHomesOnMap()) { final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowPublicHomes()) {
getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME).orElseThrow(); getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME).orElseThrow();
dynmapApi.getMarkerAPI().createMarkerSet(getPublicHomesKey(), dynmapApi.getMarkerAPI().createMarkerSet(getPublicHomesKey(),
getPublicHomesMarkerSetName(), dynmapApi.getMarkerAPI().getMarkerIcons(), false); getPublicHomesMarkerSetName(), dynmapApi.getMarkerAPI().getMarkerIcons(), false);
} }
if (plugin.getSettings().doWarpsOnMap()) { if (settings.isShowWarps()) {
getMarkerIcon(WARP_MARKER_IMAGE_NAME).orElseThrow(); getMarkerIcon(WARP_MARKER_IMAGE_NAME).orElseThrow();
dynmapApi.getMarkerAPI().createMarkerSet(getWarpsKey(), dynmapApi.getMarkerAPI().createMarkerSet(getWarpsKey(),
getWarpsMarkerSetName(), dynmapApi.getMarkerAPI().getMarkerIcons(), false); getWarpsMarkerSetName(), dynmapApi.getMarkerAPI().getMarkerIcons(), false);
@@ -89,7 +91,7 @@ public class DynmapHook extends MapHook {
home.getX(), home.getY(), home.getZ(), home.getX(), home.getY(), home.getZ(),
getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME).orElseThrow(), false) getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME).orElseThrow(), false)
.setDescription(MarkerInformationPopup.publicHome( .setDescription(MarkerInformationPopup.publicHome(
home, ICON_PATH + PUBLIC_HOME_MARKER_IMAGE_NAME, plugin home, ICON_PATH + PUBLIC_HOME_MARKER_IMAGE_NAME
).toHtml()); ).toHtml());
}); });
}); });
@@ -135,7 +137,7 @@ public class DynmapHook extends MapHook {
warp.getX(), warp.getY(), warp.getZ(), warp.getX(), warp.getY(), warp.getZ(),
getMarkerIcon(WARP_MARKER_IMAGE_NAME).orElseThrow(), false) getMarkerIcon(WARP_MARKER_IMAGE_NAME).orElseThrow(), false)
.setDescription(MarkerInformationPopup.warp( .setDescription(MarkerInformationPopup.warp(
warp, ICON_PATH + WARP_MARKER_IMAGE_NAME, plugin warp, ICON_PATH + WARP_MARKER_IMAGE_NAME
).toHtml()); ).toHtml());
}); });
}); });
@@ -69,7 +69,7 @@ public abstract class EconomyHook extends Hook {
*/ */
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin,
@NotNull TransactionResolver.Action action) { @NotNull TransactionResolver.Action action) {
plugin.getSettings().getEconomyCost(action) plugin.getSettings().getEconomy().getCost(action)
.flatMap(cost -> plugin.getLocales().getLocale( .flatMap(cost -> plugin.getLocales().getLocale(
"economy_transaction_complete", "economy_transaction_complete",
formatCurrency(cost), formatCurrency(cost),
@@ -125,7 +125,7 @@ public abstract class EconomyHook extends Hook {
* Create an action with a default cost. * Create an action with a default cost.
* *
* @return the default cost * @return the default cost
* @deprecated Use the new {@link TransactionResolver.Action#getDefaultCost()} instead * @deprecated Use the new {@code TransactionResolver.Action#getDefaultCost()} instead
*/ */
@Deprecated(since = "4.4", forRemoval = true) @Deprecated(since = "4.4", forRemoval = true)
public double getDefaultCost() { public double getDefaultCost() {
@@ -20,6 +20,7 @@
package net.william278.huskhomes.hook; package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition; import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
@@ -47,12 +48,13 @@ public abstract class MapHook extends Hook {
* Populate the map with public homes and warps. * Populate the map with public homes and warps.
*/ */
protected void populateMap() { protected void populateMap() {
if (plugin.getSettings().doPublicHomesOnMap()) { final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowPublicHomes()) {
plugin.getDatabase() plugin.getDatabase()
.getLocalPublicHomes(plugin) .getLocalPublicHomes(plugin)
.forEach(this::updateHome); .forEach(this::updateHome);
} }
if (plugin.getSettings().doWarpsOnMap()) { if (settings.isShowWarps()) {
plugin.getDatabase() plugin.getDatabase()
.getLocalWarps(plugin) .getLocalWarps(plugin)
.forEach(this::updateWarp); .forEach(this::updateWarp);
@@ -121,14 +123,16 @@ public abstract class MapHook extends Hook {
*/ */
@SuppressWarnings("BooleanMethodIsAlwaysInverted") @SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected final boolean isValidPosition(@NotNull SavedPosition position) { 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; return false;
} }
if (position instanceof Home && !plugin.getSettings().doPublicHomesOnMap()) { if (position instanceof Home && !settings.isShowPublicHomes()) {
return false; return false;
} }
return !plugin.getSettings().doCrossServer() || position.getServer().equals(plugin.getServerName()); return !plugin.getSettings().getCrossServer().isEnabled()
|| position.getServer().equals(plugin.getServerName());
} }
@NotNull @NotNull
@@ -172,22 +176,20 @@ public abstract class MapHook extends Hook {
} }
@NotNull @NotNull
protected static DynmapHook.MarkerInformationPopup warp(@NotNull Warp warp, @NotNull String thumbnail, protected static DynmapHook.MarkerInformationPopup warp(@NotNull Warp warp, @NotNull String thumbnail) {
@NotNull HuskHomes plugin) {
return MarkerInformationPopup.create(warp.getName()) return MarkerInformationPopup.create(warp.getName())
.thumbnail(thumbnail) .thumbnail(thumbnail)
.field("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60)) .field("Description", warp.getMeta().getDescription())
.field("Location", warp.toString()) .field("Location", warp.toString())
.field("Command", "/warp " + warp.getSafeIdentifier()); .field("Command", "/warp " + warp.getSafeIdentifier());
} }
@NotNull @NotNull
protected static DynmapHook.MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail, protected static DynmapHook.MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail) {
@NotNull HuskHomes plugin) {
return MarkerInformationPopup.create(home.getName()) return MarkerInformationPopup.create(home.getName())
.thumbnail(thumbnail) .thumbnail(thumbnail)
.field("Owner", home.getOwner().getUsername()) .field("Owner", home.getOwner().getUsername())
.field("Description", plugin.getLocales().wrapText(home.getMeta().getDescription(), 60)) .field("Description", home.getMeta().getDescription())
.field("Location", home.toString()) .field("Location", home.toString())
.field("Command", "/phome " + home.getSafeIdentifier()); .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.markers.option.Tooltip;
import net.pl3x.map.core.world.World; import net.pl3x.map.core.world.World;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition; import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.Warp;
@@ -126,11 +127,12 @@ public class Pl3xMapHook extends MapHook implements EventListener {
} }
private void registerLayers(@NotNull World world) { 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); WarpsLayer layer = new WarpsLayer(this, world);
world.getLayerRegistry().register(layer); world.getLayerRegistry().register(layer);
} }
if (plugin.getSettings().doPublicHomesOnMap()) { if (settings.isShowPublicHomes()) {
PublicHomesLayer layer = new PublicHomesLayer(this, world); PublicHomesLayer layer = new PublicHomesLayer(this, world);
world.getLayerRegistry().register(layer); world.getLayerRegistry().register(layer);
} }
@@ -139,10 +141,11 @@ public class Pl3xMapHook extends MapHook implements EventListener {
@EventHandler @EventHandler
public void onPl3xMapEnabled(@NotNull Pl3xMapEnabledEvent event) { public void onPl3xMapEnabled(@NotNull Pl3xMapEnabledEvent event) {
// Register icons // Register icons
if (plugin.getSettings().doWarpsOnMap()) { final Settings.MapHookSettings settings = plugin.getSettings().getMapHook();
if (settings.isShowWarps()) {
this.registerIcon(WARPS_LAYER, "markers/16x/warp.png"); 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"); this.registerIcon(PUBLIC_HOMES_LAYER, "markers/16x/public-home.png");
} }
@@ -172,9 +175,9 @@ public class Pl3xMapHook extends MapHook implements EventListener {
return Options.builder() return Options.builder()
.tooltip(new Tooltip(position.getIdentifier())) .tooltip(new Tooltip(position.getIdentifier()))
.popup(new Popup(position instanceof Home home ? MarkerInformationPopup.publicHome( .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( ).toHtml() : position instanceof Warp warp ? MarkerInformationPopup.warp(
warp, ICON_PATH + PUBLIC_HOMES_LAYER, plugin warp, ICON_PATH + PUBLIC_HOMES_LAYER
).toHtml() : "")) ).toHtml() : ""))
.build(); .build();
} }
@@ -26,6 +26,9 @@ import com.djrapitops.plan.extension.ExtensionService;
import com.djrapitops.plan.extension.annotation.*; import com.djrapitops.plan.extension.annotation.*;
import com.djrapitops.plan.extension.icon.Color; import com.djrapitops.plan.extension.icon.Color;
import com.djrapitops.plan.extension.icon.Family; 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.HuskHomes;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
@@ -87,18 +90,13 @@ public class PlanHook extends Hook {
color = Color.LIGHT_BLUE color = Color.LIGHT_BLUE
) )
@SuppressWarnings("unused") @SuppressWarnings("unused")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
protected static class PlanDataExtension implements DataExtension { protected static class PlanDataExtension implements DataExtension {
private static final String UNKNOWN_STRING = "N/A"; private static final String UNKNOWN_STRING = "N/A";
private Database database; private Database database;
protected PlanDataExtension(@NotNull Database database) {
this.database = database;
}
protected PlanDataExtension() {
}
@Override @Override
public CallEvents[] callExtensionMethodsOn() { public CallEvents[] callExtensionMethodsOn() {
return new CallEvents[]{ return new CallEvents[]{
@@ -23,6 +23,7 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BackCommand; import net.william278.huskhomes.command.BackCommand;
import net.william278.huskhomes.command.Command; import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload; import net.william278.huskhomes.network.Payload;
@@ -60,7 +61,7 @@ public class EventListener {
plugin.getDatabase().ensureUser(onlineUser); plugin.getDatabase().ensureUser(onlineUser);
// Handle cross-server checks // Handle cross-server checks
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
this.handleInboundTeleport(onlineUser); this.handleInboundTeleport(onlineUser);
// Synchronize the global player list // Synchronize the global player list
@@ -106,12 +107,12 @@ public class EventListener {
plugin.getManager().homes().removeUserHomes(onlineUser); plugin.getManager().homes().removeUserHomes(onlineUser);
// Update global lists // Update global lists
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
final List<String> localPlayerList = plugin.getLocalPlayerList().stream() final List<String> localPlayerList = plugin.getLocalPlayerList().stream()
.filter(player -> !player.equals(onlineUser.getUsername())) .filter(player -> !player.equals(onlineUser.getUsername()))
.toList(); .toList();
if (plugin.getSettings().getBrokerType() == Broker.Type.REDIS) { if (plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
this.synchronizeGlobalPlayerList(onlineUser, localPlayerList); this.synchronizeGlobalPlayerList(onlineUser, localPlayerList);
return; return;
} }
@@ -139,7 +140,7 @@ public class EventListener {
try { try {
teleporter.teleportLocally( teleporter.teleportLocally(
(Position) teleport.getTarget(), (Position) teleport.getTarget(),
plugin.getSettings().doAsynchronousTeleports() plugin.getSettings().getGeneral().isTeleportAsync()
); );
} catch (TeleportationException e) { } catch (TeleportationException e) {
e.displayMessage(teleporter); e.displayMessage(teleporter);
@@ -158,7 +159,8 @@ public class EventListener {
final Optional<Position> bedPosition = teleporter.getBedSpawnPosition(); final Optional<Position> bedPosition = teleporter.getBedSpawnPosition();
if (bedPosition.isEmpty()) { if (bedPosition.isEmpty()) {
plugin.getSpawn().ifPresent(spawn -> { 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(() -> { plugin.runSyncDelayed(() -> {
try { try {
Teleport.builder(plugin) Teleport.builder(plugin)
@@ -172,7 +174,7 @@ public class EventListener {
}, 40L); }, 40L);
} else { } else {
try { try {
teleporter.teleportLocally(spawn, plugin.getSettings().doAsynchronousTeleports()); teleporter.teleportLocally(spawn, plugin.getSettings().getGeneral().isTeleportAsync());
} catch (TeleportationException e) { } catch (TeleportationException e) {
e.displayMessage(teleporter); e.displayMessage(teleporter);
} }
@@ -181,7 +183,7 @@ public class EventListener {
}); });
} else { } else {
try { try {
teleporter.teleportLocally(bedPosition.get(), plugin.getSettings().doAsynchronousTeleports()); teleporter.teleportLocally(bedPosition.get(), plugin.getSettings().getGeneral().isTeleportAsync());
} catch (TeleportationException e) { } catch (TeleportationException e) {
e.displayMessage(teleporter); e.displayMessage(teleporter);
} }
@@ -217,7 +219,7 @@ public class EventListener {
* @param onlineUser the {@link OnlineUser} who died * @param onlineUser the {@link OnlineUser} who died
*/ */
protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) { 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)) { .map(Command::getPermission).map(onlineUser::hasPermission).orElse(false)) {
plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition()); plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
} }
@@ -235,13 +237,14 @@ public class EventListener {
.map(command -> onlineUser.hasPermission(command.getPermission()) .map(command -> onlineUser.hasPermission(command.getPermission())
&& onlineUser.hasPermission(command.getPermission("death"))) && onlineUser.hasPermission(command.getPermission("death")))
.orElse(false); .orElse(false);
if (plugin.getSettings().doBackCommandReturnByDeath() && canReturnByDeath) { if (plugin.getSettings().getGeneral().getBackCommand().isReturnByDeath() && canReturnByDeath) {
plugin.getLocales().getLocale("return_by_death_notification") plugin.getLocales().getLocale("return_by_death_notification")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
} }
// Respawn the player via the global respawn system // 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); this.respawnGlobally(onlineUser);
} }
}); });
@@ -283,7 +286,7 @@ public class EventListener {
* @param sourcePosition the source {@link Position} they came from * @param sourcePosition the source {@link Position} they came from
*/ */
protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) { protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) {
if (!plugin.getSettings().doBackCommandSaveOnTeleportEvent()) { if (!plugin.getSettings().getGeneral().getBackCommand().isSaveOnTeleportEvent()) {
return; return;
} }
@@ -298,9 +301,9 @@ public class EventListener {
* @param position the new spawn point * @param position the new spawn point
*/ */
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) { protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (!plugin.getSettings().doAlwaysRespawnAtSpawn() if (!plugin.getSettings().getGeneral().isAlwaysRespawnAtSpawn()
&& plugin.getSettings().doCrossServer() && plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().isGlobalRespawning()) { && plugin.getSettings().getCrossServer().isGlobalRespawning()) {
plugin.getDatabase().setRespawnPosition(onlineUser, position); plugin.getDatabase().setRespawnPosition(onlineUser, position);
} }
} }
@@ -163,7 +163,7 @@ public class HomesManager {
* @param homeId the UUID of the home/warp to update * @param homeId the UUID of the home/warp to update
*/ */
private void propagateCacheUpdate(@NotNull UUID homeId) { private void propagateCacheUpdate(@NotNull UUID homeId) {
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_HOME) .type(Message.Type.UPDATE_HOME)
.scope(Message.Scope.SERVER) .scope(Message.Scope.SERVER)
@@ -203,7 +203,8 @@ public class HomesManager {
final SavedUser savedOwner = plugin.getSavedUser(owner) final SavedUser savedOwner = plugin.getSavedUser(owner)
.or(() -> plugin.getDatabase().getUserData(owner.getUuid())) .or(() -> plugin.getDatabase().getUserData(owner.getUuid()))
.orElseThrow(() -> new IllegalStateException("User data not found for " + 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)) { if (!buyAdditionalSlots || plugin.getEconomyHook().isEmpty() || !(owner instanceof OnlineUser online)) {
throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS); 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) public void createHome(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position)
throws ValidationException { 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 { 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) h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName)
)); ));
publicHomes.removeIf(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.getMapHook().ifPresent(hook -> hook.clearHomes(worldName));
} }
plugin.getCommands().stream() plugin.getCommands().stream()
@@ -374,23 +378,23 @@ public class HomesManager {
public int getMaxHomes(@Nullable User user) { public int getMaxHomes(@Nullable User user) {
return user instanceof OnlineUser online ? online.getMaxHomes( return user instanceof OnlineUser online ? online.getMaxHomes(
plugin.getSettings().getMaxHomes(), plugin.getSettings().getGeneral().getMaxHomes(),
plugin.getSettings().doStackPermissionLimits() plugin.getSettings().getGeneral().isStackPermissionLimits()
) : plugin.getSettings().getMaxHomes(); ) : plugin.getSettings().getGeneral().getMaxHomes();
} }
public int getMaxPublicHomes(@Nullable User user) { public int getMaxPublicHomes(@Nullable User user) {
return user instanceof OnlineUser online ? online.getMaxPublicHomes( return user instanceof OnlineUser online ? online.getMaxPublicHomes(
plugin.getSettings().getMaxPublicHomes(), plugin.getSettings().getGeneral().getMaxPublicHomes(),
plugin.getSettings().doStackPermissionLimits() plugin.getSettings().getGeneral().isStackPermissionLimits()
) : plugin.getSettings().getMaxPublicHomes(); ) : plugin.getSettings().getGeneral().getMaxPublicHomes();
} }
public int getFreeHomes(@Nullable User user) { public int getFreeHomes(@Nullable User user) {
return user instanceof OnlineUser online ? online.getFreeHomes( return user instanceof OnlineUser online ? online.getFreeHomes(
plugin.getSettings().getFreeHomeSlots(), plugin.getSettings().getEconomy().getFreeHomeSlots(),
plugin.getSettings().doStackPermissionLimits() plugin.getSettings().getGeneral().isStackPermissionLimits()
) : plugin.getSettings().getFreeHomeSlots(); ) : plugin.getSettings().getEconomy().getFreeHomeSlots();
} }
} }
@@ -54,7 +54,7 @@ public class Manager {
// Update caches on all servers // Update caches on all servers
protected void propagateCacheUpdate() { protected void propagateCacheUpdate() {
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_CACHES) .type(Message.Type.UPDATE_CACHES)
.scope(Message.Scope.SERVER) .scope(Message.Scope.SERVER)
@@ -117,7 +117,8 @@ public class RequestsManager {
} }
public void sendTeleportAllRequest(@NotNull OnlineUser requester) { 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); final TeleportRequest request = new TeleportRequest(requester, TeleportRequest.Type.TPA_HERE, expiry);
for (OnlineUser onlineUser : plugin.getOnlineUsers()) { for (OnlineUser onlineUser : plugin.getOnlineUsers()) {
if (onlineUser.equals(requester)) { if (onlineUser.equals(requester)) {
@@ -127,7 +128,7 @@ public class RequestsManager {
sendLocalTeleportRequest(request, onlineUser); sendLocalTeleportRequest(request, onlineUser);
} }
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder() Message.builder()
.type(Message.Type.TELEPORT_REQUEST) .type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request)) .payload(Payload.withTeleportRequest(request))
@@ -145,7 +146,8 @@ public class RequestsManager {
*/ */
public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser,
@NotNull TeleportRequest.Type type) throws IllegalArgumentException { @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 TeleportRequest request = new TeleportRequest(requester, type, expiry);
final Optional<OnlineUser> localTarget = plugin.getOnlineUser(targetUser); final Optional<OnlineUser> localTarget = plugin.getOnlineUser(targetUser);
if (localTarget.isPresent()) { if (localTarget.isPresent()) {
@@ -161,7 +163,7 @@ public class RequestsManager {
} }
// If the player couldn't be found locally, send the request cross-server // 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); request.setRecipientName(targetUser);
plugin.fireEvent(plugin.getSendTeleportRequestEvent(requester, request), (event -> Message.builder() plugin.fireEvent(plugin.getSendTeleportRequestEvent(requester, request), (event -> Message.builder()
.type(Message.Type.TELEPORT_REQUEST) .type(Message.Type.TELEPORT_REQUEST)
@@ -204,7 +206,8 @@ public class RequestsManager {
.ifPresent(recipient::sendMessage); .ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName()) plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
.ifPresent(recipient::sendMessage); .ifPresent(recipient::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORT_REQUEST_RECEIVED) plugin.getSettings().getGeneral().getSoundEffects()
.get(Settings.SoundEffectAction.TELEPORT_REQUEST_RECEIVED)
.ifPresent(recipient::playSound); .ifPresent(recipient::playSound);
})); }));
} }
@@ -286,15 +289,16 @@ public class RequestsManager {
// Fire event and send request response confirmation to the recipient // Fire event and send request response confirmation to the recipient
plugin.fireEvent(plugin.getReplyTeleportRequestEvent(recipient, request), (event -> { plugin.fireEvent(plugin.getReplyTeleportRequestEvent(recipient, request), (event -> {
plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation", plugin.getLocales().getLocale(
request.getRequesterName()) "teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation",
.ifPresent(recipient::sendMessage); request.getRequesterName()
).ifPresent(recipient::sendMessage);
// Find the requester and inform them of the response // Find the requester and inform them of the response
final Optional<OnlineUser> localRequester = plugin.getOnlineUserExact(request.getRequesterName()); final Optional<OnlineUser> localRequester = plugin.getOnlineUserExact(request.getRequesterName());
if (localRequester.isPresent()) { if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request); handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().doCrossServer()) { } else if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder() Message.builder()
.type(Message.Type.TELEPORT_REQUEST_RESPONSE) .type(Message.Type.TELEPORT_REQUEST_RESPONSE)
.payload(Payload.withTeleportRequest(request)) .payload(Payload.withTeleportRequest(request))
@@ -314,7 +318,7 @@ public class RequestsManager {
.teleporter(recipient); .teleporter(recipient);
// Strict /tpahere requests will teleport to where the sender was when typing the command // 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()); builder.target(request.getRequesterPosition());
} else { } else {
builder.target(request.getRequesterName()); builder.target(request.getRequesterName());
@@ -79,7 +79,7 @@ public class WarpsManager {
} }
private void propagateCacheUpdate(@NotNull UUID warpId) { private void propagateCacheUpdate(@NotNull UUID warpId) {
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_WARP) .type(Message.Type.UPDATE_WARP)
.scope(Message.Scope.SERVER) .scope(Message.Scope.SERVER)
@@ -103,7 +103,8 @@ public class WarpsManager {
@NotNull @NotNull
public List<String> getUsableWarps(@NotNull CommandUser user) { 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 getWarps();
} }
return warps.stream() return warps.stream()
@@ -137,7 +138,7 @@ public class WarpsManager {
@NotNull @NotNull
public Warp createWarp(@NotNull String name, @NotNull Position position) throws ValidationException { 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 { public void deleteWarp(@NotNull String name) throws ValidationException {
@@ -169,7 +170,7 @@ public class WarpsManager {
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) { public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
final int deleted = plugin.getDatabase().deleteAllWarps(worldName, serverName); final int deleted = plugin.getDatabase().deleteAllWarps(worldName, serverName);
warps.removeIf(warp -> warp.getServer().equals(serverName) && warp.getWorld().getName().equals(worldName)); 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.getMapHook().ifPresent(hook -> hook.clearWarps(worldName));
} }
plugin.getCommands().stream() plugin.getCommands().stream()
@@ -157,7 +157,10 @@ public abstract class Broker {
protected String getSubChannelId() { protected String getSubChannelId() {
final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor()); final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor());
try { 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) { } catch (InvalidKeyException e) {
plugin.log(Level.SEVERE, "Cluster ID specified in config contains invalid characters"); plugin.log(Level.SEVERE, "Cluster ID specified in config contains invalid characters");
} }
@@ -19,97 +19,198 @@
package net.william278.huskhomes.network; package net.william278.huskhomes.network;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis; import redis.clients.jedis.*;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.util.Pool;
import redis.clients.jedis.JedisPubSub;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level; import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.CrossServerSettings.RedisSettings;
/** /**
* Redis PubSub broker implementation. * Redis PubSub broker implementation.
*/ */
public class RedisBroker extends PluginMessageBroker { public class RedisBroker extends PluginMessageBroker {
private JedisPool jedisPool;
private final Subscriber subscriber;
public RedisBroker(@NotNull HuskHomes plugin) { public RedisBroker(@NotNull HuskHomes plugin) {
super(plugin); super(plugin);
this.subscriber = new Subscriber(this, getSubChannelId());
} }
@Blocking
@Override @Override
public void initialize() throws IllegalStateException { 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(); // Subscribe using a thread (rather than a task)
final String host = plugin.getSettings().getRedisHost(); subscriber.enable(jedisPool);
final int port = plugin.getSettings().getRedisPort(); new Thread(subscriber::subscribe, "huskhomes:redis_subscriber").start();
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");
} }
@NotNull @NotNull
private Runnable getSubscriber() { private static Pool<Jedis> getJedisPool(@NotNull RedisSettings settings) {
return () -> { // Get the Redis connection settings
try (Jedis jedis = jedisPool.getResource()) { final String password = settings.getPassword();
jedis.subscribe(new JedisPubSub() { final String host = settings.getHost();
@Override final int port = settings.getPort();
public void onMessage(@NotNull String channel, @NotNull String encodedMessage) { final boolean useSSL = settings.isUseSsl();
if (!channel.equals(getSubChannelId())) {
return; // Create the jedis pool
final JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(0);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
// 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);
} }
final Message message; // Otherwise, use the standard Jedis pool
try { return password.isEmpty()
message = plugin.getGson().fromJson(encodedMessage, Message.class); ? new JedisPool(config, host, port, 0, useSSL)
} catch (Exception e) { : new JedisPool(config, host, port, 0, password, useSSL);
plugin.log(Level.WARNING, "Failed to decode message from Redis: " + e.getMessage());
return;
}
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;
}
if (message.getTarget().equals(plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) {
plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> handle(receiver, message));
}
}
}, getSubChannelId());
}
};
} }
@Override @Override
protected void send(@NotNull Message message, @NotNull OnlineUser sender) { protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
plugin.runAsync(() -> { plugin.runAsync(() -> subscriber.send(message));
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(getSubChannelId(), plugin.getGson().toJson(message));
}
});
} }
@Override @Override
@Blocking
public void close() { public void close() {
super.close(); super.close();
if (jedisPool != null) { 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(); 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; package net.william278.huskhomes.position;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Represents a local position on this server. * Represents a local position on this server.
*/ */
@Setter
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class Location { public class Location {
@Expose @Expose
private double x; private double x;
@Expose @Expose
private double y; private double y;
@Expose @Expose
private double z; private double z;
@Expose @Expose
private float yaw; private float yaw;
@Expose @Expose
private float pitch; private float pitch;
@Expose @Expose
private World world; 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 @NotNull
public static Location at(double x, double y, double z, float yaw, float pitch, @NotNull World world) { 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); return new Location(x, y, z, yaw, pitch, world);
@@ -76,70 +74,4 @@ public class Location {
this.setWorld(position.getWorld()); 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; package net.william278.huskhomes.position;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.william278.huskhomes.teleport.Target; import net.william278.huskhomes.teleport.Target;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Represents a position - a {@link Location} somewhere on the proxy network or server. * Represents a position - a {@link Location} somewhere on the proxy network or server.
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Position extends Location implements Target { public class Position extends Location implements Target {
@Expose @Expose
@@ -43,10 +46,6 @@ public class Position extends Location implements Target {
this.setServer(server); this.setServer(server);
} }
@SuppressWarnings("unused")
private Position() {
}
@NotNull @NotNull
public static Position at(double x, double y, double z, float yaw, float pitch, public static Position at(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull String server) { @NotNull World world, @NotNull String server) {
@@ -19,6 +19,7 @@
package net.william278.huskhomes.position; package net.william278.huskhomes.position;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -28,6 +29,7 @@ import java.util.UUID;
/** /**
* Represents a world on a server. * Represents a world on a server.
*/ */
@NoArgsConstructor
public class World { public class World {
private String name; private String name;
@@ -41,10 +43,6 @@ public class World {
this.setEnvironment(environment); this.setEnvironment(environment);
} }
@SuppressWarnings("unused")
public World() {
}
@NotNull @NotNull
public static World from(@NotNull String name, @NotNull UUID uuid, @NotNull Environment environment) { public static World from(@NotNull String name, @NotNull UUID uuid, @NotNull Environment environment) {
return new World(name, uuid, environment); return new World(name, uuid, environment);
@@ -20,6 +20,7 @@
package net.william278.huskhomes.random; package net.william278.huskhomes.random;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
@@ -35,17 +36,15 @@ import java.util.logging.Level;
*/ */
public final class NormalDistributionEngine extends RandomTeleportEngine { public final class NormalDistributionEngine extends RandomTeleportEngine {
private final int radius; private final Settings.RtpSettings.RtpRadius radius;
private final int spawnRadius;
private final float mean; private final float mean;
private final float standardDeviation; private final float standardDeviation;
public NormalDistributionEngine(@NotNull HuskHomes plugin) { public NormalDistributionEngine(@NotNull HuskHomes plugin) {
super(plugin, "Normal Distribution"); super(plugin, "Normal Distribution");
this.radius = plugin.getSettings().getRtpRadius(); this.radius = plugin.getSettings().getRtp().getRegion();
this.spawnRadius = determineSpawnRadius(radius, plugin.getSettings().getRtpSpawnRadius(), plugin); this.mean = plugin.getSettings().getRtp().getDistributionMean();
this.mean = plugin.getSettings().getRtpDistributionMean(); this.standardDeviation = plugin.getSettings().getRtp().getDistributionStandardDeviation();
this.standardDeviation = plugin.getSettings().getRtpDistributionStandardDeviation();
} }
// Utility for determining a valid spawn radius // 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) { private CompletableFuture<Optional<Location>> generateSafeLocation(@NotNull World world) {
return plugin.findSafeGroundLocation(generateLocation( 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; package net.william278.huskhomes.teleport;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.william278.desertwell.util.ThrowingConsumer; import net.william278.desertwell.util.ThrowingConsumer;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BackCommand; import net.william278.huskhomes.command.BackCommand;
@@ -60,7 +62,7 @@ public class Teleport {
this.target = target; this.target = target;
this.type = type; this.type = type;
this.actions = actions; this.actions = actions;
this.async = plugin.getSettings().doAsynchronousTeleports(); this.async = plugin.getSettings().getGeneral().isTeleportAsync();
this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class) this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class)
.map(command -> executor.hasPermission(command.getPermission()) .map(command -> executor.hasPermission(command.getPermission())
&& executor.hasPermission(command.getPermission("previous"))) && executor.hasPermission(command.getPermission("previous")))
@@ -81,7 +83,7 @@ public class Teleport {
// Teleport a user on another server // Teleport a user on another server
if (localTeleporter.isEmpty()) { if (localTeleporter.isEmpty()) {
final Username teleporter = (Username) this.teleporter; final Username teleporter = (Username) this.teleporter;
if (!plugin.getSettings().doCrossServer()) { if (!plugin.getSettings().getCrossServer().isEnabled()) {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin); throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin);
} }
@@ -128,7 +130,7 @@ public class Teleport {
return; return;
} }
if (plugin.getSettings().doCrossServer()) { if (plugin.getSettings().getCrossServer().isEnabled()) {
fireEvent((event) -> { fireEvent((event) -> {
performTransactions(); performTransactions();
Message.builder() Message.builder()
@@ -149,7 +151,8 @@ public class Teleport {
} }
final Position target = (Position) this.target; 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 { try {
teleporter.teleportLocally(target, async); teleporter.teleportLocally(target, async);
} catch (TeleportationException e) { } catch (TeleportationException e) {
@@ -176,7 +179,7 @@ public class Teleport {
public void displayTeleportingComplete(@NotNull OnlineUser teleporter) { public void displayTeleportingComplete(@NotNull OnlineUser teleporter) {
plugin.getLocales().getLocale("teleporting_complete") plugin.getLocales().getLocale("teleporting_complete")
.ifPresent(teleporter::sendMessage); .ifPresent(teleporter::sendMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE) plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_COMPLETE)
.ifPresent(teleporter::playSound); .ifPresent(teleporter::playSound);
} }
@@ -217,6 +220,8 @@ public class Teleport {
/** /**
* Represents the type of teleport being used. * Represents the type of teleport being used.
*/ */
@Getter
@AllArgsConstructor
public enum Type { public enum Type {
TELEPORT(0), TELEPORT(0),
RESPAWN(1), RESPAWN(1),
@@ -224,10 +229,6 @@ public class Teleport {
private final int typeId; private final int typeId;
Type(final int typeId) {
this.typeId = typeId;
}
/** /**
* Returns a {@link Type} by its type id. * Returns a {@link Type} by its type id.
* *
@@ -240,8 +241,5 @@ public class Teleport {
.findFirst(); .findFirst();
} }
public int getTypeId() {
return typeId;
}
} }
} }
@@ -19,6 +19,8 @@
package net.william278.huskhomes.teleport; package net.william278.huskhomes.teleport;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
@@ -31,12 +33,17 @@ import java.util.List;
/** /**
* A builder for {@link Teleport} and {@link TimedTeleport} objects. * A builder for {@link Teleport} and {@link TimedTeleport} objects.
*/ */
@Accessors(fluent = true, chain = true)
public class TeleportBuilder { public class TeleportBuilder {
private final HuskHomes plugin; private final HuskHomes plugin;
@Setter
private OnlineUser executor; private OnlineUser executor;
private Teleportable teleporter; private Teleportable teleporter;
private Target target; private Target target;
@Setter
private boolean updateLastPosition = true; private boolean updateLastPosition = true;
@Setter
private Teleport.Type type = Teleport.Type.TELEPORT; private Teleport.Type type = Teleport.Type.TELEPORT;
private List<TransactionResolver.Action> actions = List.of(); private List<TransactionResolver.Action> actions = List.of();
@@ -52,12 +59,16 @@ public class TeleportBuilder {
@NotNull @NotNull
public TimedTeleport toTimedTeleport() throws IllegalStateException { public TimedTeleport toTimedTeleport() throws IllegalStateException {
validateTeleport(); this.validateTeleport();
if (!(teleporter instanceof OnlineUser onlineTeleporter)) { if (!(teleporter instanceof OnlineUser onlineTeleporter)) {
throw new IllegalStateException("Teleporter must be an OnlineUser for timed teleportation"); 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 { 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 @NotNull
public TeleportBuilder teleporter(@NotNull Teleportable teleporter) { public TeleportBuilder teleporter(@NotNull Teleportable teleporter) {
this.teleporter = teleporter; this.teleporter = teleporter;
@@ -91,8 +96,7 @@ public class TeleportBuilder {
@NotNull @NotNull
public TeleportBuilder teleporter(@NotNull String teleporter) { public TeleportBuilder teleporter(@NotNull String teleporter) {
this.teleporter = Teleportable.username(teleporter); return teleporter(Teleportable.username(teleporter));
return this;
} }
@NotNull @NotNull
@@ -103,14 +107,7 @@ public class TeleportBuilder {
@NotNull @NotNull
public TeleportBuilder target(@NotNull String target) { public TeleportBuilder target(@NotNull String target) {
this.target = Target.username(target); return target(Target.username(target));
return this;
}
@NotNull
public TeleportBuilder updateLastPosition(boolean updateLastPosition) {
this.updateLastPosition = updateLastPosition;
return this;
} }
@SuppressWarnings("removal") @SuppressWarnings("removal")
@@ -126,10 +123,4 @@ public class TeleportBuilder {
this.actions = List.of(actions); this.actions = List.of(actions);
return this; 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.Expose;
import com.google.gson.annotations.SerializedName; 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.position.Position;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull; 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. * Represents a request between players for one user to teleport to another, or vice versa.
*/ */
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TeleportRequest { public class TeleportRequest {
@Expose @Expose
@@ -40,6 +47,8 @@ public class TeleportRequest {
private Position requesterPosition; private Position requesterPosition;
@Expose @Expose
@SerializedName("expiry_time") @SerializedName("expiry_time")
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private long expiryTime; private long expiryTime;
@Expose @Expose
private Type type; private Type type;
@@ -62,10 +71,6 @@ public class TeleportRequest {
this.expiryTime = expiryTime; this.expiryTime = expiryTime;
} }
@SuppressWarnings("unused")
private TeleportRequest() {
}
/** /**
* Returns if the request has now expired. * Returns if the request has now expired.
* *
@@ -75,65 +80,6 @@ public class TeleportRequest {
return Instant.now().isAfter(Instant.ofEpochSecond(expiryTime)); 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}). * Types of teleport requests ({@code /tpa} or {@code /tpahere}).
@@ -97,7 +97,7 @@ public class TimedTeleport extends Teleport implements Runnable {
public void run() { public void run() {
// Display a countdown action bar message // Display a countdown action bar message
if (timeLeft > 0) { if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP) plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
.ifPresent(teleporter::playSound); .ifPresent(teleporter::playSound);
plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft)) plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft))
.ifPresent(this::sendStatusMessage); .ifPresent(this::sendStatusMessage);
@@ -142,7 +142,7 @@ public class TimedTeleport extends Teleport implements Runnable {
.ifPresent(teleporter::sendMessage); .ifPresent(teleporter::sendMessage);
plugin.getLocales().getLocale("teleporting_action_bar_cancelled") plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(this::sendStatusMessage); .ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED) plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound); .ifPresent(teleporter::playSound);
return true; return true;
} }
@@ -153,7 +153,7 @@ public class TimedTeleport extends Teleport implements Runnable {
.ifPresent(teleporter::sendMessage); .ifPresent(teleporter::sendMessage);
plugin.getLocales().getLocale("teleporting_action_bar_cancelled") plugin.getLocales().getLocale("teleporting_action_bar_cancelled")
.ifPresent(this::sendStatusMessage); .ifPresent(this::sendStatusMessage);
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED) plugin.getSettings().getGeneral().getSoundEffects().get(Settings.SoundEffectAction.TELEPORTATION_CANCELLED)
.ifPresent(teleporter::playSound); .ifPresent(teleporter::playSound);
return true; return true;
} }
@@ -164,7 +164,7 @@ public class TimedTeleport extends Teleport implements Runnable {
} }
private void sendStatusMessage(@NotNull MineDown message) { private void sendStatusMessage(@NotNull MineDown message) {
teleporter.sendMessage(message, plugin.getSettings().getTeleportWarmupDisplay()); teleporter.sendMessage(message, plugin.getSettings().getGeneral().getTeleportWarmupDisplay());
} }
private boolean hasTeleporterMoved() { 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 * @param slot the {@link Locales.DisplaySlot} to send the message to
*/ */
public void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) { public void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) {
if (slot == Locales.DisplaySlot.CHAT) { switch (slot) {
sendMessage(mineDown); case ACTION_BAR -> sendActionBar(mineDown);
} else if (slot == Locales.DisplaySlot.ACTION_BAR) { case TITLE -> sendTitle(mineDown, false);
sendActionBar(mineDown); case SUBTITLE -> sendTitle(mineDown, true);
} else if (slot == Locales.DisplaySlot.TITLE) { default -> sendMessage(mineDown);
sendTitle(mineDown, false);
} else if (slot == Locales.DisplaySlot.SUBTITLE) {
sendTitle(mineDown, true);
} }
} }
@@ -19,6 +19,9 @@
package net.william278.huskhomes.user; package net.william278.huskhomes.user;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.time.Duration; import java.time.Duration;
@@ -29,32 +32,23 @@ import java.util.UUID;
/** /**
* Represents data about a player on the server. * Represents data about a player on the server.
*/ */
@Getter
@AllArgsConstructor
public class SavedUser { public class SavedUser {
private final User user; private final User user;
@Setter
private int homeSlots; private int homeSlots;
@Setter
private boolean ignoringTeleports; 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. * Create a new SavedUser object.
* *
* <p>Please note that User RTP cooldowns are no longer stored in {@link SavedUser} objects; * <p>Please note that User RTP cooldowns are no longer stored in {@link SavedUser} objects;
* please use the new API methods for getting/setting cooldowns * please use the new API methods for getting/setting cooldowns
* *
* @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object. * @deprecated See {@code #SavedUser(User, int, boolean)} to create a SavedUser object.
*/ */
@Deprecated(since = "4.4", forRemoval = true) @Deprecated(since = "4.4", forRemoval = true)
@SuppressWarnings("unused") @SuppressWarnings("unused")
@@ -62,36 +56,16 @@ public class SavedUser {
this(user, homeSlots, ignoringTeleports); this(user, homeSlots, ignoringTeleports);
} }
@NotNull
public User getUser() {
return user;
}
@NotNull @NotNull
public UUID getUserUuid() { public UUID getUserUuid() {
return user.getUuid(); return getUser().getUuid();
} }
@NotNull @NotNull
public String getUsername() { 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. * 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; package net.william278.huskhomes.user;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
@@ -26,7 +29,9 @@ import java.util.UUID;
/** /**
* Represents a user who has data saved in the database. * Represents a user who has data saved in the database.
*/ */
public class User { @Getter
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class User implements Comparable<User> {
@NotNull @NotNull
private final UUID uuid; private final UUID uuid;
@@ -34,17 +39,6 @@ public class User {
@NotNull @NotNull
private final String username; 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 @NotNull
public static User of(@NotNull UUID uuid, @NotNull String username) { public static User of(@NotNull UUID uuid, @NotNull String username) {
return new User(uuid, username); return new User(uuid, username);
@@ -58,13 +52,9 @@ public class User {
return super.equals(obj); return super.equals(obj);
} }
@NotNull @Override
public UUID getUuid() { public int compareTo(@NotNull User o) {
return uuid; return getUsername().compareTo(o.getUsername());
} }
@NotNull
public String getUsername() {
return username;
}
} }
@@ -19,6 +19,8 @@
package net.william278.huskhomes.util; package net.william278.huskhomes.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
@@ -51,7 +53,7 @@ public interface TransactionResolver {
// Validates if the user has funds to perform an action // Validates if the user has funds to perform an action
private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) { private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) {
return getPlugin().getSettings().getEconomyCost(action).map(Math::abs) return getPlugin().getSettings().getEconomy().getCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) .flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c)) ? Optional.empty() : Optional.of(c))
.map(c -> getEconomyHook() .map(c -> getEconomyHook()
@@ -70,7 +72,7 @@ public interface TransactionResolver {
// Validates if the user is on cooldown for an action // Validates if the user is on cooldown for an action
private boolean isNotOnCooldown(@NotNull OnlineUser player, @NotNull Action 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)) { if (configCooldown <= 0 || player.hasPermission(Action.BYPASS_COOLDOWNS_PERMISSION)) {
return true; return true;
} }
@@ -118,8 +120,8 @@ public interface TransactionResolver {
* @param action the {@link Action action} to deduct the cost from if needed * @param action the {@link Action action} to deduct the cost from if needed
*/ */
default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) { default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) {
getEconomyHook().ifPresent(hook -> getPlugin().getSettings() getEconomyHook().ifPresent(hook -> getPlugin().getSettings().getEconomy()
.getEconomyCost(action).map(Math::abs) .getCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) .flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c)) ? Optional.empty() : Optional.of(c))
.ifPresent(cost -> { .ifPresent(cost -> {
@@ -127,7 +129,7 @@ public interface TransactionResolver {
hook.notifyDeducted(player, getPlugin(), action); 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)) { if (configCooldown > 0 && !player.hasPermission(Action.BYPASS_COOLDOWNS_PERMISSION)) {
getPlugin().getDatabase().setCooldown(action, player, Instant.now().plusSeconds(configCooldown)); 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. * Represents actions that can be the subject of a transaction.
*/ */
@Getter
@AllArgsConstructor
enum Action { enum Action {
/* /*
@@ -200,54 +204,35 @@ public interface TransactionResolver {
public static final String BYPASS_COOLDOWNS_PERMISSION = "huskhomes.bypass_cooldowns"; public static final String BYPASS_COOLDOWNS_PERMISSION = "huskhomes.bypass_cooldowns";
private final double defaultCost; private final double defaultCost;
private final int defaultCooldown; private final long defaultCooldown;
Action(double defaultCost, int defaultCooldown) {
this.defaultCost = defaultCost;
this.defaultCooldown = defaultCooldown;
}
Action() { Action() {
this(0d, 0); this(0, 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;
} }
// Get the default economy action cost map for the config // Get the default economy action cost map for the config
@NotNull @NotNull
public static Map<String, Double> getEconomyCostsConfigMap() { public static Map<Action, Double> getEconomyCosts() {
return Arrays.stream(values()) return Arrays.stream(values())
.filter(action -> action.getDefaultCost() > 0) .filter(action -> action.getDefaultCost() > 0)
.collect(Collectors.toMap( .collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH), action -> action,
Action::getDefaultCost Action::getDefaultCost,
(a, b) -> a,
TreeMap::new
)); ));
} }
// Get the default cooldown action time map for the config // Get the default cooldown action time map for the config
@NotNull @NotNull
public static Map<String, Integer> getCooldownsConfigMap() { public static Map<Action, Long> getCooldownTimes() {
return Arrays.stream(values()) return Arrays.stream(values())
.filter(action -> action.getDefaultCooldown() > 0) .filter(action -> action.getDefaultCooldown() > 0)
.collect(Collectors.toMap( .collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH), action -> action,
Action::getDefaultCooldown Action::getDefaultCooldown,
(a, b) -> a,
TreeMap::new
)); ));
} }
@@ -19,24 +19,19 @@
package net.william278.huskhomes.util; package net.william278.huskhomes.util;
import de.exlll.configlib.Configuration;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
@YamlFile(header = """ @Configuration
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ @NoArgsConstructor(access = AccessLevel.PRIVATE)
┃ Unsafe /rtp Blocks ┃
┃ Developed by William278 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
public class UnsafeBlocks { public class UnsafeBlocks {
@YamlKey("unsafe_blocks")
public List<String> unsafeBlocks; public List<String> unsafeBlocks;
@YamlKey("safe_occupation_blocks")
public List<String> safeOccupationBlocks; public List<String> safeOccupationBlocks;
/** /**
@@ -68,8 +63,4 @@ public class UnsafeBlocks {
return blockId; return blockId;
} }
@SuppressWarnings("unused")
public UnsafeBlocks() {
}
} }
@@ -19,11 +19,13 @@
package net.william278.huskhomes.util; package net.william278.huskhomes.util;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@Getter
public class ValidationException extends IllegalArgumentException { public class ValidationException extends IllegalArgumentException {
private final Type type; 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. * The type of validation error.
*/ */
@@ -19,22 +19,20 @@
package net.william278.huskhomes.util; package net.william278.huskhomes.util;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@AllArgsConstructor
public class Validator { public class Validator {
public static final int MAX_NAME_LENGTH = 16; public static final int MAX_NAME_LENGTH = 16;
public static final int MIN_NAME_LENGTH = 1;
public static final int MAX_DESCRIPTION_LENGTH = 256; public static final int MAX_DESCRIPTION_LENGTH = 256;
private final HuskHomes plugin; private final HuskHomes plugin;
public Validator(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/** /**
* Validate home and warp names. * Validate home and warp names.
* *
@@ -67,7 +65,8 @@ public class Validator {
// Check a home/warp name contains only valid characters // Check a home/warp name contains only valid characters
private boolean isValidNameCharacters(@NotNull String name) { 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") && !name.contains("\u0000")
&& !containsWhitespace(name) && !containsWhitespace(name)
&& !name.contains(Home.IDENTIFIER_DELIMITER); && !name.contains(Home.IDENTIFIER_DELIMITER);
@@ -75,13 +74,13 @@ public class Validator {
// Check a home/warp name is of a valid length // Check a home/warp name is of a valid length
private boolean isValidNameLength(@NotNull String name) { 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 // Check a home/warp description contains only valid characters
private boolean isValidDescriptionCharacters(@NotNull String description) { private boolean isValidDescriptionCharacters(@NotNull String description) {
return (description.matches(plugin.getSettings().getDescriptionRegex()) final Settings.GeneralSettings.DescriptionSettings config = plugin.getSettings().getGeneral().getDescriptions();
|| !plugin.getSettings().doRestrictDescriptions()) return (description.matches(config.getRegex()) || !config.isRestrict())
&& !description.contains("\u0000"); && !description.contains("\u0000");
} }
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teleporting you to where %1% last logged out…](#00fb9a)' teleporting_offline_player: '[Teleporting you to where %1% last logged out…](#00fb9a)'
teleporting_warmup_start: '[You will be teleported in](#00fb9a) [%1%](#00fb9a bold) [seconds, please stand still…](#00fb9a)' teleporting_warmup_start: '[You will be teleported in](#00fb9a) [%1%](#00fb9a bold) [seconds, please stand still…](#00fb9a)'
teleporting_cancelled_movement: '[Teleportation cancelled—you moved!](#ff7e5e)' teleporting_cancelled_movement: '[Teleportation cancelled—you moved!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Du wirst dorthin teleportiert, wo %1% sich zuletzt ausgeloggt hat…](#00fb9a)' teleporting_offline_player: '[Du wirst dorthin teleportiert, wo %1% sich zuletzt ausgeloggt hat…](#00fb9a)'
teleporting_warmup_start: '[Du wirst in](#00fb9a) [%1%](#00fb9a bold) [Sekunden teleportiert, bitte stillhalten…](#00fb9a)' teleporting_warmup_start: '[Du wirst in](#00fb9a) [%1%](#00fb9a bold) [Sekunden teleportiert, bitte stillhalten…](#00fb9a)'
teleporting_cancelled_movement: '[Teleportation abgebrochen—du hast dich bewegt!](#ff7e5e)' teleporting_cancelled_movement: '[Teleportation abgebrochen—du hast dich bewegt!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teleporting you to where %1% last logged out…](#00fb9a)' teleporting_offline_player: '[Teleporting you to where %1% last logged out…](#00fb9a)'
teleporting_warmup_start: '[You will be teleported in](#00fb9a) [%1%](#00fb9a bold) [seconds, please stand still…](#00fb9a)' teleporting_warmup_start: '[You will be teleported in](#00fb9a) [%1%](#00fb9a bold) [seconds, please stand still…](#00fb9a)'
teleporting_cancelled_movement: '[Teleportation cancelled—you moved!](#ff7e5e)' teleporting_cancelled_movement: '[Teleportation cancelled—you moved!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teletransportandote donde %1% se desconecto...](#00fb9a)' teleporting_offline_player: '[Teletransportandote donde %1% se desconecto...](#00fb9a)'
teleporting_warmup_start: '[Vas a ser teletransportado en... ](#00fb9a) [%1%](#00fb9a bold) [Segudos, por favor, quédese quieto…](#00fb9a)' teleporting_warmup_start: '[Vas a ser teletransportado en... ](#00fb9a) [%1%](#00fb9a bold) [Segudos, por favor, quédese quieto…](#00fb9a)'
teleporting_cancelled_movement: '[Teletransporte anulado: ¡te has movido!](#ff7e5e)' teleporting_cancelled_movement: '[Teletransporte anulado: ¡te has movido!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Téléportation en cours où %1% s''est déconnecté…](#00fb9a)' teleporting_offline_player: '[Téléportation en cours où %1% s''est déconnecté…](#00fb9a)'
teleporting_warmup_start: '[Vous allez être télépirté dans](#00fb9a) [%1%](#00fb9a bold) [secondes, ne bougez plus…](#00fb9a)' teleporting_warmup_start: '[Vous allez être télépirté dans](#00fb9a) [%1%](#00fb9a bold) [secondes, ne bougez plus…](#00fb9a)'
teleporting_cancelled_movement: '[Téléportation annulé — vous avez bougé !](#ff7e5e)' teleporting_cancelled_movement: '[Téléportation annulé — vous avez bougé !](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teletrasporto nel punto in cui %1% è uscito l''ultima volta…](#00fb9a)' teleporting_offline_player: '[Teletrasporto nel punto in cui %1% è uscito l''ultima volta…](#00fb9a)'
teleporting_warmup_start: '[Verrai teletrasportato tra](#00fb9a) [%1%](#00fb9a bold) [secondi, non muoverti…](#00fb9a)' teleporting_warmup_start: '[Verrai teletrasportato tra](#00fb9a) [%1%](#00fb9a bold) [secondi, non muoverti…](#00fb9a)'
teleporting_cancelled_movement: '[Teletrasporto cancellato, ti sei mosso!](#ff7e5e)' teleporting_cancelled_movement: '[Teletrasporto cancellato, ti sei mosso!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[%1% が最後にログアウトした座標にテレポートしています…](#00fb9a)' teleporting_offline_player: '[%1% が最後にログアウトした座標にテレポートしています…](#00fb9a)'
teleporting_warmup_start: '[%1%](#00fb9a bold) [秒後にテレポートされますので、その場でお待ち下さい…](#00fb9a)' teleporting_warmup_start: '[%1%](#00fb9a bold) [秒後にテレポートされますので、その場でお待ち下さい…](#00fb9a)'
teleporting_cancelled_movement: '[移動したため、テレポートがキャンセルされました!](#ff7e5e)' teleporting_cancelled_movement: '[移動したため、テレポートがキャンセルされました!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[%1%님의 마지막 장소로 이동 중입니다...](#00fb9a)' teleporting_offline_player: '[%1%님의 마지막 장소로 이동 중입니다...](#00fb9a)'
teleporting_warmup_start: '[%1%](#00fb9a bold) [초 뒤에 이동됩니다... 움직이지 말아주세요...](#00fb9a)' teleporting_warmup_start: '[%1%](#00fb9a bold) [초 뒤에 이동됩니다... 움직이지 말아주세요...](#00fb9a)'
teleporting_cancelled_movement: '[움직임으로 인해 이동이 취소되었습니다!](#ff7e5e)' teleporting_cancelled_movement: '[움직임으로 인해 이동이 취소되었습니다!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teleportowanie do miejsca, gdzie %1% ostatnio się wylogował(a)…](#00fb9a)' teleporting_offline_player: '[Teleportowanie do miejsca, gdzie %1% ostatnio się wylogował(a)…](#00fb9a)'
teleporting_warmup_start: '[Zostaniesz przeteleportowany(a) za](#00fb9a) [%1%](#00fb9a bold) [sekundy, proszę stań w miejscu…](#00fb9a)' teleporting_warmup_start: '[Zostaniesz przeteleportowany(a) za](#00fb9a) [%1%](#00fb9a bold) [sekundy, proszę stań w miejscu…](#00fb9a)'
teleporting_cancelled_movement: '[Teleportacja anulowana—ruszyłeś(ruszyłaś) się!](#ff7e5e)' teleporting_cancelled_movement: '[Teleportacja anulowana—ruszyłeś(ruszyłaś) się!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teleportando você para %1% onde fez o último logout…](#00fb9a)' teleporting_offline_player: '[Teleportando você para %1% onde fez o último logout…](#00fb9a)'
teleporting_warmup_start: '[Você será teleportado em](#00fb9a) [%1%](#00fb9a bold) [segundos, por favor, fique parado…](#00fb9a)' teleporting_warmup_start: '[Você será teleportado em](#00fb9a) [%1%](#00fb9a bold) [segundos, por favor, fique parado…](#00fb9a)'
teleporting_cancelled_movement: '[Teleporte cancelado — você se moveu!](#ff7e5e)' teleporting_cancelled_movement: '[Teleporte cancelado — você se moveu!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Телепортируем %1% на последнюю позицию…](#00fb9a)' teleporting_offline_player: '[Телепортируем %1% на последнюю позицию…](#00fb9a)'
teleporting_warmup_start: '[Вы будете телепортированы через](#00fb9a) [%1%](#00fb9a bold) [секунд, пожалуйста, не двигайтесь…](#00fb9a)' teleporting_warmup_start: '[Вы будете телепортированы через](#00fb9a) [%1%](#00fb9a bold) [секунд, пожалуйста, не двигайтесь…](#00fb9a)'
teleporting_cancelled_movement: '[Телепортация отменена—вы двинулись!](#ff7e5e)' teleporting_cancelled_movement: '[Телепортация отменена—вы двинулись!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Sizi en son %1% oturumunun kapatıldığı yere ışınlıyoruz…](#00fb9a)' teleporting_offline_player: '[Sizi en son %1% oturumunun kapatıldığı yere ışınlıyoruz…](#00fb9a)'
teleporting_warmup_start: '[%1%](#00fb9a bold) [saniye içinde ışınlanacaksınız, lütfen hareketsiz durun…](#00fb9a)' teleporting_warmup_start: '[%1%](#00fb9a bold) [saniye içinde ışınlanacaksınız, lütfen hareketsiz durun…](#00fb9a)'
teleporting_cancelled_movement: '[Işınlanma iptal edildi hareket ettiniz!](#ff7e5e)' teleporting_cancelled_movement: '[Işınlanma iptal edildi hareket ettiniz!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[Teleporting you to where %1% last logged out…](#00fb9a)' teleporting_offline_player: '[Teleporting you to where %1% last logged out…](#00fb9a)'
teleporting_warmup_start: '[You will be teleported in](#00fb9a) [%1%](#00fb9a bold) [seconds, please stand still…](#00fb9a)' teleporting_warmup_start: '[You will be teleported in](#00fb9a) [%1%](#00fb9a bold) [seconds, please stand still…](#00fb9a)'
teleporting_cancelled_movement: '[Teleportation cancelled—you moved!](#ff7e5e)' teleporting_cancelled_movement: '[Teleportation cancelled—you moved!](#ff7e5e)'
@@ -1,3 +1,4 @@
locales:
teleporting_offline_player: '[正在将你传送到 %1% 上次注销的位置…](#00fb9a)' teleporting_offline_player: '[正在将你传送到 %1% 上次注销的位置…](#00fb9a)'
teleporting_warmup_start: '[你将在](#00fb9a) [%1%](#00fb9a bold) [秒后被传送,请不要移动…](#00fb9a)' teleporting_warmup_start: '[你将在](#00fb9a) [%1%](#00fb9a bold) [秒后被传送,请不要移动…](#00fb9a)'
teleporting_cancelled_movement: '[传送取消: 你移动了!](#ff7e5e)' teleporting_cancelled_movement: '[传送取消: 你移动了!](#ff7e5e)'
+2 -1
View File
@@ -1,4 +1,5 @@
teleporting_offline_player: '[正在將您傳送到 %1% 上次登出的位置……](#00fb9a)' locales:
teleporting_offline_player: '[正在將您傳送到 %1% 上次登出的位置……](#00fb9a)'
teleporting_warmup_start: '[您將在](#00fb9a) [%1%](#00fb9a bold) [秒後被傳送…](#00fb9a)' teleporting_warmup_start: '[您將在](#00fb9a) [%1%](#00fb9a bold) [秒後被傳送…](#00fb9a)'
teleporting_cancelled_movement: '[傳送取消 — 您移動了!](#ff7e5e)' teleporting_cancelled_movement: '[傳送取消 — 您移動了!](#ff7e5e)'
teleporting_cancelled_damage: '[傳送取消 — 您受到了傷害!](#ff7e5e)' teleporting_cancelled_damage: '[傳送取消 — 您受到了傷害!](#ff7e5e)'
@@ -19,9 +19,8 @@
package net.william278.huskhomes.config; package net.william278.huskhomes.config;
import net.william278.annotaml.Annotaml; import de.exlll.configlib.YamlConfigurations;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -30,28 +29,28 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.MethodSource;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL; import java.net.URL;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
@DisplayName("Locales Tests") @DisplayName("Locales Tests")
public class LocalesTests { public class LocalesTests {
private static Locales englishLocales; private Locales englishLocales;
@BeforeEach @BeforeEach
@DisplayName("Test Loading English Locales") @DisplayName("Test Loading English Locales")
@Test @Test
public void testLoadEnglishLocales() { public void testLoadEnglishLocales() {
try (InputStream resource = LocalesTests.class.getClassLoader().getResourceAsStream("locales/en-gb.yml")) { try (InputStream locales = LocalesTests.class.getClassLoader().getResourceAsStream("locales/en-gb.yml")) {
Assertions.assertNotNull(resource, "en-gb.yml is missing from the locales folder"); assertNotNull(locales, "en-gb.yml is missing from the locales folder");
englishLocales = Annotaml.create(Locales.class, resource).get(); englishLocales = YamlConfigurations.read(locales, Locales.class);
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { } catch (Throwable e) {
throw new RuntimeException(e); fail("Failed to load en-gb.yml", e);
} }
} }
@@ -59,22 +58,19 @@ public class LocalesTests {
@DisplayName("Test All Locale Keys Present") @DisplayName("Test All Locale Keys Present")
@MethodSource("provideLocaleFiles") @MethodSource("provideLocaleFiles")
public void testAllLocaleKeysPresent(@NotNull File file, @SuppressWarnings("unused") @NotNull String keyName) { public void testAllLocaleKeysPresent(@NotNull File file, @SuppressWarnings("unused") @NotNull String keyName) {
try { final Set<String> fileKeys = YamlConfigurations.load(file.toPath(), Locales.class).getRawLocales().keySet();
final Set<String> fileKeys = Annotaml.create(file, Locales.class).get().rawLocales.keySet(); englishLocales.getRawLocales().keySet().forEach(key -> assertTrue(
englishLocales.rawLocales.keySet() fileKeys.contains(key), "Locale key " + key + " is missing from " + file.getName()
.forEach(key -> Assertions.assertTrue(fileKeys.contains(key), ));
"Locale key " + key + " is missing from " + file.getName()));
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
} }
@NotNull
private static Stream<Arguments> provideLocaleFiles() { private static Stream<Arguments> provideLocaleFiles() {
URL url = LocalesTests.class.getClassLoader().getResource("locales"); final URL url = LocalesTests.class.getClassLoader().getResource("locales");
Assertions.assertNotNull(url, "locales folder is missing"); assertNotNull(url, "locales folder is missing");
return Stream.of(Objects.requireNonNull(new File(url.getPath())
.listFiles(file -> file.getName().endsWith("yml") && !file.getName().equals("en-gb.yml"))))
.map(file -> Arguments.of(file, file.getName().replace(".yml", "")));
}
return Stream.of(Objects.requireNonNull(new File(url.getPath()).listFiles(
file -> file.getName().endsWith("yml") && !file.getName().equals("en-gb.yml")
))).map(file -> Arguments.of(file, file.getName().replace(".yml", "")));
}
} }
+99 -70
View File
@@ -19,38 +19,41 @@ This page contains the configuration structure for HuskHomes.
# ┣╸ Information: https://william278.net/project/huskhomes/ # ┣╸ Information: https://william278.net/project/huskhomes/
# ┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/ # ┣╸ Config Help: https://william278.net/docs/huskhomes/config-files/
# ┗╸ Documentation: https://william278.net/docs/huskhomes/ # ┗╸ Documentation: https://william278.net/docs/huskhomes/
# Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations # Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations
language: en-gb language: en-gb
# Whether to automatically check for plugin updates on startup # Whether to automatically check for plugin updates on startup
check_for_updates: true check_for_updates: true
# Database settings
database: database:
# Type of database to use (SQLITE, H2, MYSQL or MARIADB) # Type of database to use (SQLITE, H2, MYSQL, or MARIADB)
type: SQLITE type: SQLITE
mysql: # Specify credentials here if you are using MYSQL or MARIADB
credentials: credentials:
# Specify credentials here if you are using MYSQL or MARIADB as your database type
host: localhost host: localhost
port: 3306 port: 3306
database: HuskHomes database: huskhomes
username: root username: root
password: pa55w0rd password: pa55w0rd
parameters: ?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8 parameters: ?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8
connection_pool: # MYSQL / MARIADB database Hikari connection pool properties
# MYSQL / MARIADB database Hikari connection pool properties. Don't modify this unless you know what you're doing! # Don't modify this unless you know what you're doing!
pool_options:
size: 12 size: 12
idle: 12 idle: 12
lifetime: 1800000 lifetime: 1800000
keepalive: 30000 keep_alive: 30000
timeout: 20000 timeout: 20000
# Names of tables to use on your database. Don't modify this unless you know what you're doing! # Names of tables to use on your database. Don't modify this unless you know what you're doing!
table_names: table_names:
home_data: huskhomes_homes PLAYER_DATA: huskhomes_users
player_cooldowns_data: huskhomes_user_cooldowns PLAYER_COOLDOWNS_DATA: huskhomes_user_cooldowns
player_data: huskhomes_users POSITION_DATA: huskhomes_position_data
position_data: huskhomes_position_data SAVED_POSITION_DATA: huskhomes_saved_positions
saved_position_data: huskhomes_saved_positions HOME_DATA: huskhomes_homes
teleport_data: huskhomes_teleports WARP_DATA: huskhomes_warps
warp_data: huskhomes_warps TELEPORT_DATA: huskhomes_teleports
# General settings
general: general:
# The maximum homes a user can create. Override with the huskhomes.max_homes.<number> permission. # The maximum homes a user can create. Override with the huskhomes.max_homes.<number> permission.
max_homes: 10 max_homes: 10
@@ -60,8 +63,6 @@ general:
stack_permission_limits: false stack_permission_limits: false
# Whether users require a permission (huskhomes.command.warp.<warp_name>) to use warps # Whether users require a permission (huskhomes.command.warp.<warp_name>) to use warps
permission_restrict_warps: false permission_restrict_warps: false
# Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite.
overwrite_existing_homes_warps: true
# How long a player has to stand still and not take damage for when teleporting (in seconds) # How long a player has to stand still and not take damage for when teleporting (in seconds)
teleport_warmup_time: 5 teleport_warmup_time: 5
# Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE) # Where the teleport warmup timer should display (CHAT, ACTION_BAR, TITLE, SUBTITLE or NONE)
@@ -70,87 +71,113 @@ general:
teleport_request_expiry_time: 60 teleport_request_expiry_time: 60
# Whether /tpahere should use the location of the sender when sent. Docs: https://william278.net/docs/huskhomes/strict-tpahere/ # Whether /tpahere should use the location of the sender when sent. Docs: https://william278.net/docs/huskhomes/strict-tpahere/
strict_tpa_here_requests: true strict_tpa_here_requests: true
# Whether home or warp names should be case insensitive (i.e. allow /home HomeOne and /home homeone)
case_insensitive_names: false
# 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 你好).
restrict_names: true
# Regex which home and warp names must match. Names have a max length of 16 characters
name_regex: '[a-zA-Z0-9-_]*'
# Whether home/warp descriptions should be restricted. Set this to true to restrict UTF-8 usage.
restrict_descriptions: false
# Regex which home and warp descriptions must match. A hard max length of 256 characters is enforced
description_regex: '\A\p{ASCII}*\z'
# Whether /back should work to teleport the user to where they died
back_command_return_by_death: true
# Whether /back should work with other plugins that use the PlayerTeleportEvent (can cause conflicts)
back_command_save_teleport_event: false
# Whether the user should back to spawn when they die (ensure that cross_server.enabled and cross_server.global_respawning are enabled)
always_respawn_at_spawn: true
# How many items should be displayed per-page in chat menu lists # How many items should be displayed per-page in chat menu lists
list_items_per_page: 12 list_items_per_page: 12
# Whether teleportation should be carried out asynchronously (ensuring chunks load before teleporting)
asynchronous_teleports: true
# Whether to play sound effects
play_sound_effects: true
# Which sound effects to play for various actions
sound_effects:
teleport_request_received: entity.experience_orb.pickup
teleportation_cancelled: entity.item.break
teleportation_complete: entity.enderman.teleport
teleportation_warmup: block.note_block.banjo
# Whether to provide modern, rich TAB suggestions for commands (if available) # Whether to provide modern, rich TAB suggestions for commands (if available)
brigadier_tab_completion: true brigadier_tab_completion: true
# Whether the user should always be put back at the /spawn point when they die (ignores beds/respawn anchors)
always_respawn_at_spawn: false
# Whether teleportation should be carried out async (ensuring chunks load before teleporting)
teleport_async: true
# Settings for home and warp names
names:
# Whether running /sethome <name> or /setwarp <name> when one already exists should overwrite.
overwrite_existing: true
# Whether home or warp names should be case insensitive (i.e. allow /home HomeOne & /home homeone)
case_insensitive: false
# 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 你好).
restrict: true
# Regex which home and warp names must match. Names have a max length of 16 characters
regex: '[a-zA-Z0-9-_]*'
# Settings for home and warp descriptions
descriptions:
# Whether home/warp descriptions should be restricted to a regex filter. Set this to true to restrict UTF-8 usage.
restrict: false
# Regex which home and warp descriptions must match. A hard max length of 256 characters is enforced
regex: \A\p{ASCII}*\z
# Settings for the /back command
back_command:
# Whether /back should work to teleport the user to where they died
return_by_death: true
# Whether /back should work with other plugins that use the PlayerTeleportEvent (can conflict)
save_on_teleport_event: false
# Settings for sound effects
sound_effects:
# Whether to play sound effects
enabled: true
# Map of sound effect actions to types
types:
TELEPORTATION_COMPLETE: entity.enderman.teleport
TELEPORTATION_WARMUP: block.note_block.banjo
TELEPORTATION_CANCELLED: entity.item.break
TELEPORT_REQUEST_RECEIVED: entity.experience_orb.pickup
# Cross-server settings
cross_server: cross_server:
# Enable teleporting across your proxy network. Requires database type to be MYSQL # Whether to enable cross-server mode for teleporting across your proxy network.
enabled: false enabled: false
# The type of message broker to use for cross-server communication. Options: PLUGIN_MESSAGE, REDIS # The cluster ID, for if you're networking multiple separate groups of HuskHomes-enabled servers.
messenger_type: PLUGIN_MESSAGE # Do not change unless you know what you're doing
# Specify a common ID for grouping servers running HuskHomes on your proxy. Don't modify this unless you know what you're doing! cluster_id: main
cluster_id: '' # Type of network message broker to ues for data synchronization (PLUGIN_MESSAGE or REDIS)
global_spawn: broker_type: PLUGIN_MESSAGE
# Settings for if you're using REDIS as your message broker
redis:
host: localhost
port: 6379
# Password for your Redis server. Leave blank if you're not using a password.
password: ''
use_ssl: false
# Settings for if you're using Redis Sentinels.
# If you're not sure what this is, please ignore this section.
sentinel:
master_name: ''
# List of host:port pairs
nodes: []
password: ''
# Define a single global /spawn for your network via a warp. Docs: https://william278.net/docs/huskhomes/global-spawn/ # Define a single global /spawn for your network via a warp. Docs: https://william278.net/docs/huskhomes/global-spawn/
global_spawn:
# Whether to define a single global /spawn for your network via a warp.
enabled: false enabled: false
# The name of the warp to use as the global spawn. # The name of the warp to use as the global spawn.
warp_name: Spawn warp_name: Spawn
# Whether player respawn positions should work cross-server. Docs: https://william278.net/docs/huskhomes/global-respawning/ # Whether player respawn positions should work cross-server. Docs: https://william278.net/docs/huskhomes/global-respawning/
global_respawning: false global_respawning: false
redis_credentials: # Random teleport (/rtp) settings.
# Specify credentials here if you are using REDIS as your messenger_type. Docs: https://william278.net/docs/huskhomes/redis-support/
host: localhost
port: 6379
password: ''
use_ssl: false
rtp: rtp:
# Radius around the spawn point in which players cannot be random teleported to # Radial region around the /spawn position where players CAN be randomly teleported.
radius: 5000 # If no /spawn has been set, (0, 0) will be used instead.
# Radius of the spawn area in which players cannot be random teleported to region:
spawn_radius: 500 min: 500
max: 5000
# Mean of the normal distribution used to calculate the distance from the center of the world # Mean of the normal distribution used to calculate the distance from the center of the world
distribution_mean: 0.75 distribution_mean: 0.75
# Standard deviation of the normal distribution for distributing players randomly # Standard deviation of the normal distribution for distributing players randomly
distribution_deviation: 2.0 distribution_standard_deviation: 2.0
# List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether. # List of worlds in which /rtp is disabled. Please note that /rtp does not work well in the nether.
restricted_worlds: restricted_worlds:
- world_nether - world_nether
- world_the_end - world_the_end
# Action cooldown settings. Docs: https://william278.net/docs/huskhomes/cooldowns
cooldowns: cooldowns:
# Whether to apply a cooldown between performing certain actions # Whether to apply a cooldown between performing certain actions
enabled: true enabled: true
# Set a cooldown between performing actions (in seconds). Docs: https://william278.net/docs/huskhomes/cooldowns/ # Map of cooldown times to actions
cooldown_times: cooldown_times:
random_teleport: 600 RANDOM_TELEPORT: 600
# Economy settings. Docs: https://william278.net/docs/huskhomes/economy-hook
economy: economy:
# Enable economy plugin integration (requires Vault) # Enable economy plugin integration (requires Vault and a compatible Economy plugin)
enabled: false enabled: true
# Map of economy actions to costs.
economy_costs:
ADDITIONAL_HOME_SLOT: 100.0
MAKE_HOME_PUBLIC: 50.0
RANDOM_TELEPORT: 25.0
# Specify how many homes players can set for free, before they need to pay for more slots # Specify how many homes players can set for free, before they need to pay for more slots
free_home_slots: 5 free_home_slots: 5
# Charge money for perform certain actions. Docs: https://william278.net/docs/huskhomes/economy-hook/ # Web map hook settings. Docs: https://william278.net/docs/huskhomes/map-hooks
costs:
additional_home_slot: 100.0
make_home_public: 50.0
random_teleport: 25.0
map_hook: map_hook:
# Display public homes/warps on your Dynmap, BlueMap or Pl3xMap. Docs: https://william278.net/docs/huskhomes/map-hooks # Display public homes/warps on your Dynmap, BlueMap or Pl3xMap
enabled: true enabled: true
# Show public homes on the web map # Show public homes on the web map
show_public_homes: true show_public_homes: true
@@ -170,6 +197,7 @@ You should generate this file in-game with the `/setspawn` command.
# ┃ Server /spawn location cache ┃ # ┃ Server /spawn location cache ┃
# ┃ Edit in-game using /setspawn ┃ # ┃ Edit in-game using /setspawn ┃
# ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
x: 0.0 x: 0.0
y: 64.0 y: 64.0
z: 0.0 z: 0.0
@@ -186,12 +214,13 @@ world_uuid: 00000000-0000-0000-0000-000000000000
This file is only present if your server uses cross-server mode to run HuskHomes on a proxy network. This file is only present if your server uses cross-server mode to run HuskHomes on a proxy network.
```yaml ```yaml
# ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
# ┃ HuskHomes Server ID config ┃ # ┃ HuskHomes - Server ID ┃
# ┃ Developed by William278 ┃ # ┃ Developed by William278 ┃
# ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
# ┣╸ This file should contain the ID of this server as defined in your proxy config. # ┣╸ 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) # ┣╸ 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. # ┗╸ You only need to touch this if you're using cross-server mode.
name: beta name: beta
``` ```
+4 -2
View File
@@ -33,6 +33,9 @@ dependencies {
implementation include("com.h2database:h2:$h2_driver_version") implementation include("com.h2database:h2:$h2_driver_version")
compileOnly 'org.jetbrains:annotations:24.1.0' compileOnly 'org.jetbrains:annotations:24.1.0'
compileOnly 'org.projectlombok:lombok:1.18.30'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
shadow project(path: ":common") shadow project(path: ":common")
} }
@@ -52,10 +55,9 @@ shadowJar {
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown'
relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell'
relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml' relocate 'de.exlll', 'net.william278.huskhomes.libraries'
relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
} }
@@ -19,7 +19,12 @@
package net.william278.huskhomes; package net.william278.huskhomes;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.netty.buffer.ByteBufUtil; import io.netty.buffer.ByteBufUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.fabricmc.api.DedicatedServerModInitializer; import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
@@ -34,8 +39,6 @@ import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayNetworkHandler; import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.Version; import net.william278.desertwell.util.Version;
import net.william278.huskhomes.command.Command; import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.FabricCommand; import net.william278.huskhomes.command.FabricCommand;
@@ -55,7 +58,6 @@ import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.PluginMessageBroker; import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker; import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RandomTeleportEngine; import net.william278.huskhomes.random.RandomTeleportEngine;
@@ -73,26 +75,31 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.slf4j.spi.LoggingEventBuilder; import org.slf4j.spi.LoggingEventBuilder;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Getter
@Setter
@NoArgsConstructor
public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier, public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier,
FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler { FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler {
public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes"); public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes");
private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes") private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes")
.orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); .orElseThrow(() -> new RuntimeException("Failed to get Mod Container"));
private final Map<String, Boolean> permissions = Maps.newHashMap();
private final Set<SavedUser> savedUsers = Sets.newHashSet();
private final ConcurrentMap<String, List<String>> globalPlayerList = Maps.newConcurrentMap();
private final Set<UUID> currentlyOnWarmup = Sets.newHashSet();
private MinecraftServer minecraftServer; private MinecraftServer minecraftServer;
private Map<String, Boolean> permissions;
private Set<SavedUser> savedUsers;
private Settings settings; private Settings settings;
private Locales locales; private Locales locales;
private Database database; private Database database;
@@ -104,8 +111,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
private UnsafeBlocks unsafeBlocks; private UnsafeBlocks unsafeBlocks;
private List<Hook> hooks; private List<Hook> hooks;
private List<Command> commands; private List<Command> commands;
private ConcurrentHashMap<String, List<String>> globalPlayerList;
private Set<UUID> currentlyOnWarmup;
private Server server; private Server server;
@Nullable @Nullable
private Broker broker; private Broker broker;
@@ -114,18 +119,10 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
@Override @Override
public void onInitializeServer() { public void onInitializeServer() {
// Get plugin version from mod container // Get plugin version from mod container
this.permissions = new HashMap<>();
this.savedUsers = new HashSet<>();
this.globalPlayerList = new ConcurrentHashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.validator = new Validator(this); this.validator = new Validator(this);
// Load settings and locales // Load settings and locales
initialize("plugin config & locale files", (plugin) -> { initialize("plugin config & locale files", (plugin) -> loadConfigs());
if (!loadConfigs()) {
throw new IllegalStateException("Failed to load config files. Please check the console for errors");
}
});
// Pre-register commands // Pre-register commands
initialize("commands", (plugin) -> this.commands = registerCommands()); initialize("commands", (plugin) -> this.commands = registerCommands());
@@ -142,8 +139,9 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
this.audiences = FabricServerAudiences.of(minecraftServer); this.audiences = FabricServerAudiences.of(minecraftServer);
// Initialize the database // Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { final Database.Type type = getSettings().getDatabase().getType();
this.database = switch (getSettings().getDatabaseType()) { initialize(type.getDisplayName() + " database connection", (plugin) -> {
this.database = switch (type) {
case MYSQL, MARIADB -> new MySqlDatabase(this); case MYSQL, MARIADB -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this); case SQLITE -> new SqLiteDatabase(this);
case H2 -> new H2Database(this); case H2 -> new H2Database(this);
@@ -156,9 +154,10 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
this.manager = new Manager(this); this.manager = new Manager(this);
// Initialize the network messenger if proxy mode is enabled // Initialize the network messenger if proxy mode is enabled
if (getSettings().doCrossServer()) { final Settings.CrossServerSettings crossServer = getSettings().getCrossServer();
initialize(settings.getBrokerType().getDisplayName() + " message broker", (plugin) -> { if (crossServer.isEnabled()) {
broker = switch (settings.getBrokerType()) { initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> {
broker = switch (crossServer.getBrokerType()) {
case PLUGIN_MESSAGE -> new PluginMessageBroker(this); case PLUGIN_MESSAGE -> new PluginMessageBroker(this);
case REDIS -> new RedisBroker(this); case REDIS -> new RedisBroker(this);
}; };
@@ -229,105 +228,22 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return audiences.player(user); return audiences.player(user);
} }
@Override
@NotNull
public Set<SavedUser> getSavedUsers() {
return savedUsers;
}
@Override
@NotNull
public Settings getSettings() {
return settings;
}
@Override
public void setSettings(@NotNull Settings settings) {
this.settings = settings;
}
@Override
@NotNull
public Locales getLocales() {
return locales;
}
@Override
public void setLocales(@NotNull Locales locales) {
this.locales = locales;
}
@Override @Override
public Optional<Spawn> getServerSpawn() { public Optional<Spawn> getServerSpawn() {
return Optional.ofNullable(serverSpawn); return Optional.ofNullable(serverSpawn);
} }
@Override
public void setServerSpawn(@NotNull Spawn spawn) {
this.serverSpawn = spawn;
}
@Override
public void setServerSpawn(@NotNull Location location) {
try {
// Create or update the spawn.yml file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists() && !spawnFile.delete()) {
log(Level.WARNING, "Failed to delete the existing spawn.yml file");
}
this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get();
// Update the world spawn location, too
minecraftServer.getWorlds().forEach(world -> {
if (world.getRegistryKey().getValue().asString().equals(location.getWorld().getName())) {
world.setSpawnPos(BlockPos.ofFloored(location.getX(), location.getY(), location.getZ()), 0);
}
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.WARNING, "Failed to save the server spawn.yml file", e);
}
}
@Override @Override
@NotNull @NotNull
public String getServerName() { public String getServerName() {
return server.getName(); return server == null ? "server" : server.getName();
} }
@Override @Override
public void setServer(@NotNull Server server) { public void setServerName(@NotNull Server server) {
this.server = server; this.server = server;
} }
@Override
public void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks) {
this.unsafeBlocks = unsafeBlocks;
}
@NotNull
@Override
public UnsafeBlocks getUnsafeBlocks() {
return unsafeBlocks;
}
@Override
@NotNull
public Database getDatabase() {
return database;
}
@Override
@NotNull
public Validator getValidator() {
return validator;
}
@Override
@NotNull
public Manager getManager() {
return manager;
}
@Override @Override
@NotNull @NotNull
public Broker getMessenger() { public Broker getMessenger() {
@@ -337,28 +253,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return broker; return broker;
} }
@Override
@NotNull
public RandomTeleportEngine getRandomTeleportEngine() {
return randomTeleportEngine;
}
@Override
public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) {
this.randomTeleportEngine = randomTeleportEngine;
}
@Override
@NotNull
public List<Hook> getHooks() {
return hooks;
}
@Override
public void setHooks(@NotNull List<Hook> hooks) {
this.hooks = hooks;
}
@Override @Override
@Nullable @Nullable
public InputStream getResource(@NotNull String name) { public InputStream getResource(@NotNull String name) {
@@ -376,8 +270,8 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
@Override @Override
@NotNull @NotNull
public File getDataFolder() { public Path getConfigDirectory() {
return FabricLoader.getInstance().getConfigDir().resolve("huskhomes").toFile(); return FabricLoader.getInstance().getConfigDir().resolve("huskhomes");
} }
@Override @Override
@@ -397,12 +291,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-"); return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-");
} }
@Override
@NotNull
public List<Command> getCommands() {
return commands;
}
@NotNull @NotNull
public List<Command> registerCommands() { public List<Command> registerCommands() {
final List<Command> commands = FabricCommand.Type.getCommands(getPlugin()); final List<Command> commands = FabricCommand.Type.getCommands(getPlugin());
@@ -417,18 +305,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
|| FabricLoader.getInstance().isModLoaded(name.toLowerCase(Locale.ENGLISH)); || FabricLoader.getInstance().isModLoaded(name.toLowerCase(Locale.ENGLISH));
} }
@Override
@NotNull
public Map<String, List<String>> getGlobalPlayerList() {
return globalPlayerList;
}
@Override
@NotNull
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
@Override @Override
public void registerMetrics(int metricsId) { public void registerMetrics(int metricsId) {
// No metrics for Fabric // No metrics for Fabric
@@ -445,7 +321,7 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
@NotNull ServerPlayNetworkHandler handler, @NotNull PacketByteBuf buf, @NotNull ServerPlayNetworkHandler handler, @NotNull PacketByteBuf buf,
@NotNull PacketSender responseSender) { @NotNull PacketSender responseSender) {
if (broker instanceof PluginMessageBroker messenger if (broker instanceof PluginMessageBroker messenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
messenger.onReceive( messenger.onReceive(
PluginMessageBroker.BUNGEE_CHANNEL_ID, PluginMessageBroker.BUNGEE_CHANNEL_ID,
FabricUser.adapt(player, this), FabricUser.adapt(player, this),
+4 -4
View File
@@ -7,15 +7,16 @@ dependencies {
compileOnly project(':common') compileOnly project(':common')
compileOnly 'io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT' compileOnly 'io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT'
compileOnly 'org.bstats:bstats-bukkit:3.0.2' compileOnly 'org.bstats:bstats-bukkit:3.0.2'
compileOnly 'org.jetbrains:annotations:24.1.0' compileOnly 'org.jetbrains:annotations:24.1.0'
compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
compileOnly 'net.william278:annotaml:2.0.5'
compileOnly 'net.william278:DesertWell:2.0.4' compileOnly 'net.william278:DesertWell:2.0.4'
compileOnly 'me.lucko:commodore:2.2' compileOnly 'me.lucko:commodore:2.2'
compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1' compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1'
compileOnly 'me.clip:placeholderapi:2.11.5' compileOnly 'me.clip:placeholderapi:2.11.5'
compileOnly 'org.projectlombok:lombok:1.18.30'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
} }
shadowJar { shadowJar {
@@ -30,11 +31,10 @@ shadowJar {
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown'
relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell'
relocate 'de.exlll', 'net.william278.huskhomes.libraries'
relocate 'org.json', 'net.william278.huskhomes.libraries.json' relocate 'org.json', 'net.william278.huskhomes.libraries.json'
relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml'
relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats' relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats'
@@ -19,12 +19,12 @@
package net.william278.huskhomes; package net.william278.huskhomes;
import de.exlll.configlib.Configuration;
import de.exlll.configlib.YamlConfigurations;
import io.papermc.paper.plugin.loader.PluginClasspathBuilder; import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
import io.papermc.paper.plugin.loader.PluginLoader; import io.papermc.paper.plugin.loader.PluginLoader;
import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver; import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver;
import net.william278.annotaml.Annotaml; import lombok.NoArgsConstructor;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.RemoteRepository;
@@ -35,12 +35,13 @@ import java.io.InputStream;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@SuppressWarnings({"UnstableApiUsage", "unused"}) @NoArgsConstructor
@SuppressWarnings("UnstableApiUsage")
public class PaperHuskHomesLoader implements PluginLoader { public class PaperHuskHomesLoader implements PluginLoader {
@Override @Override
public void classloader(@NotNull PluginClasspathBuilder classpathBuilder) { public void classloader(@NotNull PluginClasspathBuilder classpathBuilder) {
MavenLibraryResolver resolver = new MavenLibraryResolver(); final MavenLibraryResolver resolver = new MavenLibraryResolver();
resolveLibraries(classpathBuilder).stream() resolveLibraries(classpathBuilder).stream()
.map(DefaultArtifact::new) .map(DefaultArtifact::new)
@@ -55,8 +56,11 @@ public class PaperHuskHomesLoader implements PluginLoader {
@NotNull @NotNull
private static List<String> resolveLibraries(@NotNull PluginClasspathBuilder classpathBuilder) { private static List<String> resolveLibraries(@NotNull PluginClasspathBuilder classpathBuilder) {
try (InputStream input = getLibraryListFile()) { try (InputStream input = getLibraryListFile()) {
return Annotaml.create(PaperLibraries.class, Objects.requireNonNull(input)).get().libraries; return YamlConfigurations.read(
} catch (Exception e) { Objects.requireNonNull(input, "Failed to read libraries file"),
PaperLibraries.class
).libraries;
} catch (Throwable e) {
classpathBuilder.getContext().getLogger().error("Failed to resolve libraries", e); classpathBuilder.getContext().getLogger().error("Failed to resolve libraries", e);
} }
return List.of(); return List.of();
@@ -67,16 +71,12 @@ public class PaperHuskHomesLoader implements PluginLoader {
return PaperHuskHomesLoader.class.getClassLoader().getResourceAsStream("paper-libraries.yml"); return PaperHuskHomesLoader.class.getClassLoader().getResourceAsStream("paper-libraries.yml");
} }
@YamlFile(header = "Dependencies for HuskHomes on Paper") @Configuration
@NoArgsConstructor
public static class PaperLibraries { public static class PaperLibraries {
@YamlKey("libraries")
private List<String> libraries; private List<String> libraries;
@SuppressWarnings("unused")
private PaperLibraries() {
}
} }
} }
@@ -22,6 +22,7 @@ package net.william278.huskhomes.listener;
import com.destroystokyo.paper.event.player.PlayerSetSpawnEvent; import com.destroystokyo.paper.event.player.PlayerSetSpawnEvent;
import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.PaperHuskHomes; import net.william278.huskhomes.PaperHuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.util.BukkitAdapter; import net.william278.huskhomes.util.BukkitAdapter;
@@ -48,7 +49,8 @@ public class PaperEventListener extends BukkitEventListener implements Listener
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerUpdateRespawnLocation(PlayerSetSpawnEvent event) { public void onPlayerUpdateRespawnLocation(PlayerSetSpawnEvent event) {
if (!(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) { final Settings.CrossServerSettings crossServer = plugin.getSettings().getCrossServer();
if (!(crossServer.isEnabled() && crossServer.isGlobalRespawning())) {
return; return;
} }
+10 -7
View File
@@ -9,11 +9,15 @@ dependencies {
implementation project(path: ':common') implementation project(path: ':common')
implementation 'org.bstats:bstats-sponge:3.0.2' implementation 'org.bstats:bstats-sponge:3.0.2'
implementation "redis.clients:jedis:$jedis_version" implementation "redis.clients:jedis:${jedis_version}"
implementation "com.mysql:mysql-connector-j:$mysql_driver_version" implementation "com.mysql:mysql-connector-j:${mysql_driver_version}"
implementation "org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version" implementation "org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}"
implementation "org.xerial:sqlite-jdbc:$sqlite_driver_version" implementation "org.xerial:sqlite-jdbc:${sqlite_driver_version}"
implementation "com.h2database:h2:$h2_driver_version" implementation "com.h2database:h2:${h2_driver_version}"
compileOnly 'org.projectlombok:lombok:1.18.30'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
} }
sponge { sponge {
@@ -67,11 +71,10 @@ shadowJar {
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown'
relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell'
relocate 'de.exlll', 'net.william278.huskhomes.libraries'
relocate 'org.json', 'net.william278.huskhomes.libraries.json' relocate 'org.json', 'net.william278.huskhomes.libraries.json'
relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml'
relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats' relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats'
@@ -19,9 +19,13 @@
package net.william278.huskhomes; package net.william278.huskhomes;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Inject; import com.google.inject.Inject;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.Version; import net.william278.desertwell.util.Version;
import net.william278.huskhomes.command.Command; import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.SpongeCommand; import net.william278.huskhomes.command.SpongeCommand;
@@ -41,7 +45,6 @@ import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.PluginMessageBroker; import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker; import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RandomTeleportEngine; import net.william278.huskhomes.random.RandomTeleportEngine;
@@ -71,20 +74,19 @@ import org.spongepowered.api.network.channel.ChannelBuf;
import org.spongepowered.api.network.channel.raw.RawDataChannel; import org.spongepowered.api.network.channel.raw.RawDataChannel;
import org.spongepowered.api.network.channel.raw.play.RawPlayDataChannel; import org.spongepowered.api.network.channel.raw.play.RawPlayDataChannel;
import org.spongepowered.api.network.channel.raw.play.RawPlayDataHandler; import org.spongepowered.api.network.channel.raw.play.RawPlayDataHandler;
import org.spongepowered.math.vector.Vector3i;
import org.spongepowered.plugin.PluginContainer; import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.builtin.jvm.Plugin; import org.spongepowered.plugin.builtin.jvm.Plugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI; import java.net.URI;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Getter
@Setter
@NoArgsConstructor
@Plugin("huskhomes") @Plugin("huskhomes")
public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSafetyResolver, SpongeEventDispatcher, public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSafetyResolver, SpongeEventDispatcher,
RawPlayDataHandler<EngineConnection> { RawPlayDataHandler<EngineConnection> {
@@ -95,17 +97,21 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
private static final int METRICS_ID = 18423; private static final int METRICS_ID = 18423;
private static final ResourceKey PLUGIN_MESSAGE_CHANNEL_KEY = ResourceKey.of("bungeecord", "main"); private static final ResourceKey PLUGIN_MESSAGE_CHANNEL_KEY = ResourceKey.of("bungeecord", "main");
private final Set<SavedUser> savedUsers = Sets.newHashSet();
private final Map<String, List<String>> globalPlayerList = Maps.newConcurrentMap();
private final Set<UUID> currentlyOnWarmup = Sets.newHashSet();
@Inject @Inject
@ConfigDir(sharedRoot = false) @ConfigDir(sharedRoot = false)
private Path pluginDirectory; private Path configDirectory;
@Inject @Inject
private PluginContainer pluginContainer; private PluginContainer pluginContainer;
@Inject @Inject
private Game game; private Game game;
@Inject @Inject
private Metrics.Factory metricsFactory; private Metrics.Factory metricsFactory;
private RawPlayDataChannel pluginMessageChannel;
private Set<SavedUser> savedUsers;
private Settings settings; private Settings settings;
private Locales locales; private Locales locales;
private Database database; private Database database;
@@ -116,31 +122,22 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
private UnsafeBlocks unsafeBlocks; private UnsafeBlocks unsafeBlocks;
private List<Hook> hooks; private List<Hook> hooks;
private List<SpongeCommand> commands; private List<SpongeCommand> commands;
private Map<String, List<String>> globalPlayerList;
private Set<UUID> currentlyOnWarmup;
private Server server; private Server server;
@Nullable @Nullable
private Broker broker; private Broker broker;
private RawPlayDataChannel channel;
@Listener @Listener
public void onConstructPlugin(final ConstructPluginEvent event) { public void onConstructPlugin(final ConstructPluginEvent event) {
// Get plugin version from mod container // Get plugin version from mod container
this.savedUsers = new HashSet<>();
this.globalPlayerList = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.validator = new Validator(this); this.validator = new Validator(this);
// Load settings and locales // Load settings and locales
initialize("plugin config & locale files", (plugin) -> { initialize("plugin config & locale files", (plugin) -> loadConfigs());
if (!loadConfigs()) {
throw new IllegalStateException("Failed to load config files. Please check the console for errors");
}
});
// Initialize the database // Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { final Database.Type type = getSettings().getDatabase().getType();
this.database = switch (getSettings().getDatabaseType()) { initialize(type.getDisplayName() + " database connection", (plugin) -> {
this.database = switch (type) {
case MYSQL, MARIADB -> new MySqlDatabase(this); case MYSQL, MARIADB -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this); case SQLITE -> new SqLiteDatabase(this);
case H2 -> new H2Database(this); case H2 -> new H2Database(this);
@@ -150,9 +147,10 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
}); });
// Initialize the network messenger if proxy mode is enabled // Initialize the network messenger if proxy mode is enabled
if (getSettings().doCrossServer()) { final Settings.CrossServerSettings crossServer = getSettings().getCrossServer();
initialize(settings.getBrokerType().getDisplayName() + " message broker", (plugin) -> { if (crossServer.isEnabled()) {
broker = switch (settings.getBrokerType()) { initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> {
broker = switch (crossServer.getBrokerType()) {
case PLUGIN_MESSAGE -> new PluginMessageBroker(this); case PLUGIN_MESSAGE -> new PluginMessageBroker(this);
case REDIS -> new RedisBroker(this); case REDIS -> new RedisBroker(this);
}; };
@@ -236,107 +234,22 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
return game.server().player(user).map(player -> (Audience) player).orElse(Audience.empty()); return game.server().player(user).map(player -> (Audience) player).orElse(Audience.empty());
} }
@NotNull
@Override
public Set<SavedUser> getSavedUsers() {
return savedUsers;
}
@NotNull
@Override
public Settings getSettings() {
return settings;
}
@Override
public void setSettings(@NotNull Settings settings) {
this.settings = settings;
}
@NotNull
@Override
public Locales getLocales() {
return locales;
}
@Override
public void setLocales(@NotNull Locales locales) {
this.locales = locales;
}
@Override @Override
public Optional<Spawn> getServerSpawn() { public Optional<Spawn> getServerSpawn() {
return Optional.ofNullable(serverSpawn); return Optional.ofNullable(serverSpawn);
} }
@Override
public void setServerSpawn(@NotNull Spawn spawn) {
this.serverSpawn = spawn;
}
@Override
public void setServerSpawn(@NotNull Location location) {
try {
// Create or update the spawn.yml file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists() && !spawnFile.delete()) {
log(Level.WARNING, "Failed to delete the existing spawn.yml file");
}
this.serverSpawn = Annotaml.create(spawnFile, new Spawn(location)).get();
// Update the world spawn location, too
game.server().worldManager().worlds().forEach(world -> {
if (world.properties().key().asString().equals(location.getWorld().getName())) {
world.properties().setSpawnPosition(Vector3i.from(
(int) location.getX(), (int) location.getY(), (int) location.getZ())
);
}
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.WARNING, "Failed to save the server spawn.yml file", e);
}
}
@NotNull @NotNull
@Override @Override
public String getServerName() { public String getServerName() {
return server.getName(); return server == null ? "server" : server.getName();
} }
@Override @Override
public void setServer(@NotNull Server server) { public void setServerName(@NotNull Server server) {
this.server = server; this.server = server;
} }
@Override
public void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks) {
this.unsafeBlocks = unsafeBlocks;
}
@NotNull
@Override
public UnsafeBlocks getUnsafeBlocks() {
return unsafeBlocks;
}
@NotNull
@Override
public Database getDatabase() {
return database;
}
@NotNull
@Override
public Validator getValidator() {
return validator;
}
@NotNull
@Override
public Manager getManager() {
return manager;
}
@NotNull @NotNull
@Override @Override
public Broker getMessenger() { public Broker getMessenger() {
@@ -346,34 +259,13 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
return broker; return broker;
} }
@NotNull
@Override
public RandomTeleportEngine getRandomTeleportEngine() {
return randomTeleportEngine;
}
@Override
public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) {
this.randomTeleportEngine = randomTeleportEngine;
}
@NotNull
@Override
public List<Hook> getHooks() {
return hooks;
}
@Override
public void setHooks(@NotNull List<Hook> hooks) {
this.hooks = hooks;
}
@Override @Override
public void registerHooks() { public void registerHooks() {
HuskHomes.super.registerHooks(); HuskHomes.super.registerHooks();
// Register the sponge economy service if it is available // Register the sponge economy service if it is available
if (getSettings().doEconomy() && getGame().server().serviceProvider().economyService().isPresent()) { if (getSettings().getEconomy().isEnabled()
&& getGame().server().serviceProvider().economyService().isPresent()) {
getHooks().add(new SpongeEconomyHook(this)); getHooks().add(new SpongeEconomyHook(this));
} }
} }
@@ -381,14 +273,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
@Nullable @Nullable
@Override @Override
public InputStream getResource(@NotNull String name) { public InputStream getResource(@NotNull String name) {
return pluginContainer.openResource(URI.create(name)) return pluginContainer.openResource(URI.create(name)).orElse(null);
.orElse(null);
}
@NotNull
@Override
public File getDataFolder() {
return pluginDirectory.toFile();
} }
@NotNull @NotNull
@@ -429,18 +314,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
return game.pluginManager().plugin(name).isPresent(); return game.pluginManager().plugin(name).isPresent();
} }
@NotNull
@Override
public Map<String, List<String>> getGlobalPlayerList() {
return globalPlayerList;
}
@NotNull
@Override
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
@Override @Override
public void registerMetrics(int metricsId) { public void registerMetrics(int metricsId) {
if (!getVersion().getMetadata().isBlank()) { if (!getVersion().getMetadata().isBlank()) {
@@ -450,19 +323,20 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
try { try {
final Metrics metrics = metricsFactory.make(METRICS_ID); final Metrics metrics = metricsFactory.make(METRICS_ID);
metrics.addCustomChart(new SimplePie("bungee_mode", metrics.addCustomChart(new SimplePie("bungee_mode",
() -> Boolean.toString(getSettings().doCrossServer()))); () -> Boolean.toString(getSettings().getCrossServer().isEnabled())));
if (getSettings().doCrossServer()) { if (getSettings().getCrossServer().isEnabled()) {
metrics.addCustomChart(new SimplePie("messenger_type", metrics.addCustomChart(new SimplePie("messenger_type",
() -> getSettings().getBrokerType().getDisplayName())); () -> getSettings().getCrossServer().getBrokerType().getDisplayName())
);
} }
metrics.addCustomChart(new SimplePie("language", metrics.addCustomChart(new SimplePie("language",
() -> getSettings().getLanguage().toLowerCase())); () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", metrics.addCustomChart(new SimplePie("database_type",
() -> getSettings().getDatabaseType().getDisplayName())); () -> getSettings().getDatabase().getType().getDisplayName()));
metrics.addCustomChart(new SimplePie("using_economy", metrics.addCustomChart(new SimplePie("using_economy",
() -> Boolean.toString(getSettings().doEconomy()))); () -> Boolean.toString(getSettings().getEconomy().isEnabled())));
metrics.addCustomChart(new SimplePie("using_map", metrics.addCustomChart(new SimplePie("using_map",
() -> Boolean.toString(getSettings().doMapHook()))); () -> Boolean.toString(getSettings().getMapHook().isEnabled())));
getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName))); getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName)));
} catch (Throwable e) { } catch (Throwable e) {
log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")");
@@ -471,8 +345,10 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
@Override @Override
public void initializePluginChannels() { public void initializePluginChannels() {
this.channel = game.channelManager().ofType(PLUGIN_MESSAGE_CHANNEL_KEY, RawDataChannel.class).play(); this.pluginMessageChannel = game.channelManager().ofType(
this.channel.addHandler(this); PLUGIN_MESSAGE_CHANNEL_KEY, RawDataChannel.class
).play();
this.pluginMessageChannel.addHandler(this);
} }
@Override @Override
@@ -491,7 +367,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
final SpongeUser user = (SpongeUser) playerConnection.get(); final SpongeUser user = (SpongeUser) playerConnection.get();
final String channel = pluginMessage.readUTF(); final String channel = pluginMessage.readUTF();
if (broker instanceof PluginMessageBroker messenger if (broker instanceof PluginMessageBroker messenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
messenger.onReceive(channel, user, pluginMessage.readBytes(pluginMessage.available())); messenger.onReceive(channel, user, pluginMessage.readBytes(pluginMessage.available()));
} }
} }
@@ -509,24 +385,10 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa
pluginContainer.logger().log(adaptedLevel, message); pluginContainer.logger().log(adaptedLevel, message);
} }
@NotNull
public PluginContainer getPluginContainer() {
return pluginContainer;
}
@NotNull
public Game getGame() {
return game;
}
@NotNull
public RawPlayDataChannel getPluginMessageChannel() {
return channel;
}
@NotNull @NotNull
@Override @Override
public SpongeHuskHomes getPlugin() { public SpongeHuskHomes getPlugin() {
return this; return this;
} }
} }