refactor: significantly refactor internals, remove Sponge (#708)

* feat: start database refactor

Adds database migrations

* refactor: refactor database system

Now supports migrations

* refactor: begin major internals rewrite

move to using provider-style interfaces similar to huskclaims
bukkit done, still need to do fabric and sponge

* refactor: remove sponge, checkstyle

Low usage and high maintenance time cost. We will examine Forge instead in the future.

* refactor: implement refactoring changes on fabric

also fix various refactor quirks on Bukkit

* refactor: tidy metrics logic

* build: bump deps
This commit is contained in:
William authored and GitHub committed 2024-10-28 20:49:57 +00:00
1 parent 05bcad9249
commit ffe995ef5f
162 files changed
+3890 -5730

No files matched your search

@@ -21,49 +21,138 @@ package net.william278.huskhomes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.william278.desertwell.util.ThrowingConsumer;
import net.william278.desertwell.util.UpdateChecker;
import net.william278.desertwell.util.Version;
import net.william278.huskhomes.api.BaseHuskHomesAPI;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.CommandProvider;
import net.william278.huskhomes.config.ConfigProvider;
import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.database.DatabaseProvider;
import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.hook.*;
import net.william278.huskhomes.importer.Importer;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.hook.HookProvider;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.listener.ListenerProvider;
import net.william278.huskhomes.manager.ManagerProvider;
import net.william278.huskhomes.network.BrokerProvider;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.random.RandomTeleportProvider;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.UserProvider;
import net.william278.huskhomes.util.*;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream;
import java.util.*;
import java.util.function.Consumer;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Represents a cross-platform instance of the plugin.
*/
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver, ConfigProvider {
public interface HuskHomes extends Task.Supplier, EventDispatcher, SavePositionProvider, TransactionResolver,
ConfigProvider, DatabaseProvider, BrokerProvider, MetaProvider, HookProvider, RandomTeleportProvider,
AudiencesProvider, UserProvider, TextValidator, ManagerProvider, ListenerProvider, CommandProvider {
int BSTATS_BUKKIT_PLUGIN_ID = 8430;
/**
* The spigot resource ID, used for update checking.
* Load plugin systems.
*
* @since 4.8
*/
int SPIGOT_RESOURCE_ID = 83767;
default void load() {
try {
loadConfigs();
loadHooks();
registerHooks(PluginHook.Register.ON_LOAD);
} catch (Throwable e) {
log(Level.SEVERE, "An error occurred whilst loading HuskHomes", e);
disablePlugin();
return;
}
log(Level.INFO, String.format("Successfully loaded HuskHomes v%s", getPluginVersion()));
}
/**
* Enable all plugin systems.
*
* @since 4.8
*/
default void enable() {
try {
loadDatabase();
loadBroker();
loadManager();
loadRandomTeleportEngine();
loadListeners();
registerHooks(PluginHook.Register.ON_ENABLE);
loadAPI();
if (getPluginVersion().getMetadata().isBlank()) {
loadMetrics();
}
} catch (Throwable e) {
log(Level.SEVERE, "An error occurred whilst enabling HuskHomes", e);
disablePlugin();
return;
}
log(Level.INFO, String.format("Successfully enabled HuskHomes v%s", getPluginVersion()));
checkForUpdates();
}
/**
* Shutdown plugin subsystems.
*
* @since 4.8
*/
default void shutdown() {
log(Level.INFO, String.format("Disabling HuskHomes v%s...", getPluginVersion()));
try {
unloadHooks();
closeDatabase();
closeBroker();
cancelTasks();
unloadAPI();
} catch (Throwable e) {
log(Level.SEVERE, "An error occurred whilst disabling HuskHomes", e);
}
log(Level.INFO, String.format("Successfully disabled HuskHomes v%s", getPluginVersion()));
}
/**
* Register the API instance.
*
* @since 4.8
*/
void loadAPI();
/**
* Unregister the API instance.
*
* @since 4.8
*/
default void unloadAPI() {
BaseHuskHomesAPI.unregister();
}
/**
* Load plugin metrics.
*
* @since 4.8
*/
void loadMetrics();
/**
* Disable the plugin.
*
* @since 4.8
*/
void disablePlugin();
/**
* Get the user representing the server console.
@@ -73,82 +162,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
@NotNull
ConsoleUser getConsole();
/**
* The {@link Set} of online {@link OnlineUser}s on this server.
*
* @return a {@link Set} of currently online {@link OnlineUser}s
*/
@NotNull
List<OnlineUser> getOnlineUsers();
/**
* Get the adventure {@link Audience} for a given {@link UUID}.
*
* @param user The {@link UUID} of the user to get the {@link Audience} for.
* @return The {@link Audience} for the given {@link UUID}.
*/
@NotNull
Audience getAudience(@NotNull UUID user);
/**
* Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match
*
* @param playerName the name of the player to find
* @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found
*/
default Optional<OnlineUser> getOnlineUser(@NotNull String playerName) {
return getOnlineUserExact(playerName)
.or(() -> getOnlineUsers().stream()
.filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase()))
.findFirst());
}
/**
* Finds a local {@link OnlineUser} by their name.
*
* @param playerName the name of the player to find
* @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found
*/
default Optional<OnlineUser> getOnlineUserExact(@NotNull String playerName) {
return getOnlineUsers().stream()
.filter(user -> user.getUsername().equalsIgnoreCase(playerName))
.findFirst();
}
@NotNull
Set<SavedUser> getSavedUsers();
default Optional<SavedUser> getSavedUser(@NotNull User user) {
return getSavedUsers().stream()
.filter(savedUser -> savedUser.getUser().equals(user))
.findFirst();
}
default void editUserData(@NotNull User user, @NotNull Consumer<SavedUser> editor) {
runAsync(() -> getSavedUser(user)
.ifPresent(result -> {
editor.accept(result);
getDatabase().updateUserData(result);
}));
}
/**
* Initialize a faucet of the plugin.
*
* @param name the name of the faucet
* @param runner a runnable for initializing the faucet
*/
default void initialize(@NotNull String name, @NotNull ThrowingConsumer<HuskHomes> runner) {
log(Level.INFO, "Initializing " + name + "...");
try {
runner.accept(this);
} catch (Exception e) {
throw new IllegalStateException("Failed to initialize " + name, e);
}
log(Level.INFO, "Successfully initialized " + name);
}
/**
* The canonical spawn {@link Position} of this server, if it has been set.
*
@@ -168,96 +181,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
*/
void setWorldSpawn(@NotNull Position position);
/**
* Returns the {@link Server} the plugin is on.
*
* @return The {@link Server} object
*/
@NotNull
String getServerName();
void setServer(@NotNull Server server);
void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks);
@NotNull
UnsafeBlocks getUnsafeBlocks();
/**
* The {@link Database} that store persistent plugin data.
*
* @return the {@link Database} implementation for accessing data
*/
@NotNull
Database getDatabase();
/**
* The {@link Validator} for validating home names and descriptions.
*
* @return the {@link Validator} instance
*/
@NotNull
Validator getValidator();
/**
* The {@link Manager} that manages home, warp and user data.
*
* @return the {@link Manager} implementation
*/
@NotNull
Manager getManager();
/**
* The {@link Broker} that sends cross-network messages.
*
* @return the {@link Broker} implementation
*/
@NotNull
Broker getMessenger();
/**
* The {@link RandomTeleportEngine} that manages random teleports.
*
* @return the {@link RandomTeleportEngine} implementation
*/
@NotNull
RandomTeleportEngine getRandomTeleportEngine();
/**
* Sets the {@link RandomTeleportEngine} to be used for processing random teleports.
*
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use
*/
void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine);
/**
* Set of active {@link Hook}s running on the server.
*
* @return the {@link Set} of active {@link Hook}s
*/
@NotNull
List<Hook> getHooks();
void setHooks(@NotNull List<Hook> hooks);
default <T extends Hook> Optional<T> getHook(@NotNull Class<T> hookClass) {
return getHooks().stream()
.filter(hook -> hookClass.isAssignableFrom(hook.getClass()))
.map(hookClass::cast)
.findFirst();
}
default Optional<MapHook> getMapHook() {
return getHook(MapHook.class);
}
@NotNull
default List<Importer> getImporters() {
return getHooks().stream()
.filter(hook -> Importer.class.isAssignableFrom(hook.getClass()))
.map(Importer.class::cast)
.collect(Collectors.toList());
}
void setServerName(@NotNull Server serverName);
/**
* Returns a resource read from the plugin resources folder.
@@ -276,14 +200,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
@NotNull
List<World> getWorlds();
/**
* Returns the plugin version.
*
* @return the plugin {@link Version}
*/
@NotNull
Version getVersion();
/**
* Returns a list of enabled commands.
*
@@ -299,64 +215,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
.map(type::cast);
}
default void registerHooks() {
setHooks(new ArrayList<>());
if (getSettings().getMapHook().isEnabled()) {
if (isDependencyLoaded("Dynmap")) {
getHooks().add(new DynmapHook(this));
} else if (isDependencyLoaded("BlueMap")) {
getHooks().add(new BlueMapHook(this));
} else if (isDependencyLoaded("Pl3xMap")) {
getHooks().add(new Pl3xMapHook(this));
}
}
if (isDependencyLoaded("Plan")) {
getHooks().add(new PlanHook(this));
}
}
default void registerImporters() {
}
boolean isDependencyLoaded(@NotNull String name);
@NotNull
Map<String, List<String>> getGlobalPlayerList();
default List<String> getPlayerList(boolean includeVanished) {
return Stream.concat(
getGlobalPlayerList().values().stream().flatMap(Collection::stream),
getLocalPlayerList(includeVanished).stream()
).distinct().sorted().toList();
}
@NotNull
@SuppressWarnings("unused")
default List<String> getPlayerList() {
return getPlayerList(true);
}
default void setPlayerList(@NotNull String server, @NotNull List<String> players) {
getGlobalPlayerList().values().forEach(list -> {
list.removeAll(players);
list.removeAll(getLocalPlayerList());
});
getGlobalPlayerList().put(server, players);
}
@NotNull
default List<String> getLocalPlayerList(boolean includeVanished) {
return getOnlineUsers().stream()
.filter(user -> includeVanished || !user.isVanished())
.map(OnlineUser::getUsername)
.toList();
}
default List<String> getLocalPlayerList() {
return getLocalPlayerList(true);
}
@NotNull
Set<UUID> getCurrentlyOnWarmup();
@@ -383,38 +241,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
return this.getCurrentlyInvulnerable().contains(uuid);
}
@NotNull
default UpdateChecker getUpdateChecker() {
return UpdateChecker.builder()
.currentVersion(getVersion())
.endpoint(UpdateChecker.Endpoint.SPIGOT)
.resource(Integer.toString(SPIGOT_RESOURCE_ID))
.build();
}
default void checkForUpdates() {
if (getSettings().isCheckForUpdates()) {
getUpdateChecker().check().thenAccept(checked -> {
if (!checked.isUpToDate()) {
log(Level.WARNING, "A new version of HuskHomes is available: v"
+ checked.getLatestVersion() + " (running v" + getVersion() + ")");
}
});
}
}
/**
* Registers the plugin with bStats metrics.
*
* @param metricsId the bStats id for the plugin
*/
void registerMetrics(int metricsId);
/**
* Initialize plugin messaging channels.
*/
void initializePluginChannels();
/**
* Log a message to the console.
*
@@ -95,7 +95,7 @@ public class BaseHuskHomesAPI {
* @since 3.0
*/
public final CompletableFuture<Optional<SavedUser>> getUserData(@NotNull UUID uuid) {
return plugin.supplyAsync(() -> plugin.getDatabase().getUserData(uuid));
return plugin.supplyAsync(() -> plugin.getDatabase().getUser(uuid));
}
/**
@@ -106,7 +106,7 @@ public class BaseHuskHomesAPI {
* @since 3.0
*/
public final CompletableFuture<Optional<SavedUser>> getUserData(@NotNull String username) {
return plugin.supplyAsync(() -> plugin.getDatabase().getUserDataByName(username));
return plugin.supplyAsync(() -> plugin.getDatabase().getUser(username));
}
/**
@@ -779,27 +779,28 @@ public class BaseHuskHomesAPI {
* @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still
* for a period of time)
* @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine}
* @since 3.0
* @apiNote This method was updated in version 4.6.3 to support the new Cross-Server RTP function,
* for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser, boolean, String...)}
* for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser, boolean, String...)}
* @since 3.0
*/
public final void randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport,
@NotNull String... rtpArgs) {
if (plugin.getSettings().getRtp().isCrossServer() && (plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS)) {
if (plugin.getSettings().getRtp().isCrossServer() && (plugin.getSettings().getCrossServer().isEnabled() &&
plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS)) {
List<String> allowedServers = plugin.getSettings().getRtp().getRandomTargetServers();
String randomServer = allowedServers.get(random.nextInt(allowedServers.size()));
if (randomServer.equals(plugin.getServerName())) {
randomlyTeleportPlayerLocally(user, timedTeleport, rtpArgs);
return;
}
Message.builder()
plugin.getBroker().ifPresent(b -> Message.builder()
.scope(Message.Scope.SERVER)
.target(randomServer)
.type(Message.Type.REQUEST_RTP_LOCATION)
.payload(Payload.withStringList(
List.of(user.getPosition().getWorld().getName(), user.getUsername())))
.build().send(plugin.getMessenger(), user);
List.of(user.getPosition().getWorld().getName(), user.getName())))
.build().send(b, user));
return;
}
randomlyTeleportPlayerLocally(user, timedTeleport, rtpArgs);
@@ -810,9 +811,9 @@ public class BaseHuskHomesAPI {
* generated by the current {@link RandomTeleportEngine}.
*
* @param user The {@link OnlineUser} to teleport
* @since 3.0
* @apiNote This method was updated in version 4.6.3 to support the new Cross-Server RTP function,
* for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser)}
* for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser)}
* @since 3.0
*/
public final void randomlyTeleportPlayer(@NotNull OnlineUser user) {
this.randomlyTeleportPlayer(user, false);
@@ -831,7 +832,7 @@ public class BaseHuskHomesAPI {
* @since 4.6.3
*/
public final void randomlyTeleportPlayerLocally(@NotNull OnlineUser user, boolean timedTeleport,
@NotNull String... rtpArgs) {
@NotNull String... rtpArgs) {
plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().getWorld(), rtpArgs)
.thenAccept(position -> {
@@ -904,7 +905,7 @@ public class BaseHuskHomesAPI {
*
* @return instance of the HuskHomes API
* @throws NotRegisteredException if the API has not yet been registered.
* @since 1.0
* @since 4.8
*/
@NotNull
public static BaseHuskHomesAPI getInstance() throws NotRegisteredException {
@@ -917,7 +918,7 @@ public class BaseHuskHomesAPI {
/**
* <b>(Internal use only)</b> - Unregister the API instance.
*
* @since 1.0
* @since 4.8
*/
@ApiStatus.Internal
public static void unregister() {
@@ -33,7 +33,11 @@ import java.util.Optional;
public class BackCommand extends InGameCommand {
protected BackCommand(@NotNull HuskHomes plugin) {
super("back", List.of(), "", plugin);
super(
List.of("back"),
"",
plugin
);
addAdditionalPermissions(Map.of(
"death", false,
"previous", false
@@ -19,11 +19,11 @@
package net.william278.huskhomes.command;
import com.google.common.collect.Maps;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -32,11 +32,10 @@ public abstract class Command extends Node {
private final String usage;
private final Map<String, Boolean> additionalPermissions;
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, plugin);
protected Command(@NotNull List<String> aliases, @NotNull String usage, @NotNull HuskHomes plugin) {
super(aliases, plugin);
this.usage = usage;
this.additionalPermissions = new HashMap<>();
this.additionalPermissions = Maps.newTreeMap();
}
@Override
@@ -82,7 +81,7 @@ public abstract class Command extends Node {
@NotNull
public String getDescription() {
return plugin.getLocales().getRawLocale(getName() + "_command_description")
return plugin.getLocales().getRawLocale(String.format("%s_command_description", getName()))
.orElse(getUsage());
}
@@ -0,0 +1,126 @@
/*
* 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.command;
import com.google.common.collect.Lists;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public interface CommandProvider {
/**
* Get the list of registered commands
*
* @return the list of commands
* @since 4.8
*/
@NotNull
List<Command> getCommands();
/**
* Get a command by its class
*
* @param commandClass the class of the command to get
* @param <T> the type of command
* @return the command, or null if not found
*/
default <T extends Command> Optional<T> getCommand(@NotNull Class<T> commandClass) {
return getCommands().stream()
.filter(commandClass::isInstance)
.map(commandClass::cast)
.findFirst();
}
/**
* Returns whether a user can use a command
*
* @param commandClass the class of the command to check
* @param user the user to check
* @param nodes the nodes to check
* @param <T> the type of command
* @return whether the user can use the command
*/
default <T extends Command> boolean canUseCommand(@NotNull Class<T> commandClass, @NotNull CommandUser user,
@NotNull String... nodes) {
return getCommand(commandClass).map(command -> command.hasPermission(user, nodes)).orElse(false);
}
/**
* Register a batch of command with the platform implementation
*
* @param commands the list of commands to register
* @since 4.8
*/
void registerCommands(@NotNull List<Command> commands);
/**
* Registers all plugin commands
*
* @since 4.8
*/
default void loadCommands() {
final List<Command> commands = Lists.newArrayList();
// Instantiate commands
commands.add(new PrivateHomeCommand(getPlugin()));
commands.add(new SetHomeCommand(getPlugin()));
commands.add(new HomeListCommand(getPlugin()));
commands.add(new DelHomeCommand(getPlugin()));
commands.add(new EditHomeCommand(getPlugin()));
commands.add(new PublicHomeCommand(getPlugin()));
commands.add(new PublicHomeListCommand(getPlugin()));
commands.add(new WarpCommand(getPlugin()));
commands.add(new SetWarpCommand(getPlugin()));
commands.add(new WarpListCommand(getPlugin()));
commands.add(new DelWarpCommand(getPlugin()));
commands.add(new EditWarpCommand(getPlugin()));
commands.add(new TpCommand(getPlugin()));
commands.add(new TpHereCommand(getPlugin()));
commands.add(new TpRequestCommand(getPlugin(), TeleportRequest.Type.TPA));
commands.add(new TpRequestCommand(getPlugin(), TeleportRequest.Type.TPA_HERE));
commands.add(new TpRespondCommand(getPlugin(), true));
commands.add(new TpRespondCommand(getPlugin(), false));
commands.add(new RtpCommand(getPlugin()));
commands.add(new TpIgnoreCommand(getPlugin()));
commands.add(new TpOfflineCommand(getPlugin()));
commands.add(new TpAllCommand(getPlugin()));
commands.add(new SpawnCommand(getPlugin()));
commands.add(new SetSpawnCommand(getPlugin()));
commands.add(new BackCommand(getPlugin()));
commands.add(new HuskHomesCommand(getPlugin()));
// Filter, sort, and register
registerCommands(commands.stream()
.filter((command) -> !getPlugin().getSettings().isCommandDisabled(command))
.sorted(Comparator.comparing(Command::getName))
.toList());
}
@NotNull
HuskHomes getPlugin();
}
@@ -31,7 +31,12 @@ import java.util.List;
public class DelHomeCommand extends SavedPositionCommand<Home> {
public DelHomeCommand(@NotNull HuskHomes plugin) {
super("delhome", List.of(), PositionCommandType.HOME, List.of(), plugin);
super(
List.of("delhome"),
PositionCommandType.HOME,
List.of(),
plugin
);
}
@Override
@@ -45,7 +50,7 @@ public class DelHomeCommand extends SavedPositionCommand<Home> {
@Override
public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) {
if (executor instanceof OnlineUser user && !home.getOwner().equals(user)
&& !user.hasPermission(getOtherPermission())) {
&& !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(user::sendMessage);
return;
@@ -30,7 +30,12 @@ import java.util.List;
public class DelWarpCommand extends SavedPositionCommand<Warp> {
public DelWarpCommand(@NotNull HuskHomes plugin) {
super("delwarp", List.of(), PositionCommandType.WARP, List.of(), plugin);
super(
List.of("delwarp"),
PositionCommandType.WARP,
List.of(),
plugin
);
setOperatorCommand(true);
}
@@ -28,7 +28,11 @@ import java.util.List;
public class DisabledCommand extends Command {
public DisabledCommand(@NotNull String name, @NotNull HuskHomes plugin) {
super(name, List.of(), "", plugin);
super(
List.of(name),
"",
plugin
);
setOperatorCommand(true);
}
@@ -40,8 +40,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
public EditHomeCommand(@NotNull HuskHomes plugin) {
super(
"edithome",
List.of(),
List.of("edithome"),
PositionCommandType.HOME,
List.of("rename", "description", "relocate", "privacy"),
plugin
@@ -104,7 +103,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_name_other",
home.getOwner().getUsername(), original.getName(), newName)
home.getOwner().getName(), original.getName(), newName)
.ifPresent(executor::sendMessage);
}
});
@@ -137,7 +136,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_description_other",
home.getOwner().getUsername(), home.getName(),
home.getOwner().getName(), home.getName(),
original.getMeta().getDescription(), newDescription)
.ifPresent(executor::sendMessage);
}
@@ -166,7 +165,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_location_other",
home.getOwner().getUsername(), home.getName())
home.getOwner().getName(), home.getName())
.ifPresent(executor::sendMessage);
}
});
@@ -220,7 +219,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_privacy_" + privacy + "_success_other",
home.getOwner().getUsername(), home.getName())
home.getOwner().getName(), home.getName())
.ifPresent(executor::sendMessage);
}
});
@@ -244,7 +243,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
.ifPresent(messages::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_title_other",
home.getOwner().getUsername(), home.getName())
home.getOwner().getName(), home.getName())
.ifPresent(messages::add);
}
@@ -38,8 +38,7 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
public EditWarpCommand(@NotNull HuskHomes plugin) {
super(
"editwarp",
List.of(),
List.of("editwarp"),
PositionCommandType.WARP,
List.of("rename", "description", "relocate"),
plugin
@@ -33,9 +33,9 @@ import java.util.Optional;
public abstract class HomeCommand extends SavedPositionCommand<Home> {
protected HomeCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull PositionCommandType type,
protected HomeCommand(@NotNull List<String> aliases, @NotNull PositionCommandType type,
@NotNull HuskHomes plugin) {
super(name, aliases, type, List.of(), plugin);
super(aliases, type, List.of(), plugin);
addAdditionalPermissions(Map.of("player", true));
}
@@ -51,7 +51,7 @@ public abstract class HomeCommand extends SavedPositionCommand<Home> {
if (executor instanceof OnlineUser user && !user.hasPermission(getOtherPermission())
&& (!home.getOwner().equals(user) && !home.isPublic())) {
plugin.getLocales().getLocale("error_public_home_invalid",
home.getOwner().getUsername(), home.getName())
home.getOwner().getName(), home.getName())
.ifPresent(executor::sendMessage);
return;
}
@@ -37,14 +37,18 @@ import java.util.stream.Collectors;
public class HomeListCommand extends ListCommand {
protected HomeListCommand(@NotNull HuskHomes plugin) {
super("homelist", List.of("homes"), "[player] [page]", plugin);
super(
List.of("homelist", "homes"),
"[player] [page]",
plugin
);
addAdditionalPermissions(Map.of("other", true));
}
@Override
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
final Optional<String> homeOwner = args.length > 0 ? parseStringArg(args, 0)
: executor instanceof OnlineUser user ? Optional.of(user.getUsername()) : Optional.empty();
: executor instanceof OnlineUser user ? Optional.of(user.getName()) : Optional.empty();
final int pageNumber = parseIntArg(args, args.length > 1 ? 1 : 0).orElse(1);
if (homeOwner.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
@@ -56,7 +60,7 @@ public class HomeListCommand extends ListCommand {
}
protected void showHomeList(@NotNull CommandUser executor, @NotNull String homeOwner, int pageNumber) {
final Optional<User> targetUser = plugin.getDatabase().getUserDataByName(homeOwner).map(SavedUser::getUser);
final Optional<User> targetUser = plugin.getDatabase().getUser(homeOwner).map(SavedUser::getUser);
final User user;
final int page;
if (targetUser.isEmpty()) {
@@ -74,7 +78,7 @@ public class HomeListCommand extends ListCommand {
}
if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid())
&& !executor.hasPermission(getPermission("other"))) {
&& !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
@@ -97,7 +101,7 @@ public class HomeListCommand extends ListCommand {
@NotNull List<Home> homes) {
if (homes.isEmpty()) {
if (!executor.equals(user)) {
plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername())
plugin.getLocales().getLocale("error_no_homes_set_other", user.getName())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("error_no_homes_set").ifPresent(executor::sendMessage);
@@ -105,7 +109,7 @@ public class HomeListCommand extends ListCommand {
return Optional.empty();
}
final String homeListArguments = !executor.equals(user) ? " " + user.getUsername() : "";
final String homeListArguments = !executor.equals(user) ? " " + user.getName() : "";
final PaginatedList homeList = PaginatedList.of(homes.stream().map(home ->
plugin.getLocales()
.getRawLocale("home_list_item",
@@ -124,7 +128,7 @@ public class HomeListCommand extends ListCommand {
plugin.getLocales()
.getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage())
.setHeaderFormat(plugin.getLocales().getRawLocale("home_list_page_title",
user.getUsername(), "%first_item_on_page_index%",
user.getName(), "%first_item_on_page_index%",
"%last_item_on_page_index%", "%total_items%")
.orElse(""))
.setCommand("/huskhomes:homelist" + homeListArguments).build());
@@ -39,7 +39,7 @@ import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class HuskHomesCommand extends Command implements TabProvider {
public class HuskHomesCommand extends Command implements TabCompletable {
private static final Map<String, Boolean> SUB_COMMANDS = Map.of(
"about", false,
@@ -55,14 +55,18 @@ public class HuskHomesCommand extends Command implements TabProvider {
private final AboutMenu aboutMenu;
protected HuskHomesCommand(@NotNull HuskHomes plugin) {
super("huskhomes", List.of(), "[" + String.join("|", SUB_COMMANDS.keySet()) + "]", plugin);
super(
List.of("huskhomes"),
"[" + String.join("|", SUB_COMMANDS.keySet()) + "]",
plugin
);
addAdditionalPermissions(SUB_COMMANDS);
this.updateChecker = plugin.getUpdateChecker();
this.aboutMenu = AboutMenu.builder()
.title(Component.text("HuskHomes"))
.description(Component.text("The powerful & intuitive homes, warps, and teleportation suite"))
.version(plugin.getVersion())
.version(plugin.getPluginVersion())
.credits("Author",
AboutMenu.Credit.of("William278").description("Click to visit website").url("https://william278.net"))
.credits("Contributors",
@@ -118,14 +122,14 @@ public class HuskHomesCommand extends Command implements TabProvider {
executor.sendMessage(new MineDown(
"[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)\n"
+ "[ℹ If you have modified the database or cross-server message broker settings,"
+ " you need to restart your server for these changes to take effect.](gray)"
+ "[ℹ If you have modified the database or cross-server message broker settings,"
+ " you need to restart your server for these changes to take effect.](gray)"
));
}
case "import" -> {
if (!importersLoaded) {
importersLoaded = true;
plugin.registerImporters();
plugin.loadHooks();
}
if (plugin.getImporters().isEmpty()) {
plugin.getLocales().getLocale("error_no_importers_available")
@@ -152,12 +156,12 @@ public class HuskHomesCommand extends Command implements TabProvider {
}
case "update" -> updateChecker.check().thenAccept(checked -> {
if (checked.isUpToDate()) {
plugin.getLocales().getLocale("up_to_date", plugin.getVersion().toString())
plugin.getLocales().getLocale("up_to_date", plugin.getPlugin().toString())
.ifPresent(executor::sendMessage);
return;
}
plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(),
plugin.getVersion().toString()).ifPresent(executor::sendMessage);
plugin.getPluginVersion().toString()).ifPresent(executor::sendMessage);
});
default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
@@ -169,8 +173,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
switch (parseStringArg(args, 0).orElse("list")) {
case "start" -> parseStringArg(args, 1).ifPresentOrElse(
name -> {
final Optional<Importer> importer = plugin.getImporters().stream()
.filter(available -> available.getImporterName().equalsIgnoreCase(name)).findFirst();
final Optional<Importer> importer = plugin.getImporterByName(name);
if (importer.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_importer")
.ifPresent(executor::sendMessage);
@@ -203,9 +206,9 @@ public class HuskHomesCommand extends Command implements TabProvider {
plugin.runAsync(() -> {
Optional<SavedUser> savedUser;
try {
savedUser = plugin.getDatabase().getUserData(UUID.fromString(nameOrUuid.get()));
savedUser = plugin.getDatabase().getUser(UUID.fromString(nameOrUuid.get()));
} catch (IllegalArgumentException e) {
savedUser = plugin.getDatabase().getUserDataByName(nameOrUuid.get());
savedUser = plugin.getDatabase().getUser(nameOrUuid.get());
}
if (savedUser.isEmpty()) {
@@ -218,14 +221,14 @@ public class HuskHomesCommand extends Command implements TabProvider {
if (!parseStringArg(args, 1)
.map(a -> a.equalsIgnoreCase("confirm")).orElse(false)) {
plugin.getLocales().getLocale("delete_player_confirm",
savedUser.get().getUser().getUsername()).ifPresent(executor::sendMessage);
savedUser.get().getUser().getName()).ifPresent(executor::sendMessage);
return;
}
final int homesDeleted = plugin.getManager().homes().deleteAllHomes(user);
plugin.getDatabase().deleteUserData(user.getUuid());
plugin.getDatabase().deleteUser(user.getUuid());
plugin.getLocales().getLocale("delete_player_success",
savedUser.get().getUser().getUsername(), Integer.toString(homesDeleted))
savedUser.get().getUser().getName(), Integer.toString(homesDeleted))
.ifPresent(executor::sendMessage);
});
}
@@ -318,7 +321,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
private PaginatedList getImporterList() {
return PaginatedList.of(plugin.getImporters().stream()
.map(importer -> plugin.getLocales().getRawLocale("importer_list_item",
Locales.escapeText(importer.getImporterName()),
Locales.escapeText(importer.getName()),
Locales.escapeText(importer.getSupportedImportData().stream()
.map(Importer.ImportData::getName)
.collect(Collectors.joining(", "))))
@@ -346,7 +349,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
if (!args[0].equalsIgnoreCase("import") && !args[1].equalsIgnoreCase("start")) {
yield null;
}
yield plugin.getImporters().stream().map(Importer::getImporterName).toList();
yield plugin.getImporters().stream().map(Importer::getName).toList();
}
default -> null;
};
@@ -28,9 +28,9 @@ import java.util.List;
public abstract class InGameCommand extends Command {
protected InGameCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
protected InGameCommand(@NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, usage, plugin);
super(aliases, usage, plugin);
}
@Override
@@ -32,9 +32,9 @@ public abstract class ListCommand extends Command {
protected final Map<UUID, PaginatedList> cachedLists;
protected ListCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
protected ListCommand(@NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, usage, plugin);
super(aliases, usage, plugin);
this.cachedLists = new HashMap<>();
}
@@ -27,55 +27,64 @@ import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.*;
public abstract class Node implements Executable {
protected static final String PERMISSION_PREFIX = "huskhomes.command";
protected final HuskHomes plugin;
private final String name;
private final List<String> aliases;
@Setter
@Getter
private final List<String> aliases;
@Getter
@Setter
private boolean operatorCommand = false;
protected Node(@NotNull String name, @NotNull List<String> aliases, @NotNull HuskHomes plugin) {
if (name.isBlank()) {
protected Node(@NotNull List<String> aliases, @NotNull HuskHomes plugin) {
if (aliases.isEmpty()) {
throw new IllegalArgumentException("Command name cannot be blank");
}
this.name = name;
this.aliases = aliases;
this.plugin = plugin;
}
@NotNull
public String getName() {
return name;
}
@NotNull
public List<String> getAliases() {
return aliases;
}
@NotNull
public String getPermission(@NotNull String... child) {
final StringJoiner joiner = new StringJoiner(".")
.add(PERMISSION_PREFIX)
.add(getName());
for (final String node : child) {
for (String node : child) {
joiner.add(node);
}
return joiner.toString().trim();
}
public boolean hasPermission(@NotNull CommandUser executor, @NotNull String... child) {
return executor.hasPermission(getPermission(child)) || executor.hasPermission(getPermission("*"));
}
@NotNull
public String getName() {
if (aliases.isEmpty()) {
throw new IllegalStateException("Primary alias of command node is blank");
}
return aliases.get(0);
}
protected Optional<User> resolveUser(@NotNull CommandUser executor, @NotNull String[] args) {
return parseStringArg(args, 0)
.flatMap(a -> plugin.getDatabase().getUser(a)).map(SavedUser::getUser)
.or(() -> {
if (executor instanceof OnlineUser online) {
return Optional.of(online);
}
return Optional.empty();
});
}
protected Optional<Integer> parseIntArg(@NotNull String[] args, int index) {
try {
if (args.length > index) {
@@ -184,4 +193,17 @@ public abstract class Node implements Executable {
}
protected Optional<Boolean> parseBooleanArg(@NotNull String[] args, int index) {
if (args.length <= index) {
return Optional.empty();
}
final String arg = args[index].toLowerCase(Locale.ENGLISH);
if (arg.equals("true") || arg.equals("enable") || arg.equals("on")) {
return Optional.of(true);
} else if (arg.equals("false") || arg.equals("disable") || arg.equals("off")) {
return Optional.of(false);
}
return Optional.empty();
}
}
@@ -30,7 +30,11 @@ import java.util.List;
public class PrivateHomeCommand extends HomeCommand {
protected PrivateHomeCommand(@NotNull HuskHomes plugin) {
super("home", List.of(), PositionCommandType.HOME, plugin);
super(
List.of("home"),
PositionCommandType.HOME,
plugin
);
}
@Override
@@ -49,7 +53,7 @@ public class PrivateHomeCommand extends HomeCommand {
return;
}
plugin.getCommand(HomeListCommand.class)
.ifPresent(command -> command.showHomeList(executor, user.getUsername(), 1));
.ifPresent(command -> command.showHomeList(executor, user.getName(), 1));
return;
}
super.execute(executor, args);
@@ -26,10 +26,14 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
public class PublicHomeCommand extends HomeCommand implements TabProvider {
public class PublicHomeCommand extends HomeCommand implements TabCompletable {
protected PublicHomeCommand(@NotNull HuskHomes plugin) {
super("phome", List.of("publichome"), PositionCommandType.PUBLIC_HOME, plugin);
super(
List.of("phome", "publichome"),
PositionCommandType.PUBLIC_HOME,
plugin
);
}
@Override
@@ -35,7 +35,11 @@ import java.util.stream.Collectors;
public class PublicHomeListCommand extends ListCommand {
protected PublicHomeListCommand(@NotNull HuskHomes plugin) {
super("phomelist", List.of("phomes", "publichomelist"), "[page]", plugin);
super(
List.of("phomelist", "phomes", "publichomelist"),
"[page]",
plugin
);
}
@Override
@@ -75,7 +79,7 @@ public class PublicHomeListCommand extends ListCommand {
.filter(h -> h.getName().equals(home.getName())).count() > 1
? home.getSafeIdentifier() : Locales.escapeText(home.getName()),
home.getSafeIdentifier(),
Locales.escapeText(home.getOwner().getUsername()),
Locales.escapeText(home.getOwner().getName()),
home.getMeta().getDescription().isBlank()
? plugin.getLocales().getNone()
: Locales.escapeText(home.getMeta().getDescription())
@@ -37,12 +37,16 @@ import java.util.Map;
import java.util.Optional;
import java.util.Random;
public class RTPCommand extends Command implements UserListTabProvider {
public class RtpCommand extends Command implements UserListTabCompletable {
private final Random random = new Random();
protected RTPCommand(@NotNull HuskHomes plugin) {
super("rtp", List.of(), "[player] [world]", plugin);
protected RtpCommand(@NotNull HuskHomes plugin) {
super(
List.of("rtp"),
"[player] [world]",
plugin
);
addAdditionalPermissions(Map.of(
"other", true
@@ -75,8 +79,9 @@ public class RTPCommand extends Command implements UserListTabProvider {
@Override
public List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
return switch (args.length) {
case 0, 1 -> user.hasPermission(getPermission("other")) ? UserListTabProvider.super.suggestLocal(args)
: user instanceof OnlineUser online ? List.of(online.getUsername()) : List.of();
case 0, 1 -> user.hasPermission(getPermission("other"))
? UserListTabCompletable.super.suggest(user, args)
: user instanceof OnlineUser online ? List.of(online.getName()) : List.of();
case 2 -> plugin.getWorlds().stream()
.filter(world -> !plugin.getSettings().getRtp().isWorldRtpRestricted(world))
.map(World::getName)
@@ -148,19 +153,20 @@ public class RTPCommand extends Command implements UserListTabProvider {
.ifPresent(teleporter::sendMessage);
if (plugin.getSettings().getRtp().isCrossServer() && plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
&& plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
List<String> allowedServers = plugin.getSettings().getRtp().getRandomTargetServers();
String randomServer = allowedServers.get(random.nextInt(allowedServers.size()));
if (randomServer.equals(plugin.getServerName())) {
performLocalRTP(teleporter, executor, world, args);
return;
}
Message.builder()
plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.Type.REQUEST_RTP_LOCATION)
.scope(Message.Scope.SERVER)
.target(randomServer)
.payload(Payload.withRTPRequest(Payload.RTPRequest.of(teleporter.getUsername(), world.getName())))
.build().send(plugin.getMessenger(), teleporter);
.payload(Payload.withRTPRequest(Payload.RTPRequest.of(teleporter.getName(), world.getName())))
.build().send(b, teleporter));
return;
}
@@ -171,9 +177,9 @@ public class RTPCommand extends Command implements UserListTabProvider {
* Performs the RTP locally.
*
* @param teleporter person to teleport
* @param executor the person executing the teleport
* @param world the world to teleport to
* @param args rtp engine args
* @param executor the person executing the teleport
* @param world the world to teleport to
* @param args rtp engine args
*/
private void performLocalRTP(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull World world,
@NotNull String[] args) {
@@ -33,15 +33,15 @@ import org.jetbrains.annotations.NotNull;
import java.util.*;
public abstract class SavedPositionCommand<T extends SavedPosition> extends Command implements TabProvider {
public abstract class SavedPositionCommand<T extends SavedPosition> extends Command implements TabCompletable {
protected final List<String> arguments;
protected final PositionCommandType positionType;
protected SavedPositionCommand(@NotNull String name, @NotNull List<String> aliases,
protected SavedPositionCommand(@NotNull List<String> aliases,
@NotNull PositionCommandType positionType,
@NotNull List<String> arguments, @NotNull HuskHomes plugin) {
super(name, aliases, "<name>" + formatUsage(arguments), plugin);
super(aliases, "<name>" + formatUsage(arguments), plugin);
this.positionType = positionType;
this.arguments = arguments;
@@ -98,7 +98,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
return Optional.empty();
}
final Optional<Home> optionalHome = plugin.getDatabase().getUserDataByName(ownerUsername)
final Optional<Home> optionalHome = plugin.getDatabase().getUser(ownerUsername)
.flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHome));
if (optionalHome.isEmpty()) {
plugin.getLocales().getLocale(executor.hasPermission(getOtherPermission())
@@ -243,7 +243,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
yield plugin.getManager().homes().getUserHomeIdentifiers();
}
if (executor instanceof OnlineUser user) {
yield plugin.getManager().homes().getUserHomes().get(user.getUsername());
yield plugin.getManager().homes().getUserHomes().get(user.getName());
}
yield plugin.getManager().homes().getUserHomeIdentifiers();
}
@@ -32,7 +32,10 @@ import java.util.Optional;
public class SetHomeCommand extends SetPositionCommand {
protected SetHomeCommand(@NotNull HuskHomes plugin) {
super("sethome", plugin);
super(
List.of("sethome"),
plugin
);
}
@Override
@@ -28,8 +28,8 @@ import java.util.Optional;
public abstract class SetPositionCommand extends InGameCommand {
protected SetPositionCommand(@NotNull String name, @NotNull HuskHomes plugin) {
super(name, List.of(), "<name>", plugin);
protected SetPositionCommand(@NotNull List<String> aliases, @NotNull HuskHomes plugin) {
super(aliases, "<name>", plugin);
}
@Override
@@ -32,7 +32,11 @@ import static net.william278.huskhomes.config.Settings.CrossServerSettings.Globa
public class SetSpawnCommand extends InGameCommand {
protected SetSpawnCommand(@NotNull HuskHomes plugin) {
super("setspawn", List.of(), "", plugin);
super(
List.of("setspawn"),
"",
plugin
);
setOperatorCommand(true);
}
@@ -24,10 +24,15 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class SetWarpCommand extends SetPositionCommand {
protected SetWarpCommand(@NotNull HuskHomes plugin) {
super("setwarp", plugin);
super(
List.of("setwarp"),
plugin
);
setOperatorCommand(true);
}
@@ -34,7 +34,11 @@ import java.util.Optional;
public class SpawnCommand extends Command {
protected SpawnCommand(@NotNull HuskHomes plugin) {
super("spawn", List.of(), "[player]", plugin);
super(
List.of("spawn"),
"[player]",
plugin
);
addAdditionalPermissions(Map.of("other", true));
}
@@ -25,7 +25,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface TabProvider {
public interface TabCompletable {
@Nullable
List<String> suggest(@NotNull CommandUser user, @NotNull String[] args);
@@ -33,13 +33,17 @@ import java.util.List;
public class TpAllCommand extends InGameCommand {
protected TpAllCommand(@NotNull HuskHomes plugin) {
super("tpall", List.of(), "", plugin);
super(
List.of("tpall"),
"",
plugin
);
setOperatorCommand(true);
}
@Override
public void execute(@NotNull OnlineUser executor, @NotNull String[] args) {
if (plugin.getGlobalPlayerList().size() <= 1) {
if (plugin.getGlobalUserList().size() <= 1) {
plugin.getLocales().getLocale("error_no_players_online")
.ifPresent(executor::sendMessage);
return;
@@ -58,13 +62,11 @@ public class TpAllCommand extends InGameCommand {
return;
}
if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder()
.target(Message.TARGET_ALL)
.type(Message.Type.TELEPORT_TO_POSITION)
.payload(Payload.withPosition(targetPosition))
.build().send(plugin.getMessenger(), executor);
}
plugin.getBroker().ifPresent(b -> Message.builder()
.target(Message.TARGET_ALL)
.type(Message.Type.TELEPORT_TO_POSITION)
.payload(Payload.withPosition(targetPosition))
.build().send(b, executor));
plugin.getLocales().getLocale("teleporting_all_players")
.ifPresent(executor::sendMessage);
@@ -25,16 +25,22 @@ import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.*;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
public class TpCommand extends Command implements TabProvider {
public class TpCommand extends Command implements TabCompletable {
protected TpCommand(@NotNull HuskHomes plugin) {
super("tp", List.of("tpo"), "[<player|position>] [target]", plugin);
super(
List.of("tp", "tpo"),
"[<player|position>] [target]",
plugin
);
addAdditionalPermissions(Map.of("coordinates", true, "other", true));
setOperatorCommand(true);
}
@@ -89,7 +95,7 @@ public class TpCommand extends Command implements TabProvider {
// Determine teleporter and target names, validate permissions
final @Nullable String targetName = target instanceof Username username ? username.name()
: target instanceof OnlineUser online ? online.getUsername() : null;
: target instanceof OnlineUser online ? online.getName() : null;
if (executor instanceof OnlineUser online) {
if (online.equals(teleporter)) {
if (teleporter.getUsername().equalsIgnoreCase(targetName)) {
@@ -136,7 +142,7 @@ public class TpCommand extends Command implements TabProvider {
((int) relative.getX() + " " + (int) relative.getY()),
((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ()))
: List.of());
completions.addAll(plugin.getPlayerList(false));
plugin.getUserList().stream().map(User::getName).forEach(completions::add);
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList());
@@ -155,7 +161,7 @@ public class TpCommand extends Command implements TabProvider {
: List.of()
);
if (user.hasPermission(getPermission("other"))) {
completions.addAll(plugin.getPlayerList(false));
plugin.getUserList().stream().map(User::getName).forEach(completions::add);
}
}
return completions.stream()
@@ -27,10 +27,14 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
public class TpHereCommand extends InGameCommand implements UserListTabProvider {
public class TpHereCommand extends InGameCommand implements UserListTabCompletable {
protected TpHereCommand(@NotNull HuskHomes plugin) {
super("tphere", List.of("tpohere"), "<player>", plugin);
super(
List.of("tphere", "tpohere"),
"<player>",
plugin
);
setOperatorCommand(true);
}
@@ -51,7 +55,7 @@ public class TpHereCommand extends InGameCommand implements UserListTabProvider
.target(executor.getPosition())
.buildAndComplete(false, target);
plugin.getLocales().getLocale("teleporting_other_complete", target, executor.getUsername());
plugin.getLocales().getLocale("teleporting_other_complete", target, executor.getName());
}
}
@@ -31,7 +31,11 @@ import java.util.List;
public class TpIgnoreCommand extends InGameCommand {
protected TpIgnoreCommand(@NotNull HuskHomes plugin) {
super("tpignore", List.of(), "", plugin);
super(
List.of("tpignore"),
"",
plugin
);
}
@Override
@@ -39,7 +43,7 @@ public class TpIgnoreCommand extends InGameCommand {
final RequestsManager manager = plugin.getManager().requests();
final boolean isIgnoringRequests = !manager.isIgnoringRequests(onlineUser);
plugin.editUserData(onlineUser, (SavedUser user) -> user.setIgnoringTeleports(isIgnoringRequests));
plugin.editSavedUser(onlineUser, (SavedUser user) -> user.setIgnoringTeleports(isIgnoringRequests));
plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"),
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
@@ -30,10 +30,15 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
public class TpOfflineCommand extends InGameCommand implements UserListTabProvider {
public class TpOfflineCommand extends InGameCommand implements UserListTabCompletable {
protected TpOfflineCommand(@NotNull HuskHomes plugin) {
super("tpoffline", List.of(), "<player>", plugin);
super(
List.of("tpoffline"),
"<player>",
plugin
);
setOperatorCommand(true);
}
@@ -47,7 +52,7 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid
}
final Optional<User> targetUserData = plugin.getDatabase()
.getUserDataByName(optionalUser.get())
.getUser(optionalUser.get())
.map(SavedUser::getUser);
if (targetUserData.isEmpty()) {
plugin.getLocales().getLocale("error_player_not_found", optionalUser.get())
@@ -61,12 +66,12 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid
private void teleportToOfflinePosition(@NotNull OnlineUser user, @NotNull User target, @NotNull String[] args) {
final Optional<Position> position = plugin.getDatabase().getOfflinePosition(target);
if (position.isEmpty()) {
plugin.getLocales().getLocale("error_no_offline_position", target.getUsername())
plugin.getLocales().getLocale("error_no_offline_position", target.getName())
.ifPresent(user::sendMessage);
return;
}
plugin.getLocales().getLocale("teleporting_offline_player", target.getUsername())
plugin.getLocales().getLocale("teleporting_offline_player", target.getName())
.ifPresent(user::sendMessage);
Teleport.builder(plugin)
.teleporter(user)
@@ -29,13 +29,17 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
public class TeleportRequestCommand extends InGameCommand implements UserListTabProvider {
public class TpRequestCommand extends InGameCommand implements UserListTabCompletable {
private final TeleportRequest.Type requestType;
protected TeleportRequestCommand(@NotNull HuskHomes plugin, @NotNull TeleportRequest.Type requestType) {
super(requestType == TeleportRequest.Type.TPA ? "tpa" : "tpahere", List.of(), "<player>", plugin);
this.requestType = requestType;
protected TpRequestCommand(@NotNull HuskHomes plugin, @NotNull TeleportRequest.Type type) {
super(
List.of(type == TeleportRequest.Type.TPA ? "tpa" : "tpahere"),
"<player>",
plugin
);
this.requestType = type;
}
@Override
@@ -56,7 +60,7 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab
// Ensure the user does not send a request to themselves
final String target = optionalTarget.get();
if (target.equalsIgnoreCase(onlineUser.getUsername())) {
if (target.equalsIgnoreCase(onlineUser.getName())) {
plugin.getLocales().getLocale("error_teleport_request_self")
.ifPresent(onlineUser::sendMessage);
return;
@@ -30,14 +30,14 @@ import java.util.Optional;
* A command used for responding to tp requests - can either be a /tpaccept or /tpdecline command, controlled by the
* acceptRequestCommand flag.
*/
public class TpRespondCommand extends InGameCommand implements UserListTabProvider {
public class TpRespondCommand extends InGameCommand implements UserListTabCompletable {
private final boolean accept;
protected TpRespondCommand(@NotNull HuskHomes plugin, boolean accept) {
super(
accept ? "tpaccept" : "tpdecline",
accept ? List.of("tpyes") : List.of("tpno", "tpdeny"),
accept ? List.of("tpaccept", "tpyes")
: List.of("tpdecline", "tpno", "tpdeny"),
"[player]",
plugin
);
@@ -28,13 +28,13 @@ import java.util.List;
public class TpaAllCommand extends InGameCommand {
protected TpaAllCommand(@NotNull HuskHomes plugin) {
super("tpaall", List.of(), "", plugin);
super(List.of("tpaall"), "", plugin);
setOperatorCommand(true);
}
@Override
public void execute(@NotNull OnlineUser executor, @NotNull String[] args) {
if (plugin.getGlobalPlayerList().size() <= 1) {
if (plugin.getGlobalUserList().size() <= 1) {
plugin.getLocales().getLocale("error_no_players_online")
.ifPresent(executor::sendMessage);
return;
@@ -21,22 +21,18 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface UserListTabProvider extends TabProvider {
public interface UserListTabCompletable extends TabCompletable {
@Override
@Nullable
default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
return args.length < 2 ? getPlugin().getPlayerList(false) : null;
}
@Nullable
default List<String> suggestLocal(@NotNull String[] args) {
return args.length < 2 ? getPlugin().getLocalPlayerList(false) : null;
return args.length < 2 ? getPlugin().getUserList().stream().map(User::getName).toList() : null;
}
@NotNull
@@ -33,7 +33,12 @@ import java.util.Optional;
public class WarpCommand extends SavedPositionCommand<Warp> {
protected WarpCommand(@NotNull HuskHomes plugin) {
super("warp", List.of(), PositionCommandType.WARP, List.of(), plugin);
super(
List.of("warp"),
PositionCommandType.WARP,
List.of(),
plugin
);
addAdditionalPermissions(Map.of("player", true));
}
@@ -34,7 +34,11 @@ import java.util.stream.Collectors;
public class WarpListCommand extends ListCommand {
protected WarpListCommand(@NotNull HuskHomes plugin) {
super("warplist", List.of("warps"), "[player] [page]", plugin);
super(
List.of("warplist", "warps"),
"[player] [page]",
plugin
);
}
@Override
@@ -89,7 +93,7 @@ public class WarpListCommand extends ListCommand {
private List<Warp> getItems(@NotNull CommandUser executor) {
List<Warp> warps = plugin.getDatabase().getWarps();
if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()
&& !executor.hasPermission(Warp.getWildcardPermission())) {
&& !executor.hasPermission(Warp.getWildcardPermission())) {
warps = warps.stream().filter(warp -> executor.hasPermission(warp.getPermission())).toList();
}
return warps;
@@ -47,7 +47,7 @@ public class Locales {
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits
┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
┣╸ Formatted in MineDown: https://github.com/WiIIiam278/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""";
protected static final String DEFAULT_LOCALE = "en-gb";
@@ -19,11 +19,12 @@
package net.william278.huskhomes.database;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.SavedPosition;
@@ -33,80 +34,162 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Instant;
import java.util.*;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* An abstract representation of the plugin database, storing home, warp and player data.
*
* <p>Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator.
*/
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class Database {
protected final HuskHomes plugin;
protected HuskHomes plugin;
/**
* Loads SQL table creation schema statements from a resource file as a string array.
*
* @param schemaFileName database script resource file to load from
* @return Array of string-formatted table creation schema statements
* @throws IOException if the resource could not be read
*/
protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException {
return formatStatementTables(
new String(Objects.requireNonNull(plugin.getResource(schemaFileName)).readAllBytes(),
StandardCharsets.UTF_8))
.split(";");
}
@Getter
@Setter
private boolean loaded;
/**
* Format all table name placeholder strings in an SQL statement.
*
* @param sql the SQL statement with unformatted table name placeholders
* @return the formatted statement, with table placeholders replaced with the correct names
*/
protected final String formatStatementTables(@NotNull String sql) {
final Settings.DatabaseSettings settings = plugin.getSettings().getDatabase();
return sql
.replaceAll("%positions_table%", settings
.getTableName(Table.POSITION_DATA))
.replaceAll("%players_table%", settings
.getTableName(Table.PLAYER_DATA))
.replaceAll("%cooldowns_table%", settings
.getTableName(Table.PLAYER_COOLDOWNS_DATA))
.replaceAll("%teleports_table%", settings
.getTableName(Table.TELEPORT_DATA))
.replaceAll("%saved_positions_table%", settings
.getTableName(Table.SAVED_POSITION_DATA))
.replaceAll("%homes_table%", settings
.getTableName(Table.HOME_DATA))
.replaceAll("%warps_table%", settings
.getTableName(Table.WARP_DATA));
}
/**
* Create a database instance, pulling table names from the plugin config.
*
* @param plugin the implementing plugin instance
*/
protected Database(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/**
* Initialize the database and ensure tables are present; create tables if they do not exist.
* Get the schema statements from the schema file.
*
* @return the {@link #format formatted} schema statements
*/
@NotNull
protected final String[] getScript(@NotNull String name) {
name = (name.startsWith("database/") ? "" : "database/") + name + (name.endsWith(".sql") ? "" : ".sql");
try (InputStream file = Objects.requireNonNull(plugin.getResource(name), "Invalid script %s".formatted(name))) {
@Language("SQL") final String schema = new String(file.readAllBytes(), StandardCharsets.UTF_8);
return format(schema).split(";");
} catch (IOException e) {
plugin.log(Level.SEVERE, "Failed to load database schema", e);
}
return new String[0];
}
protected abstract void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException;
/**
* Format a string for use in an SQL query.
*
* @param statement The SQL statement to format
* @return The formatted SQL statement
*/
@NotNull
protected final String format(@NotNull @Language("SQL") String statement) {
final Pattern pattern = Pattern.compile("%(\\w+)%");
final Matcher matcher = pattern.matcher(statement);
final StringBuilder sb = new StringBuilder();
while (matcher.find()) {
final Table table = Table.match(matcher.group(1));
matcher.appendReplacement(sb, plugin.getSettings().getDatabase().getTableName(table));
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* Backup a flat file database.
*
* @param file the file to back up
*/
protected final void backupFlatFile(@NotNull Path file) {
if (!file.toFile().exists()) {
return;
}
final Path backup = file.getParent().resolve(String.format("%s.bak", file.getFileName().toString()));
try {
final File backupFile = backup.toFile();
if (!backupFile.exists() || backupFile.delete()) {
Files.copy(file, backup);
}
} catch (IOException e) {
plugin.log(Level.WARNING, "Failed to backup flat file database", e);
}
}
/**
* Initialize the database connection.
*
* @throws IllegalStateException if the database initialization fails
*/
public abstract void initialize() throws IllegalStateException;
/**
* Check if the database has been created.
*
* @return {@code true} if the database has been created; {@code false} otherwise
*/
public abstract boolean isCreated();
/**
* Perform database migrations.
*
* @param connection the database connection
* @throws SQLException if an SQL error occurs during migration
*/
protected final void performMigrations(@NotNull Connection connection, @NotNull Type type) throws SQLException {
final int currentVersion = getSchemaVersion();
final int latestVersion = Migration.getLatestVersion();
if (currentVersion < latestVersion) {
plugin.log(Level.INFO, "Performing database migrations (Target version: v" + latestVersion + ")");
for (Migration migration : Migration.getOrderedMigrations()) {
if (!migration.isSupported(type)) {
continue;
}
if (migration.getVersion() > currentVersion) {
try {
plugin.log(Level.INFO, "Performing database migration: " + migration.getMigrationName()
+ " (v" + migration.getVersion() + ")");
executeScript(connection, "migrations/%s-%s-%s.sql".formatted(
migration.getVersion(),
type.name().toLowerCase(Locale.ENGLISH),
migration.getMigrationName()
));
} catch (SQLException e) {
plugin.log(Level.WARNING, "Migration " + migration.getMigrationName()
+ " (v" + migration.getVersion() + ") failed; skipping", e);
}
}
}
setSchemaVersion(latestVersion);
plugin.log(Level.INFO, "Completed database migration (Target version: v" + latestVersion + ")");
}
}
/**
* Get the database schema version.
*
* @return the database schema version
*/
public abstract int getSchemaVersion();
/**
* Set the database schema version.
*
* @param version the database schema version
*/
public abstract void setSchemaVersion(int version);
/**
* <b>(Internal use only)</b> - Sets a position to the position table in the database.
*
@@ -166,7 +249,7 @@ public abstract class Database {
* @param name Username of the {@link SavedUser} to get (<i>case-insensitive</i>)
* @return An optional with the {@link SavedUser} present if they exist
*/
public abstract Optional<SavedUser> getUserDataByName(@NotNull String name);
public abstract Optional<SavedUser> getUser(@NotNull String name);
/**
* Get {@link SavedUser} for a user by their Minecraft account {@link UUID}.
@@ -174,14 +257,14 @@ public abstract class Database {
* @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get
* @return An optional with the {@link SavedUser} present if they exist
*/
public abstract Optional<SavedUser> getUserData(@NotNull UUID uuid);
public abstract Optional<SavedUser> getUser(@NotNull UUID uuid);
/**
* Delete a {@link SavedUser} from the database.
*
* @param uuid The {@link UUID} of the {@link SavedUser} to delete
*/
public abstract void deleteUserData(@NotNull UUID uuid);
public abstract void deleteUser(@NotNull UUID uuid);
/**
* Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
@@ -479,10 +562,9 @@ public abstract class Database {
public abstract int deleteAllWarps(@NotNull String worldName, @NotNull String serverName);
/**
* Close any remaining connection to the database source.
* Close the database connection.
*/
public abstract void terminate();
public abstract void close();
/**
* Identifies types of databases.
@@ -506,6 +588,7 @@ public abstract class Database {
@Getter
@AllArgsConstructor
public enum Table {
META_DATA("huskhomes_metadata"),
PLAYER_DATA("huskhomes_users"),
PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"),
POSITION_DATA("huskhomes_position_data"),
@@ -514,8 +597,19 @@ public abstract class Database {
WARP_DATA("huskhomes_warps"),
TELEPORT_DATA("huskhomes_teleports");
@NotNull
private final String defaultName;
@NotNull
public static Database.Table match(@NotNull String placeholder) throws IllegalArgumentException {
return Table.valueOf(placeholder.toUpperCase(Locale.ENGLISH));
}
@NotNull
public String getDefaultName() {
return defaultName;
}
@NotNull
public static Map<Table, String> getConfigMap() {
return Arrays.stream(values()).collect(
@@ -524,4 +618,49 @@ public abstract class Database {
}
}
/**
* Represents database migrations that need to be run.
*/
public enum Migration {
ADD_METADATA_TABLE(
0, "add_metadata_table",
Type.MYSQL, Type.MARIADB, Type.POSTGRESQL, Type.SQLITE, Type.H2
);
private final int version;
private final String migrationName;
private final Type[] supportedTypes;
Migration(int version, @NotNull String migrationName, @NotNull Type... supportedTypes) {
this.version = version;
this.migrationName = migrationName;
this.supportedTypes = supportedTypes;
}
private int getVersion() {
return version;
}
private String getMigrationName() {
return migrationName;
}
private boolean isSupported(@NotNull Type type) {
return Arrays.stream(supportedTypes).anyMatch(supportedType -> supportedType == type);
}
@NotNull
public static List<Migration> getOrderedMigrations() {
return Arrays.stream(Migration.values())
.sorted(Comparator.comparingInt(Migration::getVersion))
.collect(Collectors.toList());
}
public static int getLatestVersion() {
return getOrderedMigrations().get(getOrderedMigrations().size() - 1).getVersion();
}
}
}
@@ -0,0 +1,74 @@
/*
* 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.database;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
public interface DatabaseProvider {
@NotNull
String DATA_POOL_NAME = "HuskHomesHikariPool";
@NotNull
Database getDatabase();
void setDatabase(@NotNull Database database);
void closeDatabase();
default void loadDatabase() throws IllegalStateException {
// Create database instance
final Database database = createDatabase();
// Initialize database
database.initialize();
if (!database.isLoaded()) {
throw new IllegalStateException("Failed to initialize database");
}
// Set database
setDatabase(database);
}
@NotNull
private Database createDatabase() {
final Database.Type type = getPlugin().getSettings().getDatabase().getType();
switch (type) {
case MYSQL, MARIADB -> {
return new MySqlDatabase(getPlugin());
}
case POSTGRESQL -> {
return new PostgreSqlDatabase(getPlugin());
}
case SQLITE -> {
return new SqLiteDatabase(getPlugin());
}
case H2 -> {
return new H2Database(getPlugin());
}
default -> throw new IllegalStateException("Unexpected value: " + type);
}
}
@NotNull
HuskHomes getPlugin();
}
@@ -31,8 +31,7 @@ import org.h2.jdbcx.JdbcConnectionPool;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.sql.*;
import java.time.Instant;
import java.util.*;
@@ -47,7 +46,7 @@ public class H2Database extends Database {
/**
* Path to the H2 HuskHomesData.h2 file.
*/
private final File databaseFile;
private final Path databaseFile;
/**
* The name of the database file.
@@ -58,7 +57,7 @@ public class H2Database extends Database {
public H2Database(@NotNull HuskHomes plugin) {
super(plugin);
this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile();
this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME);
}
/**
@@ -71,29 +70,112 @@ public class H2Database extends Database {
return connectionPool.getConnection();
}
@SuppressWarnings("SqlSourceToSinkFlow")
@Override
public void initialize() throws IllegalStateException {
protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException {
try (Statement statement = connection.createStatement()) {
for (String schemaStatement : getScript(name)) {
statement.execute(schemaStatement);
}
}
}
@Override
public void initialize() throws RuntimeException {
// Backup database file
this.backupFlatFile(databaseFile);
// Prepare the database flat file
final String url = String.format("jdbc:h2:%s", databaseFile.getAbsolutePath());
final String url = String.format("jdbc:h2:%s", databaseFile.toAbsolutePath());
this.connectionPool = JdbcConnectionPool.create(url, "sa", "sa");
// Prepare database schema; make tables if they don't exist
try (Connection connection = getConnection()) {
final String[] databaseSchema = getSchemaStatements("database/h2_schema.sql");
try (Statement statement = connection.createStatement()) {
for (String tableCreationStatement : databaseSchema) {
statement.execute(tableCreationStatement);
}
// Create tables
if (!isCreated()) {
plugin.log(Level.INFO, "Creating H2 database tables");
try {
executeScript(getConnection(), "h2_schema.sql");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to create H2 database tables");
setLoaded(false);
return;
}
} catch (SQLException | IOException e) {
throw new IllegalStateException("Failed to initialize the H2 database", e);
setSchemaVersion(Migration.getLatestVersion());
plugin.log(Level.INFO, "H2 database tables created!");
setLoaded(true);
return;
}
// Perform migrations
try {
performMigrations(getConnection(), Type.H2);
setLoaded(true);
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to perform H2 database migrations");
setLoaded(false);
}
}
@Override
public boolean isCreated() {
if (!databaseFile.toFile().exists()) {
return false;
}
try (PreparedStatement statement = getConnection().prepareStatement(format("""
SELECT `uuid`
FROM `%player_data%`
LIMIT 1;"""))) {
statement.executeQuery();
return true;
} catch (SQLException e) {
return false;
}
}
@Override
public int getSchemaVersion() {
try (PreparedStatement statement = getConnection().prepareStatement(format("""
SELECT `schema_version`
FROM `%meta_data%`
LIMIT 1;"""))) {
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("schema_version");
}
} catch (SQLException e) {
plugin.log(Level.WARNING, "The database schema version could not be fetched; "
+ "migrations will be carried out.");
}
return -1;
}
@Override
public void setSchemaVersion(int version) {
if (getSchemaVersion() == -1) {
try (PreparedStatement insertStatement = getConnection().prepareStatement(format("""
INSERT INTO `%meta_data%` (`schema_version`)
VALUES (?);"""))) {
insertStatement.setInt(1, version);
insertStatement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to insert schema version in table", e);
}
return;
}
try (PreparedStatement statement = getConnection().prepareStatement(format("""
UPDATE `%meta_data%`
SET `schema_version` = ?;"""))) {
statement.setInt(1, version);
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update schema version in table", e);
}
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%positions_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%position_data%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
@@ -120,8 +202,8 @@ public class H2Database extends Database {
@Override
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%positions_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
UPDATE `%position_data%`
SET `x`=?,
`y`=?,
`z`=?,
@@ -147,8 +229,8 @@ public class H2Database extends Database {
@Override
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%saved_positions_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%saved_position_data%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
@@ -172,9 +254,9 @@ public class H2Database extends Database {
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement selectStatement = connection.prepareStatement(format("""
SELECT `position_id`
FROM `%saved_positions_table%`
FROM `%saved_position_data%`
WHERE `id`=?;"""))) {
selectStatement.setInt(1, savedPositionId);
@@ -183,8 +265,8 @@ public class H2Database extends Database {
final int positionId = resultSet.getInt("position_id");
updatePosition(positionId, position, connection);
try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
UPDATE `%saved_positions_table%`
try (PreparedStatement updateStatement = connection.prepareStatement(format("""
UPDATE `%saved_position_data%`
SET `name`=?,
`description`=?,
`tags`=?
@@ -201,23 +283,23 @@ public class H2Database extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(
getUser(onlineUser.getUuid()).ifPresentOrElse(
existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
if (!existingUserData.getUsername().equals(onlineUser.getName())) {
// Update a player's name if it has changed in the database
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
UPDATE `%player_data%`
SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, onlineUser.getUsername());
statement.setString(1, onlineUser.getName());
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
+ "'s name in the database (" + existingUserData.getUsername()
+ " -> " + onlineUser.getUsername() + ")");
plugin.log(Level.INFO, "Updated " + onlineUser.getName()
+ "'s name in the database (" + existingUserData.getUsername()
+ " -> " + onlineUser.getName() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -226,12 +308,12 @@ public class H2Database extends Database {
() -> {
// Insert new player data into the database
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%players_table%` (`uuid`,`username`)
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%player_data%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.getUuid().toString());
statement.setString(2, onlineUser.getUsername());
statement.setString(2, onlineUser.getName());
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -241,11 +323,11 @@ public class H2Database extends Database {
}
@Override
public Optional<SavedUser> getUserDataByName(@NotNull String name) {
public Optional<SavedUser> getUser(@NotNull String name) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
FROM `%players_table%`
FROM `%player_data%`
WHERE `username`=?"""))) {
statement.setString(1, name);
@@ -266,11 +348,11 @@ public class H2Database extends Database {
}
@Override
public Optional<SavedUser> getUserData(@NotNull UUID uuid) {
public Optional<SavedUser> getUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
FROM `%players_table%`
FROM `%player_data%`
WHERE `uuid`=?"""))) {
statement.setString(1, uuid.toString());
@@ -292,22 +374,22 @@ public class H2Database extends Database {
}
@Override
public void deleteUserData(@NotNull UUID uuid) {
public void deleteUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
// Delete Position
PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `id`
IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
(SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""));
IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?),
(SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?),
(SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));"""));
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
statement.executeUpdate();
statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
statement = connection.prepareStatement(format("""
DELETE FROM `%player_data%`
WHERE `uuid`=?;"""));
statement.setString(1, uuid.toString());
statement.executeUpdate();
@@ -320,9 +402,9 @@ public class H2Database extends Database {
@Override
public Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `type`, `start_timestamp`, `end_timestamp`
FROM `%cooldowns_table%`
FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?
ORDER BY `start_timestamp` DESC
LIMIT 1;"""))) {
@@ -344,8 +426,8 @@ public class H2Database extends Database {
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, action.name().toLowerCase(Locale.ENGLISH));
@@ -361,8 +443,8 @@ public class H2Database extends Database {
@Override
public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%cooldowns_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?;"""))) {
statement.setString(1, user.getUuid().toString());
@@ -378,16 +460,16 @@ public class H2Database extends Database {
public List<Home> getHomes(@NotNull User user) {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`,
`timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
FROM `%home_data%`
INNER JOIN `%saved_position_data%`
ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
INNER JOIN `%player_data%`
ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
@@ -413,7 +495,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName());
}
return userHomes;
}
@@ -422,14 +504,14 @@ public class H2Database extends Database {
public List<Warp> getWarps() {
final List<Warp> warps = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
FROM `%warp_data%`
INNER JOIN `%saved_position_data%`
ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -459,17 +541,17 @@ public class H2Database extends Database {
public List<Home> getPublicHomes() {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`,
`description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`,
`server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
FROM `%home_data%`
INNER JOIN `%saved_position_data%`
ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
INNER JOIN `%player_data%`
ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -502,17 +584,17 @@ public class H2Database extends Database {
public List<Home> getPublicHomes(@NotNull String name, boolean caseInsensitive) {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`,
`description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`,
`server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
FROM `%home_data%`
INNER JOIN `%saved_position_data%`
ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%positions_table`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
INNER JOIN `%players_table`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))
ORDER BY `name`;"""))) {
@@ -549,17 +631,17 @@ public class H2Database extends Database {
@Override
public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
FROM `%home_data%`
INNER JOIN `%saved_position_data%`
ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
INNER JOIN `%player_data%`
ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -595,18 +677,18 @@ public class H2Database extends Database {
@Override
public Optional<Home> getHome(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `%homes_table%`.`uuid`=?;"""))) {
FROM `%home_data%`
INNER JOIN `%saved_position_data%`
ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
INNER JOIN `%player_data%`
ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `%home_data%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -638,14 +720,14 @@ public class H2Database extends Database {
@Override
public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
FROM `%warp_data%`
INNER JOIN `%saved_position_data%`
ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -677,15 +759,15 @@ public class H2Database extends Database {
@Override
public Optional<Warp> getWarp(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
WHERE `%warps_table%`.uuid=?;"""))) {
FROM `%warp_data%`
INNER JOIN `%saved_position_data%`
ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%position_data%`
ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
WHERE `%warp_data%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -714,10 +796,10 @@ public class H2Database extends Database {
@Override
public Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type`
FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
FROM `%teleport_data%`
INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, onlineUser.getUuid().toString());
@@ -740,7 +822,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e);
} catch (TeleportationException e) {
e.displayMessage(onlineUser);
}
@@ -750,8 +832,8 @@ public class H2Database extends Database {
@Override
public void updateUserData(@NotNull SavedUser savedUser) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
UPDATE `%player_data%`
SET `home_slots`=?, `ignoring_requests`=?
WHERE `uuid`=?"""))) {
@@ -769,12 +851,12 @@ public class H2Database extends Database {
public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
try (Connection connection = getConnection()) {
// Clear the user's current teleport
try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `destination_id`
FROM `%teleports_table%`
WHERE `%teleports_table%`.`player_uuid`=?
FROM `%teleport_data%`
WHERE `%teleport_data%`.`player_uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -782,8 +864,8 @@ public class H2Database extends Database {
// Set the user's teleport into the database (if it's not null)
if (teleport != null) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%teleport_data%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition((Position) teleport.getTarget(), connection));
@@ -793,17 +875,17 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e);
}
}
@Override
public Optional<Position> getLastPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id`
FROM `%player_data%`
INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -820,7 +902,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -828,10 +910,10 @@ public class H2Database extends Database {
@Override
public void setLastPosition(@NotNull User user, @NotNull Position position) {
try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement queryStatement = connection.prepareStatement(format("""
SELECT `last_position`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
FROM `%player_data%`
INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -841,8 +923,8 @@ public class H2Database extends Database {
updatePosition(resultSet.getInt("last_position"), position, connection);
} else {
// Set the last position
try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
try (PreparedStatement updateStatement = connection.prepareStatement(format("""
UPDATE `%player_data%`
SET `last_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -852,17 +934,17 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e);
}
}
@Override
public Optional<Position> getOfflinePosition(@NotNull User user) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
FROM `%player_data%`
INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -879,7 +961,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -887,9 +969,9 @@ public class H2Database extends Database {
@Override
public void setOfflinePosition(@NotNull User user, @NotNull Position position) {
try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `offline_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
try (PreparedStatement queryStatement = connection.prepareStatement(format("""
SELECT `offline_position` FROM `%player_data%`
INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -899,8 +981,8 @@ public class H2Database extends Database {
updatePosition(resultSet.getInt("offline_position"), position, connection);
} else {
// Set the offline position
try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
try (PreparedStatement updateStatement = connection.prepareStatement(format("""
UPDATE `%player_data%`
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -910,17 +992,17 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e);
}
}
@Override
public Optional<Position> getRespawnPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id`
FROM `%player_data%`
INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -937,7 +1019,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -945,9 +1027,9 @@ public class H2Database extends Database {
@Override
public void setRespawnPosition(@NotNull User user, @Nullable Position position) {
try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `respawn_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
try (PreparedStatement queryStatement = connection.prepareStatement(format("""
SELECT `respawn_position` FROM `%player_data%`
INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -955,12 +1037,12 @@ public class H2Database extends Database {
if (resultSet.next()) {
if (position == null) {
// Delete a respawn position
try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `respawn_position`
FROM `%players_table%`
WHERE `%players_table%`.`uuid`=?
FROM `%player_data%`
WHERE `%player_data%`.`uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -972,8 +1054,8 @@ public class H2Database extends Database {
} else {
if (position != null) {
// Set a respawn position
try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
try (PreparedStatement updateStatement = connection.prepareStatement(format("""
UPDATE `%player_data%`
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -984,7 +1066,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e);
}
}
@@ -993,8 +1075,8 @@ public class H2Database extends Database {
getHome(home.getUuid()).ifPresentOrElse(presentHome -> {
try (Connection connection = getConnection()) {
// Update the home's saved position, including metadata
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%homes_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `saved_position_id` FROM `%home_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, home.getUuid().toString());
@@ -1005,8 +1087,8 @@ public class H2Database extends Database {
}
// Update the home privacy
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%homes_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
UPDATE `%home_data%`
SET `public`=?
WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic());
@@ -1015,12 +1097,12 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
"Failed to update a home in the database for " + home.getOwner().getUsername(), e);
"Failed to update a home in the database for " + home.getOwner().getName(), e);
}
}, () -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
@@ -1031,7 +1113,7 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().getUsername(), e);
"Failed to set a home to the database for " + home.getOwner().getName(), e);
}
});
}
@@ -1040,8 +1122,8 @@ public class H2Database extends Database {
public void saveWarp(@NotNull Warp warp) {
getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%`
try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `saved_position_id` FROM `%warp_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, warp.getUuid().toString());
@@ -1055,8 +1137,8 @@ public class H2Database extends Database {
}
}, () -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
try (PreparedStatement statement = connection.prepareStatement(format("""
INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) {
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
@@ -1072,14 +1154,14 @@ public class H2Database extends Database {
@Override
public void deleteHome(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id`=(
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `%position_data%`.`id`=(
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id`=(
FROM `%saved_position_data%`
WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
FROM `%homes_table%`
FROM `%home_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1095,14 +1177,14 @@ public class H2Database extends Database {
@Override
public int deleteAllHomes(@NotNull User user) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `%position_data%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
FROM `%saved_position_data%`
WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
FROM `%homes_table%`
FROM `%home_data%`
WHERE `owner_uuid`=?
)
);"""))) {
@@ -1111,7 +1193,7 @@ public class H2Database extends Database {
return statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e);
plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e);
}
return 0;
}
@@ -1119,14 +1201,14 @@ public class H2Database extends Database {
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `%position_data%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
FROM `%saved_position_data%`
WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
FROM `%homes_table%`
FROM `%home_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1138,7 +1220,7 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
+ serverName + " from the database", e);
+ serverName + " from the database", e);
}
return 0;
}
@@ -1146,14 +1228,14 @@ public class H2Database extends Database {
@Override
public void deleteWarp(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id`=(
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `%position_data%`.`id`=(
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id`=(
FROM `%saved_position_data%`
WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
FROM `%warps_table%`
FROM `%warp_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1169,14 +1251,14 @@ public class H2Database extends Database {
@Override
public int deleteAllWarps() {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `%position_data%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
FROM `%saved_position_data%`
WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
FROM `%warps_table%`
FROM `%warp_data%`
)
);"""))) {
return statement.executeUpdate();
@@ -1190,14 +1272,14 @@ public class H2Database extends Database {
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
try (PreparedStatement statement = connection.prepareStatement(format("""
DELETE FROM `%position_data%`
WHERE `%position_data%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
FROM `%saved_position_data%`
WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
FROM `%warps_table%`
FROM `%warp_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1209,13 +1291,13 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
+ serverName + " from the database", e);
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void terminate() {
public void close() {
if (connectionPool != null) {
connectionPool.dispose();
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -43,20 +43,21 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
/**
* Hook to display warps and public homes on <a href="https://github.com/BlueMap-Minecraft/BlueMap">BlueMap</a> maps.
*/
@PluginHook(
name = "BlueMap",
register = PluginHook.Register.ON_ENABLE
)
public class BlueMapHook extends MapHook {
private Map<String, MarkerSet> publicHomesMarkerSets;
private Map<String, MarkerSet> warpsMarkerSets;
public BlueMapHook(@NotNull HuskHomes plugin) {
super(plugin, "BlueMap");
super(plugin);
}
@Override
public void initialize() {
public void load() {
BlueMapAPI.onEnable(api -> {
this.publicHomesMarkerSets = new ConcurrentHashMap<>();
this.warpsMarkerSets = new ConcurrentHashMap<>();
@@ -81,7 +82,7 @@ public class BlueMapHook extends MapHook {
}
@Override
public void updateHome(@NotNull Home home) {
public void addHome(@NotNull Home home) {
if (!isValidPosition(home)) {
return;
}
@@ -121,7 +122,7 @@ public class BlueMapHook extends MapHook {
}
@Override
public void updateWarp(@NotNull Warp warp) {
public void addWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) {
return;
}
@@ -34,9 +34,10 @@ import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Hook to display warps and public homes on Dynmap.
*/
@PluginHook(
name = "Dynmap",
register = PluginHook.Register.ON_ENABLE
)
public class DynmapHook extends MapHook {
private static final String ICON_PATH = "/tiles/_markers_/";
@@ -48,11 +49,11 @@ public class DynmapHook extends MapHook {
private MarkerSet warpsMarkers;
public DynmapHook(@NotNull HuskHomes plugin) {
super(plugin, "Dynmap");
super(plugin);
}
@Override
public void initialize() {
public void load() {
DynmapCommonAPIListener.register(new DynmapCommonAPIListener() {
@Override
public void apiEnabled(@NotNull DynmapCommonAPI dynmapCommonAPI) {
@@ -76,7 +77,7 @@ public class DynmapHook extends MapHook {
}
@Override
public void updateHome(@NotNull Home home) {
public void addHome(@NotNull Home home) {
if (!isValidPosition(home)) {
return;
}
@@ -122,7 +123,7 @@ public class DynmapHook extends MapHook {
}
@Override
public void updateWarp(@NotNull Warp warp) {
public void addWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) {
return;
}
@@ -32,8 +32,8 @@ import java.util.Locale;
*/
public abstract class EconomyHook extends Hook {
protected EconomyHook(@NotNull HuskHomes plugin, @NotNull String hookName) {
super(plugin, hookName);
protected EconomyHook(@NotNull HuskHomes plugin) {
super(plugin);
}
/**
@@ -19,47 +19,35 @@
package net.william278.huskhomes.hook;
import com.google.common.base.Preconditions;
import lombok.Getter;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
/**
* A plugin hook, where HuskHomes hooks into another plugin.
*/
@Getter
public abstract class Hook {
/**
* The plugin that this hook is for.
*/
protected final HuskHomes plugin;
protected final PluginHook hook;
/**
* The name of the hook.
*/
protected final String name;
/**
* Construct a new {@link Hook}.
*
* @param plugin the {@link HuskHomes} instance
*/
protected Hook(@NotNull HuskHomes plugin, @NotNull String name) {
protected Hook(@NotNull HuskHomes plugin) {
this.plugin = plugin;
this.name = name;
this.hook = getClass().getAnnotation(PluginHook.class);
Preconditions.checkNotNull(hook, "Hook class must be annotated with PluginHook");
}
/**
* Initialize the hook and return {@code true} if it could be enabled.
*/
public abstract void initialize();
/**
* Get the name of the hook.
*
* @return the name of the hook
*/
@NotNull
public String getName() {
return name;
return hook.name();
}
}
@NotNull
public PluginHook.Register getRegister() {
return hook.register();
}
public abstract void load();
public abstract void unload();
}
@@ -0,0 +1,120 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* 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.hook;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.importer.Importer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
public interface HookProvider extends MapHookProvider {
@NotNull
Set<Hook> getHooks();
default <H extends Hook> Optional<H> getHook(@NotNull Class<H> hookClass) {
return getHooks().stream()
.filter(hook -> hookClass.isAssignableFrom(hook.getClass()))
.map(hookClass::cast)
.findFirst();
}
@NotNull
@Unmodifiable
default Set<Importer> getImporters() {
return getHooks().stream()
.filter(hook -> hook instanceof Importer)
.map(hook -> (Importer) hook)
.collect(Collectors.toSet());
}
default Optional<Importer> getImporterByName(@NotNull String name) {
return getImporters().stream()
.filter(i -> i.getName().toLowerCase(Locale.ENGLISH).equals(name.toLowerCase(Locale.ENGLISH)))
.findFirst();
}
void setHooks(@NotNull Set<Hook> hooks);
default void loadHooks() {
setHooks(Sets.newHashSet(getAvailableHooks()));
}
default void registerHooks(@NotNull PluginHook.Register... register) {
final Set<PluginHook.Register> registers = Arrays.stream(register).collect(Collectors.toSet());
getHooks().removeIf(hook -> {
if (!registers.contains(hook.getRegister())) {
return false;
}
try {
hook.load();
return false;
} catch (Throwable e) {
getPlugin().log(Level.SEVERE, "Failed to register the %s hook".formatted(hook.getName()), e);
}
return true;
});
getPlugin().log(Level.INFO, "Registered '%s' hooks".formatted(registers.stream()
.map(h -> h.name().toLowerCase(Locale.ENGLISH)).collect(Collectors.joining(" & "))));
}
default void unloadHooks() {
getHooks().removeIf(hook -> {
try {
hook.unload();
} catch (Throwable e) {
getPlugin().log(Level.SEVERE, "Failed to unload the %s hook".formatted(hook.getName()), e);
}
return true;
});
}
@NotNull
default List<Hook> getAvailableHooks() {
final List<Hook> hooks = Lists.newArrayList();
if (getPlugin().getSettings().getMapHook().isEnabled()) {
if (isDependencyAvailable("Dynmap")) {
getHooks().add(new DynmapHook(getPlugin()));
} else if (isDependencyAvailable("BlueMap")) {
getHooks().add(new BlueMapHook(getPlugin()));
} else if (isDependencyAvailable("Pl3xMap")) {
getHooks().add(new Pl3xMapHook(getPlugin()));
}
}
if (isDependencyAvailable("Plan")) {
getHooks().add(new PlanHook(getPlugin()));
}
return hooks;
}
boolean isDependencyAvailable(@NotNull String name);
@NotNull
HuskHomes getPlugin();
}
@@ -40,8 +40,14 @@ public abstract class MapHook extends Hook {
protected static final String WARP_MARKER_IMAGE_NAME = "warp";
protected static final String PUBLIC_HOME_MARKER_IMAGE_NAME = "public-home";
protected MapHook(@NotNull HuskHomes plugin, @NotNull String name) {
super(plugin, name);
protected MapHook(@NotNull HuskHomes plugin) {
super(plugin);
}
@Override
public void unload() {
getPlugin().getWorlds().forEach(world -> clearHomes(world.getName()));
clearWarps();
}
/**
@@ -52,12 +58,12 @@ public abstract class MapHook extends Hook {
if (settings.isShowPublicHomes()) {
plugin.getDatabase()
.getLocalPublicHomes(plugin)
.forEach(this::updateHome);
.forEach(this::addHome);
}
if (settings.isShowWarps()) {
plugin.getDatabase()
.getLocalWarps(plugin)
.forEach(this::updateWarp);
.forEach(this::addWarp);
}
}
@@ -66,7 +72,7 @@ public abstract class MapHook extends Hook {
*
* @param home the home to update
*/
public abstract void updateHome(@NotNull Home home);
public abstract void addHome(@NotNull Home home);
/**
* Removes a home from the map.
@@ -94,7 +100,7 @@ public abstract class MapHook extends Hook {
*
* @param warp the warp to update
*/
public abstract void updateWarp(@NotNull Warp warp);
public abstract void addWarp(@NotNull Warp warp);
/**
* Removes a warp from the map.
@@ -191,7 +197,7 @@ public abstract class MapHook extends Hook {
protected static MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail) {
final MarkerInformationPopup popup = MarkerInformationPopup.create(home.getName())
.thumbnail(thumbnail)
.field("Owner", home.getOwner().getUsername())
.field("Owner", home.getOwner().getName())
.field("Location", home.toString())
.field("Command", "/phome " + home.getSafeIdentifier());
if (!home.getMeta().getDescription().isBlank()) {
@@ -0,0 +1,77 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* 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.hook;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Set;
import java.util.stream.Collectors;
public interface MapHookProvider {
@NotNull
@Unmodifiable
default Set<MapHook> getMapHooks() {
return getHooks().stream()
.filter(hook -> hook instanceof MapHook)
.map(hook -> (MapHook) hook)
.collect(Collectors.toSet());
}
default void addMappedHome(@NotNull Home home) {
getMapHooks().forEach(h -> h.addHome(home));
}
default void removeMappedHome(@NotNull Home home) {
getMapHooks().forEach(h -> h.removeHome(home));
}
default void removeAllMappedHomes(@NotNull String worldName) {
getMapHooks().forEach(h -> h.clearHomes(worldName));
}
default void removeAllMappedHomes(@NotNull User user) {
getMapHooks().forEach(h -> h.clearHomes(user));
}
default void addMappedWarp(@NotNull Warp warp) {
getMapHooks().forEach(h -> h.addWarp(warp));
}
default void removeMappedWarp(@NotNull Warp warp) {
getMapHooks().forEach(h -> h.removeWarp(warp));
}
default void removeAllMappedWarps(@NotNull String worldName) {
getMapHooks().forEach(h -> h.clearWarps(worldName));
}
default void removeAllMappedWarps() {
getMapHooks().forEach(MapHook::clearWarps);
}
@NotNull
Set<Hook> getHooks();
}
@@ -62,11 +62,11 @@ public class Pl3xMapHook extends MapHook implements EventListener {
private final ConcurrentLinkedQueue<Warp> warps = new ConcurrentLinkedQueue<>();
public Pl3xMapHook(@NotNull HuskHomes plugin) {
super(plugin, "Pl3xMap");
super(plugin);
}
@Override
public void initialize() {
public void load() {
Pl3xMap.api().getEventRegistry().register(this);
if (Pl3xMap.api().isEnabled()) {
onPl3xMapEnabled(new Pl3xMapEnabledEvent());
@@ -74,7 +74,7 @@ public class Pl3xMapHook extends MapHook implements EventListener {
}
@Override
public void updateHome(@NotNull Home home) {
public void addHome(@NotNull Home home) {
publicHomes.remove(home);
if (isValidPosition(home)) {
publicHomes.add(home);
@@ -97,7 +97,7 @@ public class Pl3xMapHook extends MapHook implements EventListener {
}
@Override
public void updateWarp(@NotNull Warp warp) {
public void addWarp(@NotNull Warp warp) {
warps.remove(warp);
if (isValidPosition(warp)) {
warps.add(warp);
@@ -159,8 +159,8 @@ public class Pl3xMapHook extends MapHook implements EventListener {
// Update home positions
plugin.runAsync(() -> {
plugin.getDatabase().getLocalPublicHomes(plugin).forEach(this::updateHome);
plugin.getDatabase().getLocalWarps(plugin).forEach(this::updateWarp);
plugin.getDatabase().getLocalPublicHomes(plugin).forEach(this::addHome);
plugin.getDatabase().getLocalWarps(plugin).forEach(this::addWarp);
});
}
@@ -39,20 +39,17 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import java.util.logging.Level;
/**
* Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel.
*/
@PluginHook(
name = "Plan",
register = PluginHook.Register.ON_ENABLE
)
public class PlanHook extends Hook {
private final HuskHomes plugin;
public PlanHook(@NotNull HuskHomes plugin) {
super(plugin, "Plan");
this.plugin = plugin;
super(plugin);
}
@Override
public void initialize() {
public void load() {
if (!areAllCapabilitiesAvailable()) {
return;
}
@@ -60,6 +57,9 @@ public class PlanHook extends Hook {
handlePlanReload();
}
@Override
public void unload() {
}
private boolean areAllCapabilitiesAvailable() {
CapabilityService capabilities = CapabilityService.getInstance();
@@ -114,7 +114,7 @@ public class PlanHook extends Hook {
hidden = true
)
public boolean getHasUserData(@NotNull UUID uuid) {
return database.getUserData(uuid).isPresent();
return database.getUser(uuid).isPresent();
}
@NumberProvider(
@@ -126,7 +126,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public long getHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid)
return database.getUser(uuid)
.map(userData -> (long) database.getHomes(userData.getUser()).size())
.orElse(0L);
}
@@ -140,7 +140,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public long getPublicHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid)
return database.getUser(uuid)
.map(userData -> database.getHomes(userData.getUser()).stream()
.filter(Home::isPublic).count())
.orElse(0L);
@@ -155,7 +155,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public long getPurchasedHomeSlots(@NotNull UUID uuid) {
return database.getUserData(uuid)
return database.getUser(uuid)
.map(userData -> (long) userData.getHomeSlots())
.orElse(0L);
}
@@ -169,7 +169,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) {
return database.getUserData(uuid)
return database.getUser(uuid)
.map(SavedUser::isIgnoringTeleports)
.orElse(false);
}
@@ -183,7 +183,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public String getOfflinePosition(@NotNull UUID uuid) {
return database.getUserData(uuid)
return database.getUser(uuid)
.map(userData -> database.getOfflinePosition(userData.getUser())
.map(Position::toString)
.orElse(UNKNOWN_STRING))
@@ -0,0 +1,44 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* 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.hook;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface PluginHook {
@NotNull
String name();
@NotNull
Register register();
enum Register {
ON_LOAD,
ON_ENABLE
}
}
@@ -35,24 +35,27 @@ import java.util.logging.Level;
public abstract class Importer extends Hook {
protected final HuskHomes plugin;
private final String name;
private final List<ImportData> supportedImportData;
protected Importer(@NotNull String name, @NotNull List<ImportData> supportedData, @NotNull HuskHomes plugin) {
super(plugin, name + " Importer");
this.name = name;
protected Importer(@NotNull List<ImportData> supportedData, @NotNull HuskHomes plugin) {
super(plugin);
this.supportedImportData = supportedData;
this.plugin = plugin;
}
@Override
public void initialize() {
// No initialization required
public void load() {
// Empty
}
@Override
public void unload() {
// Empty
}
public final void start(@NotNull CommandUser user) {
final LocalDateTime startTime = LocalDateTime.now();
log(user, Level.INFO, "⌚ Starting " + name + " data import...");
log(user, Level.INFO, "⌚ Starting " + getName() + " data import...");
for (ImportData data : supportedImportData) {
try {
@@ -66,7 +69,7 @@ public abstract class Importer extends Hook {
}
final long timeTaken = startTime.until(LocalDateTime.now(), ChronoUnit.SECONDS);
log(user, Level.INFO, "✔ Completed import from " + name + " (took " + timeTaken + "s)");
log(user, Level.INFO, "✔ Completed import from " + getName() + " (took " + timeTaken + "s)");
}
protected abstract int importData(@NotNull ImportData importData) throws Throwable;
@@ -83,11 +86,6 @@ public abstract class Importer extends Hook {
plugin.log(level, message, e);
}
@NotNull
public String getImporterName() {
return name;
}
@NotNull
public List<ImportData> getSupportedImportData() {
return supportedImportData;
@@ -20,6 +20,8 @@
package net.william278.huskhomes.listener;
import de.themoep.minedown.adventure.MineDown;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BackCommand;
import net.william278.huskhomes.command.Command;
@@ -32,23 +34,22 @@ import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
/**
* A handler for when events take place.
*/
public class EventListener {
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class EventListener {
@NotNull
protected final HuskHomes plugin;
private final HuskHomes plugin;
protected EventListener(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
public abstract void register();
/**
* Handle when a {@link OnlineUser} joins the server.
@@ -67,7 +68,7 @@ public class EventListener {
// Synchronize the global player list
plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(
onlineUser, plugin.getLocalPlayerList()),
onlineUser, plugin.getOnlineUsers().stream().map(User::getName).toList()),
onlineUser, 40L
);
@@ -82,7 +83,7 @@ public class EventListener {
plugin.getManager().homes().cacheUserHomes(onlineUser);
// Set their ignoring requests state
plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> {
plugin.getDatabase().getUser(onlineUser.getUuid()).ifPresent(userData -> {
plugin.getSavedUsers().add(userData);
// Send a reminder message if they are still ignoring requests
@@ -111,10 +112,8 @@ public class EventListener {
// Update global lists
if (plugin.getSettings().getCrossServer().isEnabled()) {
final List<String> localPlayerList = plugin.getLocalPlayerList().stream()
.filter(player -> !player.equals(onlineUser.getUsername()))
.toList();
final List<String> localPlayerList = plugin.getOnlineUsers().stream().map(User::getName)
.filter(player -> !player.equals(onlineUser.getName())).toList();
if (plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
this.synchronizeGlobalPlayerList(onlineUser, localPlayerList);
return;
@@ -125,6 +124,9 @@ public class EventListener {
.findAny()
.ifPresent(player -> this.synchronizeGlobalPlayerList(player, localPlayerList));
}
// Remove from user map
plugin.getOnlineUserMap().remove(onlineUser.getUuid());
});
}
@@ -164,7 +166,7 @@ public class EventListener {
if (bedPosition.isEmpty()) {
plugin.getSpawn().ifPresent(spawn -> {
if (plugin.getSettings().getCrossServer().isEnabled()
&& !spawn.getServer().equals(plugin.getServerName())) {
&& !spawn.getServer().equals(plugin.getServerName())) {
plugin.runSyncDelayed(() -> Teleport.builder(plugin)
.teleporter(teleporter)
.target(spawn)
@@ -190,25 +192,27 @@ public class EventListener {
plugin.getDatabase().setRespawnPosition(teleporter, bedPosition.orElse(null));
}
// Synchronize the global player list
// Synchronize the global player list TODO CHECK
private void synchronizeGlobalPlayerList(@NotNull OnlineUser user, @NotNull List<String> localPlayerList) {
// Send this server's player list to all servers
Message.builder()
.type(Message.Type.PLAYER_LIST)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.payload(Payload.withStringList(localPlayerList))
.build().send(plugin.getMessenger(), user);
// Clear cached global player lists and request updated lists from all servers
if (plugin.getOnlineUsers().size() == 1) {
plugin.getGlobalPlayerList().clear();
plugin.getBroker().ifPresent(broker -> {
// Send this server's player list to all servers
Message.builder()
.type(Message.Type.REQUEST_PLAYER_LIST)
.type(Message.Type.PLAYER_LIST)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.build().send(plugin.getMessenger(), user);
}
.payload(Payload.withStringList(localPlayerList))
.build().send(broker, user);
// Clear cached global player lists and request updated lists from all servers
if (plugin.getOnlineUsers().size() == 1) {
plugin.getGlobalUserList().clear();
Message.builder()
.type(Message.Type.REQUEST_PLAYER_LIST)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.build().send(broker, user);
}
});
}
/**
@@ -233,7 +237,7 @@ public class EventListener {
// Display the return by death via /back notification
final boolean canReturnByDeath = plugin.getCommand(BackCommand.class)
.map(command -> onlineUser.hasPermission(command.getPermission())
&& onlineUser.hasPermission(command.getPermission("death")))
&& onlineUser.hasPermission(command.getPermission("death")))
.orElse(false);
if (plugin.getSettings().getGeneral().getBackCommand().isReturnByDeath() && canReturnByDeath) {
plugin.getLocales().getLocale("return_by_death_notification")
@@ -288,7 +292,7 @@ public class EventListener {
return;
}
plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.getUuid())
plugin.runAsync(() -> plugin.getDatabase().getUser(onlineUser.getUuid())
.ifPresent(data -> plugin.getDatabase().setLastPosition(data.getUser(), sourcePosition)));
}
@@ -300,17 +304,15 @@ public class EventListener {
*/
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (!plugin.getSettings().getGeneral().isAlwaysRespawnAtSpawn()
&& plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().getCrossServer().isGlobalRespawning()) {
&& plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().getCrossServer().isGlobalRespawning()) {
plugin.getDatabase().setRespawnPosition(onlineUser, position);
}
}
/**
* Handle when the plugin is disabling (server is shutting down).
*/
public final void handlePluginDisable() {
plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion());
@NotNull
protected HuskHomes getPlugin() {
return plugin;
}
}
@@ -0,0 +1,34 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.listener;
import org.jetbrains.annotations.NotNull;
public interface ListenerProvider {
@NotNull
EventListener createListener();
default void loadListeners() {
createListener().register();
}
}
@@ -83,7 +83,7 @@ public class HomesManager {
public Map<String, List<String>> getPublicHomes() {
return publicHomes.stream().collect(
HashMap::new,
(m, e) -> m.put(e.getOwner().getUsername(), List.of(e.getName())),
(m, e) -> m.put(e.getOwner().getName(), List.of(e.getName())),
HashMap::putAll
);
}
@@ -123,7 +123,7 @@ public class HomesManager {
* @param user the user to cache homes for
*/
public void cacheUserHomes(@NotNull User user) {
userHomes.put(user.getUsername(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user)));
userHomes.put(user.getName(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user)));
}
/**
@@ -133,17 +133,17 @@ public class HomesManager {
* @param propagate whether to propagate the cache update to other servers (if cross-server is enabled)
*/
public void cacheHome(@NotNull Home home, boolean propagate) {
userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> {
userHomes.computeIfPresent(home.getOwner().getName(), (k, v) -> {
v.remove(home);
v.add(home);
return v;
});
if (publicHomes.remove(home) && !home.isPublic()) {
plugin.getMapHook().ifPresent(hook -> hook.removeHome(home));
plugin.removeMappedHome(home);
}
if (home.isPublic()) {
publicHomes.add(home);
plugin.getMapHook().ifPresent(hook -> hook.updateHome(home));
plugin.addMappedHome(home);
}
plugin.getCommands().stream()
@@ -159,7 +159,7 @@ public class HomesManager {
userHomes.values().forEach(homes -> homes.removeIf(home -> home.getUuid().equals(homeId)));
publicHomes.removeIf(home -> {
if (home.getUuid().equals(homeId)) {
plugin.getMapHook().ifPresent(hook -> hook.removeHome(home));
plugin.removeMappedHome(home);
return true;
}
return false;
@@ -182,14 +182,13 @@ public class HomesManager {
* @param homeId the UUID of the home/warp to update
*/
private void propagateCacheUpdate(@NotNull UUID homeId) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_HOME)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.payload(Payload.withString(homeId.toString()))
.build().send(plugin.getMessenger(), user));
}
plugin.getBroker().ifPresent(b -> plugin.getOnlineUsers().stream().findAny()
.ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_HOME)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.payload(Payload.withString(homeId.toString()))
.build().send(b, user)));
}
public void updatePublicHomeCache() {
@@ -210,7 +209,7 @@ public class HomesManager {
}
// Validate the home name; throw an exception if invalid
plugin.getValidator().validateName(name);
plugin.validateName(name);
// Determine what the new home count would be & validate against user max homes
int homes = plugin.getDatabase().getHomes(owner).size() + (existingHome.isPresent() ? 0 : 1);
@@ -220,10 +219,10 @@ public class HomesManager {
// Validate against user home slots
final SavedUser savedOwner = plugin.getSavedUser(owner)
.or(() -> plugin.getDatabase().getUserData(owner.getUuid()))
.or(() -> plugin.getDatabase().getUser(owner.getUuid()))
.orElseThrow(() -> new IllegalStateException("User data not found for " + owner.getUuid()));
if (plugin.getSettings().getEconomy().isEnabled()
&& homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) {
&& homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) {
if (!buyAdditionalSlots || plugin.getEconomyHook().isEmpty() || !(owner instanceof OnlineUser online)) {
throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS);
}
@@ -233,7 +232,7 @@ public class HomesManager {
throw new ValidationException(ValidationException.Type.TRANSACTION_FAILED);
}
plugin.performTransaction(online, TransactionResolver.Action.ADDITIONAL_HOME_SLOT);
plugin.editUserData(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1));
plugin.editSavedUser(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1));
}
final Home home = existingHome
@@ -272,12 +271,12 @@ public class HomesManager {
public int deleteAllHomes(@NotNull User owner) {
final int deleted = plugin.getDatabase().deleteAllHomes(owner);
userHomes.computeIfPresent(owner.getUsername(), (k, v) -> {
userHomes.computeIfPresent(owner.getName(), (k, v) -> {
v.clear();
return v;
});
publicHomes.removeIf(h -> h.getOwner().getUuid().equals(owner.getUuid()));
plugin.getMapHook().ifPresent(hook -> hook.clearHomes(owner));
plugin.removeAllMappedHomes(owner);
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
.map(command -> (ListCommand) command)
@@ -293,7 +292,7 @@ public class HomesManager {
));
publicHomes.removeIf(h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName));
if (plugin.getSettings().getCrossServer().isEnabled() && serverName.equals(plugin.getServerName())) {
plugin.getMapHook().ifPresent(hook -> hook.clearHomes(worldName));
plugin.removeAllMappedHomes(worldName);
}
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
@@ -333,7 +332,7 @@ public class HomesManager {
if (plugin.getDatabase().getHome(home.getOwner(), newName).isPresent()) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
}
plugin.getValidator().validateName(newName);
plugin.validateName(newName);
home.getMeta().setName(newName);
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
@@ -350,7 +349,7 @@ public class HomesManager {
}
public void setHomeDescription(@NotNull Home home, @NotNull String description) {
plugin.getValidator().validateDescription(description);
plugin.validateDescription(description);
home.getMeta().setDescription(description);
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
@@ -54,12 +54,11 @@ public class Manager {
// Update caches on all servers
protected void propagateCacheUpdate() {
if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_CACHES)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.build().send(plugin.getMessenger(), user));
}
plugin.getBroker().ifPresent(b -> plugin.getOnlineUsers().stream()
.findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_CACHES)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.build().send(b, user)));
}
}
@@ -0,0 +1,39 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* 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.manager;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
public interface ManagerProvider {
default void loadManager() {
setManager(new Manager(getPlugin()));
}
@NotNull
Manager getManager();
void setManager(Manager manager);
@NotNull
HuskHomes getPlugin();
}
@@ -117,23 +117,21 @@ public class RequestsManager {
public void sendTeleportAllRequest(@NotNull OnlineUser requester) {
final long expiry = Instant.now().getEpochSecond()
+ plugin.getSettings().getGeneral().getTeleportRequestExpiryTime();
+ plugin.getSettings().getGeneral().getTeleportRequestExpiryTime();
final TeleportRequest request = new TeleportRequest(requester, TeleportRequest.Type.TPA_HERE, expiry);
for (OnlineUser onlineUser : plugin.getOnlineUsers()) {
if (onlineUser.equals(requester)) {
continue;
}
request.setRecipientName(onlineUser.getUsername());
request.setRecipientName(onlineUser.getName());
sendLocalTeleportRequest(request, onlineUser);
}
if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request))
.target(Message.TARGET_ALL)
.build().send(plugin.getMessenger(), requester);
}
plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request))
.target(Message.TARGET_ALL)
.build().send(b, requester));
}
/**
@@ -146,7 +144,7 @@ public class RequestsManager {
public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser,
@NotNull TeleportRequest.Type type) throws IllegalArgumentException {
final long expiry = Instant.now().getEpochSecond()
+ plugin.getSettings().getGeneral().getTeleportRequestExpiryTime();
+ plugin.getSettings().getGeneral().getTeleportRequestExpiryTime();
final TeleportRequest request = new TeleportRequest(requester, type, expiry);
final Optional<OnlineUser> localTarget = plugin.getOnlineUser(targetUser);
if (localTarget.isPresent()) {
@@ -164,11 +162,14 @@ public class RequestsManager {
// If the player couldn't be found locally, send the request cross-server
if (plugin.getSettings().getCrossServer().isEnabled()) {
request.setRecipientName(targetUser);
plugin.fireEvent(plugin.getSendTeleportRequestEvent(requester, request), (event -> Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request))
.target(targetUser)
.build().send(plugin.getMessenger(), requester)));
plugin.fireEvent(
plugin.getSendTeleportRequestEvent(requester, request),
(event -> plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.Type.TELEPORT_REQUEST)
.payload(Payload.withTeleportRequest(request))
.target(targetUser)
.build().send(b, requester)))
);
return;
}
throw new IllegalArgumentException("Player not found");
@@ -181,7 +182,7 @@ public class RequestsManager {
* @param recipient The online recipient of the request
*/
public void sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) {
request.setRecipientName(recipient.getUsername());
request.setRecipientName(recipient.getName());
// Silently ignore the request if the recipient is ignoring requests or is vanished
if (isIgnoringRequests(recipient) || recipient.isVanished()) {
@@ -201,7 +202,7 @@ public class RequestsManager {
plugin.fireEvent(plugin.getReceiveTeleportRequestEvent(recipient, request), (event -> {
addTeleportRequest(request, recipient);
plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere")
+ "_request_received", request.getRequesterName())
+ "_request_received", request.getRequesterName())
.ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
.ifPresent(recipient::sendMessage);
@@ -298,12 +299,12 @@ public class RequestsManager {
if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().getCrossServer().isEnabled()) {
Message.builder()
plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.Type.TELEPORT_REQUEST_RESPONSE)
.payload(Payload.withTeleportRequest(request))
.target(request.getRequesterName())
.build()
.send(plugin.getMessenger(), recipient);
.send(b, recipient));
} else {
plugin.getLocales().getLocale("error_teleport_request_sender_not_online")
.ifPresent(recipient::sendMessage);
@@ -21,7 +21,6 @@ package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.ListCommand;
import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.position.Position;
@@ -49,7 +48,7 @@ public class WarpsManager {
public void cacheWarp(@NotNull Warp warp, boolean propagate) {
warps.remove(warp);
warps.add(warp);
plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp));
plugin.addMappedWarp(warp);
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
@@ -63,7 +62,7 @@ public class WarpsManager {
public void unCacheWarp(@NotNull UUID warpId, boolean propagate) {
warps.removeIf(warp -> {
if (warp.getUuid().equals(warpId)) {
plugin.getMapHook().ifPresent(hook -> hook.removeWarp(warp));
plugin.removeMappedWarp(warp);
return true;
}
return false;
@@ -79,14 +78,13 @@ public class WarpsManager {
}
private void propagateCacheUpdate(@NotNull UUID warpId) {
if (plugin.getSettings().getCrossServer().isEnabled()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
.type(Message.Type.UPDATE_WARP)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.payload(Payload.withString(warpId.toString()))
.build().send(plugin.getMessenger(), user));
}
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> plugin.getBroker()
.ifPresent(b -> Message.builder()
.type(Message.Type.UPDATE_WARP)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.payload(Payload.withString(warpId.toString()))
.build().send(b, user)));
}
public void updateWarpCache() {
@@ -104,7 +102,7 @@ public class WarpsManager {
@NotNull
public List<String> getUsableWarps(@NotNull CommandUser user) {
if (!plugin.getSettings().getGeneral().isPermissionRestrictWarps()
|| user.hasPermission(Warp.getWildcardPermission())) {
|| user.hasPermission(Warp.getWildcardPermission())) {
return getWarps();
}
return warps.stream()
@@ -122,7 +120,7 @@ public class WarpsManager {
}
// Validate the home name; throw an exception if invalid
plugin.getValidator().validateName(name);
plugin.validateName(name);
final Warp warp = existingWarp
.map(existing -> {
@@ -158,7 +156,7 @@ public class WarpsManager {
public int deleteAllWarps() {
final int deleted = plugin.getDatabase().deleteAllWarps();
warps.clear();
plugin.getMapHook().ifPresent(MapHook::clearWarps);
plugin.removeAllMappedWarps();
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
.map(command -> (ListCommand) command)
@@ -171,7 +169,7 @@ public class WarpsManager {
final int deleted = plugin.getDatabase().deleteAllWarps(worldName, serverName);
warps.removeIf(warp -> warp.getServer().equals(serverName) && warp.getWorld().getName().equals(worldName));
if (plugin.getSettings().getCrossServer().isEnabled() && plugin.getServerName().equals(serverName)) {
plugin.getMapHook().ifPresent(hook -> hook.clearWarps(worldName));
plugin.removeAllMappedWarps(worldName);
}
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
@@ -209,7 +207,7 @@ public class WarpsManager {
if (plugin.getDatabase().getWarp(newName).isPresent()) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
}
plugin.getValidator().validateName(newName);
plugin.validateName(newName);
warp.getMeta().setName(newName);
plugin.getDatabase().saveWarp(warp);
this.cacheWarp(warp, true);
@@ -225,7 +223,7 @@ public class WarpsManager {
}
public void setWarpDescription(@NotNull Warp warp, @NotNull String description) {
plugin.getValidator().validateDescription(description);
plugin.validateDescription(description);
warp.getMeta().setDescription(description);
plugin.getDatabase().saveWarp(warp);
this.cacheWarp(warp, true);
@@ -27,6 +27,7 @@ import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.NotNull;
@@ -87,11 +88,11 @@ public abstract class Broker {
.type(Message.Type.PLAYER_LIST)
.scope(Message.Scope.SERVER)
.target(message.getSourceServer())
.payload(Payload.withStringList(plugin.getLocalPlayerList()))
.payload(Payload.withUserList(plugin.getOnlineUsers().stream().map(u -> (User) u).toList()))
.build().send(this, receiver);
case PLAYER_LIST -> message.getPayload()
.getStringList()
.ifPresent(players -> plugin.setPlayerList(message.getSourceServer(), players));
.getUserList()
.ifPresent(players -> plugin.setUserList(message.getSourceServer(), players));
case UPDATE_HOME -> message.getPayload().getString()
.map(UUID::fromString)
.ifPresent(homeId -> {
@@ -148,11 +149,11 @@ public abstract class Broker {
if (world.isEmpty()) {
plugin.log(Level.SEVERE, "%s requested a position in a world we don't have! World: %s"
.formatted(message.getSourceServer(), request.getWorldName()));
Message.builder()
plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.Type.RTP_LOCATION)
.target(request.getUsername())
.payload(Payload.empty())
.build().send(plugin.getMessenger(), request.getUsername());
.build().send(b, request.getUsername()));
return;
}
plugin.getRandomTeleportEngine().getRandomPosition(world.get(), null)
@@ -166,7 +167,7 @@ public abstract class Broker {
builder.payload(Payload.withRTPResponse(
Payload.RTPResponse.of(request.getUsername(), position.get())));
}
builder.build().send(plugin.getMessenger(), request.getUsername());
plugin.getBroker().ifPresent(b -> builder.build().send(b, request.getUsername()));
});
});
}
@@ -209,7 +210,11 @@ public abstract class Broker {
// Get the formatted channel ID for the broker
@NotNull
protected String getSubChannelId() {
final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor());
final String version = String.format(
"%s.%s",
plugin.getPluginVersion().getMajor(),
plugin.getPluginVersion().getMinor()
);
try {
return plugin.getKey(
plugin.getSettings().getCrossServer().getClusterId().toLowerCase(Locale.ENGLISH),
@@ -0,0 +1,53 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* 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.network;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public interface BrokerProvider {
Optional<Broker> getBroker();
void setBroker(@NotNull Broker broker);
void closeBroker();
void setupPluginMessagingChannels();
default void loadBroker() {
if (!getPlugin().getSettings().getCrossServer().isEnabled()) {
return;
}
switch (getPlugin().getSettings().getCrossServer().getBrokerType()) {
case REDIS -> setBroker(new RedisBroker(getPlugin()));
case PLUGIN_MESSAGE -> setBroker(new PluginMessageBroker(getPlugin()));
}
getBroker().ifPresent(Broker::initialize);
}
@NotNull
HuskHomes getPlugin();
}
@@ -70,7 +70,7 @@ public class Message {
}
public void send(@NotNull Broker broker, @NotNull OnlineUser sender) {
this.sender = sender.getUsername();
this.sender = sender.getName();
this.sourceServer = broker.getServer();
broker.send(this, sender);
}
@@ -21,10 +21,12 @@ package net.william278.huskhomes.network;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.NoArgsConstructor;
import lombok.Value;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -34,6 +36,7 @@ import java.util.Optional;
/**
* Represents a payload sent in a cross-server {@link Message}.
*/
@NoArgsConstructor
public class Payload {
@Nullable
@@ -68,6 +71,11 @@ public class Payload {
@SerializedName("string_list")
private List<String> stringList;
@Nullable
@Expose
@SerializedName("user_list")
private List<User> userList;
/**
* Returns an empty cross-server message payload.
*
@@ -137,6 +145,16 @@ public class Payload {
return payload;
}
/**
* A usr list field.
*/
@NotNull
public static Payload withUserList(@NotNull List<User> target) {
final Payload payload = new Payload();
payload.userList = target;
return payload;
}
/**
* An RTP Response field.
*/
@@ -157,9 +175,6 @@ public class Payload {
return payload;
}
private Payload() {
}
/**
* A position field.
*/
@@ -195,6 +210,13 @@ public class Payload {
return Optional.ofNullable(stringList);
}
/**
* A string list field.
*/
public Optional<List<User>> getUserList() {
return Optional.ofNullable(userList);
}
/**
* An RTP response.
*/
@@ -49,7 +49,7 @@ public class PluginMessageBroker extends Broker {
@Override
public void initialize() throws IllegalStateException {
plugin.initializePluginChannels();
plugin.setupPluginMessagingChannels();
}
public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) {
@@ -214,7 +214,7 @@ public class RedisBroker extends PluginMessageBroker {
if (message.getScope() == Message.Scope.PLAYER) {
broker.plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
|| online.getName().equals(message.getTarget()))
.forEach(receiver -> broker.handle(receiver, message));
return;
}
@@ -134,7 +134,7 @@ public class Home extends SavedPosition {
@NotNull
@Override
public String getSafeIdentifier() {
return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getSafeIdentifier();
return getOwner().getName() + IDENTIFIER_DELIMITER + super.getSafeIdentifier();
}
/**
@@ -148,7 +148,7 @@ public class Home extends SavedPosition {
@NotNull
@Override
public String getIdentifier() {
return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getIdentifier();
return getOwner().getName() + IDENTIFIER_DELIMITER + super.getIdentifier();
}
}
@@ -0,0 +1,49 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* 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.random;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
public interface RandomTeleportProvider {
/**
* The {@link RandomTeleportEngine} that manages random teleports.
*
* @return the {@link RandomTeleportEngine} implementation
*/
@NotNull
RandomTeleportEngine getRandomTeleportEngine();
/**
* Sets the {@link RandomTeleportEngine} to be used for processing random teleports.
*
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use
*/
void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine);
default void loadRandomTeleportEngine() {
setRandomTeleportEngine(new NormalDistributionEngine(getPlugin()));
}
@NotNull
HuskHomes getPlugin();
}
@@ -66,7 +66,7 @@ public class Teleport implements Completable {
this.async = plugin.getSettings().getGeneral().isTeleportAsync();
this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class)
.map(command -> executor.hasPermission(command.getPermission())
&& executor.hasPermission(command.getPermission("previous")))
&& executor.hasPermission(command.getPermission("previous")))
.orElse(false);
}
@@ -105,10 +105,10 @@ public class Teleport implements Completable {
if (plugin.getSettings().getCrossServer().isEnabled()) {
fireEvent((event) -> {
performTransactions();
Message.builder()
plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_POSITION)
.target(username.name())
.build().send(plugin.getMessenger(), executor);
.build().send(b, executor));
});
return;
}
@@ -124,7 +124,7 @@ public class Teleport implements Completable {
final Position target = (Position) this.target;
if (!plugin.getSettings().getCrossServer().isEnabled()
|| target.getServer().equals(plugin.getServerName())) {
|| target.getServer().equals(plugin.getServerName())) {
teleporter.teleportLocally(target, async);
this.displayTeleportingComplete(teleporter);
teleporter.handleInvulnerability();
@@ -132,7 +132,7 @@ public class Teleport implements Completable {
}
plugin.getDatabase().setCurrentTeleport(teleporter, this);
plugin.getMessenger().changeServer(teleporter, target.getServer());
plugin.getBroker().ifPresent(b -> b.changeServer(teleporter, target.getServer()));
});
}
@@ -142,14 +142,14 @@ public class Teleport implements Completable {
throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin);
}
fireEvent((event) -> {
fireEvent((event) -> plugin.getBroker().ifPresent(b -> {
performTransactions();
if (target instanceof Username username) {
Message.builder()
.type(Message.Type.TELEPORT_TO_NETWORKED_USER)
.target(teleporter.name())
.payload(Payload.withString(username.name()))
.build().send(plugin.getMessenger(), executor);
.build().send(b, executor);
return;
}
@@ -157,8 +157,8 @@ public class Teleport implements Completable {
.type(Message.Type.TELEPORT_TO_POSITION)
.target(teleporter.name())
.payload(Payload.withPosition((Position) target))
.build().send(plugin.getMessenger(), executor);
});
.build().send(b, executor);
}));
}
@NotNull
@@ -64,7 +64,7 @@ public class TeleportRequest {
* @param requester The user making the request
*/
public TeleportRequest(@NotNull OnlineUser requester, @NotNull TeleportRequest.Type type, final long expiryTime) {
this.setRequesterName(requester.getUsername());
this.setRequesterName(requester.getName());
this.setRequesterPosition(requester.getPosition());
this.setType(type);
this.setStatus(Status.PENDING);
@@ -36,7 +36,7 @@ public record Username(@NotNull String name) implements Teleportable, Target {
/**
* Search for a local {@link OnlineUser} by their name.
*
* <p>If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this
* <p>If a user by the name provided is on the {@link HuskHomes#getUserList() player list}, then this
* method will search for the user by exact name.
*
* <p>Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for
@@ -48,7 +48,8 @@ public record Username(@NotNull String name) implements Teleportable, Target {
*/
@NotNull
public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) {
return plugin.getPlayerList(true).stream().anyMatch(listedName -> listedName.equalsIgnoreCase(name))
return plugin.getUserList().stream()
.anyMatch((user) -> user.getName().equalsIgnoreCase(name))
? plugin.getOnlineUserExact(name) : plugin.getOnlineUser(name);
}
@@ -19,26 +19,26 @@
package net.william278.huskhomes.user;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.kyori.adventure.audience.Audience;
import org.jetbrains.annotations.NotNull;
@Getter
@AllArgsConstructor
public final class ConsoleUser implements CommandUser {
@NotNull
private final Audience audience;
public ConsoleUser(@NotNull Audience console) {
this.audience = console;
}
@Override
@NotNull
public Audience getAudience() {
return audience;
public static ConsoleUser wrap(@NotNull Audience audience) {
return new ConsoleUser(audience);
}
@Override
public boolean hasPermission(@NotNull String permission) {
return true;
}
}
@@ -63,7 +63,7 @@ public class SavedUser {
@NotNull
public String getUsername() {
return getUser().getUsername();
return getUser().getName();
}
@@ -37,13 +37,19 @@ public class User implements Comparable<User> {
private final UUID uuid;
@NotNull
private final String username;
private final String name;
@NotNull
public static User of(@NotNull UUID uuid, @NotNull String username) {
return new User(uuid, username);
}
@Deprecated(since = "4.8")
@NotNull
public String getUsername() {
return getName();
}
@Override
public boolean equals(@NotNull Object obj) {
if (obj instanceof User user) {
@@ -54,7 +60,7 @@ public class User implements Comparable<User> {
@Override
public int compareTo(@NotNull User o) {
return getUsername().compareTo(o.getUsername());
return getName().compareTo(o.getName());
}
}
@@ -0,0 +1,105 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.user;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* A provider for the plugin user list, tracking online users across the network.
*
* @since 4.8
*/
public interface UserProvider {
@NotNull
Map<UUID, OnlineUser> getOnlineUserMap();
@NotNull
Map<String, List<User>> getGlobalUserList();
@NotNull
Set<SavedUser> getSavedUsers();
@NotNull
OnlineUser getOnlineUser(@NotNull UUID uuid);
@NotNull
@Unmodifiable
default Collection<OnlineUser> getOnlineUsers() {
return getOnlineUserMap().values();
}
@NotNull
default List<User> getUserList() {
return Stream.concat(
getGlobalUserList().values().stream().flatMap(Collection::stream),
getOnlineUsers().stream().filter(o -> !o.isVanished())
).distinct().sorted().toList();
}
default void setUserList(@NotNull String server, @NotNull List<User> players) {
getGlobalUserList().values().forEach(list -> {
list.removeAll(players);
list.removeAll(getOnlineUsers());
});
getGlobalUserList().put(server, players);
}
default boolean isUserOnline(@NotNull User user) {
return getOnlineUserMap().containsKey(user.getUuid());
}
default Optional<OnlineUser> getOnlineUser(@NotNull String playerName) {
return getOnlineUserExact(playerName)
.or(() -> getOnlineUsers().stream()
.filter(user -> user.getName().toLowerCase().startsWith(playerName.toLowerCase()))
.findFirst());
}
default Optional<OnlineUser> getOnlineUserExact(@NotNull String playerName) {
return getOnlineUsers().stream()
.filter(user -> user.getName().equalsIgnoreCase(playerName))
.findFirst();
}
default Optional<SavedUser> getSavedUser(@NotNull User user) {
return getSavedUsers().stream()
.filter(savedUser -> savedUser.getUser().equals(user))
.findFirst();
}
default void editSavedUser(@NotNull User user, @NotNull Consumer<SavedUser> editor) {
getPlugin().runAsync(() -> getSavedUser(user)
.ifPresent(result -> {
editor.accept(result);
getPlugin().getDatabase().updateUserData(result);
}));
}
@NotNull
HuskHomes getPlugin();
}
@@ -0,0 +1,69 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.util;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.Audiences;
import net.kyori.adventure.platform.AudienceProvider;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Interface for providing the {@link ConsoleUser} and {@link Audiences} instances
*
* @since 4.8
*/
public interface AudiencesProvider {
/**
* Get the {@link Audiences} instance.
*
* @return the {@link Audiences} instance
* @since 4.8
*/
@NotNull
AudienceProvider getAudiences();
/**
* Get the {@link Audience} instance for the given {@link OnlineUser}.
*
* @param user the {@link OnlineUser} to get the {@link Audience} for
* @return the {@link Audience} instance
*/
@NotNull
default Audience getAudience(@NotNull UUID user) {
return getAudiences().player(user);
}
/**
* Get the {@link ConsoleUser} instance.
*
* @return the {@link ConsoleUser} instance
* @since 4.8
*/
@NotNull
default ConsoleUser getConsole() {
return ConsoleUser.wrap(getAudiences().console());
}
}
@@ -0,0 +1,98 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.util;
import net.william278.desertwell.util.UpdateChecker;
import net.william278.desertwell.util.Version;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.logging.Level;
public interface MetaProvider {
int SPIGOT_RESOURCE_ID = 83767;
/**
* Get the plugin {@link Version}.
*
* @return the plugin version
* @since 4.8
*/
@NotNull
Version getPluginVersion();
/**
* Get the plugin {@link UpdateChecker}.
*
* @return the plugin {@link UpdateChecker}
* @since 4.8
*/
@NotNull
default UpdateChecker getUpdateChecker() {
return UpdateChecker.builder()
.currentVersion(getPluginVersion())
.endpoint(UpdateChecker.Endpoint.SPIGOT)
.resource(Integer.toString(SPIGOT_RESOURCE_ID))
.build();
}
/**
* Check for updates and log a warning if an update is available.
*
* @since 4.8
*/
default void checkForUpdates() {
if (!getPlugin().getSettings().isCheckForUpdates()) {
return;
}
getUpdateChecker().check().thenAccept(checked -> {
if (checked.isUpToDate()) {
return;
}
getPlugin().log(Level.WARNING, String.format(
"A new version of HuskHomes is available: v%s (running v%s)",
checked.getLatestVersion(), getPluginVersion())
);
});
}
/**
* Get the server type.
*
* @return the server type
* @since 4.8
*/
@NotNull
String getServerType();
/**
* Get the Minecraft version.
*
* @return the Minecraft version
* @since 4.8
*/
@NotNull
Version getMinecraftVersion();
@NotNull
HuskHomes getPlugin();
}
@@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public interface SafetyResolver {
public interface SavePositionProvider {
int SEARCH_RADIUS = 2;
@@ -19,27 +19,18 @@
package net.william278.huskhomes.util;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import org.jetbrains.annotations.NotNull;
@AllArgsConstructor
public class Validator {
public interface TextValidator {
public static final int MAX_NAME_LENGTH = 16;
public static final int MAX_DESCRIPTION_LENGTH = 256;
int MAX_NAME_LENGTH = 16;
int MAX_DESCRIPTION_LENGTH = 256;
private final HuskHomes plugin;
/**
* Validate home and warp names.
*
* @param name The name to validate
* @throws ValidationException If the name is invalid
*/
public void validateName(@NotNull String name) throws ValidationException {
// Validate home and warp names
default void validateName(@NotNull String name) throws ValidationException {
if (!isValidNameCharacters(name)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID_CHARACTERS);
}
@@ -48,13 +39,8 @@ public class Validator {
}
}
/**
* Validate home and warp descriptions.
*
* @param description The description to validate
* @throws ValidationException If the description is invalid
*/
public void validateDescription(@NotNull String description) throws ValidationException {
// Validate home and warp descriptions.
default void validateDescription(@NotNull String description) throws ValidationException {
if (!isValidDescriptionCharacters(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID_CHARACTERS);
}
@@ -65,7 +51,7 @@ public class Validator {
// Check a home/warp name contains only valid characters
private boolean isValidNameCharacters(@NotNull String name) {
final Settings.GeneralSettings.NameSettings config = plugin.getSettings().getGeneral().getNames();
final Settings.GeneralSettings.NameSettings config = getSettings().getGeneral().getNames();
return (name.matches(config.getRegex()) || !config.isRestrict())
&& !name.contains("\u0000")
&& !containsWhitespace(name)
@@ -79,7 +65,7 @@ public class Validator {
// Check a home/warp description contains only valid characters
private boolean isValidDescriptionCharacters(@NotNull String description) {
final Settings.GeneralSettings.DescriptionSettings config = plugin.getSettings().getGeneral().getDescriptions();
final Settings.GeneralSettings.DescriptionSettings config = getSettings().getGeneral().getDescriptions();
return (description.matches(config.getRegex()) || !config.isRestrict())
&& !description.contains("\u0000");
}
@@ -93,5 +79,11 @@ public class Validator {
private boolean containsWhitespace(@NotNull String string) {
return string.matches(".*\\s.*");
}
@NotNull
HuskHomes getPlugin();
@NotNull
Settings getSettings();
}