New task system & improve DB case-insensitive SELECTs, support fabric 1.20.1 (#433)

This commit is contained in:
William authored and GitHub committed 2023-06-16 12:19:31 +01:00
1 parent d4b37e3677
commit fb052340c0
27 files changed
+687 -505

No files matched your search

@@ -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;
@@ -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()) {
@@ -433,15 +433,17 @@ public class SqLiteDatabase extends Database {
public Optional<Home> 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<Warp> 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()) {
@@ -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)
@@ -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<UUID> 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
* <p>
@@ -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(
@@ -0,0 +1,135 @@
/*
* 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.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 <T> CompletableFuture<T> supplyAsync(@NotNull java.util.function.Supplier<T> supplier) {
final CompletableFuture<T> 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();
}
@@ -1,52 +0,0 @@
/*
* 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.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);
<T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> 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<UUID, ?> getTasks();
@NotNull
HuskHomes getPlugin();
}