New player list caching system, further refinements and fixes

This commit is contained in:
William committed 2023-03-21 12:49:36 +00:00
1 parent 054811676d
commit 93dd15007a
59 files changed
+445 -317

No files matched your search

@@ -50,8 +50,6 @@ import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -73,15 +71,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
private UnsafeBlocks unsafeBlocks;
private Set<PluginHook> pluginHooks;
private List<Command> commands;
private Map<String, List<String>> globalPlayerList;
private Server server;
@Nullable
private Broker broker;
// Adventure audience
private BukkitAudiences audiences;
// Instance of the plugin
private static BukkitHuskHomes instance;
public static BukkitHuskHomes getInstance() {
@@ -90,40 +85,37 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override
public void onLoad() {
// Set the instance
instance = this;
}
@Override
public void onEnable() {
// Initialize HuskHomes
final AtomicBoolean initialized = new AtomicBoolean(true);
// Create adventure audience
this.audiences = BukkitAudiences.create(this);
this.validator = new Validator(this);
this.manager = new Manager(this);
this.globalPlayerList = new HashMap<>();
// Load settings and locales
log(Level.INFO, "Loading plugin configuration settings & locales...");
initialized.set(reload());
if (initialized.get()) {
log(Level.INFO, "Successfully loaded plugin configuration settings & locales");
} else {
throw new IllegalStateException("Failed to load plugin configuration settings and/or locales");
}
initialize("plugin config & locale files", (plugin) -> {
if (!loadConfigs()) {
throw new IllegalStateException("Failed to load config files. Please check the console for errors");
}
});
// Initialize the database
log(Level.INFO, "Attempting to establish connection to the database...");
final Database.DatabaseType databaseType = settings.getDatabaseType();
this.database = switch (databaseType == null ? Database.DatabaseType.MYSQL : databaseType) {
case MYSQL -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this);
};
initialized.set(this.database.initialize());
if (initialized.get()) {
log(Level.INFO, "Successfully established a connection to the database");
} else {
throw new IllegalStateException("Failed to establish a connection to the database. " +
"Please check the supplied database credentials in the config file");
}
final Database.Type databaseType = getSettings().getDatabaseType();
initialize(databaseType.getDisplayName() + " database connection", (plugin) -> {
this.database = switch (databaseType) {
case MYSQL -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this);
};
if (!database.initialize()) {
throw new IllegalStateException("Failed to establish a connection to the database. " +
"Please check the supplied database credentials in the config file");
}
});
// Initialize the network messenger if proxy mode is enabled
if (getSettings().isCrossServer()) {
@@ -136,50 +128,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
});
}
// Prepare the validator
this.validator = new Validator(this);
this.cache = new Cache(this);
this.manager = new Manager(this);
// Initialize the RTP engine with the default normal distribution engine
this.cache = new Cache(this); // todo remove
setRandomTeleportEngine(new NormalDistributionEngine(this));
// Register plugin hooks (Economy, Maps, Plan)
initialize("hooks", (plugin) -> {
this.pluginHooks = new HashSet<>();
if (settings.doEconomy()) {
if (Bukkit.getPluginManager().getPlugin("RedisEconomy") != null) {
pluginHooks.add(new RedisEconomyHook(this));
} else if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
pluginHooks.add(new VaultEconomyHook(this));
}
}
if (settings.doMapHook()) {
switch (settings.getMappingPlugin()) {
case DYNMAP -> {
final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap");
if (dynmapPlugin != null) {
pluginHooks.add(new DynMapHook(this, dynmapPlugin));
}
}
case BLUEMAP -> {
if (Bukkit.getPluginManager().getPlugin("BlueMap") != null) {
pluginHooks.add(new BlueMapHook(this));
}
}
}
}
if (Bukkit.getPluginManager().getPlugin("Plan") != null) {
pluginHooks.add(new PlanHook(this));
}
if (pluginHooks.size() > 0) {
pluginHooks.forEach(PluginHook::initialize);
log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " + pluginHooks.stream()
.map(PluginHook::getHookName)
.collect(Collectors.joining(", ")));
}
});
initialize("hooks", (plugin) -> loadHooks());
// Register events
initialize("events", (plugin) -> this.eventListener = new BukkitEventListener(this));
@@ -199,22 +152,58 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
.filter(Objects::nonNull)
.collect(Collectors.toList()));
// Hook into bStats metrics
// Hook into bStats and check for updates
initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID));
// Check for updates
if (settings.doCheckForUpdates()) {
log(Level.INFO, "Checking for updates...");
getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getVersion() + ")")));
}
this.checkForUpdates();
}
private void initialize(@NotNull String name, @NotNull Consumer<HuskHomes> runner) {
private void initialize(@NotNull String name, @NotNull ThrowingConsumer<HuskHomes> runner) {
log(Level.INFO, "Initializing " + name + "...");
runner.accept(this);
try {
runner.accept(this);
} catch (Exception e) {
Bukkit.getPluginManager().disablePlugin(this);
throw new IllegalStateException("Failed to initialize " + name, e);
}
log(Level.INFO, "Successfully initialized " + name);
}
private void loadHooks() {
this.pluginHooks = new HashSet<>();
if (settings.doEconomy()) {
if (Bukkit.getPluginManager().getPlugin("RedisEconomy") != null) {
pluginHooks.add(new RedisEconomyHook(this));
} else if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
pluginHooks.add(new VaultEconomyHook(this));
}
}
if (settings.doMapHook()) {
switch (settings.getMappingPlugin()) {
case DYNMAP -> {
final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap");
if (dynmapPlugin != null) {
pluginHooks.add(new DynMapHook(this, dynmapPlugin));
}
}
case BLUEMAP -> {
if (Bukkit.getPluginManager().getPlugin("BlueMap") != null) {
pluginHooks.add(new BlueMapHook(this));
}
}
}
}
if (Bukkit.getPluginManager().getPlugin("Plan") != null) {
pluginHooks.add(new PlanHook(this));
}
if (pluginHooks.size() > 0) {
pluginHooks.forEach(PluginHook::initialize);
log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " + pluginHooks.stream()
.map(PluginHook::getHookName)
.collect(Collectors.joining(", ")));
}
}
@Override
public void onDisable() {
if (this.eventListener != null) {
@@ -325,7 +314,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
bukkitLocation.getWorld().setSpawnLocation(bukkitLocation);
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.WARNING, "Failed to save server spawn to disk", e);
log(Level.WARNING, "Failed to save the server spawn.yml file", e);
}
}
@@ -379,6 +368,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
return commands;
}
@Override
@NotNull
public Map<String, List<String>> getGlobalPlayerList() {
return globalPlayerList;
}
@Override
@NotNull
public String getServerName() {
@@ -395,7 +390,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
}
@Override
public boolean reload() {
public boolean loadConfigs() {
try {
// Load settings
this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get();
@@ -442,7 +437,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().getBrokerType().getDisplayName()));
}
metrics.addCustomChart(new SimplePie("language", () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().displayName));
metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().getDisplayName()));
metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().doEconomy())));
metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook())));
if (getSettings().doMapHook()) {
@@ -489,7 +484,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
}
// Super constructor for unit testing
@SuppressWarnings("unused")
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file);
}
@@ -1,12 +1,12 @@
package net.william278.huskhomes.api;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@@ -4,7 +4,10 @@ import me.lucko.commodore.CommodoreProvider;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.BukkitUser;
import org.bukkit.command.*;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
@@ -1,7 +1,7 @@
package net.william278.huskhomes.event;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@@ -3,9 +3,9 @@ package net.william278.huskhomes.hook;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.User;
import org.apache.commons.lang.StringEscapeUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
@@ -1,9 +1,9 @@
package net.william278.huskhomes.listener;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@@ -35,9 +35,19 @@ public interface BukkitTaskRunner extends TaskRunner {
return taskId.get();
}
@Override
default int runLater(@NotNull Runnable runnable, long delay) {
return Bukkit.getScheduler().runTaskLater((BukkitHuskHomes) getPlugin(), runnable, delay).getTaskId();
}
@Override
default void cancelTask(int taskId) {
Bukkit.getScheduler().cancelTask(taskId);
}
@Override
default void cancelAllTasks() {
Bukkit.getScheduler().cancelTasks((BukkitHuskHomes) getPlugin());
}
}
@@ -2,12 +2,9 @@ package net.william278.huskhomes;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* A cache used to hold frequently accessed data (i.e. TAB-completed homes and warps)
@@ -18,7 +15,6 @@ public class Cache {
private final Map<String, List<String>> homes = new HashMap<>();
private final Map<String, List<String>> publicHomes = new HashMap<>();
private final List<String> warps = new ArrayList<>();
private final Set<String> players = new HashSet<>();
private final Set<UUID> currentlyOnWarmup = new HashSet<>();
/**
@@ -43,22 +39,6 @@ public class Cache {
});
}
/**
* Updates the cached list of online players and returns it
*
* @param plugin the implementing plugin
*/
public CompletableFuture<Set<String>> updatePlayerListCache(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) {
getPlayers().clear();
getPlayers().addAll(plugin.getOnlineUsers()
.stream()
.filter(player -> !player.isVanished())
.map(User::getUsername)
.toList());
return CompletableFuture.completedFuture(getPlayers());
}
/**
* Returns if the given user is currently warming up to teleport to a home.
*
@@ -92,12 +72,6 @@ public class Cache {
return warps;
}
/**
* Cached player list
*/
public Set<String> getPlayers() {
return players;
}
/**
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
@@ -16,10 +16,13 @@ import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.TaskRunner;
import net.william278.huskhomes.util.Validator;
@@ -29,11 +32,10 @@ import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Stream;
/**
* Represents a cross-platform instance of the plugin
@@ -159,22 +161,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher {
: getLocalCachedSpawn().map(spawn -> spawn.getPosition(getServerName()));
}
/**
* Returns a future returning the latest plugin {@link Version} if the plugin is out-of-date
*
* @return a {@link CompletableFuture} returning the latest {@link Version} if the current one is out-of-date
*/
default CompletableFuture<Optional<Version>> getLatestVersionIfOutdated() {
final UpdateChecker updateChecker = UpdateChecker.create(getVersion(), SPIGOT_RESOURCE_ID);
return updateChecker.isUpToDate().thenApply(upToDate -> {
if (upToDate) {
return Optional.empty();
} else {
return Optional.of(updateChecker.getLatestVersion().join());
}
});
}
/**
* Update the {@link Spawn} position to a location on the server
*
@@ -330,12 +316,54 @@ public interface HuskHomes extends TaskRunner, EventDispatcher {
.map(type::cast);
}
@NotNull
Map<String, List<String>> getGlobalPlayerList();
@NotNull
default List<String> getPlayerList() {
return Stream.concat(
getGlobalPlayerList().values().stream().flatMap(Collection::stream),
getLocalPlayerList().stream()
).distinct().sorted().toList();
}
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() {
return getOnlineUsers().stream()
.map(OnlineUser::getUsername)
.toList();
}
/**
* Reloads the {@link Settings} and {@link Locales} from their respective config files
*
* @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful
*/
boolean reload();
boolean loadConfigs();
@NotNull
default UpdateChecker getUpdateChecker() {
return UpdateChecker.create(getVersion(), SPIGOT_RESOURCE_ID);
}
default void checkForUpdates() {
if (getSettings().doCheckForUpdates()) {
getUpdateChecker().isUpToDate().thenAccept(updated -> {
if (!updated) {
getUpdateChecker().getLatestVersion().thenAccept(latest -> log(Level.WARNING,
"A new version of HuskTowns is available: v" + latest + " (running v" + getVersion() + ")"));
}
});
}
}
/**
* Returns if the block, by provided identifier, is unsafe
@@ -386,5 +414,4 @@ public interface HuskHomes extends TaskRunner, EventDispatcher {
return new GsonBuilder().create();
}
}
@@ -10,8 +10,8 @@ import net.william278.huskhomes.random.RandomTeleportEngine;
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.user.SavedUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -2,7 +2,6 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.ConsoleUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -24,11 +23,6 @@ public abstract class Command extends Node implements TabProvider {
.ifPresent(executor::sendMessage);
return;
}
if (executor instanceof ConsoleUser && !isConsoleExecutable()) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
plugin.runAsync(() -> this.execute(executor, args));
}
@@ -2,6 +2,7 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.desertwell.AboutMenu;
import net.william278.desertwell.UpdateChecker;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.user.CommandUser;
@@ -14,13 +15,18 @@ import java.util.stream.Collectors;
public class HuskHomesCommand extends Command {
private static final List<String> SUB_COMMANDS = List.of("about", "help", "reload", "update");
private final UpdateChecker updateChecker;
private final AboutMenu aboutMenu;
protected HuskHomesCommand(@NotNull HuskHomes implementor) {
super("huskhomes", List.of(), "[" + String.join("|", SUB_COMMANDS) + "]", implementor);
protected HuskHomesCommand(@NotNull HuskHomes plugin) {
super("huskhomes", List.of(), "[" + String.join("|", SUB_COMMANDS) + "]", plugin);
setOperatorCommand(true);
this.updateChecker = plugin.getUpdateChecker();
this.aboutMenu = AboutMenu.create("HuskHomes")
.withDescription("A powerful, intuitive and flexible teleportation suite")
.withVersion(implementor.getVersion())
.withVersion(plugin.getVersion())
.addAttribution("Author",
AboutMenu.Credit.of("William278").withDescription("Click to visit website").withUrl("https://william278.net"))
.addAttribution("Contributors",
@@ -57,20 +63,22 @@ public class HuskHomesCommand extends Command {
case "help" -> executor.sendMessage(getCommandList(executor)
.getNearestValidPage(parseIntArg(args, 0).orElse(1)));
case "reload" -> {
if (!plugin.reload()) {
if (!plugin.loadConfigs()) {
executor.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"));
return;
}
executor.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) &#00fb9a&| Reloaded config & message files."));
}
case "update" -> plugin.getLatestVersionIfOutdated()
.thenAccept(newestVersion -> newestVersion.ifPresentOrElse(
newVersion -> executor.sendMessage(
new MineDown("[HuskHomes](#00fb9a bold) [| A new version of HuskHomes is available!"
+ " (v" + newVersion + " (Running: v" + plugin.getVersion() + ")](#00fb9a)")),
() -> executor.sendMessage(
new MineDown("[HuskHomes](#00fb9a bold) [| HuskHomes is up-to-date."
+ " (Running: v" + plugin.getVersion() + ")](#00fb9a)"))));
case "update" -> updateChecker.isUpToDate().thenAccept(upToDate -> {
if (upToDate) {
plugin.getLocales().getLocale("up_to_date", plugin.getVersion().toString())
.ifPresent(executor::sendMessage);
return;
}
updateChecker.getLatestVersion().thenAccept(latest -> plugin.getLocales()
.getLocale("update_available", latest.toString(), plugin.getVersion().toString())
.ifPresent(executor::sendMessage));
});
default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
}
@@ -97,10 +105,7 @@ public class HuskHomesCommand extends Command {
@Override
@NotNull
public List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
if (args.length < 2) {
return filter(SUB_COMMANDS, args);
}
return List.of();
return args.length < 2 ? SUB_COMMANDS : List.of();
}
}
@@ -5,7 +5,6 @@ import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
@@ -21,7 +20,6 @@ public abstract class Node implements Executable {
protected final HuskHomes plugin;
private final String name;
private final List<String> aliases;
private boolean consoleExecutable = false;
private boolean operatorCommand = false;
protected Node(@NotNull String name, @NotNull List<String> aliases, @NotNull HuskHomes plugin) {
@@ -43,10 +41,6 @@ public abstract class Node implements Executable {
return aliases;
}
public final boolean matchesInput(@NotNull String input) {
return input.equalsIgnoreCase(getName()) || getAliases().contains(input.toLowerCase());
}
@NotNull
public String getPermission(@NotNull String... child) {
return new StringJoiner(".")
@@ -56,21 +50,6 @@ public abstract class Node implements Executable {
.toString();
}
public boolean canPerform(@NotNull CommandUser user) {
if (user instanceof ConsoleUser) {
return isConsoleExecutable();
}
return user.hasPermission(getPermission());
}
public boolean isConsoleExecutable() {
return consoleExecutable;
}
public void setConsoleExecutable(boolean consoleExecutable) {
this.consoleExecutable = consoleExecutable;
}
public boolean isOperatorCommand() {
return operatorCommand;
}
@@ -10,7 +10,8 @@ import net.william278.huskhomes.user.User;
import net.william278.paginedown.PaginatedList;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class PrivateHomeListCommand extends ListCommand {
@@ -2,9 +2,9 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.paginedown.PaginatedList;
import org.jetbrains.annotations.NotNull;
@@ -66,7 +66,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
final Home home = optionalHome.get();
if (executor instanceof OnlineUser user && !home.isPublic() && !user.equals(home.getOwner())
&& !user.hasPermission(getOtherPermission())) {
&& !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_public_home_invalid",
splitHomeName[0], splitHomeName[1])
.ifPresent(executor::sendMessage);
@@ -91,8 +91,8 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
private Optional<Warp> resolveWarp(@NotNull CommandUser executor, @NotNull String warpName) {
final Optional<Warp> warp = plugin.getDatabase().getWarp(warpName);
if (warp.isPresent() && executor instanceof OnlineUser user && (plugin.getSettings().isPermissionRestrictWarps()
&& user.hasPermission(Warp.getWildcardPermission()) || user.hasPermission(Warp.getPermission(warpName)))) {
if (warp.isPresent() && executor instanceof OnlineUser user && plugin.getSettings().isPermissionRestrictWarps()
&& (!user.hasPermission(Warp.getWildcardPermission()) && !user.hasPermission(Warp.getPermission(warpName)))) {
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(executor::sendMessage);
return Optional.empty();
@@ -123,22 +123,30 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
@Override
@NotNull
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
return switch (args.length) {
case 0, 1 -> {
if (args.length == 1 && args[0].contains(".")) {
if (executor.hasPermission(getOtherPermission())) {
if (positionType == Home.class) {
return switch (args.length) {
case 0, 1 -> {
if (args.length == 1 && args[0].contains(".")) {
if (executor.hasPermission(getOtherPermission())) {
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
}
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
}
if (executor instanceof OnlineUser user) {
yield filter(plugin.getCache().getHomes().get(user.getUsername()), args);
}
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
}
if (executor instanceof OnlineUser user) {
yield filter(plugin.getCache().getHomes().get(user.getUsername()), args);
}
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
}
case 2 -> filter(arguments.stream().toList(), args);
default -> List.of();
};
case 2 -> filter(arguments.stream().toList(), args);
default -> List.of();
};
} else {
return switch (args.length) {
case 0, 1 -> filter(plugin.getCache().getWarps(), args);
case 2 -> filter(arguments.stream().toList(), args);
default -> List.of();
};
}
}
@NotNull
@@ -1,9 +1,9 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
@@ -12,6 +12,7 @@ public class SetSpawnCommand extends InGameCommand {
protected SetSpawnCommand(@NotNull HuskHomes plugin) {
super("setspawn", List.of(), "", plugin);
setOperatorCommand(true);
}
@Override
@@ -9,6 +9,7 @@ public class SetWarpCommand extends SetPositionCommand {
protected SetWarpCommand(@NotNull HuskHomes plugin) {
super("setwarp", plugin);
setOperatorCommand(true);
}
@Override
@@ -1,7 +1,6 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.ConsoleUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -29,15 +28,4 @@ public interface TabProvider {
.toList();
}
@NotNull
static List<String> getMatchingNames(@Nullable String argument, @NotNull CommandUser user,
@NotNull List<? extends Node> providers) {
return providers.stream()
.filter(command -> !(user instanceof ConsoleUser) || command.isConsoleExecutable())
.map(Node::getName)
.filter(commandName -> argument == null || argument.isBlank() || commandName.toLowerCase()
.startsWith(argument.toLowerCase().trim()))
.toList();
}
}
@@ -3,10 +3,9 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -15,6 +14,7 @@ public class TpAllCommand extends InGameCommand {
protected TpAllCommand(@NotNull HuskHomes plugin) {
super("tpall", List.of(), "", plugin);
setOperatorCommand(true);
}
@Override
@@ -1,19 +1,22 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
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.position.Position;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class TpCommand extends Command implements TabProvider {
protected TpCommand(@NotNull HuskHomes implementor) {
super("tp", List.of("tpo"), "[<player|position>] [target]", implementor);
setOperatorCommand(true);
}
@Override
@@ -85,7 +88,7 @@ public class TpCommand extends Command implements TabProvider {
((int) basePosition.getX() + " " + (int) basePosition.getY()),
((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ()))
: List.of());
completions.addAll(plugin.getCache().getPlayers());
completions.addAll(plugin.getPlayerList());
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList());
@@ -102,7 +105,7 @@ public class TpCommand extends Command implements TabProvider {
((int) basePosition.getX() + " " + (int) basePosition.getY()),
((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ()))
: List.of());
completions.addAll(plugin.getCache().getPlayers());
completions.addAll(plugin.getPlayerList());
}
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase()))
@@ -1,25 +1,19 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.teleport.Target;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class TpHereCommand extends InGameCommand implements UserListTabProvider {
protected TpHereCommand(@NotNull HuskHomes plugin) {
super("tphere", List.of("tpohere"), "<player>", plugin);
setOperatorCommand(true);
}
@Override
@@ -5,7 +5,6 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.manager.RequestsManager;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -16,6 +16,7 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid
protected TpOfflineCommand(@NotNull HuskHomes plugin) {
super("tpoffline", List.of(), "<player>", plugin);
setOperatorCommand(true);
}
@Override
@@ -1,25 +1,16 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.TeleportRequest;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
public class TpaAllCommand extends InGameCommand {
protected TpaAllCommand(@NotNull HuskHomes plugin) {
super("tpaall", List.of(), "", plugin);
setOperatorCommand(true);
}
@Override
@@ -5,18 +5,14 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public interface UserListTabProvider extends TabProvider {
@Override
@Nullable
default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
return args.length <= 1 ? getPlugin().getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
return args.length < 2 ? getPlugin().getPlayerList() : List.of();
}
@NotNull
@@ -4,7 +4,6 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -14,6 +13,7 @@ public class WarpCommand extends SavedPositionCommand<Warp> {
protected WarpCommand(@NotNull HuskHomes plugin) {
super("warp", List.of(), Warp.class, List.of(), plugin);
setOperatorCommand(true);
}
@Override
@@ -39,7 +39,7 @@ public class Settings {
// Database settings
@YamlComment("Database connection settings")
@YamlKey("database.type")
private Database.DatabaseType databaseType = Database.DatabaseType.SQLITE;
private Database.Type databaseType = Database.Type.SQLITE;
@YamlKey("database.mysql.credentials.host")
private String mySqlHost = "localhost";
@@ -77,17 +77,17 @@ public class Settings {
@YamlKey("database.table_names")
private Map<String, String> tableNames = Map.of(
Database.TableName.PLAYER_DATA.name().toLowerCase(), Database.TableName.PLAYER_DATA.getDefaultName(),
Database.TableName.POSITION_DATA.name().toLowerCase(), Database.TableName.POSITION_DATA.getDefaultName(),
Database.TableName.SAVED_POSITION_DATA.name().toLowerCase(), Database.TableName.SAVED_POSITION_DATA.getDefaultName(),
Database.TableName.HOME_DATA.name().toLowerCase(), Database.TableName.HOME_DATA.getDefaultName(),
Database.TableName.WARP_DATA.name().toLowerCase(), Database.TableName.WARP_DATA.getDefaultName(),
Database.TableName.TELEPORT_DATA.name().toLowerCase(), Database.TableName.TELEPORT_DATA.getDefaultName()
Database.Table.PLAYER_DATA.name().toLowerCase(), Database.Table.PLAYER_DATA.getDefaultName(),
Database.Table.POSITION_DATA.name().toLowerCase(), Database.Table.POSITION_DATA.getDefaultName(),
Database.Table.SAVED_POSITION_DATA.name().toLowerCase(), Database.Table.SAVED_POSITION_DATA.getDefaultName(),
Database.Table.HOME_DATA.name().toLowerCase(), Database.Table.HOME_DATA.getDefaultName(),
Database.Table.WARP_DATA.name().toLowerCase(), Database.Table.WARP_DATA.getDefaultName(),
Database.Table.TELEPORT_DATA.name().toLowerCase(), Database.Table.TELEPORT_DATA.getDefaultName()
);
@NotNull
public String getTableName(@NotNull Database.TableName tableName) {
return Optional.ofNullable(getTableNames().get(tableName.name().toLowerCase())).orElse(tableName.getDefaultName());
public String getTableName(@NotNull Database.Table table) {
return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getDefaultName());
}
@@ -275,7 +275,7 @@ public class Settings {
return checkForUpdates;
}
public Database.DatabaseType getDatabaseType() {
public Database.Type getDatabaseType() {
return databaseType;
}
@@ -1,11 +1,11 @@
package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -139,12 +139,12 @@ public abstract class Database {
*/
protected Database(@NotNull HuskHomes implementor) {
this.plugin = implementor;
this.playerTableName = implementor.getSettings().getTableName(TableName.PLAYER_DATA);
this.positionsTableName = implementor.getSettings().getTableName(TableName.POSITION_DATA);
this.savedPositionsTableName = implementor.getSettings().getTableName(TableName.SAVED_POSITION_DATA);
this.homesTableName = implementor.getSettings().getTableName(TableName.HOME_DATA);
this.warpsTableName = implementor.getSettings().getTableName(TableName.WARP_DATA);
this.teleportsTableName = implementor.getSettings().getTableName(TableName.TELEPORT_DATA);
this.playerTableName = implementor.getSettings().getTableName(Table.PLAYER_DATA);
this.positionsTableName = implementor.getSettings().getTableName(Table.POSITION_DATA);
this.savedPositionsTableName = implementor.getSettings().getTableName(Table.SAVED_POSITION_DATA);
this.homesTableName = implementor.getSettings().getTableName(Table.HOME_DATA);
this.warpsTableName = implementor.getSettings().getTableName(Table.WARP_DATA);
this.teleportsTableName = implementor.getSettings().getTableName(Table.TELEPORT_DATA);
}
/**
@@ -160,7 +160,7 @@ public abstract class Database {
* @param inputStream The input stream to read the script from
*/
public abstract void runScript(@NotNull InputStream inputStream,
@NotNull Map<String, String> replacements);
@NotNull Map<String, String> replacements);
/**
* <b>(Internal use only)</b> - Sets a position to the position table in the database
@@ -432,22 +432,26 @@ public abstract class Database {
/**
* Identifies types of databases
*/
public enum DatabaseType {
public enum Type {
MYSQL("MySQL"),
SQLITE("SQLite");
@NotNull
public final String displayName;
private final String displayName;
DatabaseType(@NotNull String displayName) {
Type(@NotNull String displayName) {
this.displayName = displayName;
}
@NotNull
public String getDisplayName() {
return displayName;
}
}
/**
* Represents the names of tables in the database
*/
public enum TableName {
public enum Table {
PLAYER_DATA("huskhomes_users"),
POSITION_DATA("huskhomes_position_data"),
SAVED_POSITION_DATA("huskhomes_saved_positions"),
@@ -457,7 +461,7 @@ public abstract class Database {
private final String defaultName;
TableName(@NotNull String defaultName) {
Table(@NotNull String defaultName) {
this.defaultName = defaultName;
}
@@ -2,11 +2,11 @@ package net.william278.huskhomes.database;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -1,11 +1,11 @@
package net.william278.huskhomes.database;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.sqlite.SQLiteConfig;
@@ -6,10 +6,10 @@ import de.bluecolored.bluemap.api.BlueMapWorld;
import de.bluecolored.bluemap.api.markers.MarkerSet;
import de.bluecolored.bluemap.api.markers.POIMarker;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import javax.imageio.ImageIO;
@@ -1,11 +1,11 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
@@ -2,10 +2,13 @@ package net.william278.huskhomes.listener;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -34,9 +37,25 @@ public class EventListener {
// Ensure the user is in the database
plugin.getDatabase().ensureUser(onlineUser);
// Handle any inbound teleports
// Handle cross server checks
if (plugin.getSettings().isCrossServer()) {
this.handleInboundTeleport(onlineUser);
// Update the player list
plugin.runLater(() -> {
if (plugin.getOnlineUsers().size() == 1) {
Message.builder()
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.type(Message.Type.REQUEST_PLAYER_LIST)
.build().send(plugin.getMessenger(), onlineUser);
}
plugin.getOnlineUsers().stream()
.filter(user -> !user.equals(onlineUser))
.findAny()
.ifPresent(this::sendPlayerListUpdates);
}, plugin.getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE ? 40L : 0L);
}
// Set their ignoring requests state
@@ -101,6 +120,22 @@ public class EventListener {
// Set offline position
plugin.getDatabase().setOfflinePosition(onlineUser, onlineUser.getPosition());
// Update global lists
if (plugin.getSettings().isCrossServer()) {
plugin.getOnlineUsers().stream()
.filter(user -> !user.equals(onlineUser))
.findAny()
.ifPresent(this::sendPlayerListUpdates);
}
}
private void sendPlayerListUpdates(@NotNull OnlineUser user) {
Message.builder()
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
.payload(Payload.withStringList(plugin.getLocalPlayerList()))
.build().send(plugin.getMessenger(), user);
}
/**
@@ -2,13 +2,13 @@ package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.util.ValidationException;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
@@ -1,10 +1,10 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.util.ValidationException;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
@@ -1,8 +1,8 @@
package net.william278.huskhomes.network;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -54,6 +54,15 @@ public abstract class Broker {
.getTeleportRequest()
.ifPresent(teleportRequest -> plugin.getManager().requests()
.handleLocalRequestResponse(receiver, teleportRequest));
case REQUEST_PLAYER_LIST -> Message.builder()
.type(Message.Type.PLAYER_LIST)
.scope(Message.Scope.SERVER)
.target(message.getSourceServer())
.payload(Payload.withStringList(plugin.getLocalPlayerList()))
.build().send(this, receiver);
case PLAYER_LIST -> message.getPayload()
.getStringList()
.ifPresent(players -> plugin.setPlayerList(message.getSourceServer(), players));
}
}
@@ -96,23 +105,23 @@ public abstract class Broker {
return plugin.getServerName();
}
/**
* Identifies types of message brokers
*/
public enum Type {
PLUGIN_MESSAGE("Plugin Messages"),
REDIS("Redis");
@NotNull
private final String displayName;
/**
* Identifies types of message brokers
*/
public enum Type {
PLUGIN_MESSAGE("Plugin Messages"),
REDIS("Redis");
@NotNull
private final String displayName;
Type(@NotNull String displayName) {
this.displayName = displayName;
}
Type(@NotNull String displayName) {
this.displayName = displayName;
}
@NotNull
public String getDisplayName() {
return displayName;
@NotNull
public String getDisplayName() {
return displayName;
}
}
}
}
@@ -22,6 +22,8 @@ public class Message {
@Expose
private Type type;
@Expose
private Scope scope;
@Expose
private String target;
@Expose
private Payload payload;
@@ -30,8 +32,9 @@ public class Message {
@Expose
private String sourceServer;
private Message(@NotNull Type type, @NotNull String target, @NotNull Payload payload) {
private Message(@NotNull Type type, @NotNull Scope scope, @NotNull String target, @NotNull Payload payload) {
this.type = type;
this.scope = scope;
this.target = target;
this.payload = payload;
this.id = UUID.randomUUID();
@@ -56,6 +59,11 @@ public class Message {
return type;
}
@NotNull
public Scope getScope() {
return scope;
}
@NotNull
public String getTarget() {
return target;
@@ -86,6 +94,7 @@ public class Message {
*/
public static class Builder {
private Type type;
private Scope scope = Scope.PLAYER;
private Payload payload = Payload.empty();
private String target;
@@ -98,6 +107,12 @@ public class Message {
return this;
}
@NotNull
public Builder scope(@NotNull Scope scope) {
this.scope = scope;
return this;
}
@NotNull
public Builder payload(@NotNull Payload payload) {
this.payload = payload;
@@ -112,7 +127,7 @@ public class Message {
@NotNull
public Message build() {
return new Message(type, target, payload);
return new Message(type, scope, target, payload);
}
}
@@ -125,7 +140,31 @@ public class Message {
TELEPORT_TO_NETWORKED_POSITION,
TELEPORT_REQUEST,
TELEPORT_TO_NETWORKED_USER,
TELEPORT_REQUEST_RESPONSE
TELEPORT_REQUEST_RESPONSE,
REQUEST_PLAYER_LIST,
PLAYER_LIST,
}
public enum Scope {
/**
* The target is a server name, or "all" to indicate all servers.
*/
SERVER("Forward"),
/**
* The target is a player name, or "all" to indicate all players.
*/
PLAYER("ForwardToPlayer");
private final String pluginMessageChannel;
Scope(@NotNull String pluginMessageChannel) {
this.pluginMessageChannel = pluginMessageChannel;
}
@NotNull
public String getPluginMessageChannel() {
return pluginMessageChannel;
}
}
}
@@ -4,10 +4,10 @@ import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.teleport.TeleportResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Optional;
/**
@@ -28,6 +28,10 @@ public class Payload {
@Expose
private String string;
@Nullable
@Expose
private List<String> stringList;
/**
* Returns an empty cross-server message payload
*
@@ -74,6 +78,16 @@ public class Payload {
return payload;
}
/**
* A string list field
*/
@NotNull
public static Payload withStringList(@NotNull List<String> target) {
final Payload payload = new Payload();
payload.stringList = target;
return payload;
}
private Payload() {
}
@@ -85,6 +99,9 @@ public class Payload {
}
/**
* A teleport request field
*/
public Optional<TeleportRequest> getTeleportRequest() {
return Optional.ofNullable(teleportRequest);
}
@@ -95,4 +112,12 @@ public class Payload {
public Optional<String> getString() {
return Optional.ofNullable(string);
}
/**
* A string list field
*/
public Optional<List<String>> getStringList() {
return Optional.ofNullable(stringList);
}
}
@@ -63,7 +63,7 @@ public class PluginMessageBroker extends Broker {
@SuppressWarnings("UnstableApiUsage")
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF("ForwardToPlayer");
messageWriter.writeUTF(message.getScope().getPluginMessageChannel());
messageWriter.writeUTF(message.getTarget());
messageWriter.writeUTF(getSubChannelId());
@@ -49,10 +49,19 @@ public class RedisBroker extends PluginMessageBroker {
}
final Message message = plugin.getGson().fromJson(encodedMessage, Message.class);
plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> handle(receiver, message));
if (message.getScope() == Message.Scope.PLAYER) {
plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> handle(receiver, message));
return;
}
if (message.getTarget().equals(plugin.getServerName())) {
plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> handle(receiver, message));
}
}
}, getSubChannelId());
}
@@ -2,8 +2,8 @@ package net.william278.huskhomes.teleport;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
@@ -1,9 +1,9 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -4,8 +4,8 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
@@ -10,13 +10,11 @@ import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.TitlePart;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.teleport.Teleportable;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* A cross-platform representation of a logged-in {@link User}
@@ -11,8 +11,9 @@ public interface TaskRunner {
<T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier);
int runSync(@NotNull Runnable runnable);
int runAsyncRepeating(@NotNull Runnable runnable, long delay);
int runLater(@NotNull Runnable runnable, long delay);
void cancelTask(int taskId);
void cancelAllTasks();
@NotNull
HuskHomes getPlugin();
}
@@ -0,0 +1,19 @@
package net.william278.huskhomes.util;
import java.util.function.Consumer;
@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T> {
@Override
default void accept(final T elem) {
try {
acceptThrows(elem);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
void acceptThrows(T elem) throws Exception;
}
@@ -19,7 +19,7 @@ public class ValidationException extends IllegalArgumentException {
.getLocale(other ? "error_home_invalid_other" : "error_home_invalid", args)
.ifPresent(viewer::sendMessage);
case NAME_TAKEN -> plugin.getLocales()
.getLocale("error_home_name_taken", args)
.getLocale("error_home_name_taken")
.ifPresent(viewer::sendMessage);
case NAME_INVALID -> plugin.getLocales()
.getLocale("error_home_name_characters", args)
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Spent %1% to make your home public.](gray
economy_action_random_teleport: '[ℹ Spent %1% to randomly teleport.](gray)'
economy_action_back_command: '[ℹ Spent %1% to return to your last position.](gray)'
return_by_death_notification: '[Return to where you died?](gray) [[⏪ Teleport…]](#00fb9a show_text=&#00fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Error:](#ff3300) [You already have a home set with that name.](#ff7e5e)'
error_home_name_length: '[Error:](#ff3300) [Home names can only contain up to 16 characters!](#ff7e5e)'
error_home_name_characters: '[Error:](#ff3300) [Home names must be alphanumeric (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ %1% für das Setzen deines Homes auf öff
economy_action_random_teleport: '[ℹ %1% ausgegeben, um zufällig teleportiert zu werden.](gray)'
economy_action_back_command: '[ℹ %1% ausgegeben, um zu deiner letzten Position zurückzukehren.](gray)'
return_by_death_notification: '[Dorthin zurückkehren, wo du gestorben bist?](gray) [[⏪ Teleportieren…]](#00fb9a show_text=&#00fb9a&Klicke, um dich zu teleportieren\n&7Kehre dorthin zurück, wo du gestorben bist run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Fehler:](#ff3300) [Du hast bereits ein Home mit diesem Namen gesetzt.](#ff7e5e)'
error_home_name_length: '[Fehler:](#ff3300) [Home-Namen dürfen nur bis zu 16 Zeichen enthalten!](#ff7e5e)'
error_home_name_characters: '[Fehler:](#ff3300) [Home-Namen müssen alphanumerisch sein (A-Z, 0-9, -_)!](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Spent %1% to make your home public.](gray
economy_action_random_teleport: '[ℹ Spent %1% to randomly teleport.](gray)'
economy_action_back_command: '[ℹ Spent %1% to return to your last position.](gray)'
return_by_death_notification: '[Return to where you died?](gray) [[⏪ Teleport…]](#00fb9a show_text=&#00fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Error:](#ff3300) [You already have a home set with that name.](#ff7e5e)'
error_home_name_length: '[Error:](#ff3300) [Home names can only contain up to 16 characters!](#ff7e5e)'
error_home_name_characters: '[Error:](#ff3300) [Home names must be alphanumeric (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Paga %1% Para hacer tu casa pública.](gr
economy_action_random_teleport: '[ℹ Paga %1% para teletransportarse aleatoriamente.](gray)'
economy_action_back_command: '[ℹ Paga %1% para volver a su última posición.](gray)'
return_by_death_notification: '[¿Regresar al lugar donde murió?](gray) [[⏪ Teletransportar…]](#00fb9a show_text=&#00fb9a&Clic para teletransportarte\n&7Regresa al lugar donde moriste run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Error:](#ff3300) [Ya tienes una casa con ese nombre.](#ff7e5e)'
error_home_name_length: '[Error:](#ff3300) [Los nombres de las casas sólo pueden contener hasta 16 caracteres.](#ff7e5e)'
error_home_name_characters: '[Error:](#ff3300) [Los nombres de las casas deben ser alfanuméricos (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Hai pagato %1% per impostare la tua home
economy_action_random_teleport: '[ℹ Hai pagato %1% per teletrasportarti randomicamente.](gray)'
economy_action_back_command: '[ℹ Hai pagato %1% per tornare alla posizione precedente.](gray)'
return_by_death_notification: '[Vuoi ritornare dove sei morto?](gray) [[⏪ Teletrasportati…]](#00fb9a show_text=&#00fb9a&Clicca per teletrasportarti\n&7e tornare dove sei morto run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Errore:](#ff3300) [Hai già una home impostata con quel nome.](#ff7e5e)'
error_home_name_length: '[Errore:](#ff3300) [I nomi delle home possono essere lunghi massimo 16 caratteri!](#ff7e5e)'
error_home_name_characters: '[Errore:](#ff3300) [I nomi delle home devono essere alfanumerici (A-Z, 0-9, -_)](#ff7e5e)'
+2
View File
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Spent %1% to make your home public.](gray
economy_action_random_teleport: '[ℹ Spent %1% to randomly teleport.](gray)'
economy_action_back_command: '[ℹ Spent %1% to return to your last position.](gray)'
return_by_death_notification: '[Return to where you died?](gray) [[⏪ Teleport…]](#00fb9a show_text=&#00fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Error:](#ff3300) [You already have a home set with that name.](#ff7e5e)'
error_home_name_length: '[Error:](#ff3300) [Home names can only contain up to 16 characters!](#ff7e5e)'
error_home_name_characters: '[Error:](#ff3300) [Home names must be alphanumeric (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Evinizi herkese açık hale getirmek içi
economy_action_random_teleport: '[ℹ Rastgele ışınlanmak için %1% harcadınız.](gray)'
economy_action_back_command: '[ℹ Son konumunuza dönmek için %1% harcadınız.](gray)'
return_by_death_notification: '[Öldüğün yere dön?](gray) [[⏪ Işınlanma…]](#00fb9a show_text=&#00fb9a&Işınlanmak için tıklayın\n&7Öldüğün yere dön run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Hata:](#ff3300) [Bu ada sahip bir eviniz zaten var.](#ff7e5e)'
error_home_name_length: '[Hata:](#ff3300) [Ev adları en fazla 16 karakter içerebilir!](#ff7e5e)'
error_home_name_characters: '[Hata:](#ff3300) [Ev adları alfanümerik olmalıdır (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ Spent %1% to make your home public.](gray
economy_action_random_teleport: '[ℹ Spent %1% to randomly teleport.](gray)'
economy_action_back_command: '[ℹ Spent %1% to return to your last position.](gray)'
return_by_death_notification: '[Return to where you died?](gray) [[⏪ Teleport…]](#00fb9a show_text=&#00fb9a&Click to teleport\n&7Return to where you died run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[Error:](#ff3300) [You already have a home set with that name.](#ff7e5e)'
error_home_name_length: '[Error:](#ff3300) [Home names can only contain up to 16 characters!](#ff7e5e)'
error_home_name_characters: '[Error:](#ff3300) [Home names must be alphanumeric (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ 花费 %1% 将家设为公开.](gray)'
economy_action_random_teleport: '[ℹ 花费 %1% 使用随机传送.](gray)'
economy_action_back_command: '[ℹ 花费 %1% 回到上一位置.](gray)'
return_by_death_notification: '[回到上一个位置?](gray) [[⏪ 点击传送…]](#00fb9a show_text=&#00fb9a&点击传送\n&7返回上一位置 run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[错误:](#ff3300) [已有一个相同名称的家.](#ff7e5e)'
error_home_name_length: '[错误:](#ff3300) [家的名称只能输入16个字符!](#ff7e5e)'
error_home_name_characters: '[错误:](#ff3300) [家的名称只能使用这些字符: (A-Z, 0-9, -_)](#ff7e5e)'
@@ -94,6 +94,8 @@ economy_action_make_home_public: '[ℹ 花費 %1% 將家設為公開.](gray)'
economy_action_random_teleport: '[ℹ 花費 %1% 使用隨機傳送.](gray)'
economy_action_back_command: '[ℹ 花費 %1% 回到上一位置.](gray)'
return_by_death_notification: '[回到上一個位置?](gray) [[⏪ 傳送…]](#00fb9a show_text=&#00fb9a&點擊傳送\n&7返回上一位置 run_command=/huskhomes:back)'
up_to_date: '[HuskHomes](#00fb9a bold) [| You are running the latest version of HuskHomes (v%1%).](#00fb9a)'
update_available: '[HuskHomes](#ff7e5e bold) [| A new version of HuskHomes is available: v%1% (running: v%2%).](#ff7e5e)'
error_home_name_taken: '[錯誤:](#ff3300) [已有一個相同名稱的家.](#ff7e5e)'
error_home_name_length: '[錯誤:](#ff3300) [家名稱最多只能包含16個字符!](#ff7e5e)'
error_home_name_characters: '[錯誤:](#ff3300) [家名稱只能使用這些字符: (A-Z, 0-9, -_)](#ff7e5e)'