This commit is contained in:
itqop 2025-11-12 12:12:58 +03:00
parent 6bf526305b
commit eccf850d11
17 changed files with 459 additions and 326 deletions

View File

@ -4,7 +4,9 @@
"Bash(./gradlew tasks:*)", "Bash(./gradlew tasks:*)",
"Bash(./gradlew build:*)", "Bash(./gradlew build:*)",
"Bash(./gradlew compileJava:*)", "Bash(./gradlew compileJava:*)",
"Bash(./gradlew clean build:*)" "Bash(./gradlew clean build:*)",
"Bash(.gradlew clean build)",
"Bash(gradlew.bat clean build)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []

View File

@ -12,6 +12,8 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
import java.time.Duration; import java.time.Duration;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/** /**
* HTTP client for HubGW API integration. * HTTP client for HubGW API integration.
@ -22,9 +24,9 @@ public class HubGWClient {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final Gson GSON = new GsonBuilder().create(); private static final Gson GSON = new GsonBuilder().create();
// Circuit breaker to prevent log spam // Circuit breaker to prevent log spam (thread-safe with atomics)
private volatile long lastErrorLogTime = 0; private final AtomicLong lastErrorLogTime = new AtomicLong(0);
private volatile int consecutiveErrors = 0; private final AtomicInteger consecutiveErrors = new AtomicInteger(0);
private static final long ERROR_LOG_COOLDOWN_MS = 60_000; // 1 minute private static final long ERROR_LOG_COOLDOWN_MS = 60_000; // 1 minute
private static final int ERROR_THRESHOLD = 3; private static final int ERROR_THRESHOLD = 3;
@ -215,52 +217,54 @@ public class HubGWClient {
} }
/** /**
* Log HTTP error with circuit breaker logic. * Log HTTP error with circuit breaker logic (thread-safe).
*/ */
private void logHttpError(String endpoint, int statusCode, String responseBody) { private void logHttpError(String endpoint, int statusCode, String responseBody) {
consecutiveErrors++; int errorCount = consecutiveErrors.incrementAndGet();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (consecutiveErrors == 1 || (now - lastErrorLogTime) > ERROR_LOG_COOLDOWN_MS) { long lastLog = lastErrorLogTime.get();
if (errorCount == 1 || (now - lastLog) > ERROR_LOG_COOLDOWN_MS) {
if (Config.enableDebugLogging) { if (Config.enableDebugLogging) {
LOGGER.warn("API request failed: {} returned {} - Response: {}", endpoint, statusCode, responseBody); LOGGER.warn("API request failed: {} returned {} - Response: {}", endpoint, statusCode, responseBody);
} else { } else {
LOGGER.warn("API request failed: {} returned {}", endpoint, statusCode); LOGGER.warn("API request failed: {} returned {}", endpoint, statusCode);
} }
lastErrorLogTime = now; lastErrorLogTime.set(now);
if (consecutiveErrors > ERROR_THRESHOLD) { if (errorCount > ERROR_THRESHOLD) {
LOGGER.warn("API has failed {} times consecutively. Further errors will be throttled.", consecutiveErrors); LOGGER.warn("API has failed {} times consecutively. Further errors will be throttled.", errorCount);
} }
} }
} }
/** /**
* Log API connection error with circuit breaker logic. * Log API connection error with circuit breaker logic (thread-safe).
*/ */
private void logApiError(String message, Throwable ex) { private void logApiError(String message, Throwable ex) {
consecutiveErrors++; int errorCount = consecutiveErrors.incrementAndGet();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (consecutiveErrors == 1 || (now - lastErrorLogTime) > ERROR_LOG_COOLDOWN_MS) { long lastLog = lastErrorLogTime.get();
LOGGER.warn("{}: {} (consecutive errors: {})", message, ex.getMessage(), consecutiveErrors);
lastErrorLogTime = now;
if (consecutiveErrors > ERROR_THRESHOLD) { if (errorCount == 1 || (now - lastLog) > ERROR_LOG_COOLDOWN_MS) {
LOGGER.warn("API has failed {} times consecutively. Further errors will be throttled.", consecutiveErrors); LOGGER.warn("{}: {} (consecutive errors: {})", message, ex.getMessage(), errorCount);
lastErrorLogTime.set(now);
if (errorCount > ERROR_THRESHOLD) {
LOGGER.warn("API has failed {} times consecutively. Further errors will be throttled.", errorCount);
} }
} }
} }
/** /**
* Reset error counter after successful request. * Reset error counter after successful request (thread-safe).
*/ */
private void resetErrorCounter() { private void resetErrorCounter() {
if (consecutiveErrors > 0) { int previousErrors = consecutiveErrors.getAndSet(0);
if (consecutiveErrors > ERROR_THRESHOLD) { if (previousErrors > ERROR_THRESHOLD) {
LOGGER.info("API connection restored after {} consecutive errors", consecutiveErrors); LOGGER.info("API connection restored after {} consecutive errors", previousErrors);
}
consecutiveErrors = 0;
} }
} }
} }

View File

@ -19,6 +19,8 @@ import org.itqop.HubmcEssentials.util.LocationUtil;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /goto command - Custom teleport command with cooldowns and logging. * /goto command - Custom teleport command with cooldowns and logging.
* *
@ -82,18 +84,25 @@ public class GotoCommand {
String cooldownType = "tp|" + target.getGameProfile().getName(); String cooldownType = "tp|" + target.getGameProfile().getName();
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, cooldownType).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, cooldownType).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, cooldownType, Config.cooldownGoto).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Save current location for /back // NOW perform action - save location and teleport
LocationStorage.saveLocation(player); LocationStorage.saveLocation(player);
// Store from location for teleport history // Store from location for teleport history
@ -101,7 +110,7 @@ public class GotoCommand {
String fromWorld = LocationUtil.getWorldId(player.level()); String fromWorld = LocationUtil.getWorldId(player.level());
// Teleport to target // Teleport to target
boolean success = LocationUtil.teleportPlayer( boolean teleportSuccess = LocationUtil.teleportPlayer(
player, player,
target.serverLevel(), target.serverLevel(),
target.getX(), target.getX(),
@ -111,7 +120,7 @@ public class GotoCommand {
target.getXRot() target.getXRot()
); );
if (success) { if (teleportSuccess) {
MessageUtil.sendSuccess(player, "Телепортация к игроку §6" + target.getGameProfile().getName()); MessageUtil.sendSuccess(player, "Телепортация к игроку §6" + target.getGameProfile().getName());
// Log teleport history // Log teleport history
@ -125,12 +134,10 @@ public class GotoCommand {
target.getGameProfile().getName() target.getGameProfile().getName()
); );
TeleportService.logTeleport(historyRequest); TeleportService.logTeleport(historyRequest);
// Set cooldown
CooldownService.createCooldown(playerUuid, cooldownType, Config.cooldownGoto);
} else { } else {
MessageUtil.sendError(player, "Ошибка телепортации"); MessageUtil.sendError(player, "Ошибка телепортации");
} }
});
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;
@ -227,18 +234,25 @@ public class GotoCommand {
String cooldownType = "tp|coords"; String cooldownType = "tp|coords";
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, cooldownType).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, cooldownType).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, cooldownType, Config.cooldownGoto).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Save current location for /back // NOW perform action - save location and teleport
LocationStorage.saveLocation(player); LocationStorage.saveLocation(player);
// Store from location for teleport history // Store from location for teleport history
@ -246,7 +260,7 @@ public class GotoCommand {
String fromWorld = LocationUtil.getWorldId(player.level()); String fromWorld = LocationUtil.getWorldId(player.level());
// Teleport to coordinates // Teleport to coordinates
boolean success = LocationUtil.teleportPlayer( boolean teleportSuccess = LocationUtil.teleportPlayer(
player, player,
player.serverLevel(), player.serverLevel(),
location.x, location.x,
@ -254,7 +268,7 @@ public class GotoCommand {
location.z location.z
); );
if (success) { if (teleportSuccess) {
MessageUtil.sendSuccess(player, "Телепортация на координаты: " + MessageUtil.sendSuccess(player, "Телепортация на координаты: " +
MessageUtil.formatCoords(location.x, location.y, location.z)); MessageUtil.formatCoords(location.x, location.y, location.z));
@ -269,12 +283,10 @@ public class GotoCommand {
MessageUtil.formatCoords(location.x, location.y, location.z) MessageUtil.formatCoords(location.x, location.y, location.z)
); );
TeleportService.logTeleport(historyRequest); TeleportService.logTeleport(historyRequest);
// Set cooldown
CooldownService.createCooldown(playerUuid, cooldownType, Config.cooldownGoto);
} else { } else {
MessageUtil.sendError(player, "Ошибка телепортации"); MessageUtil.sendError(player, "Ошибка телепортации");
} }
});
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -20,6 +20,7 @@ import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/** /**
* /pot command - Apply potion effects to player. * /pot command - Apply potion effects to player.
@ -82,18 +83,25 @@ public class PotCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownPot).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Apply effect // NOW perform action - apply effect
MobEffect effect = effectHolder.get().value(); MobEffect effect = effectHolder.get().value();
int durationTicks = durationSeconds * 20; // Convert seconds to ticks int durationTicks = durationSeconds * 20; // Convert seconds to ticks
MobEffectInstance effectInstance = new MobEffectInstance( MobEffectInstance effectInstance = new MobEffectInstance(
@ -111,9 +119,7 @@ public class PotCommand {
String effectDisplayName = effect.getDisplayName().getString(); String effectDisplayName = effect.getDisplayName().getString();
MessageUtil.sendSuccess(player, "Эффект применен: §6" + effectDisplayName + MessageUtil.sendSuccess(player, "Эффект применен: §6" + effectDisplayName +
"§a (Уровень " + (amplifier + 1) + ", " + durationSeconds + " сек.)"); "§a (Уровень " + (amplifier + 1) + ", " + durationSeconds + " сек.)");
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownPot);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -13,6 +13,8 @@ import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* Time control commands - Set world time. * Time control commands - Set world time.
* Commands: /day, /night, /morning, /evening * Commands: /day, /night, /morning, /evening
@ -66,27 +68,32 @@ public class TimeCommand {
String cooldownType = "time|" + timeType; String cooldownType = "time|" + timeType;
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, cooldownType).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, cooldownType).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, cooldownType, Config.cooldownTime).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Set world time // NOW perform action - set world time
ServerLevel level = player.serverLevel(); ServerLevel level = player.serverLevel();
level.setDayTime(timeValue); level.setDayTime(timeValue);
// Send success message // Send success message
String timeDisplayName = getTimeDisplayName(timeType); String timeDisplayName = getTimeDisplayName(timeType);
MessageUtil.sendSuccess(player, "Время установлено: §6" + timeDisplayName); MessageUtil.sendSuccess(player, "Время установлено: §6" + timeDisplayName);
});
// Set cooldown
CooldownService.createCooldown(playerUuid, cooldownType, Config.cooldownTime);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -17,6 +17,8 @@ import org.itqop.HubmcEssentials.util.LocationUtil;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /top command - Teleport to the highest block above player. * /top command - Teleport to the highest block above player.
* Permission: hubmc.cmd.top * Permission: hubmc.cmd.top
@ -48,17 +50,25 @@ public class TopCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownTop).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// NOW perform action - find highest block and teleport
MessageUtil.sendInfo(player, "Поиск самого высокого блока..."); MessageUtil.sendInfo(player, "Поиск самого высокого блока...");
// Find highest block // Find highest block
@ -75,7 +85,7 @@ public class TopCommand {
LocationStorage.saveLocation(player); LocationStorage.saveLocation(player);
// Teleport player // Teleport player
boolean success = LocationUtil.teleportPlayer( boolean teleportSuccess = LocationUtil.teleportPlayer(
player, player,
level, level,
currentPos.getX() + 0.5, currentPos.getX() + 0.5,
@ -83,15 +93,13 @@ public class TopCommand {
currentPos.getZ() + 0.5 currentPos.getZ() + 0.5
); );
if (success) { if (teleportSuccess) {
MessageUtil.sendSuccess(player, "Телепортация на самый высокий блок: " + MessageUtil.sendSuccess(player, "Телепортация на самый высокий блок: " +
MessageUtil.formatCoords(currentPos.getX(), highestY + 1, currentPos.getZ())); MessageUtil.formatCoords(currentPos.getX(), highestY + 1, currentPos.getZ()));
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownTop);
} else { } else {
MessageUtil.sendError(player, "Ошибка телепортации"); MessageUtil.sendError(player, "Ошибка телепортации");
} }
});
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -8,6 +8,8 @@ import net.minecraft.server.level.ServerPlayer;
import org.itqop.HubmcEssentials.Config; import org.itqop.HubmcEssentials.Config;
import org.itqop.HubmcEssentials.api.dto.cooldown.CooldownCheckResponse; import org.itqop.HubmcEssentials.api.dto.cooldown.CooldownCheckResponse;
import org.itqop.HubmcEssentials.api.service.CooldownService; import org.itqop.HubmcEssentials.api.service.CooldownService;
import java.util.concurrent.CompletableFuture;
import org.itqop.HubmcEssentials.permission.PermissionManager; import org.itqop.HubmcEssentials.permission.PermissionManager;
import org.itqop.HubmcEssentials.permission.PermissionNodes; import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
@ -24,7 +26,7 @@ public class ClearCommand {
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) { public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
dispatcher.register(Commands.literal("clear") dispatcher.register(Commands.literal("clear")
.requires(source -> source.isPlayer()) .requires(CommandSourceStack::isPlayer)
.executes(ClearCommand::execute)); .executes(ClearCommand::execute));
} }
@ -43,23 +45,29 @@ public class ClearCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST to prevent race condition
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownClear)
.thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Clear inventory // NOW perform action (cooldown already set)
player.getInventory().clearContent(); player.getInventory().clearContent();
MessageUtil.sendSuccess(player, "Инвентарь очищен"); MessageUtil.sendSuccess(player, "Инвентарь очищен");
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownClear);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -16,6 +16,8 @@ import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /ec command - Open player's ender chest. * /ec command - Open player's ender chest.
* Permission: hubmc.cmd.ec * Permission: hubmc.cmd.ec
@ -46,25 +48,30 @@ public class EcCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownEc).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Open ender chest // NOW perform action - open ender chest
player.openMenu(new SimpleMenuProvider( player.openMenu(new SimpleMenuProvider(
(id, playerInventory, p) -> ChestMenu.threeRows(id, playerInventory, player.getEnderChestInventory()), (id, playerInventory, p) -> ChestMenu.threeRows(id, playerInventory, player.getEnderChestInventory()),
Component.literal("Эндер-сундук") Component.literal("Эндер-сундук")
)); ));
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownEc);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -15,6 +15,8 @@ import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /hat command - Wear held item as a hat. * /hat command - Wear held item as a hat.
* Permission: hubmc.cmd.hat * Permission: hubmc.cmd.hat
@ -52,18 +54,25 @@ public class HatCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownHat).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Get current helmet // NOW perform action - swap hand item with helmet
ItemStack currentHelmet = player.getItemBySlot(EquipmentSlot.HEAD); ItemStack currentHelmet = player.getItemBySlot(EquipmentSlot.HEAD);
// Swap hand item with helmet // Swap hand item with helmet
@ -71,9 +80,7 @@ public class HatCommand {
player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, currentHelmet); player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, currentHelmet);
MessageUtil.sendSuccess(player, "Предмет надет на голову"); MessageUtil.sendSuccess(player, "Предмет надет на голову");
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownHat);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -13,6 +13,8 @@ import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /repair all command - Repair all items in inventory and armor. * /repair all command - Repair all items in inventory and armor.
* Permission: hubmc.cmd.repair.all * Permission: hubmc.cmd.repair.all
@ -46,18 +48,25 @@ public class RepairAllCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownRepairAll).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Repair all items // NOW perform action - repair all items
int repairedCount = 0; int repairedCount = 0;
// Repair inventory items // Repair inventory items
@ -83,9 +92,7 @@ public class RepairAllCommand {
} }
MessageUtil.sendSuccess(player, "Отремонтировано предметов: " + repairedCount); MessageUtil.sendSuccess(player, "Отремонтировано предметов: " + repairedCount);
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownRepairAll);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -18,6 +18,8 @@ import org.itqop.HubmcEssentials.util.LocationUtil;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /back command - Teleport to last location. * /back command - Teleport to last location.
* Permission: hubmc.cmd.back * Permission: hubmc.cmd.back
@ -55,18 +57,25 @@ public class BackCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownBack).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Get last location // NOW perform action - get last location and teleport
LocationStorage.LastLocation lastLoc = LocationStorage.getLastLocation(player); LocationStorage.LastLocation lastLoc = LocationStorage.getLastLocation(player);
if (lastLoc == null) { if (lastLoc == null) {
MessageUtil.sendError(player, "Нет сохраненной позиции для возврата"); MessageUtil.sendError(player, "Нет сохраненной позиции для возврата");
@ -95,7 +104,7 @@ public class BackCommand {
LocationStorage.saveLocation(player); LocationStorage.saveLocation(player);
// Teleport player // Teleport player
boolean success = LocationUtil.teleportPlayer( boolean teleportSuccess = LocationUtil.teleportPlayer(
player, player,
targetLevel, targetLevel,
lastLoc.getX(), lastLoc.getX(),
@ -105,14 +114,12 @@ public class BackCommand {
lastLoc.getPitch() lastLoc.getPitch()
); );
if (success) { if (teleportSuccess) {
MessageUtil.sendSuccess(player, "Телепортация на последнюю позицию"); MessageUtil.sendSuccess(player, "Телепортация на последнюю позицию");
} else { } else {
MessageUtil.sendError(player, "Ошибка телепортации"); MessageUtil.sendError(player, "Ошибка телепортации");
} }
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownBack);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -7,6 +7,8 @@ import net.minecraft.commands.Commands;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import org.itqop.HubmcEssentials.Config; import org.itqop.HubmcEssentials.Config;
import org.itqop.HubmcEssentials.api.service.CooldownService; import org.itqop.HubmcEssentials.api.service.CooldownService;
import java.util.concurrent.CompletableFuture;
import org.itqop.HubmcEssentials.permission.PermissionManager; import org.itqop.HubmcEssentials.permission.PermissionManager;
import org.itqop.HubmcEssentials.permission.PermissionNodes; import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
@ -43,25 +45,31 @@ public class FeedCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST to prevent race condition
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownFeed)
.thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Feed player // NOW perform action (cooldown already set)
player.getFoodData().setFoodLevel(20); player.getFoodData().setFoodLevel(20);
player.getFoodData().setSaturation(20.0f); player.getFoodData().setSaturation(20.0f);
MessageUtil.sendSuccess(player, "Вы сыты"); MessageUtil.sendSuccess(player, "Вы сыты");
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownFeed);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -6,6 +6,8 @@ import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands; import net.minecraft.commands.Commands;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import org.itqop.HubmcEssentials.Config; import org.itqop.HubmcEssentials.Config;
import java.util.concurrent.CompletableFuture;
import org.itqop.HubmcEssentials.api.service.CooldownService; import org.itqop.HubmcEssentials.api.service.CooldownService;
import org.itqop.HubmcEssentials.permission.PermissionManager; import org.itqop.HubmcEssentials.permission.PermissionManager;
import org.itqop.HubmcEssentials.permission.PermissionNodes; import org.itqop.HubmcEssentials.permission.PermissionNodes;
@ -43,18 +45,26 @@ public class HealCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST to prevent race condition
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownHeal)
.thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Heal player // NOW perform action (cooldown already set)
player.setHealth(player.getMaxHealth()); player.setHealth(player.getMaxHealth());
player.getFoodData().setFoodLevel(20); player.getFoodData().setFoodLevel(20);
player.getFoodData().setSaturation(20.0f); player.getFoodData().setSaturation(20.0f);
@ -63,9 +73,7 @@ public class HealCommand {
player.removeAllEffects(); player.removeAllEffects();
MessageUtil.sendSuccess(player, "Вы полностью исцелены"); MessageUtil.sendSuccess(player, "Вы полностью исцелены");
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownHeal);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -14,6 +14,7 @@ import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture;
/** /**
* /near [radius] command - Show nearby players. * /near [radius] command - Show nearby players.
@ -52,18 +53,25 @@ public class NearCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownNear).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Find nearby players // NOW perform action - find nearby players
List<ServerPlayer> nearbyPlayers = PlayerUtil.getPlayersNear(player, radius); List<ServerPlayer> nearbyPlayers = PlayerUtil.getPlayersNear(player, radius);
if (nearbyPlayers.isEmpty()) { if (nearbyPlayers.isEmpty()) {
@ -77,9 +85,7 @@ public class NearCommand {
MessageUtil.sendInfo(player, " §7- §f" + nearby.getName().getString() + " §7(" + distanceStr + ")"); MessageUtil.sendInfo(player, " §7- §f" + nearby.getName().getString() + " §7(" + distanceStr + ")");
} }
} }
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownNear);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -13,6 +13,8 @@ import org.itqop.HubmcEssentials.permission.PermissionNodes;
import org.itqop.HubmcEssentials.util.MessageUtil; import org.itqop.HubmcEssentials.util.MessageUtil;
import org.itqop.HubmcEssentials.util.PlayerUtil; import org.itqop.HubmcEssentials.util.PlayerUtil;
import java.util.concurrent.CompletableFuture;
/** /**
* /repair command - Repair item in hand. * /repair command - Repair item in hand.
* Permission: hubmc.cmd.repair * Permission: hubmc.cmd.repair
@ -63,24 +65,28 @@ public class RepairCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return CompletableFuture.completedFuture(null);
}
// Set cooldown FIRST
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownRepair).thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return;
} }
// Repair item // NOW perform action - repair item
handItem.setDamageValue(0); handItem.setDamageValue(0);
MessageUtil.sendSuccess(player, "Предмет отремонтирован"); MessageUtil.sendSuccess(player, "Предмет отремонтирован");
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownRepair);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -7,6 +7,8 @@ import net.minecraft.commands.Commands;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import org.itqop.HubmcEssentials.Config; import org.itqop.HubmcEssentials.Config;
import java.util.concurrent.CompletableFuture;
import org.itqop.HubmcEssentials.api.service.CooldownService; import org.itqop.HubmcEssentials.api.service.CooldownService;
import org.itqop.HubmcEssentials.permission.PermissionManager; import org.itqop.HubmcEssentials.permission.PermissionManager;
import org.itqop.HubmcEssentials.permission.PermissionNodes; import org.itqop.HubmcEssentials.permission.PermissionNodes;
@ -53,35 +55,44 @@ public class RtpCommand {
String playerUuid = PlayerUtil.getUUIDString(player); String playerUuid = PlayerUtil.getUUIDString(player);
// Check cooldown // Check cooldown
CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenAccept(cooldownResponse -> { CooldownService.checkCooldown(playerUuid, COOLDOWN_TYPE).thenCompose(cooldownResponse -> {
if (cooldownResponse == null) { if (cooldownResponse == null) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return; return CompletableFuture.completedFuture(null);
} }
if (cooldownResponse.isActive()) { if (cooldownResponse.isActive()) {
MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds()); MessageUtil.sendCooldownMessage(player, cooldownResponse.getRemainingSeconds());
return; return CompletableFuture.completedFuture(null);
} }
MessageUtil.sendInfo(player, "Поиск безопасной локации..."); MessageUtil.sendInfo(player, "Поиск безопасной локации...");
// Find random safe location // Find random safe location (synchronous, fast operation)
ServerLevel level = player.serverLevel(); ServerLevel level = player.serverLevel();
Optional<RandomLocation> randomLoc = findSafeRandomLocation(level); Optional<RandomLocation> randomLoc = findSafeRandomLocation(level);
if (randomLoc.isEmpty()) { if (randomLoc.isEmpty()) {
MessageUtil.sendError(player, "Не удалось найти безопасную локацию"); MessageUtil.sendError(player, "Не удалось найти безопасную локацию");
return; return CompletableFuture.completedFuture(null);
} }
RandomLocation loc = randomLoc.get(); RandomLocation loc = randomLoc.get();
// Set cooldown FIRST to prevent race condition (only if location found)
return CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownRtp)
.thenAccept(success -> {
if (!success) {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return;
}
// NOW perform teleport (cooldown already set)
// Save current location for /back // Save current location for /back
LocationStorage.saveLocation(player); LocationStorage.saveLocation(player);
// Teleport player // Teleport player
boolean success = LocationUtil.teleportPlayer( boolean tpSuccess = LocationUtil.teleportPlayer(
player, player,
level, level,
loc.x, loc.x,
@ -89,15 +100,13 @@ public class RtpCommand {
loc.z loc.z
); );
if (success) { if (tpSuccess) {
MessageUtil.sendSuccess(player, "Телепортация на случайную локацию: " + MessageUtil.sendSuccess(player, "Телепортация на случайную локацию: " +
MessageUtil.formatCoords(loc.x, loc.y, loc.z)); MessageUtil.formatCoords(loc.x, loc.y, loc.z));
} else { } else {
MessageUtil.sendError(player, "Ошибка телепортации"); MessageUtil.sendError(player, "Ошибка телепортации");
} }
});
// Set cooldown
CooldownService.createCooldown(playerUuid, COOLDOWN_TYPE, Config.cooldownRtp);
}).exceptionally(ex -> { }).exceptionally(ex -> {
MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE); MessageUtil.sendError(player, MessageUtil.API_UNAVAILABLE);
return null; return null;

View File

@ -155,6 +155,27 @@ public final class LocationUtil {
if (feet.is(Blocks.FIRE) || head.is(Blocks.FIRE)) { if (feet.is(Blocks.FIRE) || head.is(Blocks.FIRE)) {
return false; return false;
} }
if (ground.is(Blocks.MAGMA_BLOCK)) {
return false;
}
if (ground.is(Blocks.CAMPFIRE) || ground.is(Blocks.SOUL_CAMPFIRE)) {
return false;
}
if (feet.is(Blocks.CACTUS) || head.is(Blocks.CACTUS) || ground.is(Blocks.CACTUS)) {
return false;
}
if (feet.is(Blocks.SWEET_BERRY_BUSH) || ground.is(Blocks.SWEET_BERRY_BUSH)) {
return false;
}
if (feet.is(Blocks.WITHER_ROSE)) {
return false;
}
if (feet.is(Blocks.POWDER_SNOW) || head.is(Blocks.POWDER_SNOW)) {
return false;
}
if (feet.is(Blocks.POINTED_DRIPSTONE) || head.is(Blocks.POINTED_DRIPSTONE)) {
return false;
}
return true; return true;
} }