Add Sponge (API v8) server mod support (#354)

This commit is contained in:
William authored and GitHub committed 2023-04-15 15:24:48 +01:00
1 parent 059fc638c6
commit be43fbc345
35 files changed
+2603 -9

No files matched your search

+29
View File
@@ -45,6 +45,7 @@ jobs:
bluemap | suggests | *
dynmap | suggests | *
pl3xmap | suggests | *
plan | suggests | *
files-primary: target/HuskHomes-Plugin-*.jar
name: HuskHomes (Spigot) v${{ env.version_name }}
version: ${{ env.version_name }}
@@ -60,6 +61,28 @@ jobs:
1.18.2
1.19.4
java: 16
- name: Upload to Modrinth (Sponge)
uses: Kir-Antipov/[email protected]
with:
modrinth-id: J6U9o3JG
modrinth-featured: false
modrinth-token: ${{ secrets.MODRINTH_TOKEN }}
modrinth-dependencies: |
bluemap | suggests | *
plan | suggests | *
files-primary: target/HuskHomes-Sponge-*.jar
name: HuskHomes (Sponge) v${{ env.version_name }}
version: ${{ env.version_name }}
version-type: alpha
changelog: ${{ github.event.head_commit.message }}
loaders: |
sponge
game-versions: |
1.16.5
1.17.1
1.18.2
1.19.4
java: 16
- name: Upload to Modrinth & CurseForge (Fabric)
uses: Kir-Antipov/[email protected]
with:
@@ -72,6 +95,7 @@ jobs:
fabric-api | requires | *
bluemap | suggests | *
dynmap | suggests | *
plan | suggests | *
luckperms | suggests | *
files-primary: target/HuskHomes-Fabric-*.jar
name: HuskHomes (Fabric) v${{ env.version_name }}
@@ -88,6 +112,11 @@ jobs:
with:
name: HuskHomes (Spigot)
path: target/HuskHomes-Plugin-*.jar
- name: Upload GitHub Artifact (Sponge)
uses: actions/upload-artifact@v2
with:
name: HuskHomes (Sponge)
path: target/HuskHomes-Sponge-*.jar
- name: Upload GitHub Artifact
uses: actions/upload-artifact@v2
with:
+29
View File
@@ -38,6 +38,7 @@ jobs:
bluemap | suggests | *
dynmap | suggests | *
pl3xmap | suggests | *
plan-player-analytics | suggests | *
files-primary: target/HuskHomes-Plugin-*.jar
name: HuskHomes (Spigot) v${{ github.event.release.tag_name }}
version: ${{ github.event.release.tag_name }}
@@ -53,6 +54,28 @@ jobs:
1.18.2
1.19.4
java: 16
- name: Upload to Modrinth (Sponge)
uses: Kir-Antipov/[email protected]
with:
modrinth-id: J6U9o3JG
modrinth-featured: false
modrinth-token: ${{ secrets.MODRINTH_TOKEN }}
modrinth-dependencies: |
bluemap | suggests | *
plan-player-analytics | suggests | *
files-primary: target/HuskHomes-Sponge-*.jar
name: HuskHomes (Sponge) v${{ github.event.release.tag_name }}
version: ${{ env.version_name }}
version-type: release
changelog: ${{ github.event.release.body }}
loaders: |
sponge
game-versions: |
1.16.5
1.17.1
1.18.2
1.19.4
java: 16
- name: Upload to Modrinth & CurseForge (Fabric)
uses: Kir-Antipov/[email protected]
with:
@@ -66,6 +89,7 @@ jobs:
bluemap | suggests | *
dynmap | suggests | *
luckperms | suggests | *
plan-player-analytics | suggests | *
files-primary: target/HuskHomes-Fabric-*.jar
name: HuskHomes (Fabric) v${{ github.event.release.tag_name }}
version: ${{ github.event.release.tag_name }}
@@ -81,6 +105,11 @@ jobs:
with:
name: HuskHomes (Spigot)
path: target/HuskHomes-Plugin-*.jar
- name: Upload GitHub Artifact (Sponge)
uses: actions/upload-artifact@v2
with:
name: HuskHomes (Sponge)
path: target/HuskHomes-Sponge-*.jar
- name: Upload GitHub Artifact
uses: actions/upload-artifact@v2
with:
+4 -1
View File
@@ -10,6 +10,7 @@ plugins {
group 'net.william278'
version "$ext.plugin_version-${versionMetadata()}"
description "$ext.plugin_description"
defaultTasks 'licenseFormat', 'build'
ext {
@@ -17,6 +18,7 @@ ext {
set 'jedis_version', jedis_version.toString()
set 'sqlite_driver_version', sqlite_driver_version.toString()
set 'mysql_driver_version', mysql_driver_version.toString()
set 'description', description.toString()
}
allprojects {
@@ -37,6 +39,7 @@ allprojects {
maven { url 'https://api.modrinth.com/maven' }
maven { url 'https://repo.papermc.io/repository/maven-public/' }
maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' }
maven { url 'https://repo.spongepowered.org/repository/maven-public/' }
maven { url 'https://repo.extendedclip.com/content/repositories/placeholderapi/' }
maven { url 'https://repo.minebench.de/' }
maven { url 'https://repo.alessiodp.com/releases/' }
@@ -82,7 +85,7 @@ subprojects {
compileJava.options.release.set 17
}
if (['bukkit', 'paper', 'plugin', 'fabric'].contains(project.name)) {
if (['bukkit', 'paper', 'plugin', 'fabric', 'sponge'].contains(project.name)) {
shadowJar {
destinationDirectory.set(file("$rootDir/target"))
archiveClassifier.set('')
+1 -1
View File
@@ -1,5 +1,5 @@
name: 'HuskHomes'
description: 'A powerful, intuitive and flexible teleportation suite'
description: '${description}'
author: 'William278'
website: 'https://william278.net/'
main: 'net.william278.huskhomes.BukkitHuskHomes'
@@ -351,9 +351,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver {
.map(type::cast);
}
@NotNull
List<Command> registerCommands();
default void registerHooks() {
setHooks(new ArrayList<>());
@@ -390,7 +390,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return commands;
}
@Override
@NotNull
public List<Command> registerCommands() {
final List<Command> commands = Arrays.stream(FabricCommand.Type.values())
+1 -1
View File
@@ -4,7 +4,7 @@
"version": "${version}",
"name": "HuskHomes",
"icon": "assets/huskhomes/icon.png",
"description": "A powerful, intuitive and flexible teleportation suite",
"description": "${description}",
"authors": [
{
"name": "William278",
+1
View File
@@ -5,6 +5,7 @@ org.gradle.daemon=true
plugin_version=4.2
plugin_archive=huskhomes
plugin_description=A powerful, intuitive and flexible teleportation suite
jedis_version=4.3.1
sqlite_driver_version=3.41.0.0
+1 -1
View File
@@ -1,5 +1,5 @@
name: 'HuskHomes'
description: 'A powerful, intuitive and flexible teleportation suite'
description: '${description}'
author: 'William278'
website: 'https://william278.net/'
main: 'net.william278.huskhomes.PaperHuskHomes'
+2 -1
View File
@@ -11,5 +11,6 @@ include(
'bukkit',
'paper',
'plugin',
'fabric'
'fabric',
'sponge'
)
+73
View File
@@ -0,0 +1,73 @@
import org.spongepowered.gradle.plugin.config.PluginLoaders
import org.spongepowered.plugin.metadata.model.PluginDependency
plugins {
id 'org.spongepowered.gradle.plugin' version '2.1.1'
}
dependencies {
implementation 'redis.clients:jedis:' + jedis_version
implementation 'com.mysql:mysql-connector-j:' + mysql_driver_version
implementation 'org.xerial:sqlite-jdbc:' + sqlite_driver_version
implementation project(path: ':common')
}
sponge {
apiVersion("8.1.0")
loader {
name(PluginLoaders.JAVA_PLAIN)
version("1.0")
}
license("Apache-2.0")
plugin("huskhomes") {
displayName("HuskHomes")
version(project.version.toString())
entrypoint("net.william278.huskhomes.SpongeHuskHomes")
description(project.description.toString())
links {
homepage("https://william278.net/project/huskhomes")
source("https://github.com/WiIIiam278/HuskHomes2")
issues("https://github.com/WiIIiam278/HuskHomes2/issues")
}
contributor("William278") {
description("Author")
}
dependency("spongeapi") {
loadOrder(PluginDependency.LoadOrder.AFTER)
optional(false)
}
dependency("bluemap") {
loadOrder(PluginDependency.LoadOrder.AFTER)
optional(true)
version("3.4")
}
dependency("plan") {
loadOrder(PluginDependency.LoadOrder.AFTER)
optional(true)
version("5.4")
}
}
}
shadowJar {
destinationDirectory.set(file("$rootDir/target/"))
archiveClassifier.set('')
exclude('org.spongepowered:.*')
exclude('net.kyori:.*')
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'
}
@@ -0,0 +1,475 @@
/*
* 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 com.google.inject.Inject;
import net.william278.annotaml.Annotaml;
import net.william278.desertwell.Version;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.SpongeCommand;
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.SpongeEventDispatcher;
import net.william278.huskhomes.hook.Hook;
import net.william278.huskhomes.hook.SpongeEconomyHook;
import net.william278.huskhomes.listener.SpongeEventListener;
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.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.SpongeUser;
import net.william278.huskhomes.util.SpongeSafetyResolver;
import net.william278.huskhomes.util.SpongeTaskRunner;
import net.william278.huskhomes.util.UnsafeBlocks;
import net.william278.huskhomes.util.Validator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.api.Game;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.command.Command.Raw;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.lifecycle.ConstructPluginEvent;
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
import org.spongepowered.api.event.lifecycle.StartedEngineEvent;
import org.spongepowered.api.network.EngineConnection;
import org.spongepowered.api.network.channel.ChannelBuf;
import org.spongepowered.api.network.channel.raw.RawDataChannel;
import org.spongepowered.api.network.channel.raw.play.RawPlayDataChannel;
import org.spongepowered.api.network.channel.raw.play.RawPlayDataHandler;
import org.spongepowered.math.vector.Vector3i;
import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.builtin.jvm.Plugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.nio.file.Path;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
@Plugin("huskhomes")
public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafetyResolver, SpongeEventDispatcher, RawPlayDataHandler<EngineConnection> {
private static final ResourceKey PLUGIN_MESSAGE_CHANNEL_KEY = ResourceKey.of("bungeecord", "main");
// Instance of the plugin
private static SpongeHuskHomes instance;
public static SpongeHuskHomes getInstance() {
return instance;
}
@Inject
@ConfigDir(sharedRoot = false)
private Path pluginDirectory;
@Inject
private PluginContainer pluginContainer;
@Inject
private Game game;
private Set<SavedUser> savedUsers;
private Settings settings;
private Locales locales;
private Database database;
private Validator validator;
private Manager manager;
private RandomTeleportEngine randomTeleportEngine;
private Spawn serverSpawn;
private UnsafeBlocks unsafeBlocks;
private List<Hook> hooks;
private List<SpongeCommand> commands;
private Map<String, List<String>> globalPlayerList;
private Set<UUID> currentlyOnWarmup;
private Server server;
@Nullable
private Broker broker;
private RawPlayDataChannel channel;
@Listener
public void onConstructPlugin(final ConstructPluginEvent event) {
instance = this;
// Get plugin version from mod container
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");
}
});
// 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 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();
});
}
this.checkForUpdates();
}
@Listener
public void onServerStarted(final StartedEngineEvent<org.spongepowered.api.Server> event) {
// Initialize the manager
this.manager = new Manager(this);
// Setup RTP engine
setRandomTeleportEngine(new NormalDistributionEngine(this));
// Register events
initialize("events", (plugin) -> new SpongeEventListener(this));
// Register permissions
initialize("permissions", (plugin) -> registerPermissions());
// Initialize hooks
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(", ")));
}
});
}
@Listener
public void onRegisterCommands(final RegisterCommandEvent<Raw> event) {
initialize("commands", (plugin) -> this.commands = registerCommands(event));
}
@NotNull
@Override
public ConsoleUser getConsole() {
return new ConsoleUser(game.server());
}
@NotNull
@Override
public List<OnlineUser> getOnlineUsers() {
return game.server().onlinePlayers().stream()
.map(SpongeUser::adapt)
.collect(Collectors.toList());
}
@NotNull
@Override
public Set<SavedUser> getSavedUsers() {
return savedUsers;
}
@NotNull
@Override
public Settings getSettings() {
return settings;
}
@Override
public void setSettings(@NotNull Settings settings) {
this.settings = settings;
}
@NotNull
@Override
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;
}
@NotNull
@Override
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;
}
@NotNull
@Override
public UnsafeBlocks getUnsafeBlocks() {
return unsafeBlocks;
}
@NotNull
@Override
public Database getDatabase() {
return database;
}
@NotNull
@Override
public Validator getValidator() {
return validator;
}
@NotNull
@Override
public Manager getManager() {
return manager;
}
@NotNull
@Override
public Broker getMessenger() {
if (broker == null) {
throw new IllegalStateException("Attempted to access message broker when it was not initialized");
}
return broker;
}
@NotNull
@Override
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
game.server().worldManager().worlds().forEach(world -> {
if (world.properties().key().asString().equals(location.getWorld().getName())) {
world.properties().setSpawnPosition(Vector3i.from(
(int) location.getX(), (int) location.getY(), (int) location.getZ())
);
}
});
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
log(Level.WARNING, "Failed to save the server spawn.yml file", e);
}
}
@NotNull
@Override
public List<Hook> getHooks() {
return hooks;
}
@Override
public void setHooks(@NotNull List<Hook> hooks) {
this.hooks = hooks;
}
@Override
public void registerHooks() {
HuskHomes.super.registerHooks();
// Register the sponge economy service if it is available
if (getSettings().doEconomy() && getGame().server().serviceProvider().economyService().isPresent()) {
getHooks().add(new SpongeEconomyHook(this));
}
}
@Nullable
@Override
public InputStream getResource(@NotNull String name) {
return pluginContainer.openResource(URI.create(name))
.orElse(null);
}
@NotNull
@Override
public File getDataFolder() {
return pluginDirectory.toFile();
}
@NotNull
@Override
public List<World> getWorlds() {
return game.server().worldManager().worlds()
.stream()
.map(world -> World.from(world.key().toString(), world.uniqueId()))
.collect(Collectors.toList());
}
@NotNull
@Override
public Version getVersion() {
return Version.fromString(pluginContainer.metadata().version().toString(), "-");
}
@NotNull
@Override
public List<Command> getCommands() {
return commands.stream().map(SpongeCommand::getCommand).collect(Collectors.toList());
}
@NotNull
public List<SpongeCommand> registerCommands(@NotNull RegisterCommandEvent<Raw> event) {
final List<SpongeCommand> commands = new ArrayList<>();
for (SpongeCommand.Type type : SpongeCommand.Type.values()) {
final SpongeCommand command = new SpongeCommand(type.getCommand(), this);
commands.add(command);
command.registerCommand(event);
}
return commands;
}
public void registerPermissions() {
commands.forEach(SpongeCommand::registerPermissions);
}
@Override
public boolean isDependencyLoaded(@NotNull String name) {
return game.pluginManager().plugin(name).isPresent();
}
@NotNull
@Override
public Map<String, List<String>> getGlobalPlayerList() {
return globalPlayerList;
}
@NotNull
@Override
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
@Override
public void registerMetrics(int metricsId) {
// No metrics for Sponge
}
@Override
public void initializePluginChannels() {
this.channel = game.channelManager().ofType(PLUGIN_MESSAGE_CHANNEL_KEY, RawDataChannel.class).play();
this.channel.addHandler(this);
}
@Override
public void handlePayload(@NotNull ChannelBuf pluginMessage, @NotNull EngineConnection connection) {
final Optional<OnlineUser> playerConnection = getOnlineUsers().stream()
.filter(onlineUser -> ((SpongeUser) onlineUser).getPlayer().connection().equals(connection))
.findFirst();
// Get the associated engine connection
if (playerConnection.isEmpty()) {
log(Level.WARNING, "Received a message from a player that is not online");
return;
}
// Read the message and handle
final SpongeUser user = (SpongeUser) playerConnection.get();
final String channel = pluginMessage.readUTF();
if (broker instanceof PluginMessageBroker messenger) {
messenger.onReceive(channel, user, pluginMessage.readBytes(pluginMessage.available()));
}
}
@Override
public void log(@NotNull Level level, @NotNull String message, Throwable... exceptions) {
final org.apache.logging.log4j.Level adaptedLevel = Optional
.ofNullable(org.apache.logging.log4j.Level.getLevel(level.getName()))
.orElse(org.apache.logging.log4j.Level.INFO);
if (exceptions.length > 0) {
pluginContainer.logger().log(adaptedLevel, message, exceptions[0]);
return;
}
pluginContainer.logger().log(adaptedLevel, message);
}
@NotNull
public PluginContainer getPluginContainer() {
return pluginContainer;
}
@NotNull
public Game getGame() {
return game;
}
@NotNull
public RawPlayDataChannel getPluginMessageChannel() {
return channel;
}
@NotNull
@Override
public SpongeHuskHomes getPlugin() {
return this;
}
}
@@ -0,0 +1,200 @@
/*
* 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 net.kyori.adventure.text.Component;
import net.william278.huskhomes.SpongeHuskHomes;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.SpongeUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.command.Command.Raw;
import org.spongepowered.api.command.CommandCause;
import org.spongepowered.api.command.CommandCompletion;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.parameter.ArgumentReader;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
import org.spongepowered.api.service.permission.PermissionDescription;
import org.spongepowered.api.util.Tristate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class SpongeCommand implements Raw {
private final Command command;
private final SpongeHuskHomes plugin;
public SpongeCommand(@NotNull Command command, @NotNull SpongeHuskHomes plugin) {
this.command = command;
this.plugin = plugin;
}
// Register command
public void registerCommand(@NotNull RegisterCommandEvent<Raw> event) {
event.register(
plugin.getPluginContainer(),
this,
command.getName(),
command.getAliases().toArray(String[]::new)
);
}
// Register command permissions
public void registerPermissions() {
final Map<String, Boolean> permissionDescriptions = new HashMap<>(command.getAdditionalPermissions());
permissionDescriptions.put(command.getPermission(), command.isOperatorCommand());
for (Map.Entry<String, Boolean> node : permissionDescriptions.entrySet()) {
final PermissionDescription.Builder builder = plugin.getGame().server()
.serviceProvider().permissionService()
.newDescriptionBuilder(plugin.getPluginContainer())
.id(node.getKey());
// Set default access level
if (node.getValue()) {
builder.defaultValue(Tristate.UNDEFINED)
.assign(PermissionDescription.ROLE_ADMIN, true);
} else {
builder.defaultValue(Tristate.TRUE)
.assign(PermissionDescription.ROLE_USER, true);
}
builder.register();
}
}
@NotNull
public Command getCommand() {
return command;
}
@Override
@NotNull
public CommandResult process(@NotNull CommandCause cause, @NotNull ArgumentReader.Mutable arguments) {
command.onExecuted(resolveExecutor(cause), assimilateArguments(arguments));
return CommandResult.success();
}
@Override
@NotNull
public List<CommandCompletion> complete(@NotNull CommandCause cause, @NotNull ArgumentReader.Mutable arguments) {
if (this.command instanceof TabProvider provider) {
return provider.getSuggestions(resolveExecutor(cause), assimilateArguments(arguments)).stream()
.map(CommandCompletion::of)
.toList();
}
return List.of();
}
@NotNull
private CommandUser resolveExecutor(@NotNull CommandCause cause) {
if (cause.root() instanceof ServerPlayer player) {
return SpongeUser.adapt(player);
}
return plugin.getConsole();
}
/**
* Assimilate the arguments from a {@link ArgumentReader} into a spaced {@link String} array
*
* @param arguments the {@link ArgumentReader} to assimilate
* @return the assimilated {@link String} array
*/
@NotNull
private String[] assimilateArguments(@NotNull ArgumentReader.Mutable arguments) {
final String argumentString = arguments.immutable().remaining();
if (argumentString.isBlank()) {
return new String[0];
}
return argumentString.split(" ");
}
@Override
public boolean canExecute(@NotNull CommandCause cause) {
return resolveExecutor(cause).hasPermission(command.getPermission());
}
@Override
@NotNull
public Optional<Component> shortDescription(@NotNull CommandCause cause) {
return Optional.of(Component.text(command.getDescription()));
}
@Override
@NotNull
public Optional<Component> extendedDescription(@NotNull CommandCause cause) {
return shortDescription(cause);
}
@Override
@NotNull
public Component usage(@NotNull CommandCause cause) {
return Component.text(command.getUsage());
}
/**
* Commands available on the Sponge HuskHomes implementation
*/
public enum Type {
HOME_COMMAND(new PrivateHomeCommand(SpongeHuskHomes.getInstance())),
SET_HOME_COMMAND(new SetHomeCommand(SpongeHuskHomes.getInstance())),
HOME_LIST_COMMAND(new PrivateHomeListCommand(SpongeHuskHomes.getInstance())),
DEL_HOME_COMMAND(new DelHomeCommand(SpongeHuskHomes.getInstance())),
EDIT_HOME_COMMAND(new EditHomeCommand(SpongeHuskHomes.getInstance())),
PUBLIC_HOME_COMMAND(new PublicHomeCommand(SpongeHuskHomes.getInstance())),
PUBLIC_HOME_LIST_COMMAND(new PublicHomeListCommand(SpongeHuskHomes.getInstance())),
WARP_COMMAND(new WarpCommand(SpongeHuskHomes.getInstance())),
SET_WARP_COMMAND(new SetWarpCommand(SpongeHuskHomes.getInstance())),
WARP_LIST_COMMAND(new WarpListCommand(SpongeHuskHomes.getInstance())),
DEL_WARP_COMMAND(new DelWarpCommand(SpongeHuskHomes.getInstance())),
EDIT_WARP_COMMAND(new EditWarpCommand(SpongeHuskHomes.getInstance())),
TP_COMMAND(new TpCommand(SpongeHuskHomes.getInstance())),
TP_HERE_COMMAND(new TpHereCommand(SpongeHuskHomes.getInstance())),
TPA_COMMAND(new TeleportRequestCommand(SpongeHuskHomes.getInstance(), TeleportRequest.Type.TPA)),
TPA_HERE_COMMAND(new TeleportRequestCommand(SpongeHuskHomes.getInstance(), TeleportRequest.Type.TPA_HERE)),
TPACCEPT_COMMAND(new TpRespondCommand(SpongeHuskHomes.getInstance(), true)),
TPDECLINE_COMMAND(new TpRespondCommand(SpongeHuskHomes.getInstance(), false)),
RTP_COMMAND(new RtpCommand(SpongeHuskHomes.getInstance())),
TP_IGNORE_COMMAND(new TpIgnoreCommand(SpongeHuskHomes.getInstance())),
TP_OFFLINE_COMMAND(new TpOfflineCommand(SpongeHuskHomes.getInstance())),
TP_ALL_COMMAND(new TpAllCommand(SpongeHuskHomes.getInstance())),
TPA_ALL_COMMAND(new TpaAllCommand(SpongeHuskHomes.getInstance())),
SPAWN_COMMAND(new SpawnCommand(SpongeHuskHomes.getInstance())),
SET_SPAWN_COMMAND(new SetSpawnCommand(SpongeHuskHomes.getInstance())),
BACK_COMMAND(new BackCommand(SpongeHuskHomes.getInstance())),
HUSKHOMES_COMMAND(new HuskHomesCommand(SpongeHuskHomes.getInstance()));
private final Command command;
Type(@NotNull Command command) {
this.command = command;
}
@NotNull
public Command getCommand() {
return command;
}
}
}
@@ -0,0 +1,69 @@
/*
* 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.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeDeleteAllHomesEvent implements IDeleteAllHomesEvent, Event, Cancellable {
private boolean cancelled = false;
private final User user;
private final CommandUser deleter;
public SpongeDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) {
this.user = user;
this.deleter = deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public User getHomeOwner() {
return user;
}
@NotNull
@Override
public CommandUser getDeleter() {
return deleter;
}
@Override
public Cause cause() {
return Cause.builder()
.append(deleter)
.build();
}
}
@@ -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.event;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeDeleteAllWarpsEvent implements IDeleteAllWarpsEvent, Event, Cancellable {
private boolean cancelled = false;
private final CommandUser deleter;
public SpongeDeleteAllWarpsEvent(@NotNull CommandUser deleter) {
this.deleter = deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public CommandUser getDeleter() {
return deleter;
}
@Override
public Cause cause() {
return Cause.builder()
.append(deleter)
.build();
}
}
@@ -0,0 +1,123 @@
/*
* 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.william278.huskhomes.SpongeHuskHomes;
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 org.spongepowered.api.event.Event;
import java.util.List;
public interface SpongeEventDispatcher extends EventDispatcher {
@Override
default <T extends net.william278.huskhomes.event.Event> boolean fireIsCancelled(@NotNull T event) {
return getPlugin().getGame().eventManager().post((Event) event);
}
@Override
default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) {
return new SpongeTeleportEvent(teleport);
}
@Override
default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
return new SpongeTeleportWarmupEvent(teleport, duration);
}
@Override
default ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) {
return new SpongeSendTeleportRequestEvent(sender, request);
}
@Override
default IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
return new SpongeReceiveTeleportRequestEvent(recipient, request);
}
@Override
default IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
return new SpongeReplyTeleportRequestEvent(recipient, request);
}
@Override
default IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
return new SpongeHomeCreateEvent(owner, name, position, creator);
}
@Override
default IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) {
return new SpongeHomeEditEvent(home, editor);
}
@Override
default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) {
return new SpongeHomeDeleteEvent(home, deleter);
}
@Override
default IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
return new SpongeWarpCreateEvent(name, position, creator);
}
@Override
default IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) {
return new SpongeWarpEditEvent(warp, editor);
}
@Override
default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) {
return new SpongeWarpDeleteEvent(warp, deleter);
}
@Override
default IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList) {
return new SpongeHomeListEvent(homes, listViewer, publicHomeList);
}
@Override
default IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> homes, @NotNull CommandUser listViewer) {
return new SpongeWarpListEvent(homes, listViewer);
}
@Override
default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) {
return new SpongeDeleteAllHomesEvent(user, deleter);
}
@Override
default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) {
return new SpongeDeleteAllWarpsEvent(deleter);
}
@NotNull
@Override
SpongeHuskHomes getPlugin();
}
@@ -0,0 +1,97 @@
/*
* 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.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeHomeCreateEvent implements IHomeCreateEvent, Event, Cancellable {
private boolean cancelled = false;
private final User owner;
private String name;
private Position position;
private final CommandUser creator;
public SpongeHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
this.owner = owner;
this.name = name;
this.position = position;
this.creator = creator;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public User getOwner() {
return owner;
}
@NotNull
@Override
public String getName() {
return name;
}
@Override
public void setName(@NotNull String name) {
this.name = name;
}
@NotNull
@Override
public Position getPosition() {
return position;
}
@Override
public void setPosition(@NotNull Position position) {
this.position = position;
}
@NotNull
@Override
public CommandUser getCreator() {
return creator;
}
@Override
public Cause cause() {
return Cause.builder()
.append(creator)
.build();
}
}
@@ -0,0 +1,68 @@
/*
* 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.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeHomeDeleteEvent implements IHomeDeleteEvent, Event, Cancellable {
private boolean cancelled = false;
private final Home home;
private final CommandUser deleter;
public SpongeHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) {
this.home = home;
this.deleter = deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public Home getHome() {
return home;
}
@NotNull
@Override
public CommandUser getDeleter() {
return deleter;
}
@Override
public Cause cause() {
return Cause.builder()
.append(deleter)
.build();
}
}
@@ -0,0 +1,68 @@
/*
* 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.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeHomeEditEvent implements IHomeEditEvent, Event, Cancellable {
private boolean cancelled = false;
private final Home home;
private final CommandUser editor;
public SpongeHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor) {
this.home = home;
this.editor = editor;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public Home getHome() {
return home;
}
@NotNull
@Override
public CommandUser getEditor() {
return editor;
}
@Override
public Cause cause() {
return Cause.builder()
.append(editor)
.build();
}
}
@@ -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.william278.huskhomes.position.Home;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
import java.util.List;
public class SpongeHomeListEvent implements IHomeListEvent, Event, Cancellable {
private boolean cancelled = false;
private List<Home> homes;
private final CommandUser listViewer;
private final boolean publicHomeList;
public SpongeHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList) {
this.homes = homes;
this.listViewer = listViewer;
this.publicHomeList = publicHomeList;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public List<Home> getHomes() {
return homes;
}
@Override
public void setHomes(@NotNull List<Home> homes) {
this.homes = homes;
}
@NotNull
@Override
public CommandUser getListViewer() {
return listViewer;
}
@Override
public boolean getIsPublicHomeList() {
return publicHomeList;
}
@Override
public Cause cause() {
return Cause.builder()
.append(listViewer)
.build();
}
}
@@ -0,0 +1,69 @@
/*
* 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.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeReceiveTeleportRequestEvent implements IReceiveTeleportRequestEvent, Event, Cancellable {
private boolean cancelled = false;
private final OnlineUser recipient;
private final TeleportRequest request;
public SpongeReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
this.recipient = recipient;
this.request = request;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public OnlineUser getRecipient() {
return recipient;
}
@NotNull
@Override
public TeleportRequest getRequest() {
return request;
}
@Override
public Cause cause() {
return Cause.builder()
.append(recipient)
.build();
}
}
@@ -0,0 +1,69 @@
/*
* 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.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeReplyTeleportRequestEvent implements IReplyTeleportRequestEvent, Event, Cancellable {
private boolean cancelled = false;
private final OnlineUser recipient;
private final TeleportRequest request;
public SpongeReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) {
this.recipient = recipient;
this.request = request;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public OnlineUser getRecipient() {
return recipient;
}
@NotNull
@Override
public TeleportRequest getRequest() {
return request;
}
@Override
public Cause cause() {
return Cause.builder()
.append(recipient)
.build();
}
}
@@ -0,0 +1,69 @@
/*
* 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.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeSendTeleportRequestEvent implements ISendTeleportRequestEvent, Event, Cancellable {
private boolean cancelled = false;
private final OnlineUser sender;
private final TeleportRequest request;
public SpongeSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) {
this.sender = sender;
this.request = request;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public OnlineUser getSender() {
return sender;
}
@NotNull
@Override
public TeleportRequest getRequest() {
return request;
}
@Override
public Cause cause() {
return Cause.builder()
.append(sender)
.build();
}
}
@@ -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.event;
import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeTeleportEvent implements ITeleportEvent, Event, Cancellable {
private boolean cancelled = false;
private final Teleport teleport;
public SpongeTeleportEvent(@NotNull Teleport teleport) {
this.teleport = teleport;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public Teleport getTeleport() {
return teleport;
}
@Override
public Cause cause() {
return Cause.builder()
.append(teleport.getTeleporter())
.build();
}
}
@@ -0,0 +1,65 @@
/*
* 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.william278.huskhomes.teleport.TimedTeleport;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeTeleportWarmupEvent implements ITeleportWarmupEvent, Event, Cancellable {
private boolean cancelled = false;
private final TimedTeleport teleport;
private final int duration;
public SpongeTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) {
this.teleport = teleport;
this.duration = duration;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public Cause cause() {
return Cause.builder()
.append(teleport.getTeleporter())
.build();
}
@Override
public int getWarmupDuration() {
return duration;
}
@NotNull
@Override
public TimedTeleport getTimedTeleport() {
return teleport;
}
}
@@ -0,0 +1,87 @@
/*
* 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.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeWarpCreateEvent implements IWarpCreateEvent, Event, Cancellable {
private boolean cancelled = false;
private String name;
private Position position;
private final CommandUser creator;
public SpongeWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator) {
this.name = name;
this.position = position;
this.creator = creator;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public String getName() {
return name;
}
@Override
public void setName(@NotNull String name) {
this.name = name;
}
@NotNull
@Override
public Position getPosition() {
return position;
}
@Override
public void setPosition(@NotNull Position position) {
this.position = position;
}
@NotNull
@Override
public CommandUser getCreator() {
return creator;
}
@Override
public Cause cause() {
return Cause.builder()
.append(creator)
.build();
}
}
@@ -0,0 +1,69 @@
/*
* 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.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeWarpDeleteEvent implements IWarpDeleteEvent, Event, Cancellable {
private boolean cancelled = false;
private final Warp warp;
private final CommandUser deleter;
public SpongeWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) {
this.warp = warp;
this.deleter = deleter;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public Warp getWarp() {
return warp;
}
@NotNull
@Override
public CommandUser getDeleter() {
return deleter;
}
@Override
public Cause cause() {
return Cause.builder()
.append(deleter)
.build();
}
}
@@ -0,0 +1,69 @@
/*
* 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.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
public class SpongeWarpEditEvent implements IWarpEditEvent, Event, Cancellable {
private boolean cancelled = false;
private final Warp warp;
private final CommandUser editor;
public SpongeWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor) {
this.warp = warp;
this.editor = editor;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public Warp getWarp() {
return warp;
}
@NotNull
@Override
public CommandUser getEditor() {
return editor;
}
@Override
public Cause cause() {
return Cause.builder()
.append(editor)
.build();
}
}
@@ -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.william278.huskhomes.position.Warp;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.Event;
import java.util.List;
public class SpongeWarpListEvent implements IWarpListEvent, Event, Cancellable {
private boolean cancelled = false;
private List<Warp> warps;
private final CommandUser listViewer;
public SpongeWarpListEvent(@NotNull List<Warp> warps, @NotNull CommandUser listViewer) {
this.warps = warps;
this.listViewer = listViewer;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@NotNull
@Override
public List<Warp> getWarps() {
return warps;
}
@Override
public void setWarps(@NotNull List<Warp> warps) {
this.warps = warps;
}
@NotNull
@Override
public CommandUser getListViewer() {
return listViewer;
}
@Override
public Cause cause() {
return Cause.builder()
.append(listViewer)
.build();
}
}
@@ -0,0 +1,81 @@
/*
* 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.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.SpongeHuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.Server;
import org.spongepowered.api.service.economy.Currency;
import org.spongepowered.api.service.economy.EconomyService;
import org.spongepowered.api.service.economy.account.Account;
import java.math.BigDecimal;
public class SpongeEconomyHook extends EconomyHook {
private EconomyService economyService;
private Currency currency;
public SpongeEconomyHook(@NotNull HuskHomes plugin) {
super(plugin, "Sponge Economy");
}
@Override
public double getPlayerBalance(@NotNull OnlineUser player) {
return economyService.findOrCreateAccount(player.getUuid())
.map(account -> account.balance(currency))
.orElse(BigDecimal.ZERO)
.doubleValue();
}
@Override
public void changePlayerBalance(@NotNull OnlineUser player, double amount) {
if (amount != 0d) {
final Account account = economyService.findOrCreateAccount(player.getUuid())
.orElseThrow(() -> new IllegalStateException("Account not found for " + player.getUsername()));
final double currentBalance = getPlayerBalance(player);
final double amountToChange = Math.abs(currentBalance - Math.max(0d, currentBalance + amount));
if (amount < 0d) {
account.withdraw(currency, BigDecimal.valueOf(amountToChange), getServer().causeStackManager().currentCause());
} else {
account.deposit(currency, BigDecimal.valueOf(amountToChange), getServer().causeStackManager().currentCause());
}
}
}
@Override
public String formatCurrency(double amount) {
return currency.format(BigDecimal.valueOf(amount)).insertion();
}
@Override
public void initialize() {
this.economyService = getServer().serviceProvider().economyService()
.orElseThrow(() -> new IllegalStateException("No economy service has been registered!"));
this.currency = economyService.defaultCurrency();
}
@NotNull
private Server getServer() {
return ((SpongeHuskHomes) plugin).getGame().server();
}
}
@@ -0,0 +1,105 @@
/*
* 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.william278.huskhomes.SpongeHuskHomes;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.SpongeUser;
import net.william278.huskhomes.util.SpongeAdapter;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.EventContextKeys;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.cause.entity.MovementType;
import org.spongepowered.api.event.cause.entity.MovementTypes;
import org.spongepowered.api.event.entity.DestructEntityEvent;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.entity.living.player.RespawnPlayerEvent;
import org.spongepowered.api.event.network.ServerSideConnectionEvent;
import org.spongepowered.api.world.server.ServerLocation;
import java.util.Optional;
public class SpongeEventListener extends EventListener {
public SpongeEventListener(@NotNull SpongeHuskHomes plugin) {
super(plugin);
plugin.getGame().eventManager().registerListeners(plugin.getPluginContainer(), this);
}
@Listener
public void onPlayerJoin(final ServerSideConnectionEvent.Join event) {
super.handlePlayerJoin(SpongeUser.adapt(event.player()));
}
@Listener
public void onPlayerLeave(final ServerSideConnectionEvent.Disconnect event) {
super.handlePlayerJoin(SpongeUser.adapt(event.player()));
}
@Listener
public void onPlayerDeath(final DestructEntityEvent.Death event) {
if (event.entity() instanceof ServerPlayer player) {
super.handlePlayerJoin(SpongeUser.adapt(player));
}
}
@Listener
public void onPlayerRespawn(final RespawnPlayerEvent event) {
super.handlePlayerJoin(SpongeUser.adapt(event.entity()));
}
@Listener
public void onPlayerTeleport(final MoveEntityEvent event) {
if (event.entity() instanceof ServerPlayer player) {
final Optional<MovementType> type = event.context().get(EventContextKeys.MOVEMENT_TYPE);
if (type.isPresent() && type.get().equals(MovementTypes.ENTITY_TELEPORT.get())) {
SpongeAdapter.adaptLocation(ServerLocation.of(player.world(), event.originalPosition()))
.ifPresent(location -> super.handlePlayerTeleport(SpongeUser.adapt(player),
Position.at(location, plugin.getServerName())));
}
}
}
@Listener
@SuppressWarnings("unchecked")
public void onPlayerUpdateRespawnLocation(InteractBlockEvent.Secondary event) {
if (event.context().get(EventContextKeys.PLAYER).isPresent()) {
final ServerPlayer player = (ServerPlayer) event.context().get(EventContextKeys.PLAYER).get();
final BlockType type = event.block().state().type();
if (type.isAnyOf(BlockTypes.BLACK_BED, BlockTypes.BLUE_BED, BlockTypes.BROWN_BED, BlockTypes.CYAN_BED,
BlockTypes.GRAY_BED, BlockTypes.GREEN_BED, BlockTypes.LIGHT_BLUE_BED, BlockTypes.LIGHT_GRAY_BED,
BlockTypes.LIME_BED, BlockTypes.MAGENTA_BED, BlockTypes.ORANGE_BED, BlockTypes.PINK_BED,
BlockTypes.PURPLE_BED, BlockTypes.RED_BED, BlockTypes.WHITE_BED, BlockTypes.YELLOW_BED,
BlockTypes.RESPAWN_ANCHOR)) {
super.handlePlayerUpdateSpawnPoint(SpongeUser.adapt(player), Position.at(
SpongeAdapter.adaptLocation(player.serverLocation()).orElseThrow(),
plugin.getServerName()
));
}
}
}
}
@@ -0,0 +1,130 @@
/*
* 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.kyori.adventure.audience.Audience;
import net.william278.huskhomes.SpongeHuskHomes;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.SpongeAdapter;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.service.permission.SubjectData;
import org.spongepowered.api.util.RespawnLocation;
import org.spongepowered.api.world.server.ServerLocation;
import java.util.Map;
import java.util.Optional;
public class SpongeUser extends OnlineUser {
private final ServerPlayer player;
private final SpongeHuskHomes plugin;
private SpongeUser(@NotNull ServerPlayer player) {
super(player.uniqueId(), player.name());
this.player = player;
this.plugin = SpongeHuskHomes.getInstance();
}
/**
* Adapt a {@link ServerPlayer} to a {@link OnlineUser}
*
* @param player the online {@link ServerPlayer} to adapt
* @return the adapted {@link OnlineUser}
*/
@NotNull
public static SpongeUser adapt(@NotNull ServerPlayer player) {
return new SpongeUser(player);
}
@Override
public Position getPosition() {
return Position.at(
SpongeAdapter.adaptLocation(player.serverLocation())
.orElseThrow(() -> new IllegalStateException("Failed to adapt player location")),
plugin.getServerName()
);
}
@Override
public Optional<Position> getBedSpawnPosition() {
// Resolve the player's RespawnLocation from the world-key map and adapt as location
return player.get(Keys.RESPAWN_LOCATIONS)
.flatMap(resourceMap -> resourceMap.values().stream().findFirst())
.flatMap(RespawnLocation::asLocation).flatMap(SpongeAdapter::adaptLocation)
.map(location -> Position.at(location, plugin.getServerName()));
}
@Override
public double getHealth() {
return player.health().asImmutable().get();
}
@Override
public boolean hasPermission(@NotNull String node) {
return player.hasPermission(node);
}
@Override
@NotNull
public Map<String, Boolean> getPermissions() {
return player.transientSubjectData().permissions(SubjectData.GLOBAL_CONTEXT);
}
@Override
@NotNull
public Audience getAudience() {
return player;
}
@Override
public void teleportLocally(@NotNull Location location, boolean asynchronous) {
plugin.runSync(() -> {
final Optional<ServerLocation> serverLocation = SpongeAdapter.adaptLocation(location);
if (serverLocation.isEmpty()) {
return;
}
player.setLocation(serverLocation.get());
});
}
@Override
public void sendPluginMessage(@NotNull String channel, byte[] message) {
plugin.getPluginMessageChannel().sendTo(player, channelBuf -> channelBuf.writeBytes(message));
}
@Override
public boolean isMoving() {
return player.velocity().get().lengthSquared() > 0.0075;
}
@Override
public boolean isVanished() {
return false;
}
@NotNull
public ServerPlayer getPlayer() {
return player;
}
}
@@ -0,0 +1,88 @@
/*
* 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.position.Location;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.world.WorldTypeTemplate;
import org.spongepowered.api.world.server.ServerLocation;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.api.world.server.WorldManager;
import java.util.Optional;
public final class SpongeAdapter {
/**
* Adapt a Sponge {@link ServerLocation} to a HuskHomes {@link Location}
*
* @param location the Sponge {@link ServerLocation} to adapt
* @return the adapted {@link Location}
*/
public static Optional<ServerLocation> adaptLocation(@NotNull Location location) {
final WorldManager worldManager = Sponge.server().worldManager();
return worldManager
.world(ResourceKey.resolve(location.getWorld().getName()))
.map(world -> ServerLocation.of(world, location.getX(), location.getY(), location.getZ()))
.or(() -> {
final Optional<ResourceKey> worldKey = worldManager.worldKey(location.getWorld().getUuid());
return worldKey.flatMap(resourceKey -> worldManager.world(resourceKey)
.map(world -> ServerLocation.of(world, location.getX(), location.getY(), location.getZ())));
});
}
/**
* Adapt a HuskHomes {@link Location} to a Sponge {@link ServerLocation}
*
* @param location the HuskHomes {@link Location} to adapt
* @return the adapted {@link ServerLocation}
*/
public static Optional<Location> adaptLocation(@NotNull ServerLocation location) {
return Optional.of(Location.at(
location.x(), location.y(), location.z(),
adaptWorld(location.world()).orElse(new World()))
);
}
/**
* Adapt a Sponge {@link ServerWorld} to a HuskHomes {@link World}
*
* @param world the Sponge {@link ServerWorld} to adapt
* @return the adapted {@link World}
*/
public static Optional<World> adaptWorld(@Nullable ServerWorld world) {
if (world == null) {
return Optional.empty();
}
final String worldType = world.properties().worldType().asTemplate().key().asString();
return Optional.of(World.from(
world.key().toString(), world.uniqueId(),
(worldType.equals(WorldTypeTemplate.theNether().key().toString()) ? World.Environment.NETHER
: worldType.equals(WorldTypeTemplate.theEnd().key().toString()) ? World.Environment.THE_END
: worldType.equals(WorldTypeTemplate.overworld().key().toString()) ? World.Environment.OVERWORLD
: World.Environment.CUSTOM)
));
}
}
@@ -0,0 +1,35 @@
/*
* 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.position.Location;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public interface SpongeSafetyResolver extends SafetyResolver {
@Override
default CompletableFuture<Optional<Location>> findSafeGroundLocation(@NotNull Location location) {
return CompletableFuture.completedFuture(Optional.of(location)); // todo
}
}
@@ -0,0 +1,147 @@
/*
* 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.SpongeHuskHomes;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.util.Ticks;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public interface SpongeTaskRunner extends TaskRunner {
Map<Integer, CancellableRunnable> tasks = new HashMap<>();
@Override
default int runAsync(@NotNull Runnable runnable) {
final CancellableRunnable task = wrap(runnable);
final int taskId = tasks.size();
tasks.put(taskId, task);
getPlugin().getGame().asyncScheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(task)
.build());
return taskId;
}
@Override
default <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier) {
final CompletableFuture<T> future = new CompletableFuture<>();
getPlugin().getGame().asyncScheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(() -> future.complete(supplier.get()))
.build());
return future;
}
@Override
default void runSync(@NotNull Runnable runnable) {
getPlugin().getGame().server().scheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(runnable)
.build());
}
@Override
default int runAsyncRepeating(@NotNull Runnable runnable, long delay) {
final CancellableRunnable task = wrap(runnable);
final int taskId = tasks.size();
tasks.put(taskId, task);
getPlugin().getGame().asyncScheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(task)
.interval(Ticks.of(delay))
.build());
return taskId;
}
@Override
default void runLater(@NotNull Runnable runnable, long delay) {
getPlugin().getGame().server().scheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(runnable)
.delay(Ticks.of(delay))
.build());
}
@Override
default void cancelTask(int taskId) {
if (tasks.containsKey(taskId)) {
tasks.get(taskId).cancel();
}
}
@Override
default void cancelAllTasks() {
tasks.values().forEach(CancellableRunnable::cancel);
tasks.clear();
}
@NotNull
private CancellableRunnable wrap(@NotNull Runnable runnable) {
return new CancellableRunnable(runnable);
}
@NotNull
@Override
SpongeHuskHomes getPlugin();
/**
* A wrapper for a {@link Runnable} that can be cancelled
*/
class CancellableRunnable implements Runnable {
private final Runnable runnable;
private boolean cancelled = false;
private CancellableRunnable(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
if (cancelled) {
return;
}
runnable.run();
}
public void cancel() {
cancelled = true;
}
}
}