From fb052340c089659744396adb48cf9824d78d80ac Mon Sep 17 00:00:00 2001 From: William Date: Fri, 16 Jun 2023 12:19:31 +0100 Subject: [PATCH] New task system & improve DB case-insensitive SELECTs, support fabric 1.20.1 (#433) --- .github/workflows/ci.yml | 4 +- .github/workflows/release.yml | 4 +- build.gradle | 12 +- .../william278/huskhomes/BukkitHuskHomes.java | 18 +-- .../event/BukkitEventDispatcher.java | 1 - .../william278/huskhomes/util/BukkitTask.java | 141 +++++++++++++++++ .../huskhomes/util/BukkitTaskRunner.java | 95 ------------ common/build.gradle | 4 +- .../net/william278/huskhomes/HuskHomes.java | 2 +- .../huskhomes/database/MySqlDatabase.java | 12 +- .../huskhomes/database/SqLiteDatabase.java | 32 ++-- .../huskhomes/listener/EventListener.java | 4 +- .../huskhomes/teleport/TimedTeleport.java | 58 +++---- .../william278/huskhomes/user/OnlineUser.java | 12 +- .../net/william278/huskhomes/util/Task.java | 135 ++++++++++++++++ .../william278/huskhomes/util/TaskRunner.java | 52 ------- fabric/build.gradle | 10 +- .../william278/huskhomes/FabricHuskHomes.java | 29 ++-- .../william278/huskhomes/user/FabricUser.java | 6 + .../william278/huskhomes/util/FabricTask.java | 142 +++++++++++++++++ .../huskhomes/util/FabricTaskRunner.java | 101 ------------ fabric/src/main/resources/fabric.mod.json | 4 +- gradle.properties | 9 +- paper/build.gradle | 2 +- .../william278/huskhomes/SpongeHuskHomes.java | 16 +- .../william278/huskhomes/util/SpongeTask.java | 145 ++++++++++++++++++ .../huskhomes/util/SpongeTaskRunner.java | 142 ----------------- 27 files changed, 687 insertions(+), 505 deletions(-) create mode 100644 bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java delete mode 100644 bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/Task.java delete mode 100644 common/src/main/java/net/william278/huskhomes/util/TaskRunner.java create mode 100644 fabric/src/main/java/net/william278/huskhomes/util/FabricTask.java delete mode 100644 fabric/src/main/java/net/william278/huskhomes/util/FabricTaskRunner.java create mode 100644 sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/util/SpongeTaskRunner.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab56fd77..0f888823 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,7 +71,7 @@ jobs: 1.17.1 1.18.2 1.19.4 - 1.20 + 1.20.1 java: 16 - name: Upload to Modrinth (Sponge) uses: WiIIiam278/mc-publish@hangar @@ -115,7 +115,7 @@ jobs: loaders: | fabric game-versions: | - 1.20 + 1.20.1 java: 17 - name: Upload GitHub Artifact (Spigot) uses: actions/upload-artifact@v2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 118d6f34..f27b3b2e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -59,7 +59,7 @@ jobs: 1.17.1 1.18.2 1.19.4 - 1.20 + 1.20.1 java: 16 - name: Upload to Modrinth (Sponge) uses: WiIIiam278/mc-publish@hangar @@ -103,7 +103,7 @@ jobs: loaders: | fabric game-versions: | - 1.20 + 1.20.1 java: 17 - name: Upload GitHub Artifact (Spigot) uses: actions/upload-artifact@v2 diff --git a/build.gradle b/build.gradle index 5799b543..f79da830 100644 --- a/build.gradle +++ b/build.gradle @@ -15,10 +15,16 @@ defaultTasks 'licenseFormat', 'build' ext { set 'version', version.toString() + set 'description', description.toString() + 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() + + set 'fabric_minecraft_version', fabric_minecraft_version.toString() + set 'fabric_yarn_mappings', fabric_yarn_mappings.toString() + set 'fabric_loader_version', fabric_loader_version.toString() + set 'fabric_api_version', fabric_api_version.toString() } allprojects { @@ -34,6 +40,10 @@ allprojects { repositories { mavenLocal() mavenCentral() + maven { + url 'https://s01.oss.sonatype.org/content/repositories/snapshots/' + mavenContent { snapshotsOnly() } + } maven { url 'https://maven.fabricmc.net/' } maven { url 'https://libraries.minecraft.net/' } maven { url 'https://api.modrinth.com/maven' } diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 1f4842c1..1e9e20fd 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -65,23 +65,21 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import space.arim.morepaperlib.MorePaperLib; import space.arim.morepaperlib.scheduling.GracefulScheduling; -import space.arim.morepaperlib.scheduling.ScheduledTask; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.stream.Collectors; -public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTaskRunner, BukkitEventDispatcher, PluginMessageListener, BukkitSafetyResolver { +public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask.Supplier, BukkitEventDispatcher, + PluginMessageListener, BukkitSafetyResolver { /** * Metrics ID for HuskHomes on Bukkit. */ private static final int METRICS_ID = 8430; - private ConcurrentHashMap tasks; private Set savedUsers; private Settings settings; private Locales locales; @@ -130,7 +128,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask // Create adventure audience this.audiences = BukkitAudiences.create(this); this.paperLib = new MorePaperLib(this); - this.tasks = new ConcurrentHashMap<>(); this.savedUsers = new HashSet<>(); this.globalPlayerList = new HashMap<>(); this.currentlyOnWarmup = new HashSet<>(); @@ -257,7 +254,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask audiences.close(); audiences = null; } - cancelAllTasks(); + cancelTasks(); } /** @@ -485,23 +482,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask @Override public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { if (broker != null && broker instanceof PluginMessageBroker pluginMessenger - && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message); } } - @Override @NotNull public GracefulScheduling getScheduler() { return paperLib.scheduling(); } - @Override - @NotNull - public ConcurrentHashMap getTasks() { - return tasks; - } - @Override @NotNull public HuskHomes getPlugin() { diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java index a9919a2e..6dc5bec3 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java @@ -35,7 +35,6 @@ import java.util.List; public interface BukkitEventDispatcher extends EventDispatcher { - @Override default boolean fireIsCancelled(@NotNull T event) { Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event); diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java new file mode 100644 index 00000000..854c8baa --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java @@ -0,0 +1,141 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * 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.BukkitHuskHomes; +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; +import space.arim.morepaperlib.scheduling.GracefulScheduling; +import space.arim.morepaperlib.scheduling.ScheduledTask; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +public interface BukkitTask extends Task { + + class Sync extends Task.Sync implements BukkitTask { + + private ScheduledTask task; + + protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (delayTicks > 0) { + this.task = getScheduler().globalRegionalScheduler().runDelayed(runnable, delayTicks); + } else { + this.task = getScheduler().globalRegionalScheduler().run(runnable); + } + } + } + + class Async extends Task.Async implements BukkitTask { + + private ScheduledTask task; + + protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + super(plugin, runnable); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = getScheduler().asyncScheduler().run(runnable); + } + } + } + + class Repeating extends Task.Repeating implements BukkitTask { + + private ScheduledTask task; + + protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable, repeatingTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = getScheduler().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration + .of(repeatingTicks * 50L, ChronoUnit.MILLIS) + ); + } + } + } + + interface Supplier extends Task.Supplier { + + @NotNull + @Override + default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Sync(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Async getAsyncTask(@NotNull Runnable runnable) { + return new Async(getPlugin(), runnable); + } + + @NotNull + @Override + default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { + return new Repeating(getPlugin(), runnable, repeatingTicks); + } + + @Override + default void cancelTasks() { + ((BukkitHuskHomes) getPlugin()).getScheduler().cancelGlobalTasks(); + } + + } + + @NotNull + default GracefulScheduling getScheduler() { + return ((BukkitHuskHomes) getPlugin()).getScheduler(); + } + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java deleted file mode 100644 index 2ac3881e..00000000 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * 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 org.jetbrains.annotations.NotNull; -import space.arim.morepaperlib.scheduling.GracefulScheduling; -import space.arim.morepaperlib.scheduling.ScheduledTask; - -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -public interface BukkitTaskRunner extends TaskRunner { - - @Override - default void runAsync(@NotNull Runnable runnable) { - getScheduler().asyncScheduler().run(runnable); - } - - @Override - default CompletableFuture supplyAsync(@NotNull Supplier supplier) { - final CompletableFuture future = new CompletableFuture<>(); - getScheduler().asyncScheduler().run(() -> future.complete(supplier.get())); - return future; - } - - @Override - default void runSync(@NotNull Runnable runnable) { - getScheduler().globalRegionalScheduler().run(runnable); - } - - @NotNull - @Override - default UUID runAsyncRepeating(@NotNull Runnable runnable, long period) { - final UUID taskId = UUID.randomUUID(); - getTasks().put(taskId, getScheduler().asyncScheduler().runAtFixedRate( - runnable, Duration.ZERO, getDurationTicks(period)) - ); - return taskId; - } - - @Override - default void runLater(@NotNull Runnable runnable, long delay) { - getScheduler().asyncScheduler().runDelayed(runnable, getDurationTicks(delay)); - } - - @Override - default void cancelTask(@NotNull UUID taskId) { - getTasks().computeIfPresent(taskId, (id, task) -> { - task.cancel(); - return null; - }); - getTasks().remove(taskId); - } - - @Override - default void cancelAllTasks() { - getScheduler().cancelGlobalTasks(); - getTasks().values().forEach(ScheduledTask::cancel); - getTasks().clear(); - } - - @NotNull - GracefulScheduling getScheduler(); - - @NotNull - @Override - ConcurrentHashMap getTasks(); - - @NotNull - default Duration getDurationTicks(long ticks) { - return Duration.of(ticks * 50, ChronoUnit.MILLIS); - } - -} diff --git a/common/build.gradle b/common/build.gradle index d1aa4525..b999af48 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -7,7 +7,7 @@ test { } dependencies { - api 'commons-io:commons-io:2.12.0' + api 'commons-io:commons-io:2.13.0' api 'org.apache.commons:commons-text:1.10.0' api 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' api 'com.google.code.gson:gson:2.10.1' @@ -25,7 +25,7 @@ dependencies { compileOnly 'com.mysql:mysql-connector-j:' + mysql_driver_version compileOnly 'org.jetbrains:annotations:24.0.1' - compileOnly 'com.google.guava:guava:32.0.0-jre' + compileOnly 'com.google.guava:guava:32.0.1-jre' compileOnly 'com.github.plan-player-analytics:Plan:5.5.2391' compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.5.0' compileOnly 'us.dynmap:DynmapCoreAPI:3.4' diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 7080cc96..fe13db76 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -63,7 +63,7 @@ import java.util.stream.Stream; /** * Represents a cross-platform instance of the plugin */ -public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver, TransactionResolver { +public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver { int SPIGOT_RESOURCE_ID = 83767; diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index c507a5df..7c5de930 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -428,9 +428,11 @@ public class MySqlDatabase extends Database { INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` WHERE `owner_uuid`=? - """ + (caseInsensitive ? "AND UPPER(`name`) LIKE UPPER(?);" : "AND `name`=?;")))) { + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); - statement.setString(2, homeName); + statement.setBoolean(2, caseInsensitive); + statement.setString(3, homeName); + statement.setString(4, homeName); final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { @@ -503,8 +505,10 @@ public class MySqlDatabase extends Database { FROM `%warps_table%` INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - """ + (caseInsensitive ? "WHERE UPPER(`name`) LIKE UPPER(?);" : "WHERE `name`=?;")))) { - statement.setString(1, warpName); + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { + statement.setBoolean(1, caseInsensitive); + statement.setString(2, warpName); + statement.setString(3, warpName); final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 4febf1ad..c21eae59 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -433,15 +433,17 @@ public class SqLiteDatabase extends Database { public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { try { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - """ + (caseInsensitive ? "AND UPPER(`name`) LIKE UPPER(?);" : "AND `name`=?;")))) { + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); - statement.setString(2, homeName); + statement.setBoolean(2, caseInsensitive); + statement.setString(3, homeName); + statement.setString(4, homeName); final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { @@ -510,12 +512,14 @@ public class SqLiteDatabase extends Database { public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { try { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - """ + (caseInsensitive ? "WHERE UPPER(`name`) LIKE UPPER(?);" : "WHERE `name`=?;")))) { - statement.setString(1, warpName); + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { + statement.setBoolean(1, caseInsensitive); + statement.setString(2, warpName); + statement.setString(3, warpName); final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 5d5640b0..34068c90 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -64,7 +64,7 @@ public class EventListener { this.handleInboundTeleport(onlineUser); // Synchronize the global player list - plugin.runLater(() -> this.synchronizeGlobalPlayerList(onlineUser, plugin.getLocalPlayerList()), 40L); + plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(onlineUser, plugin.getLocalPlayerList()), 40L); // Request updated player lists from other servers if (plugin.getOnlineUsers().size() == 1) { @@ -122,7 +122,7 @@ public class EventListener { if (bedPosition.isEmpty()) { plugin.getSpawn().ifPresent(spawn -> { if (plugin.getSettings().doCrossServer() && !spawn.getServer().equals(plugin.getServerName())) { - plugin.runLater(() -> { + plugin.runSyncDelayed(() -> { try { Teleport.builder(plugin) .teleporter(teleporter) diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index a50e3ff0..d102e75e 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -25,11 +25,10 @@ import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.util.Task; import org.jetbrains.annotations.NotNull; import java.util.List; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; /** * Represents a {@link Teleport} that has an associated warmup time; the teleport will not be performed until the @@ -37,12 +36,13 @@ import java.util.concurrent.atomic.AtomicReference; * * @see Teleport#builder(HuskHomes) */ -public class TimedTeleport extends Teleport { +public class TimedTeleport extends Teleport implements Runnable { public static final String BYPASS_PERMISSION = "huskhomes.bypass_teleport_warmup"; private final OnlineUser teleporter; private final Position startLocation; private final double startHealth; + private Task.Repeating task; private int timeLeft; protected TimedTeleport(@NotNull OnlineUser executor, @NotNull OnlineUser teleporter, @NotNull Target target, @@ -88,34 +88,36 @@ public class TimedTeleport extends Teleport { .ifPresent(teleporter::sendMessage); // Run the warmup - final AtomicReference warmupTaskId = new AtomicReference<>(); - final Runnable countdownRunnable = (() -> { - // Display a countdown action bar message - if (timeLeft > 0) { - plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP) - .ifPresent(teleporter::playSound); - plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft)) - .ifPresent(this::sendStatusMessage); - } else { - plugin.getLocales().getLocale("teleporting_action_bar_processing") - .ifPresent(this::sendStatusMessage); - try { - super.execute(); - } catch (TeleportationException e) { - e.displayMessage(teleporter, plugin); - } - } - - // Tick (decrement) the timed teleport timer and end it if done - if (tickAndGetIfDone()) { - plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid()); - plugin.cancelTask(warmupTaskId.get()); - } - }); - warmupTaskId.set(plugin.runAsyncRepeating(countdownRunnable, 20L)); + this.task = plugin.getRepeatingTask(this, 20L); + this.task.run(); }); } + @Override + public void run() { + // Display a countdown action bar message + if (timeLeft > 0) { + plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP) + .ifPresent(teleporter::playSound); + plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft)) + .ifPresent(this::sendStatusMessage); + } else { + plugin.getLocales().getLocale("teleporting_action_bar_processing") + .ifPresent(this::sendStatusMessage); + try { + super.execute(); + } catch (TeleportationException e) { + e.displayMessage(teleporter, plugin); + } + } + + // Tick (decrement) the timed teleport timer and end it if done + if (tickAndGetIfDone()) { + task.cancel(); + plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid()); + } + } + /** * Ticks a timed teleport, decrementing the time left until the teleport is complete *

diff --git a/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java b/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java index 65112123..e58aec7b 100644 --- a/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java @@ -90,7 +90,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs * @param mineDown the parsed {@link MineDown} to send * @param subTitle whether to send the title as a subtitle ({@code true} for a subtitle, {@code false} for a title) */ - public final void sendTitle(@NotNull MineDown mineDown, boolean subTitle) { + public void sendTitle(@NotNull MineDown mineDown, boolean subTitle) { getAudience().sendTitlePart(subTitle ? TitlePart.SUBTITLE : TitlePart.TITLE, mineDown .disable(MineDownParser.Option.SIMPLE_FORMATTING) .replace().toComponent()); @@ -101,7 +101,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs * * @param mineDown the parsed {@link MineDown} to send */ - public final void sendActionBar(@NotNull MineDown mineDown) { + public void sendActionBar(@NotNull MineDown mineDown) { getAudience().sendActionBar(mineDown .disable(MineDownParser.Option.SIMPLE_FORMATTING) .replace().toComponent()); @@ -113,7 +113,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs * * @param mineDown the parsed {@link MineDown} to send */ - public final void sendMessage(@NotNull MineDown mineDown) { + public void sendMessage(@NotNull MineDown mineDown) { getAudience().sendMessage(mineDown .disable(MineDownParser.Option.SIMPLE_FORMATTING) .replace().toComponent()); @@ -125,7 +125,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs * @param mineDown the parsed {@link MineDown} to send * @param slot the {@link Locales.DisplaySlot} to send the message to */ - public final void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) { + public void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) { if (slot == Locales.DisplaySlot.CHAT) { sendMessage(mineDown); } else if (slot == Locales.DisplaySlot.ACTION_BAR) { @@ -144,7 +144,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs * @implNote This method is intended for use with Minecraft's built-in translation keys. If the key is invalid, * it will be substituted with {@code minecraft:block.minecraft.spawn.not_valid} */ - public final void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid") + public void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid") @NotNull String translationKey) { getAudience().sendMessage(Component.translatable(translationKey)); } @@ -155,7 +155,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs * @param soundEffect the sound effect to play. If the sound name is invalid, the sound will not play * @implNote If the key is invalid, it will be substituted with {@code minecraft:block.note_block.banjo} */ - public final void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo") + public void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo") @NotNull String soundEffect) throws IllegalArgumentException { try { getAudience().playSound( diff --git a/common/src/main/java/net/william278/huskhomes/util/Task.java b/common/src/main/java/net/william278/huskhomes/util/Task.java new file mode 100644 index 00000000..08152a23 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/Task.java @@ -0,0 +1,135 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * 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.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; + +public interface Task extends Runnable { + + abstract class Base implements Task { + + protected final HuskHomes plugin; + protected final Runnable runnable; + protected boolean cancelled = false; + + protected Base(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + this.plugin = plugin; + this.runnable = runnable; + } + + public void cancel() { + cancelled = true; + } + + @NotNull + @Override + public HuskHomes getPlugin() { + return plugin; + } + + } + + abstract class Async extends Base { + + protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + super(plugin, runnable); + } + + } + + abstract class Sync extends Base { + + protected long delayTicks; + + protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable); + this.delayTicks = delayTicks; + } + + } + + abstract class Repeating extends Base { + + protected final long repeatingTicks; + + protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable); + this.repeatingTicks = repeatingTicks; + } + + } + + @SuppressWarnings("UnusedReturnValue") + interface Supplier { + + @NotNull + Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks); + + @NotNull + Task.Async getAsyncTask(@NotNull Runnable runnable); + + @NotNull + Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks); + + @NotNull + default Task.Sync runSyncDelayed(@NotNull Runnable runnable, long delayTicks) { + final Task.Sync task = getSyncTask(runnable, delayTicks); + task.run(); + return task; + } + + @NotNull + default Task.Sync runSync(@NotNull Runnable runnable) { + return runSyncDelayed(runnable, 0); + } + + @NotNull + default Task.Async runAsync(@NotNull Runnable runnable) { + final Task.Async task = getAsyncTask(runnable); + task.run(); + return task; + } + + default CompletableFuture supplyAsync(@NotNull java.util.function.Supplier supplier) { + final CompletableFuture future = new CompletableFuture<>(); + runAsync(() -> { + try { + future.complete(supplier.get()); + } catch (Throwable throwable) { + future.completeExceptionally(throwable); + } + }); + return future; + } + + void cancelTasks(); + + @NotNull + HuskHomes getPlugin(); + + } + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java b/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java deleted file mode 100644 index d1de3d6c..00000000 --- a/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * 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.HuskHomes; -import org.jetbrains.annotations.NotNull; - -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -public interface TaskRunner { - - void runAsync(@NotNull Runnable runnable); - - CompletableFuture supplyAsync(@NotNull Supplier supplier); - - void runSync(@NotNull Runnable runnable); - - @NotNull - UUID runAsyncRepeating(@NotNull Runnable runnable, long delay); - - void runLater(@NotNull Runnable runnable, long delay); - - void cancelTask(@NotNull UUID taskId); - - void cancelAllTasks(); - - @NotNull - ConcurrentHashMap getTasks(); - @NotNull - HuskHomes getPlugin(); - -} diff --git a/fabric/build.gradle b/fabric/build.gradle index 431f8b9f..21edaad7 100644 --- a/fabric/build.gradle +++ b/fabric/build.gradle @@ -6,9 +6,9 @@ apply plugin: 'fabric-loom' loom.serverOnlyMinecraftJar() dependencies { - minecraft 'com.mojang:minecraft:1.20' - mappings 'net.fabricmc:yarn:1.20+build.1:v2' - modImplementation 'net.fabricmc:fabric-loader:0.14.21' + minecraft "com.mojang:minecraft:${fabric_minecraft_version}" + mappings "net.fabricmc:yarn:${fabric_yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}" // Fabric API modules Set fabricApiModules = [ @@ -19,9 +19,9 @@ dependencies { 'fabric-networking-api-v1' ] fabricApiModules.forEach { - modImplementation(fabricApi.module(it, '0.83.0+1.20')) + modImplementation(fabricApi.module(it, fabric_api_version)) } - modImplementation include('net.kyori:adventure-platform-fabric:5.8.0') + modImplementation include('net.kyori:adventure-platform-fabric:5.9.0-SNAPSHOT') modImplementation include('me.lucko:fabric-permissions-api:0.2-SNAPSHOT') implementation include('redis.clients:jedis:' + jedis_version) diff --git a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java b/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java index 937c65bd..36e12265 100644 --- a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java +++ b/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java @@ -62,7 +62,7 @@ import net.william278.huskhomes.user.FabricUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.util.FabricSafetyResolver; -import net.william278.huskhomes.util.FabricTaskRunner; +import net.william278.huskhomes.util.FabricTask; import net.william278.huskhomes.util.UnsafeBlocks; import net.william278.huskhomes.util.Validator; import org.jetbrains.annotations.NotNull; @@ -77,13 +77,11 @@ 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.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.stream.Collectors; -public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, - FabricTaskRunner, FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler { +public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier, + FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler { public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes"); private static FabricHuskHomes instance; @@ -93,10 +91,9 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes return instance; } - private final ModContainer modContainer = FabricLoader.getInstance() - .getModContainer("huskhomes").orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); + private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes") + .orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); private MinecraftServer minecraftServer; - private ConcurrentHashMap> tasks; private Map permissions; private Set savedUsers; private Settings settings; @@ -123,7 +120,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes instance = this; // Get plugin version from mod container - this.tasks = new ConcurrentHashMap<>(); this.permissions = new HashMap<>(); this.savedUsers = new HashSet<>(); this.globalPlayerList = new HashMap<>(); @@ -151,6 +147,13 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes // Create adventure audience this.audiences = FabricServerAudiences.of(minecraftServer); + // Temporarily log about sounds being disabled - todo: Remove when adventure-platform-fabric is updated + if (getSettings().doPlaySoundEffects()) { + log(Level.WARNING, "Sound effects are currently disabled for HuskHomes v" + + getVersion() + " on Fabric servers running Minecraft " + + getMinecraftServer().getVersion()); + } + // Initialize the database initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { this.database = switch (getSettings().getDatabaseType()) { @@ -209,7 +212,7 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes audiences.close(); audiences = null; } - cancelAllTasks(); + cancelTasks(); } @Override @@ -479,12 +482,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes return minecraftServer; } - @Override - @NotNull - public ConcurrentHashMap> getTasks() { - return tasks; - } - @Override @NotNull public FabricHuskHomes getPlugin() { diff --git a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java index 28c13084..175a13c6 100644 --- a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java +++ b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -120,9 +120,15 @@ public class FabricUser extends OnlineUser { return player; } + @Override + public void playSound(@NotNull String soundEffect) throws IllegalArgumentException { + // Do nothing - todo: Fix sounds when adventure-platform-fabric is updated. + } + @Override public void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException { final MinecraftServer server = player.getServer(); + assert server != null : "Server is null"; final Identifier worldId = Identifier.tryParse(location.getWorld().getName()); player.teleport( server.getWorld(server.getWorldRegistryKeys().stream() diff --git a/fabric/src/main/java/net/william278/huskhomes/util/FabricTask.java b/fabric/src/main/java/net/william278/huskhomes/util/FabricTask.java new file mode 100644 index 00000000..70b9efe8 --- /dev/null +++ b/fabric/src/main/java/net/william278/huskhomes/util/FabricTask.java @@ -0,0 +1,142 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * 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 net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public interface FabricTask extends Task { + + class Sync extends Task.Sync implements FabricTask { + + protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + if (delayTicks > 0) { + CompletableFuture.runAsync(() -> { + + try { + Thread.sleep(delayTicks * 50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + ((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable); + + }, ((FabricHuskHomes) getPlugin()).getMinecraftServer()); + } else { + ((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable); + } + } + } + } + + class Async extends Task.Async implements FabricTask { + private CompletableFuture task; + + protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + super(plugin, runnable); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(true); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = CompletableFuture.runAsync(runnable, ((FabricHuskHomes) getPlugin()).getMinecraftServer()); + } + } + } + + class Repeating extends Task.Repeating implements FabricTask { + + private ScheduledFuture task; + + protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable, repeatingTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(true); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + this.task = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate( + runnable, 0, repeatingTicks * 50, TimeUnit.MILLISECONDS + ); + } + } + } + + interface Supplier extends Task.Supplier { + + @NotNull + @Override + default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Sync(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Async getAsyncTask(@NotNull Runnable runnable) { + return new Async(getPlugin(), runnable); + } + + @NotNull + @Override + default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { + return new Repeating(getPlugin(), runnable, repeatingTicks); + } + + @Override + default void cancelTasks() { + // Do nothing + } + + } + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/util/FabricTaskRunner.java b/fabric/src/main/java/net/william278/huskhomes/util/FabricTaskRunner.java deleted file mode 100644 index 62a80be9..00000000 --- a/fabric/src/main/java/net/william278/huskhomes/util/FabricTaskRunner.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * 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.UUID; -import java.util.concurrent.*; -import java.util.function.Supplier; - -public interface FabricTaskRunner extends TaskRunner { - - @Override - default void runAsync(@NotNull Runnable runnable) { - CompletableFuture.runAsync(runnable, getPlugin().getMinecraftServer()); - } - - @Override - default CompletableFuture supplyAsync(@NotNull Supplier supplier) { - return CompletableFuture.supplyAsync(supplier, getPlugin().getMinecraftServer()); - } - - @Override - default void runSync(@NotNull Runnable runnable) { - getPlugin().getMinecraftServer().executeSync(runnable); - } - - @NotNull - @Override - default UUID runAsyncRepeating(@NotNull Runnable runnable, long delay) { - final UUID taskId = UUID.randomUUID(); - final CompletableFuture future = new CompletableFuture<>(); - - final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - executor.scheduleAtFixedRate(() -> { - if (future.isCancelled()) { - executor.shutdown(); - return; - } - runnable.run(); - }, 0, delay * 50, TimeUnit.MILLISECONDS); - - getTasks().put(taskId, future); - return taskId; - } - - @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(@NotNull UUID taskId) { - getTasks().computeIfPresent(taskId, (uuid, completableFuture) -> { - completableFuture.cancel(true); - return null; - }); - getTasks().remove(taskId); - } - - @Override - default void cancelAllTasks() { - getTasks().values().forEach(task -> task.cancel(true)); - getTasks().clear(); - } - - @NotNull - @Override - ConcurrentHashMap> getTasks(); - - @Override - @NotNull - FabricHuskHomes getPlugin(); - -} diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/src/main/resources/fabric.mod.json index 03a5728d..cb21c4aa 100644 --- a/fabric/src/main/resources/fabric.mod.json +++ b/fabric/src/main/resources/fabric.mod.json @@ -27,8 +27,8 @@ ] }, "depends": { - "fabricloader": ">=0.14.21", - "minecraft": ">=1.20", + "fabricloader": ">=${fabric_loader_version}", + "minecraft": ">=${fabric_minecraft_version}", "fabric-api": "*" }, "custom": { diff --git a/gradle.properties b/gradle.properties index 26d97fa7..08c6a8ac 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,8 +5,13 @@ org.gradle.daemon=true plugin_version=4.3.3 plugin_archive=huskhomes -plugin_description=The powerful and intuitive set homes, warps, and teleports plugin/mod +plugin_description=The powerful and intuitive homes, warps, and teleports plugin/mod jedis_version=4.4.2 sqlite_driver_version=3.42.0.0 -mysql_driver_version=8.0.33 \ No newline at end of file +mysql_driver_version=8.0.33 + +fabric_minecraft_version=1.20.1 +fabric_loader_version=0.14.21 +fabric_yarn_mappings=1.20.1+build.2 +fabric_api_version=0.83.1+1.20.1 \ No newline at end of file diff --git a/paper/build.gradle b/paper/build.gradle index fc48a48e..3a074a23 100644 --- a/paper/build.gradle +++ b/paper/build.gradle @@ -47,6 +47,6 @@ shadowJar { tasks { runServer { - minecraftVersion('1.20') + minecraftVersion('1.20.1') } } \ No newline at end of file diff --git a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java b/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java index c31c19ae..ae07699f 100644 --- a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java +++ b/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java @@ -48,7 +48,7 @@ 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.SpongeTask; import net.william278.huskhomes.util.UnsafeBlocks; import net.william278.huskhomes.util.Validator; import org.bstats.charts.SimplePie; @@ -80,12 +80,12 @@ import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.nio.file.Path; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.stream.Collectors; @Plugin("huskhomes") -public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafetyResolver, SpongeEventDispatcher, RawPlayDataHandler { +public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSafetyResolver, SpongeEventDispatcher, + RawPlayDataHandler { /** * Metrics ID for HuskHomes on Sponge. @@ -110,7 +110,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet @Inject private Metrics.Factory metricsFactory; - private ConcurrentHashMap tasks; private Set savedUsers; private Settings settings; private Locales locales; @@ -134,7 +133,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet instance = this; // Get plugin version from mod container - this.tasks = new ConcurrentHashMap<>(); this.savedUsers = new HashSet<>(); this.globalPlayerList = new HashMap<>(); this.currentlyOnWarmup = new HashSet<>(); @@ -210,7 +208,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet if (broker != null) { broker.close(); } - cancelAllTasks(); + cancelTasks(); } @Listener @@ -516,12 +514,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet return channel; } - @NotNull - @Override - public ConcurrentHashMap getTasks() { - return tasks; - } - @NotNull @Override public SpongeHuskHomes getPlugin() { diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java b/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java new file mode 100644 index 00000000..80fd13a3 --- /dev/null +++ b/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java @@ -0,0 +1,145 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * 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.HuskHomes; +import net.william278.huskhomes.SpongeHuskHomes; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.api.scheduler.ScheduledTask; +import org.spongepowered.api.util.Ticks; + +import static org.spongepowered.api.scheduler.Task.builder; + +public interface SpongeTask extends Task { + + class Sync extends Task.Sync implements SpongeTask { + + private ScheduledTask task; + + protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin()); + this.task = plugin.getGame().server().scheduler().submit(builder() + .plugin(plugin.getPluginContainer()) + .delay(Ticks.of(delayTicks)) + .execute(runnable) + .build()); + } + } + } + + class Async extends Task.Async implements SpongeTask { + + private ScheduledTask task; + + protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) { + super(plugin, runnable); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin()); + this.task = plugin.getGame().asyncScheduler().submit(builder() + .plugin(plugin.getPluginContainer()) + .execute(runnable) + .build()); + } + } + } + + class Repeating extends Task.Repeating implements SpongeTask { + + private ScheduledTask task; + + protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable, repeatingTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (!cancelled) { + final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin()); + this.task = plugin.getGame().asyncScheduler().submit(builder() + .plugin(plugin.getPluginContainer()) + .interval(Ticks.of(repeatingTicks)) + .execute(runnable) + .build()); + } + } + } + + interface Supplier extends Task.Supplier { + + @NotNull + @Override + default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Sync(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Async getAsyncTask(@NotNull Runnable runnable) { + return new Async(getPlugin(), runnable); + } + + @NotNull + @Override + default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { + return new Repeating(getPlugin(), runnable, repeatingTicks); + } + + @Override + default void cancelTasks() { + // Do nothing + } + + } + +} diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeTaskRunner.java b/sponge/src/main/java/net/william278/huskhomes/util/SpongeTaskRunner.java deleted file mode 100644 index 0dc9c263..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/util/SpongeTaskRunner.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * 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.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -public interface SpongeTaskRunner extends TaskRunner { - - @Override - default void runAsync(@NotNull Runnable runnable) { - getPlugin().getGame().asyncScheduler() - .submit(Task.builder() - .plugin(getPlugin().getPluginContainer()) - .execute(wrap(runnable)) - .build()); - } - - @Override - default CompletableFuture supplyAsync(@NotNull Supplier supplier) { - final CompletableFuture 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()); - } - - @NotNull - @Override - default UUID runAsyncRepeating(@NotNull Runnable runnable, long delay) { - final UUID taskId = UUID.randomUUID(); - final CancellableRunnable task = wrap(runnable); - getTasks().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(@NotNull UUID taskId) { - getTasks().computeIfPresent(taskId, (id, task) -> { - task.cancel(); - return null; - }); - getTasks().remove(taskId); - } - - @Override - default void cancelAllTasks() { - getTasks().values().forEach(CancellableRunnable::cancel); - getTasks().clear(); - } - - @NotNull - private CancellableRunnable wrap(@NotNull Runnable runnable) { - return new CancellableRunnable(runnable); - } - - @NotNull - @Override - ConcurrentHashMap getTasks(); - - @NotNull - @Override - SpongeHuskHomes getPlugin(); - - /** - * A wrapper for a {@link Runnable} that can be canceled - */ - class CancellableRunnable implements Runnable { - private final Runnable runnable; - private boolean cancelled = false; - - CancellableRunnable(@NotNull Runnable runnable) { - this.runnable = runnable; - } - - @Override - public void run() { - if (cancelled) { - return; - } - runnable.run(); - } - - public void cancel() { - cancelled = true; - } - - } -}