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

* feat: start database refactor

Adds database migrations

* refactor: refactor database system

Now supports migrations

* refactor: begin major internals rewrite

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

* refactor: remove sponge, checkstyle

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

* refactor: implement refactoring changes on fabric

also fix various refactor quirks on Bukkit

* refactor: tidy metrics logic

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

No files matched your search

@@ -51,10 +51,9 @@ import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.Spawn;
import net.william278.huskhomes.database.*;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.FabricEventDispatcher;
import net.william278.huskhomes.hook.FabricImpactorEconomyHook;
import net.william278.huskhomes.hook.FabricPlaceholderAPIHook;
import net.william278.huskhomes.hook.FabricHookProvider;
import net.william278.huskhomes.hook.Hook;
import net.william278.huskhomes.listener.EventListener;
import net.william278.huskhomes.listener.FabricEventListener;
@@ -62,20 +61,14 @@ import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.FabricPluginMessage;
import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.FabricUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.util.FabricSafetyResolver;
import net.william278.huskhomes.user.*;
import net.william278.huskhomes.util.FabricSavePositionProvider;
import net.william278.huskhomes.util.FabricTask;
import net.william278.huskhomes.util.UnsafeBlocks;
import net.william278.huskhomes.util.Validator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
@@ -87,152 +80,92 @@ import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.stream.Collectors;
@Getter
@Setter
@NoArgsConstructor
public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier,
FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayPayloadHandler<FabricPluginMessage> {
FabricEventDispatcher, FabricSavePositionProvider, FabricUserProvider, FabricHookProvider,
ServerPlayNetworking.PlayPayloadHandler<FabricPluginMessage> {
public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes");
private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes")
.orElseThrow(() -> new RuntimeException("Failed to get Mod Container"));
private final Map<String, Boolean> permissions = Maps.newHashMap();
private final Set<SavedUser> savedUsers = Sets.newHashSet();
private final ConcurrentMap<String, List<String>> globalPlayerList = Maps.newConcurrentMap();
private final Set<UUID> currentlyOnWarmup = Sets.newHashSet();
private final Set<UUID> currentlyInvulnerable = Sets.newHashSet();
private MinecraftServer minecraftServer;
private MinecraftServer minecraftServer;
private MinecraftServerAudiences audiences;
private final Set<SavedUser> savedUsers = Sets.newHashSet();
private final Set<UUID> currentlyOnWarmup = Sets.newConcurrentHashSet();
private final Set<UUID> currentlyInvulnerable = Sets.newConcurrentHashSet();
private final Map<UUID, OnlineUser> onlineUserMap = Maps.newHashMap();
private final Map<String, List<User>> globalUserList = Maps.newConcurrentMap();
private final List<Command> commands = Lists.newArrayList();
@Setter
private Set<Hook> hooks = Sets.newHashSet();
@Setter
private Settings settings;
@Setter
private Locales locales;
@Setter
private Database database;
private Validator validator;
@Setter
private Manager manager;
@Setter
private EventListener eventListener;
@Setter
private RandomTeleportEngine randomTeleportEngine;
@Setter
private Spawn serverSpawn;
@Setter
private UnsafeBlocks unsafeBlocks;
private List<Hook> hooks;
private List<Command> commands;
private Server server;
@Setter
@Nullable
private Broker broker;
private MinecraftServerAudiences audiences;
@Setter
@Nullable
private Server serverName;
@Override
public void onInitializeServer() {
// Get plugin version from mod container
this.validator = new Validator(this);
this.load();
this.loadCommands();
// Load settings and locales
initialize("plugin config & locale files", (plugin) -> loadConfigs());
// Pre-register commands
initialize("commands", (plugin) -> this.commands = registerCommands());
ServerLifecycleEvents.SERVER_STARTING.register(server -> {
this.minecraftServer = server;
this.onEnable();
});
ServerLifecycleEvents.SERVER_STOPPING.register(server -> this.onDisable());
ServerLifecycleEvents.SERVER_STARTING.register(this::onEnable);
ServerLifecycleEvents.SERVER_STOPPING.register(this::onDisable);
}
private void onEnable() {
// Create adventure audience
private void onEnable(@NotNull MinecraftServer server) {
this.minecraftServer = server;
this.audiences = MinecraftServerAudiences.of(minecraftServer);
// Initialize the database
final Database.Type type = getSettings().getDatabase().getType();
initialize(type.getDisplayName() + " database connection", (plugin) -> {
this.database = switch (type) {
case MYSQL, MARIADB -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this);
case H2 -> new H2Database(this);
case POSTGRESQL -> new PostgreSqlDatabase(this);
};
database.initialize();
});
// Initialize the manager
this.manager = new Manager(this);
// Initialize the network messenger if proxy mode is enabled
final Settings.CrossServerSettings crossServer = getSettings().getCrossServer();
if (crossServer.isEnabled()) {
initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> {
broker = switch (crossServer.getBrokerType()) {
case PLUGIN_MESSAGE -> new PluginMessageBroker(this);
case REDIS -> new RedisBroker(this);
};
broker.initialize();
});
}
setRandomTeleportEngine(new NormalDistributionEngine(this));
// Register plugin hooks (Economy, Maps, Plan)
initialize("hooks", (plugin) -> {
this.registerHooks();
if (!hooks.isEmpty()) {
hooks.forEach(hook -> {
try {
hook.initialize();
} catch (Throwable e) {
log(Level.WARNING, "Failed to initialize " + hook.getName() + " hook", e);
}
});
log(Level.INFO, "Registered " + hooks.size() + " mod hooks: " + hooks.stream()
.map(Hook::getName)
.collect(Collectors.joining(", ")));
}
});
// Register events
initialize("events", (plugin) -> this.eventListener = new FabricEventListener(this));
// Initialize the API
initialize("API", (plugin) -> FabricHuskHomesAPI.register(this));
this.checkForUpdates();
this.enable();
}
@Override
public void registerHooks() {
HuskHomes.super.registerHooks();
// Register the impactor economy service if it is available
if (getSettings().getEconomy().isEnabled() && isDependencyLoaded("impactor")) {
getHooks().add(new FabricImpactorEconomyHook(this));
}
if (isDependencyLoaded("placeholder-api")) {
getHooks().add(new FabricPlaceholderAPIHook(this));
}
}
private void onDisable() {
if (this.eventListener != null) {
this.eventListener.handlePluginDisable();
}
if (database != null) {
database.terminate();
}
if (broker != null) {
broker.close();
}
private void onDisable(@NotNull MinecraftServer server) {
this.shutdown();
if (audiences != null) {
audiences.close();
audiences = null;
}
cancelTasks();
}
@Override
public void loadAPI() {
FabricHuskHomesAPI.register(this);
}
@Override
public void loadMetrics() {
// No metrics on Fabric
}
@Override
public void disablePlugin() {
onDisable(minecraftServer);
}
@Override
@@ -241,14 +174,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return new ConsoleUser(audiences.console());
}
@Override
@NotNull
public List<OnlineUser> getOnlineUsers() {
return minecraftServer.getPlayerManager().getPlayerList()
.stream().map(user -> (OnlineUser) FabricUser.adapt(user, this))
.toList();
}
@NotNull
@Override
public Audience getAudience(@NotNull UUID user) {
@@ -274,21 +199,12 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
@Override
@NotNull
public String getServerName() {
return server == null ? "server" : server.getName();
return serverName == null ? "server" : serverName.getName();
}
@Override
public void setServerName(@NotNull Server server) {
this.server = server;
}
@Override
@NotNull
public Broker getMessenger() {
if (broker == null) {
throw new IllegalStateException("Attempted to access message broker when it was not initialized");
}
return broker;
public boolean isDependencyAvailable(@NotNull String name) {
return FabricLoader.getInstance().isModLoaded(name);
}
@Override
@@ -322,31 +238,44 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
@Override
@NotNull
public Version getVersion() {
public Version getPluginVersion() {
return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-");
}
@Override
@NotNull
public List<Command> registerCommands() {
final List<Command> commands = FabricCommand.Type.getCommands(getPlugin());
CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) ->
commands.forEach(command -> new FabricCommand(command, this).register(dispatcher)));
return commands;
public String getServerType() {
return String.format("fabric %s/%s", FabricLoader.getInstance()
.getModContainer("fabricloader").map(l -> l.getMetadata().getVersion().getFriendlyString())
.orElse("unknown"), minecraftServer.getVersion());
}
@Override
public boolean isDependencyLoaded(@NotNull String name) {
return FabricLoader.getInstance().isModLoaded(name)
|| FabricLoader.getInstance().isModLoaded(name.toLowerCase(Locale.ENGLISH));
@NotNull
public Version getMinecraftVersion() {
return Version.fromString(minecraftServer.getVersion());
}
@Override
public void registerMetrics(int metricsId) {
// No metrics for Fabric
public void registerCommands(@NotNull List<Command> commands) {
CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) -> commands.forEach(
(command) -> new FabricCommand(command, this).register(dispatcher))
);
}
@Override
public void initializePluginChannels() {
@NotNull
public EventListener createListener() {
return new FabricEventListener(this);
}
@Override
public Optional<Broker> getBroker() {
return Optional.ofNullable(broker);
}
@Override
public void setupPluginMessagingChannels() {
PayloadTypeRegistry.playC2S().register(FabricPluginMessage.CHANNEL_ID, FabricPluginMessage.CODEC);
PayloadTypeRegistry.playS2C().register(FabricPluginMessage.CHANNEL_ID, FabricPluginMessage.CODEC);
ServerPlayNetworking.registerGlobalReceiver(FabricPluginMessage.CHANNEL_ID, this);
@@ -356,10 +285,10 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
@Override
public void receive(@NotNull FabricPluginMessage payload, @NotNull ServerPlayNetworking.Context context) {
if (broker instanceof PluginMessageBroker messenger
&& getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
&& getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
messenger.onReceive(
PluginMessageBroker.BUNGEE_CHANNEL_ID,
FabricUser.adapt(context.player(), this),
getOnlineUser(context.player()),
payload.getData()
);
}
@@ -380,14 +309,18 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
logEvent.log(message);
}
@NotNull
public Map<String, Boolean> getPermissions() {
return permissions;
@Override
public void closeDatabase() {
if (database != null) {
database.close();
}
}
@NotNull
public MinecraftServer getMinecraftServer() {
return minecraftServer;
@Override
public void closeBroker() {
if (broker != null) {
broker.close();
}
}
@Override
@@ -87,7 +87,7 @@ public class FabricHuskHomesAPI extends BaseHuskHomesAPI {
*/
@NotNull
public OnlineUser adaptUser(@NotNull ServerPlayerEntity player) {
return FabricUser.adapt(player, (FabricHuskHomes) plugin);
return ((FabricHuskHomes) plugin).getOnlineUser(player);
}
/**
@@ -28,17 +28,10 @@ import net.fabricmc.fabric.api.util.TriState;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.william278.huskhomes.FabricHuskHomes;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.FabricUser;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
@@ -97,7 +90,7 @@ public class FabricCommand {
}
private com.mojang.brigadier.suggestion.SuggestionProvider<ServerCommandSource> getBrigadierSuggester() {
if (!(command instanceof TabProvider provider)) {
if (!(command instanceof TabCompletable provider)) {
return (context, builder) -> com.mojang.brigadier.suggestion.Suggestions.empty();
}
return (context, builder) -> {
@@ -118,64 +111,9 @@ public class FabricCommand {
private CommandUser resolveExecutor(@NotNull ServerCommandSource source) {
if (source.getEntity() instanceof ServerPlayerEntity player) {
return FabricUser.adapt(player, plugin);
return plugin.getOnlineUser(player);
}
return plugin.getConsole();
}
/**
* Commands available on the Fabric HuskHomes implementation.
*/
public enum Type {
HOME_COMMAND(PrivateHomeCommand::new),
SET_HOME_COMMAND(SetHomeCommand::new),
HOME_LIST_COMMAND(HomeListCommand::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 Function<HuskHomes, Command> supplier;
Type(@NotNull Function<HuskHomes, Command> supplier) {
this.supplier = supplier;
}
@NotNull
public Command createCommand(@NotNull HuskHomes plugin) {
return supplier.apply(plugin);
}
@NotNull
public static List<Command> getCommands(@NotNull FabricHuskHomes plugin) {
return Arrays.stream(values())
.map(type -> type.createCommand(plugin))
.map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command)
.filter(Objects::nonNull)
.toList();
}
}
}
@@ -0,0 +1,60 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.hook;
import net.fabricmc.loader.api.FabricLoader;
import net.william278.huskhomes.FabricHuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Locale;
public interface FabricHookProvider extends HookProvider {
@Override
@NotNull
default List<Hook> getAvailableHooks() {
final List<Hook> hooks = HookProvider.super.getAvailableHooks();
// Register the impactor economy service if it is available
if (getPlugin().getSettings().getEconomy().isEnabled() && isDependencyAvailable("impactor")) {
getHooks().add(new FabricImpactorEconomyHook(getPlugin()));
}
if (isDependencyAvailable("placeholder-api")) {
getHooks().add(new FabricPlaceholderAPIHook(getPlugin()));
}
return hooks;
}
@Override
default boolean isDependencyAvailable(@NotNull String name) {
return FabricLoader.getInstance().isModLoaded(name)
|| FabricLoader.getInstance().isModLoaded(name.toLowerCase(Locale.ENGLISH));
}
@Override
@NotNull
FabricHuskHomes getPlugin();
}
@@ -35,7 +35,21 @@ public class FabricImpactorEconomyHook extends EconomyHook {
private Currency currency;
public FabricImpactorEconomyHook(@NotNull HuskHomes plugin) {
super(plugin, "Fabric Impactor Economy");
super(plugin);
}
@Override
public void load() {
this.economyService = EconomyService.instance();
if (this.economyService == null) {
throw new IllegalStateException("Impactor API is not available, No economy service has been registered!");
}
this.currency = this.economyService.currencies().primary();
}
@Override
public void unload() {
this.economyService = null;
}
@Override
@@ -73,13 +87,4 @@ public class FabricImpactorEconomyHook extends EconomyHook {
public String formatCurrency(double amount) {
return PlainTextComponentSerializer.plainText().serialize(currency.format(BigDecimal.valueOf(amount)));
}
@Override
public void initialize() {
this.economyService = EconomyService.instance();
if (this.economyService == null) {
throw new IllegalStateException("Impactor API is not available, No economy service has been registered!");
}
this.currency = this.economyService.currencies().primary();
}
}
@@ -23,17 +23,20 @@ import eu.pb4.placeholders.api.PlaceholderResult;
import eu.pb4.placeholders.api.Placeholders;
import net.minecraft.util.Identifier;
import net.william278.huskhomes.FabricHuskHomes;
import net.william278.huskhomes.user.FabricUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@PluginHook(
name = "Fabric PlaceholderAPI",
register = PluginHook.Register.ON_ENABLE
)
public class FabricPlaceholderAPIHook extends Hook {
public FabricPlaceholderAPIHook(@NotNull FabricHuskHomes plugin) {
super(plugin, "Fabric PlaceholderAPI");
super(plugin);
}
@SuppressWarnings("SameParameterValue")
@@ -43,7 +46,7 @@ public class FabricPlaceholderAPIHook extends Hook {
}
@Override
public void initialize() {
public void load() {
Placeholders.register(createIdentifier("player"), (ctx, arg) -> {
if (!ctx.hasPlayer()) {
return PlaceholderResult.invalid("No player!");
@@ -54,12 +57,12 @@ public class FabricPlaceholderAPIHook extends Hook {
}
assert ctx.player() != null;
final OnlineUser player = FabricUser.adapt(ctx.player(), (FabricHuskHomes) plugin);
final OnlineUser player = ((FabricHuskHomes) plugin).getOnlineUser(ctx.player());
final String response = switch (arg) {
case "homes_count" -> String.valueOf(plugin.getManager().homes()
.getUserHomes()
.getOrDefault(player.getUsername(), List.of()).size());
.getOrDefault(player.getName(), List.of()).size());
case "max_homes" -> String.valueOf(plugin.getManager().homes().getMaxHomes(player));
case "max_public_homes" -> String.valueOf(plugin.getManager().homes().getMaxPublicHomes(player));
case "free_home_slots" -> String.valueOf(plugin.getManager().homes().getFreeHomes(player));
@@ -67,13 +70,13 @@ public class FabricPlaceholderAPIHook extends Hook {
.map(SavedUser::getHomeSlots).orElse(0));
case "homes_list" -> String.join(", ", plugin.getManager().homes()
.getUserHomes()
.getOrDefault(player.getUsername(), List.of()));
.getOrDefault(player.getName(), List.of()));
case "public_homes_count" -> String.valueOf(plugin.getManager().homes()
.getPublicHomes()
.getOrDefault(player.getUsername(), List.of()).size());
.getOrDefault(player.getName(), List.of()).size());
case "public_homes_list" -> String.join(", ", plugin.getManager().homes()
.getPublicHomes()
.getOrDefault(player.getUsername(), List.of()));
.getOrDefault(player.getName(), List.of()));
case "ignoring_tp_requests" -> String.valueOf(plugin.getManager().requests()
.isIgnoringRequests(player));
default -> null;
@@ -86,4 +89,10 @@ public class FabricPlaceholderAPIHook extends Hook {
return PlaceholderResult.value(response);
});
}
@Override
public void unload() {
Placeholders.remove(createIdentifier("player"));
}
}
@@ -24,7 +24,6 @@ import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.server.network.ServerPlayerEntity;
import net.william278.huskhomes.FabricHuskHomes;
import net.william278.huskhomes.user.FabricUser;
import org.jetbrains.annotations.NotNull;
// Note that the teleport event and update player respawn position events are not handled on Fabric.
@@ -33,32 +32,37 @@ public class FabricEventListener extends EventListener {
public FabricEventListener(@NotNull FabricHuskHomes plugin) {
super(plugin);
this.registerEvents(plugin);
}
// Register fabric event callback listeners to internal handlers
private void registerEvents(@NotNull FabricHuskHomes plugin) {
@Override
public void register() {
// Join event
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> handlePlayerJoin(
FabricUser.adapt(handler.player, plugin)
getPlugin().getOnlineUser(handler.player)
));
// Quit event
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> handlePlayerLeave(
FabricUser.adapt(handler.player, plugin)
getPlugin().getOnlineUser(handler.player)
));
// Death event
ServerLivingEntityEvents.AFTER_DEATH.register((entity, source) -> {
if (entity instanceof ServerPlayerEntity player) {
handlePlayerDeath(FabricUser.adapt(player, plugin));
handlePlayerDeath(getPlugin().getOnlineUser(player));
}
});
// Respawn event
ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> handlePlayerRespawn(
FabricUser.adapt(newPlayer, plugin)
getPlugin().getOnlineUser(newPlayer)
));
}
@NotNull
@Override
protected FabricHuskHomes getPlugin() {
return (FabricHuskHomes) super.getPlugin();
}
}
@@ -33,6 +33,7 @@ import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.teleport.TeleportationException;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.util.*;
@@ -48,6 +49,7 @@ public class FabricUser extends OnlineUser {
}
@NotNull
@ApiStatus.Internal
public static FabricUser adapt(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) {
return new FabricUser(player, plugin);
}
@@ -0,0 +1,54 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.user;
import net.minecraft.server.network.ServerPlayerEntity;
import net.william278.huskhomes.FabricHuskHomes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
public interface FabricUserProvider extends UserProvider {
@Override
@NotNull
default OnlineUser getOnlineUser(@NotNull UUID uuid) {
return getOnlineUser(getPlugin().getMinecraftServer().getPlayerManager().getPlayer(uuid));
}
@NotNull
default FabricUser getOnlineUser(@Nullable ServerPlayerEntity player) {
if (player == null) {
throw new IllegalArgumentException("Player is not online");
}
FabricUser user = (FabricUser) getOnlineUserMap().get(player.getUuid());
if (user == null) {
user = FabricUser.adapt(player, getPlugin());
getOnlineUserMap().put(player.getUuid(), user);
return user;
}
return user;
}
@NotNull
FabricHuskHomes getPlugin();
}
@@ -36,7 +36,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public interface FabricSafetyResolver extends SafetyResolver {
public interface FabricSavePositionProvider extends SavePositionProvider {
@Override
default CompletableFuture<Optional<Location>> findSafeGroundLocation(@NotNull Location location) {