diff --git a/AuxProtect_Core/plugin.yml b/AuxProtect_Core/plugin.yml index 3068210..308b396 100644 --- a/AuxProtect_Core/plugin.yml +++ b/AuxProtect_Core/plugin.yml @@ -3,6 +3,7 @@ version: '${project.version}' main: dev.heliosares.auxprotect.spigot.AuxProtectSpigot description: A plugin designed to supplement CoreProtect in a few ways. api-version: 1.13 +folia-supported: true softdepend: [ AuctionHouse, ChestShop, diff --git a/AuxProtect_Core/pom.xml b/AuxProtect_Core/pom.xml index bfded19..f078e74 100644 --- a/AuxProtect_Core/pom.xml +++ b/AuxProtect_Core/pom.xml @@ -51,9 +51,21 @@ org.json:json + io.papermc:paperlib + space.arim.morepaperlib:morepaperlib dev.heliosares:* + + + io.papermc.lib + dev.heliosares.auxprotect.lib.paperlib + + + space.arim.morepaperlib + dev.heliosares.auxprotect.lib.morepaperlib + + true @@ -109,6 +121,11 @@ https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + papermc + https://repo.papermc.io/repository/maven-public/ + + bungeecord-repo @@ -156,6 +173,12 @@ olzie-repo https://repo.olziedev.com/ + + + + arim-mvn-lgpl3 + https://mvn-repo.arim.space/lesser-gpl3/ + @@ -164,12 +187,19 @@ 4.13.2 test - + + + dev.folia + folia-api + 1.20.6-R0.1-SNAPSHOT + provided + net.md-5 bungeecord-api @@ -263,6 +293,18 @@ 1.27.3 provided + + io.papermc + paperlib + 1.0.7 + compile + + + space.arim.morepaperlib + morepaperlib + 0.4.3 + compile + dev.heliosares AuxProtect_1.20 diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/adapters/sender/SpigotSenderAdapter.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/adapters/sender/SpigotSenderAdapter.java index 526989a..c2cc0f1 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/adapters/sender/SpigotSenderAdapter.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/adapters/sender/SpigotSenderAdapter.java @@ -8,16 +8,19 @@ import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import javax.annotation.Nullable; import java.util.UUID; +import static io.papermc.lib.PaperLib.teleportAsync; + public class SpigotSenderAdapter extends SenderAdapter { private final AuxProtectSpigot plugin; private final CommandSender sender; + int tries; public SpigotSenderAdapter(AuxProtectSpigot plugin, CommandSender sender) { this.plugin = plugin; @@ -59,7 +62,11 @@ public class SpigotSenderAdapter extends SenderAdapter { @Override public void executeCommand(String command) { - plugin.runSync(() -> plugin.getServer().dispatchCommand(sender, command)); + if (sender instanceof ConsoleCommandSender) { + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().run(() -> plugin.getServer().dispatchCommand(sender, command)); + } else { + AuxProtectSpigot.getMorePaperLib().scheduling().entitySpecificScheduler((Entity) sender).run(() -> plugin.getServer().dispatchCommand(sender, command), null); + } } @Override @@ -73,21 +80,16 @@ public class SpigotSenderAdapter extends SenderAdapter { if (sender instanceof Player player) { World world = plugin.getServer().getWorld(worldname); final Location target = new Location(world, x, y, z, yaw, pitch); - player.teleport(target); + teleportAsync(player, target); if (player.getGameMode() == GameMode.SPECTATOR) { - new BukkitRunnable() { - int tries; - - @Override - public void run() { - if (tries++ >= 5 || (player.getWorld().equals(target.getWorld()) - && player.getLocation().distance(target) < 2)) { - this.cancel(); - return; - } - player.teleport(target); + AuxProtectSpigot.getMorePaperLib().scheduling().entitySpecificScheduler(player).runAtFixedRate(task -> { + if (tries++ >= 5 || (player.getWorld().equals(target.getWorld()) + && player.getLocation().distance(target) < 2)) { + task.cancel(); + return; } - }.runTaskTimer(plugin, 2, 1); + teleportAsync(player, target); + }, null, 2, 1); } } else { throw new UnsupportedOperationException(); diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/InvCommand.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/InvCommand.java index 9e395d5..b89de61 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/InvCommand.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/InvCommand.java @@ -41,6 +41,7 @@ import org.bukkit.inventory.ItemStack; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Arrays; +import java.util.Date; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -196,7 +197,7 @@ public class InvCommand extends Command { i1++; } - enderpane.onClose((p) -> plugin.getServer().getScheduler().runTaskLater(plugin, () -> player.openInventory(mainInv), 1)); + enderpane.onClose((p) -> AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> player.openInventory(mainInv), 1)); return mainInv; } return null; diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/TpCommand.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/TpCommand.java index 2113bd2..64d57a3 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/TpCommand.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/core/commands/TpCommand.java @@ -9,9 +9,14 @@ import dev.heliosares.auxprotect.exceptions.CommandException; import dev.heliosares.auxprotect.exceptions.NotPlayerException; import dev.heliosares.auxprotect.exceptions.PlatformException; import dev.heliosares.auxprotect.exceptions.SyntaxException; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; import java.util.List; +import static io.papermc.lib.PaperLib.teleportAsync; + public class TpCommand extends Command { public TpCommand(IAuxProtect plugin) { @@ -35,7 +40,7 @@ public class TpCommand extends Command { pitch = Integer.parseInt(args[5]); yaw = Integer.parseInt(args[6]); } - sender.teleport(args[4], x, y, z, pitch, yaw); + teleportAsync((Entity) sender.getSender(), new Location(Bukkit.getWorld(args[4]), x, y, z, pitch, yaw)); } catch (NumberFormatException | NullPointerException e) { throw new SyntaxException(); } catch (UnsupportedOperationException e) { diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java index 37420bf..bec5ef3 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java @@ -4,44 +4,14 @@ import dev.heliosares.auxprotect.adapters.config.SpigotConfigAdapter; import dev.heliosares.auxprotect.adapters.sender.SenderAdapter; import dev.heliosares.auxprotect.adapters.sender.SpigotSenderAdapter; import dev.heliosares.auxprotect.api.AuxProtectAPI; -import dev.heliosares.auxprotect.core.APConfig; -import dev.heliosares.auxprotect.core.APPermission; -import dev.heliosares.auxprotect.core.Activity; -import dev.heliosares.auxprotect.core.ActivityRecord; -import dev.heliosares.auxprotect.core.IAuxProtect; -import dev.heliosares.auxprotect.core.Language; -import dev.heliosares.auxprotect.core.PlatformType; +import dev.heliosares.auxprotect.core.*; import dev.heliosares.auxprotect.core.commands.CSLogsCommand; import dev.heliosares.auxprotect.core.commands.ClaimInvCommand; -import dev.heliosares.auxprotect.database.DatabaseRunnable; -import dev.heliosares.auxprotect.database.DbEntry; -import dev.heliosares.auxprotect.database.EntryAction; -import dev.heliosares.auxprotect.database.SQLManager; -import dev.heliosares.auxprotect.database.Table; -import dev.heliosares.auxprotect.database.XrayEntry; +import dev.heliosares.auxprotect.database.*; import dev.heliosares.auxprotect.exceptions.BusyException; -import dev.heliosares.auxprotect.spigot.listeners.AuctionHouseListener; -import dev.heliosares.auxprotect.spigot.listeners.ChestShopListener; -import dev.heliosares.auxprotect.spigot.listeners.CommandListener; -import dev.heliosares.auxprotect.spigot.listeners.DynamicShopListener; -import dev.heliosares.auxprotect.spigot.listeners.EconomyShopGUIListener; -import dev.heliosares.auxprotect.spigot.listeners.EntityListener; -import dev.heliosares.auxprotect.spigot.listeners.EssentialsListener; -import dev.heliosares.auxprotect.spigot.listeners.InventoryListener; -import dev.heliosares.auxprotect.spigot.listeners.JobsListener; -import dev.heliosares.auxprotect.spigot.listeners.PaneListener; -import dev.heliosares.auxprotect.spigot.listeners.PlayerAuctionsListener; -import dev.heliosares.auxprotect.spigot.listeners.PlayerListener; -import dev.heliosares.auxprotect.spigot.listeners.ProjectileListener; -import dev.heliosares.auxprotect.spigot.listeners.ShopGUIPlusListener; -import dev.heliosares.auxprotect.spigot.listeners.VeinListener; -import dev.heliosares.auxprotect.spigot.listeners.WorldListener; +import dev.heliosares.auxprotect.spigot.listeners.*; import dev.heliosares.auxprotect.towny.TownyListener; -import dev.heliosares.auxprotect.utils.Pane; -import dev.heliosares.auxprotect.utils.PlaybackSolver; -import dev.heliosares.auxprotect.utils.StackUtil; -import dev.heliosares.auxprotect.utils.Telemetry; -import dev.heliosares.auxprotect.utils.UpdateChecker; +import dev.heliosares.auxprotect.utils.*; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -56,23 +26,18 @@ import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; +import space.arim.morepaperlib.MorePaperLib; import javax.annotation.Nullable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; +import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -85,6 +50,7 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { private static final DateTimeFormatter ERROR_TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); private static AuxProtectSpigot instance; private static SQLManager sqlManager; + private static MorePaperLib morePaperLib; private final APConfig config = new APConfig(); private final Set hooks = new HashSet<>(); private final HashMap apPlayers = new HashMap<>(); @@ -98,6 +64,9 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { private APSCommand apcommand; private int SERVER_VERSION; private boolean isShuttingDown; + private boolean activityMonitorRunning; + private boolean inventoryDiffRunning; + private int lastLoggedActivityMinute = -1; private String stackLog = ""; public static IAuxProtect getInstance() { @@ -144,6 +113,7 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { @Override public void onEnable() { AuxProtectAPI.setInstance(instance = this); + morePaperLib = new MorePaperLib(this); this.saveDefaultConfig(); super.reloadConfig(); this.getConfig().options().copyDefaults(true); @@ -220,57 +190,51 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { } veinManager = new VeinManager(); - new BukkitRunnable() { - - @Override - public void run() { + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().run(() -> { + try { + sqlManager.connect(); + if (!config.isSkipRowCount()) sqlManager.count(); + } catch (Exception e) { + print(e); + getLogger().severe("Failed to connect to SQL database. Disabling."); + setEnabled(false); + return; + } + if (EntryAction.VEIN.isEnabled()) { try { - sqlManager.connect(); - if (!config.isSkipRowCount()) sqlManager.count(); + ArrayList veins = sqlManager + .getAllUnratedXrayRecords(System.currentTimeMillis() - (3600000L * 24L * 7L)); + if (veins != null) { + for (DbEntry vein : veins) { + veinManager.add((XrayEntry) vein); + } + } } catch (Exception e) { print(e); - getLogger().severe("Failed to connect to SQL database. Disabling."); - setEnabled(false); return; } - if (EntryAction.VEIN.isEnabled()) { - try { - ArrayList veins = sqlManager - .getAllUnratedXrayRecords(System.currentTimeMillis() - (3600000L * 24L * 7L)); - if (veins != null) { - for (DbEntry vein : veins) { - veinManager.add((XrayEntry) vein); - } - } - } catch (Exception e) { - print(e); - return; - } - } - long lastloaded = 0; - try { - lastloaded = sqlManager.getLast(SQLManager.LastKeys.TELEMETRY); - } catch (SQLException | BusyException ignored) { - } - long delay = 15 * 20; - if (System.currentTimeMillis() - lastloaded > 1000 * 60 * 60) { - debug("Initializing telemetry. THIS MESSAGE WILL DISPLAY REGARDLESS OF WHETHER BSTATS CONFIG IS ENABLED. THIS DOES NOT INHERENTLY MEAN ITS ENABLED", - 3); - } else { - debug("Delaying telemetry initialization to avoid rate-limiting. THIS MESSAGE WILL DISPLAY REGARDLESS OF WHETHER BSTATS CONFIG IS ENABLED. THIS DOES NOT INHERENTLY MEAN ITS ENABLED", - 3); - delay = (1000 * 60 * 60 - (System.currentTimeMillis() - lastloaded)) / 50; - } - - getServer().getScheduler().runTaskLater(AuxProtectSpigot.this, () -> Telemetry.init(AuxProtectSpigot.this, 14232), delay); - } - }.runTaskAsynchronously(this); + long lastloaded = 0; + try { + lastloaded = sqlManager.getLast(SQLManager.LastKeys.TELEMETRY); + } catch (SQLException | BusyException ignored) { + } + long delay = 15 * 20; + if (System.currentTimeMillis() - lastloaded > 1000 * 60 * 60) { + debug("Initializing telemetry. THIS MESSAGE WILL DISPLAY REGARDLESS OF WHETHER BSTATS CONFIG IS ENABLED. THIS DOES NOT INHERENTLY MEAN ITS ENABLED", + 3); + } else { + debug("Delaying telemetry initialization to avoid rate-limiting. THIS MESSAGE WILL DISPLAY REGARDLESS OF WHETHER BSTATS CONFIG IS ENABLED. THIS DOES NOT INHERENTLY MEAN ITS ENABLED", + 3); + delay = (1000 * 60 * 60 - (System.currentTimeMillis() - lastloaded)) / 50; + } + + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> Telemetry.init(AuxProtectSpigot.this, 14232), delay); + }); dbRunnable = new DatabaseRunnable(this, sqlManager); - getServer().getScheduler().runTaskTimerAsynchronously(this, dbRunnable, 60, 5); - + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runAtFixedRate(dbRunnable, Duration.ofSeconds(3), Duration.ofMillis(300)); getServer().getPluginManager().registerEvents(new ProjectileListener(this), this); getServer().getPluginManager().registerEvents(new EntityListener(this), this); getServer().getPluginManager().registerEvents(new InventoryListener(this), this); @@ -314,36 +278,11 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { Objects.requireNonNull(this.getCommand("auxprotect")).setExecutor((apcommand = new APSCommand(this))); Objects.requireNonNull(this.getCommand("auxprotect")).setTabCompleter(apcommand); - new BukkitRunnable() { - - @Override - public void run() { - checkcommand("auxprotect"); - checkcommand(getCommandAlias()); - checkcommand("claiminv"); - } - - private void checkcommand(String commandlbl) { - PluginCommand command = getCommand(commandlbl); - if (command == null || !command.getPlugin().equals(AuxProtectSpigot.this)) { - String output = "Command '" + commandlbl + "' taken by "; - if (command == null) { - output += "an unknown plugin."; - } else { - output += command.getPlugin().getName() + "."; - } - warning(output); - if (config.isOverrideCommands()) { - warning("Attempting to re-register tab completer."); - Objects.requireNonNull(getCommand("auxprotect")).setTabCompleter(apcommand); - Objects.requireNonNull(getCommand(getCommandAlias())).setTabCompleter(apcommand); - } else { - warning("If this is causing issues, try enabling 'OverrideCommands' in the config."); - } - - } - } - }.runTaskLater(this, 60); + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> { + checkcommand("auxprotect"); + checkcommand(getCommandAlias()); + checkcommand("claiminv"); + }, 60L); if (!config.isPrivate()) { EntryAction.ALERT.setEnabled(false); @@ -358,186 +297,191 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { this.getAPPlayer(player); } - new BukkitRunnable() { + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runAtFixedRate(() -> { + if (!isEnabled() || sqlManager == null || !sqlManager.isConnected() || activityMonitorRunning) { + return; + } + activityMonitorRunning = true; + try { + List players; + // Make a new list to not tie up other calls to apPlayers + synchronized (apPlayers) { + players = new ArrayList<>(apPlayers.values()); + } + Calendar calendar = Calendar.getInstance(); + int minute = calendar.get(Calendar.MINUTE); + int second = calendar.get(Calendar.SECOND); - private boolean running; - private int lastLoggedActivityMinute = -1; + boolean logActivity = lastLoggedActivityMinute != minute && second >= 30; + // Put in the middle of the minute to make parsing it later easier + if (logActivity) { + lastLoggedActivityMinute = minute; + } + for (APPlayerSpigot apPlayer : players) { + if (!apPlayer.getPlayer().isOnline()) { + continue; + } - @Override - public void run() { - if (!isEnabled() || sqlManager == null || !sqlManager.isConnected() || running) { + if (config.getInventoryInterval() > 0) { + if (System.currentTimeMillis() - apPlayer.lastLoggedInventory >= config + .getInventoryInterval()) { + apPlayer.logInventory("periodic"); + } + } + + if (config.getMoneyInterval() > 0) { + if (System.currentTimeMillis() - apPlayer.lastLoggedMoney >= config.getMoneyInterval()) { + PlayerListener.logMoney(AuxProtectSpigot.this, apPlayer.getPlayer(), "periodic"); + } + } + + if (config.getPosInterval() > 0) { + if (apPlayer.lastMoved > apPlayer.lastLoggedPos + && System.currentTimeMillis() - apPlayer.lastLoggedPos >= config.getPosInterval()) { + apPlayer.logPos(apPlayer.getPlayer().getLocation()); + } else if (config.doLogIncrementalPosition()) { + apPlayer.tickDiffPos(); + } + } + + if (getSqlManager().getTownyManager() != null) { + getSqlManager().getTownyManager().run(); + } + + if (System.currentTimeMillis() - apPlayer.lastCheckedMovement >= 1000) { + apPlayer.lastCheckedMovement = System.currentTimeMillis(); + apPlayer.move(); + } + + if (logActivity && config.isPrivate()) { + if (Set.of("flat", "void").contains(apPlayer.getPlayer().getWorld().getName()) && config.isPrivate()) { + apPlayer.addActivity(Activity.IN_SPAWN); + } + + add(new DbEntry(AuxProtectSpigot.getLabel(apPlayer.getPlayer()), EntryAction.ACTIVITY, false, apPlayer.getPlayer().getLocation(), "", apPlayer.concludeActivityForMinute())); + + int tallied = 0; + int inactive = 0; + for (ActivityRecord record : apPlayer.getActivityStack()) { + if (record == null || record.activities().isEmpty()) { + continue; + } + tallied++; + if (record.countScore() < 10) { + inactive++; + } + } + if (tallied >= 15 && (double) inactive / (double) tallied > 0.75 + && !APPermission.BYPASS_INACTIVE.hasPermission(apPlayer.getPlayer())) { + if (System.currentTimeMillis() - apPlayer.lastNotifyInactive > 600000L) { + apPlayer.lastNotifyInactive = System.currentTimeMillis(); + String msg = Language.translate(Language.L.INACTIVE_ALERT, apPlayer.getPlayer().getName(), + inactive, tallied); + for (Player player : Bukkit.getOnlinePlayers()) { + if (APPermission.NOTIFY_INACTIVE.hasPermission(player)) { + player.sendMessage(msg); + } + } + info(msg); + add(new DbEntry(AuxProtectSpigot.getLabel(apPlayer.getPlayer()), EntryAction.ALERT, false, + apPlayer.getPlayer().getLocation(), "inactive", inactive + "/" + tallied)); + } + } + } + } + } finally { + activityMonitorRunning = false; + } + }, Duration.ofSeconds(2), Duration.ofMillis(200)); + + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runAtFixedRate(() -> { + if (!isEnabled() || sqlManager == null) return; + + String migrationStatus = sqlManager.getMigrationStatus(); + if (migrationStatus != null) info(migrationStatus); + + if (inventoryDiffRunning || !sqlManager.isConnected()) return; + inventoryDiffRunning = true; + try { + List players; + // Make a new list to not tie up other calls to apPlayers + synchronized (apPlayers) { + players = new ArrayList<>(apPlayers.values()); + } + for (APPlayerSpigot apPlayer : players) { + if (!apPlayer.getPlayer().isOnline()) { + continue; + } + if (config.getInventoryDiffInterval() > 0) { + if (System.currentTimeMillis() - apPlayer.lastLoggedInventoryDiff >= config.getInventoryDiffInterval()) { + apPlayer.tickDiffInventory(); + } + } + } + } finally { + inventoryDiffRunning = false; + } + }, Duration.ofSeconds(2), Duration.ofSeconds(1)); + + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runAtFixedRate(() -> { + if (config.shouldCheckForUpdates() + && System.currentTimeMillis() - lastCheckedForUpdate > 1000 * 60 * 60) { + lastCheckedForUpdate = System.currentTimeMillis(); + debug("Checking for updates...", 1); + String newVersion; + try { + newVersion = UpdateChecker.getVersion(99147); + } catch (IOException e) { + print(e); return; } - running = true; - try { - List players; - // Make a new list to not tie up other calls to apPlayers - synchronized (apPlayers) { - players = new ArrayList<>(apPlayers.values()); - } - Calendar calendar = Calendar.getInstance(); - int minute = calendar.get(Calendar.MINUTE); - int second = calendar.get(Calendar.SECOND); - - boolean logActivity = lastLoggedActivityMinute != minute && second >= 30; - // Put in the middle of the minute to make parsing it later easier - if (logActivity) { - lastLoggedActivityMinute = minute; - } - for (APPlayerSpigot apPlayer : players) { - if (!apPlayer.getPlayer().isOnline()) { - continue; - } - - if (config.getInventoryInterval() > 0) { - if (System.currentTimeMillis() - apPlayer.lastLoggedInventory >= config - .getInventoryInterval()) { - apPlayer.logInventory("periodic"); - } - } - - if (config.getMoneyInterval() > 0) { - if (System.currentTimeMillis() - apPlayer.lastLoggedMoney >= config.getMoneyInterval()) { - PlayerListener.logMoney(AuxProtectSpigot.this, apPlayer.getPlayer(), "periodic"); - } - } - - if (config.getPosInterval() > 0) { - if (apPlayer.lastMoved > apPlayer.lastLoggedPos - && System.currentTimeMillis() - apPlayer.lastLoggedPos >= config.getPosInterval()) { - apPlayer.logPos(apPlayer.getPlayer().getLocation()); - } else if (config.doLogIncrementalPosition()) { - apPlayer.tickDiffPos(); - } - } - - if (getSqlManager().getTownyManager() != null) { - getSqlManager().getTownyManager().run(); - } - - if (System.currentTimeMillis() - apPlayer.lastCheckedMovement >= 1000) { - apPlayer.lastCheckedMovement = System.currentTimeMillis(); - apPlayer.move(); - } - - if (logActivity && config.isPrivate()) { - if (Set.of("flat", "void").contains(apPlayer.getPlayer().getWorld().getName()) && config.isPrivate()) { - apPlayer.addActivity(Activity.IN_SPAWN); - } - - add(new DbEntry(AuxProtectSpigot.getLabel(apPlayer.getPlayer()), EntryAction.ACTIVITY, false, apPlayer.getPlayer().getLocation(), "", apPlayer.concludeActivityForMinute())); - - int tallied = 0; - int inactive = 0; - for (ActivityRecord record : apPlayer.getActivityStack()) { - if (record == null || record.activities().isEmpty()) { - continue; - } - tallied++; - if (record.countScore() < 10) { - inactive++; + debug("New Version: " + newVersion + " Current Version: " + + AuxProtectSpigot.this.getDescription().getVersion(), 1); + if (newVersion != null) { + int compare = UpdateChecker.compareVersions(AuxProtectSpigot.this.getDescription().getVersion(), + newVersion); + if (compare <= 0) { + update = null; + } else { + boolean newUpdate = update == null; + update = newVersion; + if (newUpdate) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (APPermission.ADMIN.hasPermission(player)) { + AuxProtectSpigot.this.tellAboutUpdate(player); } } - if (tallied >= 15 && (double) inactive / (double) tallied > 0.75 - && !APPermission.BYPASS_INACTIVE.hasPermission(apPlayer.getPlayer())) { - if (System.currentTimeMillis() - apPlayer.lastNotifyInactive > 600000L) { - apPlayer.lastNotifyInactive = System.currentTimeMillis(); - String msg = Language.translate(Language.L.INACTIVE_ALERT, apPlayer.getPlayer().getName(), - inactive, tallied); - for (Player player : Bukkit.getOnlinePlayers()) { - if (APPermission.NOTIFY_INACTIVE.hasPermission(player)) { - player.sendMessage(msg); - } - } - info(msg); - add(new DbEntry(AuxProtectSpigot.getLabel(apPlayer.getPlayer()), EntryAction.ALERT, false, - apPlayer.getPlayer().getLocation(), "inactive", inactive + "/" + tallied)); - } - } - } - } - } finally { - running = false; - } - } - }.runTaskTimerAsynchronously(this, 40, 4); - new BukkitRunnable() { - - private boolean running; - - @Override - public void run() { - if (!isEnabled() || sqlManager == null) return; - - String migrationStatus = sqlManager.getMigrationStatus(); - if (migrationStatus != null) info(migrationStatus); - - if (running || !sqlManager.isConnected()) return; - running = true; - try { - List players; - // Make a new list to not tie up other calls to apPlayers - synchronized (apPlayers) { - players = new ArrayList<>(apPlayers.values()); - } - for (APPlayerSpigot apPlayer : players) { - if (!apPlayer.getPlayer().isOnline()) { - continue; - } - if (config.getInventoryDiffInterval() > 0) { - if (System.currentTimeMillis() - apPlayer.lastLoggedInventoryDiff >= config.getInventoryDiffInterval()) { - apPlayer.tickDiffInventory(); - } - } - } - } finally { - running = false; - } - } - }.runTaskTimerAsynchronously(this, 40, 20); - - new BukkitRunnable() { - - @Override - public void run() { - if (config.shouldCheckForUpdates() - && System.currentTimeMillis() - lastCheckedForUpdate > 1000 * 60 * 60) { - lastCheckedForUpdate = System.currentTimeMillis(); - debug("Checking for updates...", 1); - String newVersion; - try { - newVersion = UpdateChecker.getVersion(99147); - } catch (IOException e) { - print(e); - return; - } - debug("New Version: " + newVersion + " Current Version: " - + AuxProtectSpigot.this.getDescription().getVersion(), 1); - if (newVersion != null) { - int compare = UpdateChecker.compareVersions(AuxProtectSpigot.this.getDescription().getVersion(), - newVersion); - if (compare <= 0) { - update = null; - } else { - boolean newUpdate = update == null; - update = newVersion; - if (newUpdate) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (APPermission.ADMIN.hasPermission(player)) { - AuxProtectSpigot.this.tellAboutUpdate(player); - } - } - AuxProtectSpigot.this.tellAboutUpdate(Bukkit.getConsoleSender()); - } + AuxProtectSpigot.this.tellAboutUpdate(Bukkit.getConsoleSender()); } } } } - }.runTaskTimerAsynchronously(this, 20, 10 * 20); + }, Duration.ofSeconds(1), Duration.ofSeconds(10)); dbRunnable.add(new DbEntry("#console", EntryAction.PLUGINLOAD, true, "AuxProtect", "")); } + private void checkcommand(String commandlbl) { + PluginCommand command = getCommand(commandlbl); + if (command == null || !command.getPlugin().equals(AuxProtectSpigot.this)) { + String output = "Command '" + commandlbl + "' taken by "; + if (command == null) { + output += "an unknown plugin."; + } else { + output += command.getPlugin().getName() + "."; + } + warning(output); + if (config.isOverrideCommands()) { + warning("Attempting to re-register tab completer."); + Objects.requireNonNull(getCommand("auxprotect")).setTabCompleter(apcommand); + Objects.requireNonNull(getCommand(getCommandAlias())).setTabCompleter(apcommand); + } else { + warning("If this is causing issues, try enabling 'OverrideCommands' in the config."); + } + + } + } + private boolean hook(Supplier listener, String... names) { boolean hook; try { @@ -720,12 +664,12 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { @Override public void runAsync(Runnable run) { - getServer().getScheduler().runTaskAsynchronously(this, run); + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().run((run)); } @Override public void runSync(Runnable run) { - getServer().getScheduler().runTask(this, run); + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().run((run)); } public int queueSize() { @@ -804,4 +748,8 @@ public final class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { public String getCommandAlias() { return "ap"; } + + public static @NotNull MorePaperLib getMorePaperLib() { + return morePaperLib; + } } diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/EntityListener.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/EntityListener.java index 663ee97..c9594d1 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/EntityListener.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/EntityListener.java @@ -12,30 +12,12 @@ import dev.heliosares.auxprotect.utils.ChartRenderer; import dev.heliosares.auxprotect.utils.InvSerialization; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Item; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.*; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.entity.EntityDismountEvent; -import org.bukkit.event.entity.EntityDropItemEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.EntityMountEvent; -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.bukkit.event.entity.EntityResurrectEvent; -import org.bukkit.event.entity.EntityTameEvent; -import org.bukkit.event.entity.ItemDespawnEvent; -import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.EquipmentSlot; @@ -43,7 +25,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.MapMeta; import org.bukkit.map.MapRenderer; import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; @@ -194,15 +175,11 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void entityDamageEvent(EntityDamageEvent e) { if (e.getEntity() instanceof Item item) { - new BukkitRunnable() { - - @Override - public void run() { - if (e.getEntity().isDead() || !e.getEntity().isValid()) { - itemBreak(plugin, "#" + e.getCause(), item.getItemStack(), item.getLocation()); - } + AuxProtectSpigot.getMorePaperLib().scheduling().entitySpecificScheduler(e.getEntity()).runDelayed(() -> { + if (e.getEntity().isDead() || !e.getEntity().isValid()) { + itemBreak(plugin, "#" + e.getCause(), item.getItemStack(), item.getLocation()); } - }.runTaskLater(plugin, 1); + }, null, 1); } if (e.getEntity().isDead()) { return; diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/PlayerListener.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/PlayerListener.java index 6f3c38b..dc067e8 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/PlayerListener.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/PlayerListener.java @@ -33,34 +33,17 @@ import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityPlaceEvent; import org.bukkit.event.entity.EntityToggleGlideEvent; import org.bukkit.event.entity.PlayerLeashEntityEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerItemConsumeEvent; -import org.bukkit.event.player.PlayerItemDamageEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerUnleashEntityEvent; +import org.bukkit.event.player.*; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionType; -import org.bukkit.scheduler.BukkitRunnable; import java.sql.SQLException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; +import java.time.Duration; +import java.util.*; public class PlayerListener implements Listener { @@ -133,7 +116,7 @@ public class PlayerListener implements Listener { } if (item.getType() == Material.WATER_BUCKET) { if (mobs.contains(e.getRightClicked().getType())) { - plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + AuxProtectSpigot.getMorePaperLib().scheduling().regionSpecificScheduler(e.getRightClicked().getLocation()).runDelayed(() -> { ItemStack newBucket = e.getPlayer().getInventory().getItem(e.getHand()); if (newBucket != null && !buckets.contains(newBucket.getType())) newBucket = null; plugin.add(new SingleItemEntry(AuxProtectSpigot.getLabel(e.getPlayer()), EntryAction.BUCKET, true, @@ -216,7 +199,8 @@ public class PlayerListener implements Listener { String data = ""; if (plugin.getAPConfig().isSessionLogIP()) data = "IP: " + ip; logSession(e.getPlayer(), true, data); - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { + + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().run(() -> { try { plugin.getSqlManager().getUserManager().updateUsernameAndIP(e.getPlayer().getUniqueId(), e.getPlayer().getName(), ip); @@ -227,13 +211,13 @@ public class PlayerListener implements Listener { } }); if (APPermission.LOOKUP.hasPermission(e.getPlayer()) || APPermission.CSLOGS.hasPermission(e.getPlayer()) && EntryAction.SHOP_CS.isEnabled()) { - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, apPlayer::getTimeZone); + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().run(apPlayer::getTimeZone); } } apPlayer.logInventory("join"); - plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, () -> { + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runDelayed(() -> { try { if (plugin.getSqlManager().getUserManager() .getPendingInventory(plugin.getSqlManager().getUserManager() @@ -257,10 +241,10 @@ public class PlayerListener implements Listener { message.append("\n" + ChatColor.COLOR_CHAR + "f").event((ClickEvent) null).event((HoverEvent) null); e.getPlayer().spigot().sendMessage(message.create()); e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.BLOCK_NOTE_BLOCK_PLING, 1, 1); - }, 40); + }, Duration.ofMillis(2000)); if (plugin.update != null && APPermission.ADMIN.hasPermission(e.getPlayer())) { - plugin.getServer().getScheduler().runTaskLater(plugin, () -> plugin.tellAboutUpdate(e.getPlayer()), 20); + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> plugin.tellAboutUpdate(e.getPlayer()), 20); } } @@ -292,24 +276,20 @@ public class PlayerListener implements Listener { } final byte[] inventory = inventory_; - new BukkitRunnable() { - @Override - public void run() { - byte[] newInventory = null; - try { - newInventory = InvSerialization.playerToByteArray(e.getPlayer()); - } catch (Exception e1) { - plugin.warning("Error serializing inventory for teleport"); - plugin.print(e1); - } - if (Arrays.equals(inventory, newInventory)) { - return; - } - apPlayer.logInventory("worldchange", e.getFrom(), inventory); - apPlayer.logInventory("worldchange", e.getTo(), newInventory); + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> { + byte[] newInventory = null; + try { + newInventory = InvSerialization.playerToByteArray(e.getPlayer()); + } catch (Exception e1) { + plugin.warning("Error serializing inventory for teleport"); + plugin.print(e1); } - - }.runTaskLater(plugin, 3); + if (Arrays.equals(inventory, newInventory)) { + return; + } + apPlayer.logInventory("worldchange", e.getFrom(), inventory); + apPlayer.logInventory("worldchange", e.getTo(), newInventory); + }, 3L); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/VeinListener.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/VeinListener.java index e8eddee..1252a6d 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/VeinListener.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/VeinListener.java @@ -11,9 +11,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.scheduler.BukkitRunnable; import javax.annotation.Nullable; +import java.time.Duration; import java.util.ArrayList; import java.util.Iterator; import java.util.Map.Entry; @@ -37,20 +37,17 @@ public class VeinListener implements Listener { this.plugin = plugin; // Maybe overkill, just preventing memory leaks - new BukkitRunnable() { - @Override - public void run() { - synchronized (blockhistory) { - Iterator> it = blockhistory.entrySet().iterator(); - while (it.hasNext()) { - Entry entry = it.next(); - if (entry.getValue().timeSinceUsed() > 300000L) { - it.remove(); - } + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runAtFixedRate(() -> { + synchronized (blockhistory) { + Iterator> it = blockhistory.entrySet().iterator(); + while (it.hasNext()) { + Entry entry = it.next(); + if (entry.getValue().timeSinceUsed() > 300000L) { + it.remove(); } } } - }.runTaskTimerAsynchronously(plugin, 20 * 60 * 5, 20 * 60 * 5); + }, Duration.ofMinutes(5), Duration.ofMinutes(5)); NETHER_CHECK.add(Material.ANCIENT_DEBRIS); @@ -131,12 +128,7 @@ public class VeinListener implements Listener { if (nearbyNonOres < NON_ORE_THRESHOLD) { entry.setRating((short) -2, null); } - new BukkitRunnable() { - @Override - public void run() { - plugin.add(entry); - } - }.runTaskAsynchronously(plugin); + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().run(() -> plugin.add(entry)); } /** diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/WorldListener.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/WorldListener.java index 7308bc8..0236822 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/WorldListener.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/spigot/listeners/WorldListener.java @@ -36,16 +36,15 @@ public class WorldListener implements Listener { DbEntry entry = new SingleItemEntry("#" + e.getCause().toString().toLowerCase(), EntryAction.ITEMFRAME, false, item.getLocation(), item.getItem().getType().toString().toLowerCase(), "", item.getItem()); plugin.add(entry); } - } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void on(RaidTriggerEvent e) { - plugin.getServer().getScheduler().runTaskLater(plugin, () -> plugin.add(new DbEntry(AuxProtectSpigot.getLabel(e.getPlayer()), EntryAction.RAIDTRIGGER, false, e.getPlayer().getLocation(), "", "")), 3); + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> plugin.add(new DbEntry(AuxProtectSpigot.getLabel(e.getPlayer()), EntryAction.RAIDTRIGGER, false, e.getPlayer().getLocation(), "", "")), 3L); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void on(RaidSpawnWaveEvent e) { - plugin.getServer().getScheduler().runTaskLater(plugin, () -> e.getRaiders().forEach(raider -> plugin.add(new DbEntry("#raid", EntryAction.RAIDSPAWN, false, raider.getLocation(), AuxProtectSpigot.getLabel(raider), ""))), 1); + AuxProtectSpigot.getMorePaperLib().scheduling().globalRegionalScheduler().runDelayed(() -> e.getRaiders().forEach(raider -> plugin.add(new DbEntry("#raid", EntryAction.RAIDSPAWN, false, raider.getLocation(), AuxProtectSpigot.getLabel(raider), ""))), 1L); } } diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/towny/TownyManager.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/towny/TownyManager.java index 4f862f6..6a365ef 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/towny/TownyManager.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/towny/TownyManager.java @@ -4,7 +4,6 @@ import com.palmergames.bukkit.towny.TownyUniverse; import com.palmergames.bukkit.towny.object.Government; import com.palmergames.bukkit.towny.object.Nation; import com.palmergames.bukkit.towny.object.Town; -import dev.heliosares.auxprotect.api.AuxProtectAPI; import dev.heliosares.auxprotect.core.Parameters; import dev.heliosares.auxprotect.database.DbEntry; import dev.heliosares.auxprotect.database.EntryAction; @@ -145,7 +144,7 @@ public class TownyManager implements Runnable { names.put(uid, name); }; if (async) { - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, run); + AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().run((run)); } else { run.run(); } diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/MoneySolver.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/MoneySolver.java index 140280a..1bef52c 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/MoneySolver.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/MoneySolver.java @@ -109,14 +109,14 @@ public class MoneySolver extends ChartRenderer { if (!(plugin instanceof AuxProtectSpigot)) { return; } - plugin.runSync(() -> { + AuxProtectSpigot.getMorePaperLib().scheduling().entitySpecificScheduler(player).run(() -> { try { MoneySolver solver = new MoneySolver((AuxProtectSpigot) plugin, player, results, time, users); player.getInventory().addItem(solver.asItem(player)); } catch (IllegalArgumentException e) { player.sendMessage(Language.translate(Language.L.COMMAND__LOOKUP__NORESULTS)); } - }); + }, null); } @Override diff --git a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/PlaybackSolver.java b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/PlaybackSolver.java index 9a65910..4c26dac 100644 --- a/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/PlaybackSolver.java +++ b/AuxProtect_Core/src/main/java/dev/heliosares/auxprotect/utils/PlaybackSolver.java @@ -3,7 +3,6 @@ package dev.heliosares.auxprotect.utils; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import dev.heliosares.auxprotect.adapters.sender.SenderAdapter; -import dev.heliosares.auxprotect.core.APPlayer; import dev.heliosares.auxprotect.core.IAuxProtect; import dev.heliosares.auxprotect.core.Language; import dev.heliosares.auxprotect.core.PlatformType; @@ -19,21 +18,23 @@ import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; import org.json.simple.parser.ParseException; +import space.arim.morepaperlib.scheduling.ScheduledTask; import javax.annotation.Nullable; import java.io.IOException; import java.sql.SQLException; +import java.time.Duration; import java.time.ZoneId; import java.util.*; import java.util.stream.Collectors; -public class PlaybackSolver extends BukkitRunnable { +public class PlaybackSolver implements Runnable { private static final Map instances = new HashMap<>(); private final List points; private final long startTime; private final long realReferenceTime; + private ScheduledTask task; private final Map actors = new HashMap<>(); private final ProtocolManager protocol; @@ -111,7 +112,11 @@ public class PlaybackSolver extends BukkitRunnable { modified.add(action.sendChange(audience, true)); } - runTaskTimer((AuxProtectSpigot) plugin, 1, 1); + this.task = AuxProtectSpigot.getMorePaperLib().scheduling().asyncScheduler().runAtFixedRate( + this, // the Runnable instance + Duration.ofMillis(100), // initial delay + Duration.ofMillis(100) // period + ); timeZone = plugin.getAPPlayer(sender).getTimeZone().toZoneId(); } @@ -190,7 +195,6 @@ public class PlaybackSolver extends BukkitRunnable { audience.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(TimeUtil.format(timeNow, TimeUtil.entryTimeFormat, timeZone) + " " + ChatColor.COLOR_CHAR + "7- " + TimeUtil.millisToString(System.currentTimeMillis() - timeNow) + " ago")); - for (Iterator it = points.iterator(); it.hasNext(); ) { if (closed) return; PosPoint point = it.next(); @@ -228,7 +232,6 @@ public class PlaybackSolver extends BukkitRunnable { } swing.forEach(FakePlayer::swingArm); - for (Iterator it = actors.values().iterator(); it.hasNext(); ) { if (closed) return; FakePlayer pl = it.next(); @@ -242,7 +245,9 @@ public class PlaybackSolver extends BukkitRunnable { public void close() { if (closed) return; - cancel(); + if (task != null && !task.isCancelled()) { + task.cancel(); // Cancel the scheduled task + } closed = true; if (audience.isOnline()) { audience.sendMessage(Language.translate(Language.L.COMMAND__LOOKUP__PLAYBACK__STOPPED));