Add Fabric 1.19.4 server-side mod support (#348)

This commit is contained in:
William authored and GitHub committed 2023-04-11 21:44:44 +01:00
1 parent 1bdf21dd7d
commit 29e0ed6ef4
181 files changed
+5566 -67

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
plugins {
id 'fabric-loom' version '1.1-SNAPSHOT'
}
apply plugin: 'fabric-loom'
loom.serverOnlyMinecraftJar()
dependencies {
minecraft 'com.mojang:minecraft:1.19.4'
mappings 'net.fabricmc:yarn:1.19.4+build.2'
modImplementation 'net.fabricmc:fabric-loader:0.14.19'
// Fabric API modules
Set<String> fabricApiModules = [
'fabric-api-base',
'fabric-lifecycle-events-v1',
'fabric-entity-events-v1',
'fabric-command-api-v2',
'fabric-networking-api-v1'
]
fabricApiModules.forEach {
modImplementation(fabricApi.module(it, '0.77.0+1.19.4'))
}
modImplementation include('net.kyori:adventure-platform-fabric:5.8.0')
modImplementation include('me.lucko:fabric-permissions-api:0.2-SNAPSHOT')
implementation include('redis.clients:jedis:' + jedis_version)
implementation include('com.mysql:mysql-connector-j:' + mysql_driver_version)
implementation include('org.xerial:sqlite-jdbc:' + sqlite_driver_version)
compileOnly 'org.jetbrains:annotations:24.0.1'
shadow project(path: ":common")
}
shadowJar {
configurations = [project.configurations.shadow]
destinationDirectory.set(file("$projectDir/build/libs"))
exclude('net.fabricmc:.*')
exclude('net.kyori:.*')
exclude '/mappings/*'
relocate 'org.apache.commons.io', 'net.william278.huskhomes.libraries.commons.io'
relocate 'org.apache.commons.text', 'net.william278.huskhomes.libraries.commons.text'
relocate 'org.apache.commons.lang3', 'net.william278.huskhomes.libraries.commons.lang3'
relocate 'de.themoep', 'net.william278.huskhomes.libraries'
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown'
relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell'
relocate 'dev.dejvokep.boostedyaml', 'net.william278.huskhomes.libraries.boostedyaml'
relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
}
remapJar {
dependsOn tasks.shadowJar
mustRunAfter tasks.shadowJar
inputFile = shadowJar.archiveFile.get()
addNestedDependencies = true
destinationDirectory.set(file("$rootDir/target/"))
archiveClassifier.set('')
}
shadowJar.finalizedBy(remapJar)
@@ -0,0 +1,479 @@
/*
* 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;
import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.Version;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.FabricCommand;
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.Database;
import net.william278.huskhomes.database.MySqlDatabase;
import net.william278.huskhomes.database.SqLiteDatabase;
import net.william278.huskhomes.event.FabricEventDispatcher;
import net.william278.huskhomes.hook.Hook;
import net.william278.huskhomes.listener.EventListener;
import net.william278.huskhomes.listener.FabricEventListener;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.position.Location;
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.FabricTaskRunner;
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;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LoggingEventBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes,
FabricTaskRunner, FabricEventDispatcher, ServerPlayNetworking.PlayChannelHandler {
public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes");
private static FabricHuskHomes instance;
@NotNull
public static FabricHuskHomes getInstance() {
return instance;
}
private final ModContainer modContainer = FabricLoader.getInstance()
.getModContainer("huskhomes").orElseThrow(() -> new RuntimeException("Failed to get Mod Container"));
private MinecraftServer minecraftServer;
private Map<String, Boolean> permissions;
private Set<SavedUser> savedUsers;
private Settings settings;
private Locales locales;
private Database database;
private Validator validator;
private Manager manager;
private EventListener eventListener;
private RandomTeleportEngine randomTeleportEngine;
private Spawn serverSpawn;
private UnsafeBlocks unsafeBlocks;
private List<Hook> hooks;
private List<Command> commands;
private Map<String, List<String>> globalPlayerList;
private Set<UUID> currentlyOnWarmup;
private Server server;
@Nullable
private Broker broker;
private FabricServerAudiences audiences;
@Override
public void onInitializeServer() {
// Set instance
instance = this;
// Get plugin version from mod container
this.permissions = new HashMap<>();
this.savedUsers = new HashSet<>();
this.globalPlayerList = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.validator = new Validator(this);
// Load settings and locales
initialize("plugin config & locale files", (plugin) -> {
if (!loadConfigs()) {
throw new IllegalStateException("Failed to load config files. Please check the console for errors");
}
});
// 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());
}
private void onEnable() {
// Create adventure audience
this.audiences = FabricServerAudiences.of(minecraftServer);
// Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> {
this.database = switch (getSettings().getDatabaseType()) {
case MYSQL -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this);
};
database.initialize();
});
// Initialize the manager
this.manager = new Manager(this);
// Initialize the network messenger if proxy mode is enabled
if (getSettings().doCrossServer()) {
initialize(settings.getBrokerType().getDisplayName() + " message broker", (plugin) -> {
broker = switch (settings.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.size() > 0) {
hooks.forEach(Hook::initialize);
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));
this.checkForUpdates();
}
private void onDisable() {
if (this.eventListener != null) {
this.eventListener.handlePluginDisable();
}
if (database != null) {
database.terminate();
}
if (broker != null) {
broker.close();
}
if (audiences != null) {
audiences.close();
audiences = null;
}
cancelAllTasks();
}
@Override
@NotNull
public ConsoleUser getConsole() {
return new ConsoleUser(audiences.console());
}
@Override
@NotNull
public List<OnlineUser> getOnlineUsers() {
return minecraftServer.getPlayerManager().getPlayerList()
.stream().map(user -> (OnlineUser) FabricUser.adapt(this, user))
.toList();
}
@Override
@NotNull
public Set<SavedUser> getSavedUsers() {
return savedUsers;
}
@Override
@NotNull
public Settings getSettings() {
return settings;
}
@Override
public void setSettings(@NotNull Settings settings) {
this.settings = settings;
}
@Override
@NotNull
public Locales getLocales() {
return locales;
}
@Override
public void setLocales(@NotNull Locales locales) {
this.locales = locales;
}
@Override
public Optional<Spawn> getServerSpawn() {
return Optional.ofNullable(serverSpawn);
}
@Override
public void setServerSpawn(@NotNull Spawn spawn) {
this.serverSpawn = spawn;
}
@Override
@NotNull
public String getServerName() {
return server.getName();
}
@Override
public void setServer(@NotNull Server server) {
this.server = server;
}
@Override
public void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks) {
this.unsafeBlocks = unsafeBlocks;
}
@Override
@NotNull
public Database getDatabase() {
return database;
}
@Override
@NotNull
public Validator getValidator() {
return validator;
}
@Override
@NotNull
public Manager getManager() {
return manager;
}
@Override
@NotNull
public Broker getMessenger() {
if (broker == null) {
throw new IllegalStateException("Attempted to access message broker when it was not initialized");
}
return broker;
}
@Override
@NotNull
public RandomTeleportEngine getRandomTeleportEngine() {
return randomTeleportEngine;
}
@Override
public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) {
this.randomTeleportEngine = randomTeleportEngine;
}
@Override
public void setServerSpawn(@NotNull Location location) {
try {
this.serverSpawn = Annotaml.create(new File(getDataFolder(), "spawn.yml"), new Spawn(location)).get();
// Update the world spawn location, too
minecraftServer.getWorlds().forEach(world -> {
if (world.getRegistryKey().getValue().asString().equals(location.getWorld().getName())) {
world.setSpawnPos(BlockPos.ofFloored(location.getX(), location.getY(), location.getZ()), 0);
}
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.WARNING, "Failed to save the server spawn.yml file", e);
}
}
@Override
@NotNull
public List<Hook> getHooks() {
return hooks;
}
@Override
public void setHooks(@NotNull List<Hook> hooks) {
this.hooks = hooks;
}
@Override
public CompletableFuture<Optional<Location>> findSafeGroundLocation(@NotNull Location location) {
return CompletableFuture.completedFuture(Optional.of(location)); //todo
}
@Override
@Nullable
public InputStream getResource(@NotNull String name) {
return this.modContainer.findPath(name)
.map(path -> {
try {
return Files.newInputStream(path);
} catch (IOException e) {
log(Level.WARNING, "Failed to load resource: " + name, e);
}
return null;
})
.orElse(this.getClass().getClassLoader().getResourceAsStream(name));
}
@Override
@NotNull
public File getDataFolder() {
return FabricLoader.getInstance().getConfigDir().resolve("huskhomes").toFile();
}
@Override
@NotNull
public List<World> getWorlds() {
final List<World> worlds = new ArrayList<>();
minecraftServer.getWorlds().forEach(world -> worlds.add(World.from(
world.getRegistryKey().getValue().asString(),
UUID.nameUUIDFromBytes(world.getRegistryKey().getValue().asString().getBytes())
)));
return worlds;
}
@Override
@NotNull
public Version getVersion() {
return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-");
}
@Override
@NotNull
public List<Command> getCommands() {
return commands;
}
@Override
@NotNull
public List<Command> registerCommands() {
final List<Command> commands = Arrays.stream(FabricCommand.Type.values())
.map(FabricCommand.Type::getCommand)
.filter(command -> !settings.isCommandDisabled(command))
.toList();
CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) ->
commands.forEach(command -> new FabricCommand(command, this).register(dispatcher)));
return commands;
}
@Override
public boolean isDependencyLoaded(@NotNull String name) {
return FabricLoader.getInstance().isModLoaded(name);
}
@Override
@NotNull
public Map<String, List<String>> getGlobalPlayerList() {
return globalPlayerList;
}
@Override
@NotNull
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
@Override
public boolean isBlockUnsafe(@NotNull String blockId) {
return unsafeBlocks.isUnsafe(blockId);
}
@Override
public void registerMetrics(int metricsId) {
// No metrics for Fabric
}
@Override
public void initializePluginChannels() {
ServerPlayNetworking.registerGlobalReceiver(new Identifier("bungeecord", "main"), this);
}
// When a plugin message is received by the server
@Override
public void receive(@NotNull MinecraftServer server, @NotNull ServerPlayerEntity player,
@NotNull ServerPlayNetworkHandler handler, @NotNull PacketByteBuf buf, @NotNull PacketSender responseSender) {
if (broker != null && broker instanceof PluginMessageBroker pluginMessenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
pluginMessenger.onReceive(PluginMessageBroker.BUNGEE_CHANNEL_ID, FabricUser.adapt(this, player), buf.readByteArray());
}
}
@Override
public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... exceptions) {
LoggingEventBuilder logEvent = LOGGER.makeLoggingEventBuilder(
switch (level.getName()) {
case "WARNING" -> org.slf4j.event.Level.WARN;
case "SEVERE" -> org.slf4j.event.Level.ERROR;
default -> org.slf4j.event.Level.INFO;
}
);
if (exceptions.length >= 1) {
logEvent = logEvent.setCause(exceptions[0]);
}
logEvent.log(message);
}
@NotNull
public Map<String, Boolean> getPermissions() {
return permissions;
}
@NotNull
public MinecraftServer getMinecraftServer() {
return minecraftServer;
}
@Override
@NotNull
public FabricHuskHomes getPlugin() {
return this;
}
}
@@ -0,0 +1,162 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.fabric.api.permissions.v0.PermissionCheckEvent;
import me.lucko.fabric.api.permissions.v0.Permissions;
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.teleport.TeleportRequest;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.FabricUser;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
public class FabricCommand {
private final FabricHuskHomes plugin;
private final Command command;
public FabricCommand(@NotNull Command command, @NotNull FabricHuskHomes plugin) {
this.command = command;
this.plugin = plugin;
}
public void register(@NotNull CommandDispatcher<ServerCommandSource> dispatcher) {
// Register brigadier command
final LiteralArgumentBuilder<ServerCommandSource> builder = literal(command.getName())
.requires(Permissions.require(command.getPermission(), command.isOperatorCommand() ? 3 : 0))
.executes(getBrigadierExecutor());
plugin.getPermissions().put(command.getPermission(), command.isOperatorCommand());
if (!command.getRawUsage().isBlank()) {
builder.then(argument(command.getRawUsage().replaceAll("[<>\\[\\]]", ""), greedyString())
.executes(getBrigadierExecutor())
.suggests(getBrigadierSuggester()));
}
// Register additional permissions
final Map<String, Boolean> permissions = command.getAdditionalPermissions();
permissions.forEach((permission, isOp) -> plugin.getPermissions().put(permission, isOp));
PermissionCheckEvent.EVENT.register((player, node) -> {
if (permissions.containsKey(node) && permissions.get(node) && player.hasPermissionLevel(3)) {
return TriState.TRUE;
}
return TriState.DEFAULT;
});
// Register aliases
final LiteralCommandNode<ServerCommandSource> node = dispatcher.register(builder);
dispatcher.register(literal("huskhomes:" + command.getName()).executes(getBrigadierExecutor()).redirect(node));
command.getAliases().forEach(alias -> dispatcher.register(literal(alias).executes(getBrigadierExecutor()).redirect(node)));
}
private com.mojang.brigadier.Command<ServerCommandSource> getBrigadierExecutor() {
return (context) -> {
command.onExecuted(
resolveExecutor(context.getSource()),
command.removeFirstArg(context.getInput().split(" "))
);
return 1;
};
}
private com.mojang.brigadier.suggestion.SuggestionProvider<ServerCommandSource> getBrigadierSuggester() {
if (!(command instanceof TabProvider provider)) {
return (context, builder) -> com.mojang.brigadier.suggestion.Suggestions.empty();
}
return (context, builder) -> {
final String[] args = command.removeFirstArg(context.getInput().split(" "));
provider.getSuggestions(resolveExecutor(context.getSource()), args).stream()
.map(suggestion -> {
final String completedArgs = String.join(" ", args);
int lastIndex = completedArgs.lastIndexOf(" ");
if (lastIndex == -1) {
return suggestion;
}
return completedArgs.substring(0, lastIndex + 1) + suggestion;
})
.forEach(builder::suggest);
return builder.buildFuture();
};
}
private CommandUser resolveExecutor(@NotNull ServerCommandSource source) {
if (source.getEntity() instanceof ServerPlayerEntity player) {
return FabricUser.adapt(plugin, player);
}
return plugin.getConsole();
}
/**
* Commands available on the Fabric HuskHomes implementation
*/
public enum Type {
HOME_COMMAND(new PrivateHomeCommand(FabricHuskHomes.getInstance())),
SET_HOME_COMMAND(new SetHomeCommand(FabricHuskHomes.getInstance())),
HOME_LIST_COMMAND(new PrivateHomeListCommand(FabricHuskHomes.getInstance())),
DEL_HOME_COMMAND(new DelHomeCommand(FabricHuskHomes.getInstance())),
EDIT_HOME_COMMAND(new EditHomeCommand(FabricHuskHomes.getInstance())),
PUBLIC_HOME_COMMAND(new PublicHomeCommand(FabricHuskHomes.getInstance())),
PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(FabricHuskHomes.getInstance())),
WARP_COMMAND(new WarpCommand(FabricHuskHomes.getInstance())),
SET_WARP_COMMAND(new SetWarpCommand(FabricHuskHomes.getInstance())),
WARP_LIST_COMMAND(new WarpListCommand(FabricHuskHomes.getInstance())),
DEL_WARP_COMMAND(new DelWarpCommand(FabricHuskHomes.getInstance())),
EDIT_WARP_COMMAND(new EditWarpCommand(FabricHuskHomes.getInstance())),
TP_COMMAND(new TpCommand(FabricHuskHomes.getInstance())),
TP_HERE_COMMAND(new TpHereCommand(FabricHuskHomes.getInstance())),
TPA_COMMAND(new TeleportRequestCommand(FabricHuskHomes.getInstance(), TeleportRequest.Type.TPA)),
TPA_HERE_COMMAND(new TeleportRequestCommand(FabricHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)),
TPACCEPT_COMMAND(new TpRespondCommand(FabricHuskHomes.getInstance(), true)),
TPDECLINE_COMMAND(new TpRespondCommand(FabricHuskHomes.getInstance(), false)),
RTP_COMMAND(new RtpCommand(FabricHuskHomes.getInstance())),
TP_IGNORE_COMMAND(new TpIgnoreCommand(FabricHuskHomes.getInstance())),
TP_OFFLINE_COMMAND(new TpOfflineCommand(FabricHuskHomes.getInstance())),
TP_ALL_COMMAND(new TpAllCommand(FabricHuskHomes.getInstance())),
TPA_ALL_COMMAND(new TpaAllCommand(FabricHuskHomes.getInstance())),
SPAWN_COMMAND(new SpawnCommand(FabricHuskHomes.getInstance())),
SET_SPAWN_COMMAND(new SetSpawnCommand(FabricHuskHomes.getInstance())),
BACK_COMMAND(new BackCommand(FabricHuskHomes.getInstance())),
HUSKHOMES_COMMAND(new HuskHomesCommand(FabricHuskHomes.getInstance()));
private final Command command;
Type(@NotNull Command command) {
this.command = command;
}
@NotNull
public Command getCommand() {
return command;
}
}
}
@@ -0,0 +1,82 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface DeleteAllHomesCallback extends FabricEventCallback<IDeleteAllHomesEvent> {
@NotNull
Event<DeleteAllHomesCallback> EVENT = EventFactory.createArrayBacked(DeleteAllHomesCallback.class,
(listeners) -> (event) -> {
for (DeleteAllHomesCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<User, CommandUser, IDeleteAllHomesEvent> SUPPLIER = (owner, deleter) ->
new IDeleteAllHomesEvent() {
private boolean cancelled = false;
@Override
@NotNull
public User getHomeOwner() {
return owner;
}
@Override
@NotNull
public CommandUser getDeleter() {
return deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<DeleteAllHomesCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,75 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
public interface DeleteAllWarpsCallback extends FabricEventCallback<IDeleteAllWarpsEvent> {
@NotNull
Event<DeleteAllWarpsCallback> EVENT = EventFactory.createArrayBacked(DeleteAllWarpsCallback.class,
(listeners) -> (event) -> {
for (DeleteAllWarpsCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
Function<CommandUser, IDeleteAllWarpsEvent> SUPPLIER = (deleter) ->
new IDeleteAllWarpsEvent() {
private boolean cancelled = false;
@Override
@NotNull
public CommandUser getDeleter() {
return deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<DeleteAllWarpsCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,31 @@
/*
* 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.event;
import net.minecraft.util.ActionResult;
import org.jetbrains.annotations.NotNull;
public interface FabricEventCallback<E extends Event> {
@NotNull
ActionResult invoke(@NotNull E event);
}
@@ -0,0 +1,138 @@
/*
* 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.event;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.FabricHuskHomes;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Level;
public interface FabricEventDispatcher extends EventDispatcher {
@SuppressWarnings("unchecked")
@Override
default <T extends Event> boolean fireIsCancelled(@NotNull T event) {
try {
final Method field = event.getClass().getDeclaredMethod("getEvent");
field.setAccessible(true);
net.fabricmc.fabric.api.event.Event<?> fabricEvent = (net.fabricmc.fabric.api.event.Event<?>) field.invoke(event);
final FabricEventCallback<T> invoker = (FabricEventCallback<T>) fabricEvent.invoker();
return invoker.invoke(event) == ActionResult.FAIL;
} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
getPlugin().log(Level.WARNING, "Failed to fire event (" + event.getClass().getName() + ")", e);
return false;
}
}
@Override
default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) {
return TeleportCallback.SUPPLIER.apply(teleport);
}
@Override
default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
return TeleportWarmupCallback.SUPPLIER.apply(teleport, duration);
}
@Override
default ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) {
return SendTeleportRequestCallback.SUPPLIER.apply(sender, request);
}
@Override
default IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
return ReceiveTeleportRequestCallback.SUPPLIER.apply(recipient, request);
}
@Override
default IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
return ReplyTeleportRequestCallback.SUPPLIER.apply(recipient, request);
}
@Override
default IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
return HomeCreateCallback.SUPPLIER.apply(owner, name, position, creator);
}
@Override
default IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) {
return HomeEditCallback.SUPPLIER.apply(home, editor);
}
@Override
default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) {
return HomeDeleteCallback.SUPPLIER.apply(home, deleter);
}
@Override
default IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
return WarpCreateCallback.SUPPLIER.apply(name, position, creator);
}
@Override
default IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) {
return WarpEditCallback.SUPPLIER.apply(warp, editor);
}
@Override
default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) {
return WarpDeleteCallback.SUPPLIER.apply(warp, deleter);
}
@Override
default IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList) {
return HomeListCallback.SUPPLIER.apply(homes, listViewer, publicHomeList);
}
@Override
default IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> homes, @NotNull CommandUser listViewer) {
return WarpListCallback.SUPPLIER.apply(homes, listViewer);
}
@Override
default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) {
return DeleteAllHomesCallback.SUPPLIER.apply(user, deleter);
}
@Override
default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) {
return DeleteAllWarpsCallback.SUPPLIER.apply(deleter);
}
@Override
@NotNull
FabricHuskHomes getPlugin();
}
@@ -0,0 +1,103 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.data.client.BlockStateVariantMap.QuadFunction;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
public interface HomeCreateCallback extends FabricEventCallback<IHomeCreateEvent> {
@NotNull
Event<HomeCreateCallback> EVENT = EventFactory.createArrayBacked(HomeCreateCallback.class,
(listeners) -> (event) -> {
for (HomeCreateCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
QuadFunction<User, String, Position, CommandUser, IHomeCreateEvent> SUPPLIER = (user, name, position, creator) ->
new IHomeCreateEvent() {
private boolean cancelled = false;
private String homeName = name;
@Override
@NotNull
public User getOwner() {
return user;
}
@Override
@NotNull
public String getName() {
return homeName;
}
@Override
public void setName(@NotNull String name) {
this.homeName = name;
}
@Override
@NotNull
public Position getPosition() {
return position;
}
@Override
public void setPosition(@NotNull Position position) {
}
@Override
public @NotNull CommandUser getCreator() {
return creator;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<HomeCreateCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface HomeDeleteCallback extends FabricEventCallback<IHomeDeleteEvent> {
@NotNull
Event<HomeDeleteCallback> EVENT = EventFactory.createArrayBacked(HomeDeleteCallback.class,
(listeners) -> (event) -> {
for (HomeDeleteCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<Home, CommandUser, IHomeDeleteEvent> SUPPLIER = (home, deleter) ->
new IHomeDeleteEvent() {
private boolean cancelled = false;
@Override
@NotNull
public Home getHome() {
return home;
}
@Override
@NotNull
public CommandUser getDeleter() {
return deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<HomeDeleteCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface HomeEditCallback extends FabricEventCallback<IHomeEditEvent> {
@NotNull
Event<HomeEditCallback> EVENT = EventFactory.createArrayBacked(HomeEditCallback.class,
(listeners) -> (event) -> {
for (HomeEditCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<Home, CommandUser, IHomeEditEvent> SUPPLIER = (home, editor) ->
new IHomeEditEvent() {
private boolean cancelled = false;
@Override
@NotNull
public Home getHome() {
return home;
}
@Override
@NotNull
public CommandUser getEditor() {
return editor;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<HomeEditCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,95 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.apache.commons.lang3.function.TriFunction;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public interface HomeListCallback extends FabricEventCallback<IHomeListEvent> {
@NotNull
Event<HomeListCallback> EVENT = EventFactory.createArrayBacked(HomeListCallback.class,
(listeners) -> (event) -> {
for (HomeListCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
TriFunction<List<Home>, CommandUser, Boolean, IHomeListEvent> SUPPLIER = (homes, viewer, publicHomes) ->
new IHomeListEvent() {
private boolean cancelled = false;
private List<Home> listHomes = homes;
@Override
@NotNull
public List<Home> getHomes() {
return listHomes;
}
@Override
public void setHomes(@NotNull List<Home> homes) {
this.listHomes = homes;
}
@Override
@NotNull
public CommandUser getListViewer() {
return viewer;
}
@Override
public boolean getIsPublicHomeList() {
return publicHomes;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<HomeListCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface ReceiveTeleportRequestCallback extends FabricEventCallback<IReceiveTeleportRequestEvent> {
@NotNull
Event<ReceiveTeleportRequestCallback> EVENT = EventFactory.createArrayBacked(ReceiveTeleportRequestCallback.class,
(listeners) -> (event) -> {
for (ReceiveTeleportRequestCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<OnlineUser, TeleportRequest, IReceiveTeleportRequestEvent> SUPPLIER = (recipient, request) ->
new IReceiveTeleportRequestEvent() {
private boolean cancelled = false;
@Override
@NotNull
public OnlineUser getRecipient() {
return recipient;
}
@Override
@NotNull
public TeleportRequest getRequest() {
return request;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<ReceiveTeleportRequestCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface ReplyTeleportRequestCallback extends FabricEventCallback<IReplyTeleportRequestEvent> {
@NotNull
Event<ReplyTeleportRequestCallback> EVENT = EventFactory.createArrayBacked(ReplyTeleportRequestCallback.class,
(listeners) -> (event) -> {
for (ReplyTeleportRequestCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<OnlineUser, TeleportRequest, IReplyTeleportRequestEvent> SUPPLIER = (recipient, request) ->
new IReplyTeleportRequestEvent() {
private boolean cancelled = false;
@Override
@NotNull
public OnlineUser getRecipient() {
return recipient;
}
@Override
@NotNull
public TeleportRequest getRequest() {
return request;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<ReplyTeleportRequestCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface SendTeleportRequestCallback extends FabricEventCallback<ISendTeleportRequestEvent> {
@NotNull
Event<SendTeleportRequestCallback> EVENT = EventFactory.createArrayBacked(SendTeleportRequestCallback.class,
(listeners) -> (event) -> {
for (SendTeleportRequestCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<OnlineUser, TeleportRequest, ISendTeleportRequestEvent> SUPPLIER = (sender, request) ->
new ISendTeleportRequestEvent() {
private boolean cancelled = false;
@Override
@NotNull
public OnlineUser getSender() {
return sender;
}
@Override
@NotNull
public TeleportRequest getRequest() {
return request;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<SendTeleportRequestCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
public interface TeleportBackCallback extends FabricEventCallback<ITeleportBackEvent> {
@NotNull
Event<TeleportBackCallback> EVENT = EventFactory.createArrayBacked(TeleportBackCallback.class,
(listeners) -> (event) -> {
for (TeleportBackCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.FAIL;
} else if (result == ActionResult.FAIL) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
Function<Teleport, ITeleportBackEvent> SUPPLIER = (teleport) ->
new ITeleportBackEvent() {
private boolean cancelled = false;
@Override
@NotNull
public Position getLastPosition() {
return (Position) getTeleport().getTarget();
}
@Override
@NotNull
public Teleport getTeleport() {
return teleport;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<TeleportBackCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,76 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
public interface TeleportCallback extends FabricEventCallback<ITeleportEvent> {
@NotNull
Event<TeleportCallback> EVENT = EventFactory.createArrayBacked(TeleportCallback.class,
(listeners) -> (event) -> {
for (TeleportCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.FAIL;
} else if (result == ActionResult.FAIL) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
Function<Teleport, ITeleportEvent> SUPPLIER = (teleport) ->
new ITeleportEvent() {
private boolean cancelled = false;
@Override
@NotNull
public Teleport getTeleport() {
return teleport;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<TeleportCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,79 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.teleport.TimedTeleport;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface TeleportWarmupCallback extends FabricEventCallback<ITeleportWarmupEvent> {
@NotNull
Event<TeleportWarmupCallback> EVENT = EventFactory.createArrayBacked(TeleportWarmupCallback.class,
(listeners) -> (event) -> {
for (TeleportWarmupCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.FAIL;
} else if (result == ActionResult.FAIL) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<TimedTeleport, Integer, ITeleportWarmupEvent> SUPPLIER = (timedTeleport, duration) ->
new ITeleportWarmupEvent() {
private boolean cancelled = false;
@Override
@NotNull
public TimedTeleport getTimedTeleport() {
return timedTeleport;
}
@Override
public int getWarmupDuration() {
return duration;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<TeleportWarmupCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,98 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.CommandUser;
import org.apache.commons.lang3.function.TriFunction;
import org.jetbrains.annotations.NotNull;
public interface WarpCreateCallback extends FabricEventCallback<IWarpCreateEvent> {
@NotNull
Event<WarpCreateCallback> EVENT = EventFactory.createArrayBacked(WarpCreateCallback.class,
(listeners) -> (event) -> {
for (WarpCreateCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
TriFunction<String, Position, CommandUser, IWarpCreateEvent> SUPPLIER = (name, position, creator) ->
new IWarpCreateEvent() {
private boolean cancelled = false;
private String homeName = name;
@Override
@NotNull
public String getName() {
return homeName;
}
@Override
public void setName(@NotNull String name) {
this.homeName = name;
}
@Override
@NotNull
public Position getPosition() {
return position;
}
@Override
public void setPosition(@NotNull Position position) {
}
@Override
@NotNull
public CommandUser getCreator() {
return creator;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<WarpCreateCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface WarpDeleteCallback extends FabricEventCallback<IWarpDeleteEvent> {
@NotNull
Event<WarpDeleteCallback> EVENT = EventFactory.createArrayBacked(WarpDeleteCallback.class,
(listeners) -> (event) -> {
for (WarpDeleteCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<Warp, CommandUser, IWarpDeleteEvent> SUPPLIER = (warp, deleter) ->
new IWarpDeleteEvent() {
private boolean cancelled = false;
@Override
@NotNull
public Warp getWarp() {
return warp;
}
@Override
@NotNull
public CommandUser getDeleter() {
return deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<WarpDeleteCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,83 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiFunction;
public interface WarpEditCallback extends FabricEventCallback<IWarpEditEvent> {
@NotNull
Event<WarpEditCallback> EVENT = EventFactory.createArrayBacked(WarpEditCallback.class,
(listeners) -> (event) -> {
for (WarpEditCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<Warp, CommandUser, IWarpEditEvent> SUPPLIER = (warp, editor) ->
new IWarpEditEvent() {
private boolean cancelled = false;
@Override
@NotNull
public Warp getWarp() {
return warp;
}
@Override
@NotNull
public CommandUser getEditor() {
return editor;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<WarpEditCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,90 @@
/*
* 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.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.BiFunction;
public interface WarpListCallback extends FabricEventCallback<IWarpListEvent> {
@NotNull
Event<WarpListCallback> EVENT = EventFactory.createArrayBacked(WarpListCallback.class,
(listeners) -> (event) -> {
for (WarpListCallback listener : listeners) {
final ActionResult result = listener.invoke(event);
if (event.isCancelled()) {
return ActionResult.CONSUME;
} else if (result != ActionResult.PASS) {
event.setCancelled(true);
return result;
}
}
return ActionResult.PASS;
});
@NotNull
BiFunction<List<Warp>, CommandUser, IWarpListEvent> SUPPLIER = (warps, viewer) ->
new IWarpListEvent() {
private boolean cancelled = false;
private List<Warp> listWarps = warps;
@Override
@NotNull
public List<Warp> getWarps() {
return listWarps;
}
@Override
public void setWarps(@NotNull List<Warp> homes) {
this.listWarps = homes;
}
@Override
@NotNull
public CommandUser getListViewer() {
return viewer;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
public Event<WarpListCallback> getEvent() {
return EVENT;
}
};
}
@@ -0,0 +1,64 @@
/*
* 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.listener;
import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
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.
// The "update last position on teleport event" and "global respawn" features are not supported on Fabric.
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) {
// Join event
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> handlePlayerJoin(
FabricUser.adapt(plugin, handler.player)
));
// Quit event
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> handlePlayerLeave(
FabricUser.adapt(plugin, handler.player)
));
// Death event
ServerLivingEntityEvents.AFTER_DEATH.register((entity, source) -> {
if (entity instanceof ServerPlayerEntity player) {
handlePlayerDeath(FabricUser.adapt(plugin, player));
}
});
// Respawn event
ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> handlePlayerRespawn(
FabricUser.adapt(plugin, newPlayer)
));
}
}
@@ -0,0 +1,155 @@
/*
* 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 me.lucko.fabric.api.permissions.v0.Permissions;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.kyori.adventure.audience.Audience;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.william278.huskhomes.FabricHuskHomes;
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.NotNull;
import java.util.*;
public class FabricUser extends OnlineUser {
private final FabricHuskHomes plugin;
private final ServerPlayerEntity player;
private FabricUser(@NotNull FabricHuskHomes plugin, @NotNull ServerPlayerEntity player) {
super(player.getUuid(), player.getEntityName());
this.plugin = plugin;
this.player = player;
}
@NotNull
public static FabricUser adapt(@NotNull FabricHuskHomes plugin, @NotNull ServerPlayerEntity player) {
return new FabricUser(plugin, player);
}
@Override
public Position getPosition() {
return Position.at(
player.getX(), player.getY(), player.getZ(),
player.getYaw(), player.getPitch(),
World.from(
player.getWorld().getRegistryKey().getValue().asString(),
UUID.nameUUIDFromBytes(player.getWorld().getRegistryKey().getValue().asString().getBytes())
),
plugin.getServerName()
);
}
@Override
public Optional<Position> getBedSpawnPosition() {
final BlockPos spawn = player.getSpawnPointPosition();
if (spawn == null) {
return Optional.empty();
}
return Optional.of(Position.at(
spawn.getX(), spawn.getY(), spawn.getZ(),
player.getSpawnAngle(), 0,
World.from(
player.getSpawnPointDimension().getValue().asString(),
UUID.nameUUIDFromBytes(player.getSpawnPointDimension().getValue().asString().getBytes())
),
plugin.getServerName()
));
}
@Override
public double getHealth() {
return player.getHealth();
}
@Override
public boolean hasPermission(@NotNull String node) {
final boolean requiresOp = Boolean.TRUE.equals(plugin.getPermissions().computeIfPresent(node, (key, isOp) -> isOp));
return Permissions.check(player, node, !requiresOp || player.hasPermissionLevel(3));
}
@Override
@NotNull
public Map<String, Boolean> getPermissions() {
return plugin.getPermissions().entrySet().stream()
.filter(entry -> Permissions.check(player, entry.getKey(), entry.getValue()))
.collect(HashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), HashMap::putAll);
}
@Override
@NotNull
protected List<Integer> getNumericalPermissions(@NotNull String nodePrefix) {
final List<Integer> permissions = new ArrayList<>();
for (int i = 0; i < 100; i++) {
if (hasPermission(nodePrefix + i)) {
permissions.add(i);
}
}
return permissions.stream().sorted(Collections.reverseOrder()).toList();
}
@Override
@NotNull
public Audience getAudience() {
return player;
}
@Override
public void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException {
final MinecraftServer server = player.getWorld().getServer();
final Identifier worldId = Identifier.tryParse(location.getWorld().getName());
player.teleport(
server.getWorld(server.getWorldRegistryKeys().stream()
.filter(key -> key.getValue().equals(worldId)).findFirst()
.orElseThrow(() -> new TeleportationException(TeleportationException.Type.WORLD_NOT_FOUND))
),
location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch()
);
}
@Override
public void sendPluginMessage(@NotNull String channel, byte[] message) {
final PacketByteBuf buf = PacketByteBufs.create();
buf.writeBytes(message);
final CustomPayloadS2CPacket packet = new CustomPayloadS2CPacket(Identifier.tryParse(channel), buf);
player.networkHandler.sendPacket(packet);
}
@Override
public boolean isMoving() {
return player.isTouchingWater() || player.isFallFlying() || player.isSprinting() || player.isSneaking();
}
@Override
public boolean isVanished() {
return false;
}
}
@@ -0,0 +1,93 @@
/*
* 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.util;
import net.william278.huskhomes.FabricHuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public interface FabricTaskRunner extends TaskRunner {
ConcurrentHashMap<Integer, CompletableFuture<?>> tasks = new ConcurrentHashMap<>();
@Override
default int runAsync(@NotNull Runnable runnable) {
tasks.put(tasks.size(), CompletableFuture.runAsync(runnable, getPlugin().getMinecraftServer()));
return tasks.size();
}
@Override
default <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier) {
return CompletableFuture.supplyAsync(supplier, getPlugin().getMinecraftServer());
}
@Override
default void runSync(@NotNull Runnable runnable) {
getPlugin().getMinecraftServer().executeSync(runnable);
}
@Override
default int runAsyncRepeating(@NotNull Runnable runnable, long delay) {
tasks.put(tasks.size(), CompletableFuture.runAsync(() -> {
while (true) {
try {
Thread.sleep(delay * 50);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
runnable.run();
}
}, getPlugin().getMinecraftServer()));
return tasks.size();
}
@Override
default void runLater(@NotNull Runnable runnable, long delay) {
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(delay * 50);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
runnable.run();
}, getPlugin().getMinecraftServer());
}
@Override
default void cancelTask(int taskId) {
tasks.get(taskId).cancel(true);
}
@Override
default void cancelAllTasks() {
tasks.forEach((taskId, future) -> future.cancel(true));
tasks.clear();
}
@Override
@NotNull
FabricHuskHomes getPlugin();
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+37
View File
@@ -0,0 +1,37 @@
{
"schemaVersion": 1,
"id": "huskhomes",
"version": "${version}",
"name": "HuskHomes",
"icon": "assets/huskhomes/icon.png",
"description": "A powerful, intuitive and flexible teleportation suite",
"authors": [
{
"name": "William278",
"contact": {
"sources": "https://github.com/WiIIiam278/",
"homepage": "https://william278.net/"
}
}
],
"license": "Apache-2.0",
"contact": {
"homepage": "https://william278.net/project/huskhomes/",
"repo": "https://github.com/WiIIiam278/HuskHomes2",
"issues": "https://github.com/WiIIiam278/HuskHomes2/issues"
},
"environment": "server",
"entrypoints": {
"server": [
"net.william278.huskhomes.FabricHuskHomes"
]
},
"depends": {
"fabricloader": ">=0.14.19",
"minecraft": ">=1.19.4",
"fabric-api": "*"
},
"custom": {
"modmenu:api": true
}
}