Add fabric builds for older MC versions & add checkstyle (#449)

* Remove instance getters, improve command logic, register APi

* Publish multiple fabric builds, enforce checkstyle

* Bump guava

* Bump to 4.4.2
This commit is contained in:
William authored and GitHub committed 2023-07-02 13:26:12 +01:00
1 parent 51baf196b3
commit c9f5262292
219 files changed
+8032 -1392

No files matched your search

@@ -22,9 +22,9 @@ package net.william278.huskhomes;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.util.Version;
import net.william278.huskhomes.api.HuskHomesAPI;
import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
@@ -62,6 +62,7 @@ import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import space.arim.morepaperlib.MorePaperLib;
import space.arim.morepaperlib.scheduling.GracefulScheduling;
@@ -79,6 +80,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
* Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskHomes/8430">HuskHomes on Bukkit</a>.
*/
private static final int METRICS_ID = 8430;
private Set<SavedUser> savedUsers;
private Settings settings;
private Locales locales;
@@ -94,34 +96,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
private Map<String, List<String>> globalPlayerList;
private Set<UUID> currentlyOnWarmup;
private Server server;
@Nullable
private Broker broker;
private BukkitAudiences audiences;
private MorePaperLib paperLib;
private static BukkitHuskHomes instance;
public static BukkitHuskHomes getInstance() {
return instance;
}
@Nullable
private Broker broker;
// Default public constructor
@SuppressWarnings("unused")
public BukkitHuskHomes() {
super();
}
// Super constructor for unit testing
@SuppressWarnings("unused")
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) {
@TestOnly
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description,
@NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file);
}
@Override
public void onLoad() {
instance = this;
}
@Override
public void onEnable() {
// Create adventure audience
@@ -142,7 +133,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> {
this.database = switch (getSettings().getDatabaseType()) {
case MYSQL -> new MySqlDatabase(this);
case MYSQL, MARIADB -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this);
};
@@ -190,6 +181,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Register commands
initialize("commands", (plugin) -> this.commands = registerCommands());
// Initialize the API
initialize("API", (plugin) -> HuskHomesAPI.register(this));
// Hook into bStats and check for updates
initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID));
this.checkForUpdates();
@@ -197,19 +191,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@NotNull
public List<Command> registerCommands() {
return Arrays.stream(BukkitCommand.Type.values())
.map(type -> {
final Command command = type.getCommand();
if (settings.isCommandDisabled(command)) {
new BukkitCommand(new DisabledCommand(command.getName(), this), this).register();
return null;
} else {
new BukkitCommand(command, this).register();
return command;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
return BukkitCommand.Type.getCommands(this);
}
@Override
@@ -259,7 +241,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
}
/**
* Returns the adventure Bukkit audiences
* Returns the adventure Bukkit audiences.
*
* @return The adventure Bukkit audiences
*/
@@ -277,7 +259,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override
public List<OnlineUser> getOnlineUsers() {
return Bukkit.getOnlinePlayers().stream()
.map(player -> (OnlineUser) BukkitUser.adapt(player))
.map(player -> (OnlineUser) BukkitUser.adapt(player, this))
.toList();
}
@@ -369,7 +351,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Update the world spawn location, too
BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> {
assert bukkitLocation.getWorld() != null;
assert bukkitLocation.getWorld() != null : "World was null when setting server spawn";
bukkitLocation.getWorld().setSpawnLocation(bukkitLocation);
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
@@ -451,14 +433,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
try {
final Metrics metrics = new Metrics(this, metricsId);
metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().doCrossServer())));
metrics.addCustomChart(new SimplePie("bungee_mode",
() -> Boolean.toString(getSettings().doCrossServer())));
if (getSettings().doCrossServer()) {
metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().getBrokerType().getDisplayName()));
metrics.addCustomChart(new SimplePie("messenger_type",
() -> getSettings().getBrokerType().getDisplayName()));
}
metrics.addCustomChart(new SimplePie("language", () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().getDisplayName()));
metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().doEconomy())));
metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook())));
metrics.addCustomChart(new SimplePie("language",
() -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type",
() -> getSettings().getDatabaseType().getDisplayName()));
metrics.addCustomChart(new SimplePie("using_economy",
() -> Boolean.toString(getSettings().doEconomy())));
metrics.addCustomChart(new SimplePie("using_map",
() -> Boolean.toString(getSettings().doMapHook())));
getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName)));
} catch (Throwable e) {
log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")");
@@ -467,8 +458,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override
public void initializePluginChannels() {
Bukkit.getMessenger().registerIncomingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID, this);
Bukkit.getMessenger().registerOutgoingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID);
final String channelId = PluginMessageBroker.BUNGEE_CHANNEL_ID;
Bukkit.getMessenger().registerIncomingPluginChannel(this, channelId, this);
Bukkit.getMessenger().registerOutgoingPluginChannel(this, channelId);
}
@Override
@@ -483,8 +475,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) {
if (broker != null && broker instanceof PluginMessageBroker pluginMessenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message);
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
pluginMessenger.onReceive(channel, BukkitUser.adapt(player, this), message);
}
}
@@ -498,4 +490,5 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
public HuskHomes getPlugin() {
return this;
}
}
@@ -28,6 +28,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -36,32 +37,53 @@ import java.util.Objects;
/**
* The HuskHomes API implementation for the Bukkit platform, providing methods to access player data, homes, warps
* and process teleports
* <p>
* Retrieve an instance of the API class via {@link #getInstance()}.
*
* <p>Retrieve an instance of the API class via {@link #getInstance()}.
*/
@SuppressWarnings("unused")
public class HuskHomesAPI extends BaseHuskHomesAPI {
/**
* <b>(Internal use only)</b> - Instance of the API class
*/
// Instance of the plugin
private static HuskHomesAPI instance;
/**
* <b>(Internal use only)</b> - Constructor, instantiating the API
* <b>(Internal use only)</b> - Constructor, instantiating the API.
*/
private HuskHomesAPI() {
super(BukkitHuskHomes.getInstance());
@ApiStatus.Internal
private HuskHomesAPI(@NotNull BukkitHuskHomes plugin) {
super(plugin);
}
/**
* Entrypoint to the HuskHomes API - returns an instance of the API
* Get an instance of the HuskHomes API.
*
* @return instance of the HuskHomes API
* @throws NotRegisteredException if the API has not yet been registered.
*/
@NotNull
public static HuskHomesAPI getInstance() {
return instance == null ? instance = new HuskHomesAPI() : instance;
public static HuskHomesAPI getInstance() throws NotRegisteredException {
if (instance == null) {
throw new NotRegisteredException();
}
return instance;
}
/**
* <b>(Internal use only)</b> - Register the API for this platform.
*
* @param plugin the plugin instance
*/
@ApiStatus.Internal
public static void register(@NotNull BukkitHuskHomes plugin) {
instance = new HuskHomesAPI(plugin);
}
/**
* <b>(Internal use only)</b> - Unregister the API for this platform.
*/
@ApiStatus.Internal
public static void unregister() {
instance = null;
}
/**
@@ -73,7 +95,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
*/
@NotNull
public OnlineUser adaptUser(@NotNull Player player) {
return BukkitUser.adapt(player);
return BukkitUser.adapt(player, (BukkitHuskHomes) plugin);
}
/**
@@ -101,7 +123,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
}
/**
* Returns a {@link Location} instance for the given bukkit {@link Location}.
* Returns a {@link Location} instance for the given bukkit {@link Location} on the server.
*
* @param location the bukkit location to get the {@link Location} instance for
* @return the {@link Location} instance for the given bukkit {@link Location}
@@ -113,7 +135,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
}
/**
* Returns a {@link Position} instance for the given bukkit {@link Location} on the given {@link Server}.
* Returns a {@link Position} instance for the given bukkit {@link Location} on the server.
*
* @param location the bukkit location to get the {@link Position} instance for
* @param server the {@link Server} the position is on
@@ -127,10 +149,10 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
}
/**
* Returns a {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on.
* Returns a {@link Position} instance for the given bukkit {@link Location} on the server.
*
* @param location the bukkit location to get the {@link Position} instance for
* @return the {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on
* @return the {@link Position} instance for the given {@link Location} on the server
* @since 4.0
*/
@NotNull
@@ -139,9 +161,9 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
}
/**
* Get the {@link Server}, containing the ID of the server the plugin is running on
* Get the name of this server.
*
* @return the {@link Server}
* @return the server name
* @since 4.0
*/
@NotNull
@@ -31,25 +31,28 @@ import java.util.logging.Level;
public class BrigadierUtil {
/**
* Uses commodore to register command completions
* Uses commodore to register command completions.
*
* @param plugin instance of the registering Bukkit plugin
* @param bukkitCommand the Bukkit PluginCommand to register completions for
* @param command the {@link Command} to register completions for
*/
protected static void registerCommodore(@NotNull BukkitHuskHomes plugin, @NotNull org.bukkit.command.Command bukkitCommand,
protected static void registerCommodore(@NotNull BukkitHuskHomes plugin,
@NotNull org.bukkit.command.Command bukkitCommand,
@NotNull Command command) {
final InputStream commandCommodore = plugin.getResource("commodore/" + bukkitCommand.getName() + ".commodore");
if (commandCommodore == null) {
final InputStream commodoreFile = plugin.getResource(
"commodore/" + bukkitCommand.getName() + ".commodore"
);
if (commodoreFile == null) {
return;
}
try {
CommodoreProvider.getCommodore(plugin).register(bukkitCommand,
CommodoreFileReader.INSTANCE.parse(commandCommodore),
CommodoreFileReader.INSTANCE.parse(commodoreFile),
player -> player.hasPermission(command.getPermission()));
} catch (IOException e) {
plugin.log(Level.SEVERE, "Failed to read command commodore completions for "
+ bukkitCommand.getName(), e);
+ bukkitCommand.getName(), e);
}
}
@@ -21,6 +21,7 @@ package net.william278.huskhomes.command;
import me.lucko.commodore.CommodoreProvider;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.CommandUser;
@@ -36,6 +37,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Function;
public class BukkitCommand implements CommandExecutor, TabCompleter {
@@ -50,7 +52,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command,
@NotNull String label, @NotNull String[] args) {
this.command.onExecuted(sender instanceof Player player ? BukkitUser.adapt(player) : plugin.getConsole(), args);
this.command.onExecuted(sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole(), args);
return true;
}
@@ -61,7 +63,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
if (!(this.command instanceof TabProvider provider)) {
return List.of();
}
final CommandUser user = sender instanceof Player player ? BukkitUser.adapt(player) : plugin.getConsole();
final CommandUser user = sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole();
return provider.getSuggestions(user, args);
}
@@ -73,7 +75,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
// Register permissions
addPermission(plugin, command.getPermission(), command.getUsage(), getPermissionDefault(command.isOperatorCommand()));
addPermission(
plugin,
command.getPermission(),
command.getUsage(),
getPermissionDefault(command.isOperatorCommand())
);
final List<Permission> childNodes = command.getAdditionalPermissions()
.entrySet().stream()
.map((entry) -> addPermission(plugin, entry.getKey(), "", getPermissionDefault(entry.getValue())))
@@ -81,7 +88,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
.toList();
if (!childNodes.isEmpty()) {
addPermission(plugin, command.getPermission("*"), command.getUsage(), PermissionDefault.FALSE,
childNodes.toArray(new Permission[0]));
childNodes.toArray((plugin) -> new Permission[0]));
}
// Set command parameters
@@ -97,8 +104,9 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
@Nullable
protected static Permission addPermission(@NotNull BukkitHuskHomes plugin, @NotNull String node, @NotNull String description,
@NotNull PermissionDefault permissionDefault, @NotNull Permission... children) {
protected static Permission addPermission(@NotNull BukkitHuskHomes plugin, @NotNull String node,
@NotNull String description, @NotNull PermissionDefault permissionDefault,
@NotNull Permission... children) {
final Map<String, Boolean> childNodes = Arrays.stream(children)
.map(Permission::getName)
.collect(HashMap::new, (map, child) -> map.put(child, true), HashMap::putAll);
@@ -125,46 +133,62 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
/**
* Commands available on the Bukkit HuskHomes implementation
* Commands available on the Bukkit HuskHomes implementation.
*/
public enum Type {
HOME_COMMAND(new PrivateHomeCommand(BukkitHuskHomes.getInstance())),
SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())),
HOME_LIST_COMMAND(new PrivateHomeListCommand(BukkitHuskHomes.getInstance())),
DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())),
EDIT_HOME_COMMAND(new EditHomeCommand(BukkitHuskHomes.getInstance())),
PUBLIC_HOME_COMMAND(new PublicHomeCommand(BukkitHuskHomes.getInstance())),
PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(BukkitHuskHomes.getInstance())),
WARP_COMMAND(new WarpCommand(BukkitHuskHomes.getInstance())),
SET_WARP_COMMAND(new SetWarpCommand(BukkitHuskHomes.getInstance())),
WARP_LIST_COMMAND(new WarpListCommand(BukkitHuskHomes.getInstance())),
DEL_WARP_COMMAND(new DelWarpCommand(BukkitHuskHomes.getInstance())),
EDIT_WARP_COMMAND(new EditWarpCommand(BukkitHuskHomes.getInstance())),
TP_COMMAND(new TpCommand(BukkitHuskHomes.getInstance())),
TP_HERE_COMMAND(new TpHereCommand(BukkitHuskHomes.getInstance())),
TPA_COMMAND(new TeleportRequestCommand(BukkitHuskHomes.getInstance(), TeleportRequest.Type.TPA)),
TPA_HERE_COMMAND(new TeleportRequestCommand(BukkitHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)),
TPACCEPT_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), true)),
TPDECLINE_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), false)),
RTP_COMMAND(new RtpCommand(BukkitHuskHomes.getInstance())),
TP_IGNORE_COMMAND(new TpIgnoreCommand(BukkitHuskHomes.getInstance())),
TP_OFFLINE_COMMAND(new TpOfflineCommand(BukkitHuskHomes.getInstance())),
TP_ALL_COMMAND(new TpAllCommand(BukkitHuskHomes.getInstance())),
TPA_ALL_COMMAND(new TpaAllCommand(BukkitHuskHomes.getInstance())),
SPAWN_COMMAND(new SpawnCommand(BukkitHuskHomes.getInstance())),
SET_SPAWN_COMMAND(new SetSpawnCommand(BukkitHuskHomes.getInstance())),
BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance())),
HUSKHOMES_COMMAND(new HuskHomesCommand(BukkitHuskHomes.getInstance()));
HOME_COMMAND(PrivateHomeCommand::new),
SET_HOME_COMMAND(SetHomeCommand::new),
HOME_LIST_COMMAND(PrivateHomeListCommand::new),
DEL_HOME_COMMAND(DelHomeCommand::new),
EDIT_HOME_COMMAND(EditHomeCommand::new),
PUBLIC_HOME_COMMAND(PublicHomeCommand::new),
PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new),
WARP_COMMAND(WarpCommand::new),
SET_WARP_COMMAND(SetWarpCommand::new),
WARP_LIST_COMMAND(WarpListCommand::new),
DEL_WARP_COMMAND(DelWarpCommand::new),
EDIT_WARP_COMMAND(EditWarpCommand::new),
TP_COMMAND(TpCommand::new),
TP_HERE_COMMAND(TpHereCommand::new),
TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)),
TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)),
TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)),
TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)),
RTP_COMMAND(RtpCommand::new),
TP_IGNORE_COMMAND(TpIgnoreCommand::new),
TP_OFFLINE_COMMAND(TpOfflineCommand::new),
TP_ALL_COMMAND(TpAllCommand::new),
TPA_ALL_COMMAND(TpaAllCommand::new),
SPAWN_COMMAND(SpawnCommand::new),
SET_SPAWN_COMMAND(SetSpawnCommand::new),
BACK_COMMAND(BackCommand::new),
HUSKHOMES_COMMAND(HuskHomesCommand::new);
private final Command command;
private final Function<HuskHomes, Command> supplier;
Type(@NotNull Command command) {
this.command = command;
Type(@NotNull Function<HuskHomes, Command> supplier) {
this.supplier = supplier;
}
@NotNull
public Command getCommand() {
return command;
public Command createCommand(@NotNull HuskHomes plugin) {
return supplier.apply(plugin);
}
@NotNull
public static List<Command> getCommands(@NotNull BukkitHuskHomes plugin) {
return Arrays.stream(values())
.map((type) -> {
Command command = type.createCommand(plugin);
if (plugin.getSettings().isCommandDisabled(command)) {
command = new DisabledCommand(command.getName(), plugin);
}
new BukkitCommand(command, plugin).register();
return command;
})
.filter((command) -> !(command instanceof DisabledCommand))
.toList();
}
}
}
@@ -36,83 +36,90 @@ import java.util.List;
public interface BukkitEventDispatcher extends EventDispatcher {
@Override
default <T extends Event> boolean fireIsCancelled(@NotNull T event) {
default <T extends Event> @NotNull boolean fireIsCancelled(@NotNull T event) {
Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event);
return event instanceof Cancellable cancellable && cancellable.isCancelled();
}
@Override
@NotNull
default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) {
return teleport.getType() == Teleport.Type.BACK ? new TeleportBackEvent(teleport) : new TeleportEvent(teleport);
}
@Override
default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
return new TeleportWarmupEvent(teleport, duration);
}
@Override
default ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) {
default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender,
@NotNull TeleportRequest request) {
return new SendTeleportRequestEvent(sender, request);
}
@Override
default IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request) {
return new ReceiveTeleportRequestEvent(recipient, request);
}
@Override
default IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request) {
return new ReplyTeleportRequestEvent(recipient, request);
}
@Override
default IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
default @NotNull IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name,
@NotNull Position position, @NotNull CommandUser creator) {
return new HomeCreateEvent(owner, name, position, creator);
}
@Override
default IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) {
default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) {
return new HomeEditEvent(home, editor);
}
@Override
default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) {
default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) {
return new HomeDeleteEvent(home, deleter);
}
@Override
default IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
default @NotNull IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position,
@NotNull CommandUser creator) {
return new WarpCreateEvent(name, position, creator);
}
@Override
default IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) {
default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) {
return new WarpEditEvent(warp, editor);
}
@Override
default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) {
default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) {
return new WarpDeleteEvent(warp, deleter);
}
@Override
default IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList) {
default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer,
boolean publicHomeList) {
return new HomeListEvent(homes, listViewer, publicHomeList);
}
@Override
default IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> warps, @NotNull CommandUser listViewer) {
default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> warps, @NotNull CommandUser listViewer) {
return new WarpListEvent(warps, listViewer);
}
@Override
default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) {
default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) {
return new DeleteAllHomesEvent(user, deleter);
}
@Override
default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) {
default @NotNull IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) {
return new DeleteAllWarpsEvent(deleter);
}
@@ -37,7 +37,8 @@ public class HomeCreateEvent extends Event implements IHomeCreateEvent, Cancella
private final CommandUser creator;
private boolean cancelled;
public HomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
public HomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position,
@NotNull CommandUser creator) {
this.owner = owner;
this.name = name;
this.position = position;
@@ -21,7 +21,7 @@ package net.william278.huskhomes.hook;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
@@ -33,21 +33,21 @@ import java.util.List;
public class PlaceholderAPIHook extends Hook {
public PlaceholderAPIHook(@NotNull HuskHomes plugin) {
public PlaceholderAPIHook(@NotNull BukkitHuskHomes plugin) {
super(plugin, "PlaceholderAPI");
}
@Override
public void initialize() {
new HuskHomesExpansion(plugin).register();
new HuskHomesExpansion((BukkitHuskHomes) plugin).register();
}
public static class HuskHomesExpansion extends PlaceholderExpansion {
@NotNull
private final HuskHomes plugin;
private final BukkitHuskHomes plugin;
private HuskHomesExpansion(@NotNull HuskHomes plugin) {
private HuskHomesExpansion(@NotNull BukkitHuskHomes plugin) {
this.plugin = plugin;
}
@@ -59,7 +59,7 @@ public class PlaceholderAPIHook extends Hook {
}
// Return the requested data
final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer());
final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer(), plugin);
return switch (params) {
case "homes_count" -> String.valueOf(plugin.getManager().homes()
.getUserHomes()
@@ -29,7 +29,7 @@ import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull;
/**
* A hook that hooks into the Vault API to provide economy features
* A hook that hooks into the Vault API to provide economy features.
*/
public class VaultEconomyHook extends EconomyHook {
@@ -38,7 +38,8 @@ public class EssentialsXImporter extends Importer {
public EssentialsXImporter(@NotNull HuskHomes plugin) {
super("EssentialsX", List.of(ImportData.HOMES, ImportData.WARPS), plugin);
this.essentials = (Essentials) ((BukkitHuskHomes) plugin).getServer().getPluginManager().getPlugin("Essentials");
this.essentials = (Essentials) ((BukkitHuskHomes) plugin).getServer()
.getPluginManager().getPlugin("Essentials");
}
private int importHomes() {
@@ -38,24 +38,24 @@ public class BukkitEventListener extends EventListener implements Listener {
protected boolean checkForBed = true;
public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) {
super(huskHomes);
huskHomes.getServer().getPluginManager().registerEvents(this, huskHomes);
public BukkitEventListener(@NotNull BukkitHuskHomes plugin) {
super(plugin);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerJoin(PlayerJoinEvent event) {
super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer()));
super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerLeave(PlayerQuitEvent event) {
super.handlePlayerLeave(BukkitUser.adapt(event.getPlayer()));
super.handlePlayerLeave(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin));
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) {
super.handlePlayerDeath(BukkitUser.adapt(event.getEntity()));
super.handlePlayerDeath(BukkitUser.adapt(event.getEntity(), (BukkitHuskHomes) plugin));
}
@EventHandler(priority = EventPriority.NORMAL)
@@ -63,7 +63,7 @@ public class BukkitEventListener extends EventListener implements Listener {
if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) {
return;
}
super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer()));
super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin));
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@@ -71,29 +71,37 @@ public class BukkitEventListener extends EventListener implements Listener {
final Player player = event.getPlayer();
// Return if the disconnecting entity is a Citizens NPC, or if the teleport was naturally caused
if (player.hasMetadata("NPC")) return;
if (player.hasMetadata("NPC")) {
return;
}
if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND
|| event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) return;
|| event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) {
return;
}
final BukkitUser bukkitUser = BukkitUser.adapt(player);
final BukkitUser bukkitUser = BukkitUser.adapt(player, (BukkitHuskHomes) plugin);
BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation ->
handlePlayerTeleport(bukkitUser, Position.at(sourceLocation, plugin.getServerName())));
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) {
if (!checkForBed) return;
if (!(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) return;
if (event.getClickedBlock() == null) return;
if (!(event.getClickedBlock().getBlockData() instanceof Bed
|| event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return;
if (!checkForBed || !(plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalRespawning())) {
return;
}
if (event.getClickedBlock() == null || !(event.getClickedBlock().getBlockData() instanceof Bed
|| event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) {
return;
}
final Location location = event.getPlayer().getBedSpawnLocation();
if (location == null) return;
if (location == null) {
return;
}
// Update the player's respawn location
BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> super.handlePlayerUpdateSpawnPoint(
BukkitUser.adapt(event.getPlayer()),
BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin),
Position.at(adaptedLocation, plugin.getServerName()))
);
}
@@ -38,34 +38,45 @@ import java.util.logging.Level;
import java.util.stream.Collectors;
/**
* Bukkit implementation of an {@link OnlineUser}
* Bukkit's implementation of an {@link OnlineUser}.
*/
public class BukkitUser extends OnlineUser {
private final BukkitHuskHomes plugin;
private final Player player;
private BukkitUser(@NotNull Player player) {
private BukkitUser(@NotNull Player player, @NotNull BukkitHuskHomes plugin) {
super(player.getUniqueId(), player.getName());
this.plugin = BukkitHuskHomes.getInstance();
this.player = player;
this.plugin = plugin;
}
/**
* Adapt a {@link Player} to a {@link OnlineUser}
* Adapt a {@link Player} to a {@link OnlineUser}.
*
* @param player the online {@link Player} to adapt
* @return the adapted {@link OnlineUser}
*/
@NotNull
public static BukkitUser adapt(@NotNull Player player) {
return new BukkitUser(player);
public static BukkitUser adapt(@NotNull Player player, @NotNull BukkitHuskHomes plugin) {
return new BukkitUser(player, plugin);
}
/**
* Return the {@link Player} wrapped by this {@link BukkitUser}.
*
* @return the {@link Player} wrapped by this {@link BukkitUser}
*/
@NotNull
public Player getPlayer() {
return player;
}
@Override
public Position getPosition() {
return Position.at(BukkitAdapter.adaptLocation(player.getLocation())
.orElseThrow(() -> new IllegalStateException("Failed to get the position of a BukkitPlayer (null)")),
return Position.at(BukkitAdapter.adaptLocation(player.getLocation()).orElseThrow(
() -> new IllegalStateException("Failed to get the position of a BukkitPlayer (null)")
),
plugin.getServerName());
}
@@ -104,7 +115,7 @@ public class BukkitUser extends OnlineUser {
}
@Override
public void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException {
public void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException {
// Ensure the world exists
final Optional<org.bukkit.Location> resolvedLocation = BukkitAdapter.adaptLocation(location);
if (resolvedLocation.isEmpty() || resolvedLocation.get().getWorld() == null) {
@@ -120,7 +131,7 @@ public class BukkitUser extends OnlineUser {
// Run on the appropriate thread scheduler for this platform
plugin.getScheduler().entitySpecificScheduler(player).run(
() -> {
if (asynchronous || plugin.getScheduler().isUsingFolia()) {
if (async || plugin.getScheduler().isUsingFolia()) {
PaperLib.teleportAsync(player, bukkitLocation, PlayerTeleportEvent.TeleportCause.PLUGIN);
return;
}
@@ -131,7 +142,7 @@ public class BukkitUser extends OnlineUser {
}
/**
* Get the player momentum and return if they are moving
* Get the player momentum and return if they are moving.
*
* @return {@code true} if the player is moving, {@code false} otherwise
**/
@@ -141,7 +152,7 @@ public class BukkitUser extends OnlineUser {
}
/**
* Return the value of the player's "vanished" metadata tag if they have it
* Return the value of the player's "vanished" metadata tag if they have it.
*
* @return {@code true} if the player is vanished, {@code false} otherwise
*/
@@ -155,18 +166,10 @@ public class BukkitUser extends OnlineUser {
}
/**
* Send a Bukkit plugin message to the player
* Send a Bukkit plugin message to the player.
*/
public void sendPluginMessage(@NotNull String channel, final byte[] message) {
player.sendPluginMessage(plugin, channel, message);
}
/**
* Return the {@link Player} wrapped by this {@link BukkitUser}
*
* @return the {@link Player} wrapped by this {@link BukkitUser}
*/
public Player getPlayer() {
return player;
}
}
@@ -28,12 +28,12 @@ import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Static class providing utility methods for adapting Bukkit objects to HuskHomes and vice versa
* Static class providing utility methods for adapting Bukkit objects to HuskHomes and vice versa.
*/
public final class BukkitAdapter {
/**
* Adapt a Bukkit {@link org.bukkit.Location} to a HuskHomes {@link Location}
* Adapt a Bukkit {@link org.bukkit.Location} to a HuskHomes {@link Location}.
*
* @param location the Bukkit {@link org.bukkit.Location} to adapt
* @return the adapted {@link Location}
@@ -45,8 +45,9 @@ public final class BukkitAdapter {
}
if (world == null) {
world = Bukkit.getWorlds().stream()
.filter(w -> w.getEnvironment().name().equalsIgnoreCase(location.getWorld().getEnvironment().name()))
.findFirst().orElse(null);
.filter(w -> w.getEnvironment().name().equalsIgnoreCase(
location.getWorld().getEnvironment().name())).findFirst()
.orElse(null);
}
if (world == null) {
return Optional.empty();
@@ -62,13 +63,15 @@ public final class BukkitAdapter {
}
/**
* Adapt a HuskHomes {@link org.bukkit.Location} to a Bukkit {@link org.bukkit.Location}
* Adapt a HuskHomes {@link org.bukkit.Location} to a Bukkit {@link org.bukkit.Location}.
*
* @param location the HuskHomes {@link org.bukkit.Location} to adapt
* @return the adapted {@link org.bukkit.Location}
*/
public static Optional<Location> adaptLocation(@NotNull org.bukkit.Location location) {
if (location.getWorld() == null) return Optional.empty();
if (location.getWorld() == null) {
return Optional.empty();
}
return Optional.of(Location.at(location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch(),
adaptWorld(location.getWorld()).orElse(new net.william278.huskhomes.position.World())));
@@ -78,12 +81,13 @@ public final class BukkitAdapter {
if (world == null) {
return Optional.empty();
}
return Optional.of(World.from(world.getName(), world.getUID(),
return Optional.of(World.from(
world.getName(), world.getUID(),
switch (world.getEnvironment()) {
case NORMAL -> World.Environment.OVERWORLD;
case NETHER -> World.Environment.NETHER;
case THE_END -> World.Environment.THE_END;
case CUSTOM -> World.Environment.CUSTOM;
default -> World.Environment.CUSTOM;
})
);
}
@@ -54,49 +54,50 @@ public interface BukkitSafetyResolver extends SafetyResolver {
}
/**
* Search for a safe ground location near the given location
* Search for a safe ground location near the given location.
*
* @param location The location to search around
* @param snapshot The chunk snapshot to search
* @param chunk The chunk snapshot to search
* @param minY The minimum Y value of the world
* @return An optional safe location, within 4 blocks of the given location
*/
private Optional<Location> findSafeLocationNear(@NotNull Location location, @NotNull ChunkSnapshot snapshot, int minY) {
private Optional<Location> findSafeLocationNear(@NotNull Location location, @NotNull ChunkSnapshot chunk,
int minY) {
final int chunkX = ((int) location.getX()) & 0xF;
final int chunkZ = ((int) location.getZ()) & 0xF;
for (int dX = -SEARCH_RADIUS; dX <= SEARCH_RADIUS; dX++) {
for (int dZ = -SEARCH_RADIUS; dZ <= SEARCH_RADIUS; dZ++) {
final int x = chunkX + dX;
final int z = chunkZ + dZ;
for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
for (int dz = -SEARCH_RADIUS; dz <= SEARCH_RADIUS; dz++) {
final int x = chunkX + dx;
final int z = chunkZ + dz;
if (x < 0 || x >= 16 || z < 0 || z >= 16) {
continue;
}
final int y = Math.max((minY + 1), snapshot.getHighestBlockYAt(x, z)) + 1;
final Material blockType = snapshot.getBlockType(x, y - 1, z);
final Material bodyBlockType = snapshot.getBlockType(x, y, z);
final Material headBlockType = snapshot.getBlockType(x, y + 1, z);
final int y = Math.max((minY + 1), chunk.getHighestBlockYAt(x, z)) + 1;
final Material blockType = chunk.getBlockType(x, y - 1, z);
final Material bodyBlockType = chunk.getBlockType(x, y, z);
final Material headBlockType = chunk.getBlockType(x, y + 1, z);
if (isBlockSafeForStanding(blockType.getKey().toString())
&& isBlockSafeForOccupation(bodyBlockType.getKey().toString())
&& isBlockSafeForOccupation(headBlockType.getKey().toString())) {
double locx = Math.floor(location.getX()) + dX;
if (locx < 0) {
locx += 1.5d;
} else {
locx = locx + 0.5d;
}
double locz = Math.floor(location.getZ()) + dZ;
if (locz < 0) {
locz += 1.5d;
} else {
locz = locz + 0.5d;
}
return Optional.of(Location.at(
locx,
y,
locz,
location.getWorld()
));
&& isBlockSafeForOccupation(bodyBlockType.getKey().toString())
&& isBlockSafeForOccupation(headBlockType.getKey().toString())) {
double locx = Math.floor(location.getX()) + dx;
if (locx < 0) {
locx += 1.5d;
} else {
locx = locx + 0.5d;
}
double locz = Math.floor(location.getZ()) + dz;
if (locz < 0) {
locz += 1.5d;
} else {
locz = locz + 0.5d;
}
return Optional.of(Location.at(
locx,
y,
locz,
location.getWorld()
));
}
}
}