mirror of
https://github.com/RonanPlugins/BetterRTP.git
synced 2026-11-29 09:14:04 +00:00
Online editor (#267)
* web editor * editor command help * editor sync cmd * removed same user restriction * removed player executed restriction * no server identifier sent to server * editor url updated * config harsher verification + send world names to editor api * no more session controls * addons editor commands * moved rtp to /betterrtp-core to create a better env for maven compiling * bettersync lib * Own core and addon editor schemas with BetterSync validation * Simplify editor metadata and publish core and addon schemas on release * Release core and addons together using their Maven versions * Exclude unavailable ProtocolLib executor snapshot from Addons build * betterrtp compiling * log upload commands fixed - upload to mclo.gs website * Fix deferred player lookups retaining disconnected sessions (#265) * Fix RTP operation retention on cancellation and failure (#266)
This commit is contained in:
1 parent
c8c5a04a59
commit
a9e821497c
35 files changed
+941
-287
No files matched your search
@@ -7,7 +7,7 @@
|
||||
<groupId>me.SuperRonanCraft</groupId>
|
||||
<artifactId>BetterRTP</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>3.6.13</version>
|
||||
<version>3.6.15</version>
|
||||
|
||||
<!-- Upload patches to https://repo.ronanplugins.com/#/ -->
|
||||
|
||||
@@ -212,6 +212,9 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Download the tagged GitHub library through JitPack; bundled by Shade. -->
|
||||
<dependency>
|
||||
<groupId>com.github.RonanPlugins</groupId>
|
||||
|
||||
@@ -76,6 +76,8 @@ public class BetterRTP extends JavaPlugin {
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
RTP.getOperations().clear();
|
||||
playerDataManager.clear();
|
||||
if (editorBridge != null) editorBridge.close();
|
||||
invs.closeAll();
|
||||
queue.unload();
|
||||
@@ -110,8 +112,11 @@ public class BetterRTP extends JavaPlugin {
|
||||
|
||||
//(Re)Load all plugin systems/files/cache
|
||||
private void loadAll() {
|
||||
RTP.getOperations().clear();
|
||||
foliaHandler.load();
|
||||
playerDataManager.clear();
|
||||
for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
|
||||
playerDataManager.startSession(player);
|
||||
files.loadAll();
|
||||
settings.load();
|
||||
cooldowns.load();
|
||||
|
||||
@@ -16,7 +16,7 @@ public class PlayerInfo {
|
||||
@Getter private final HashMap<Player, World> invWorld = new HashMap<>();
|
||||
@Getter private final HashMap<Player, RTP_INV_SETTINGS> invNextInv = new HashMap<>();
|
||||
//private final HashMap<Player, CooldownData> cooldown = new HashMap<>();
|
||||
@Getter private final HashMap<Player, Boolean> rtping = new HashMap<>();
|
||||
|
||||
//private final HashMap<Player, List<Location>> previousLocations = new HashMap<>();
|
||||
//private final HashMap<Player, RTP_TYPE> rtpType = new HashMap<>();
|
||||
|
||||
@@ -48,14 +48,14 @@ public class PlayerInfo {
|
||||
invWorld.clear();
|
||||
invNextInv.clear();
|
||||
//cooldown.clear();
|
||||
rtping.clear();
|
||||
|
||||
//previousLocations.clear();
|
||||
}
|
||||
|
||||
private void unload(Player p) {
|
||||
clearInvs(p);
|
||||
//cooldown.remove(p);
|
||||
rtping.remove(p);
|
||||
|
||||
//previousLocations.remove(p);
|
||||
}
|
||||
|
||||
|
||||
+6
-14
@@ -13,9 +13,6 @@ import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import me.SuperRonanCraft.BetterRTP.BetterRTP;
|
||||
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommand;
|
||||
@@ -147,27 +144,22 @@ public class CmdInfo implements RTPCommand, RTPCommandHelpable {
|
||||
if (!upload) {
|
||||
sendi.sendMessage(list.toArray(new String[0]));
|
||||
if (sendi instanceof Player) {
|
||||
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &flogs.ronanplugins.com"));
|
||||
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &fmclo.gs"));
|
||||
component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd + " _UPLOAD_"));
|
||||
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Message.color("&6Suggested command&f: &7" + "/betterrtp " + String.join(" ", args) + " _UPLOAD_")).create()));
|
||||
((Player) sendi).spigot().sendMessage(component);
|
||||
} else {
|
||||
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://logs.ronanplugins.com");
|
||||
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://mclo.gs");
|
||||
}
|
||||
} else {
|
||||
list.add(0, "Command: " + cmd);
|
||||
list.forEach(str -> list.set(list.indexOf(str), ChatColor.stripColor(str)));
|
||||
CompletableFuture.runAsync(() -> {
|
||||
String key = LogUploader.post(list);
|
||||
if (key == null) {
|
||||
Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cAn error occured attempting to upload log!")), null);
|
||||
String url = LogUploader.post(list);
|
||||
if (url == null) {
|
||||
Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cCould not upload the log. Check your connection and ensure the log is under 5 MiB, then try again.")), null);
|
||||
} else {
|
||||
try {
|
||||
JSONObject json = (JSONObject) new JSONParser().parse(key);
|
||||
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6https://logs.ronanplugins.com/" + json.get("key")), null);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6" + url), null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+6
-14
@@ -13,9 +13,6 @@ import net.md_5.bungee.api.chat.TextComponent;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -36,25 +33,20 @@ public class CmdLogger implements RTPCommand {
|
||||
String cmd = "/" + label + " " + String.join(" ", args);
|
||||
if (!upload) {
|
||||
if (sendi instanceof Player) {
|
||||
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload log to &flogs.ronanplugins.com"));
|
||||
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload log to &fmclo.gs"));
|
||||
component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd + " _UPLOAD_"));
|
||||
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Message.color("&6Suggested command&f: &7" + "/betterrtp " + String.join(" ", args) + " _UPLOAD_")).create()));
|
||||
((Player) sendi).spigot().sendMessage(component);
|
||||
} else {
|
||||
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload log to https://logs.ronanplugins.com");
|
||||
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload log to https://mclo.gs");
|
||||
}
|
||||
} else {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
String key = LogUploader.post(BetterRTP.getInstance().getRtpLogger().getFile());
|
||||
if (key == null) {
|
||||
Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cAn error occured attempting to upload log!")), null);
|
||||
String url = LogUploader.post(BetterRTP.getInstance().getRtpLogger().getFile());
|
||||
if (url == null) {
|
||||
Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cCould not upload the log. Check your connection and ensure the log is under 5 MiB, then try again.")), null);
|
||||
} else {
|
||||
try {
|
||||
JSONObject json = (JSONObject) new JSONParser().parse(key);
|
||||
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6https://logs.ronanplugins.com/" + json.get("key")), null);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6" + url), null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+6
-14
@@ -22,9 +22,6 @@ import org.bukkit.World;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -59,27 +56,22 @@ public class CmdQueue implements RTPCommand {
|
||||
if (!upload) {
|
||||
sendi.sendMessage(list.toArray(new String[0]));
|
||||
if (sendi instanceof Player) {
|
||||
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &flogs.ronanplugins.com"));
|
||||
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &fmclo.gs"));
|
||||
component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd + " _UPLOAD_"));
|
||||
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Message.color("&6Suggested command&f: &7" + "/betterrtp " + String.join(" ", args) + " _UPLOAD_")).create()));
|
||||
((Player) sendi).spigot().sendMessage(component);
|
||||
} else {
|
||||
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://logs.ronanplugins.com");
|
||||
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://mclo.gs");
|
||||
}
|
||||
} else {
|
||||
list.add(0, "Command: " + cmd);
|
||||
list.forEach(str -> list.set(list.indexOf(str), ChatColor.stripColor(str)));
|
||||
CompletableFuture.runAsync(() -> {
|
||||
String key = LogUploader.post(list);
|
||||
if (key == null) {
|
||||
Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cAn error occured attempting to upload log!")), null);
|
||||
String url = LogUploader.post(list);
|
||||
if (url == null) {
|
||||
Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cCould not upload the log. Check your connection and ensure the log is under 5 MiB, then try again.")), null);
|
||||
} else {
|
||||
try {
|
||||
JSONObject json = (JSONObject) new JSONParser().parse(key);
|
||||
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6https://logs.ronanplugins.com/" + json.get("key")), null);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6" + url), null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ public class Click {
|
||||
try {
|
||||
Player p = (Player) e.getWhoClicked();
|
||||
PlayerData data = HelperPlayer.getData(p);
|
||||
if (data == null) return;
|
||||
RTPInventories menu = BetterRTP.getInstance().getInvs();
|
||||
menu.getInv(data.getMenu().getInvType()).clickEvent(e);
|
||||
} catch (NullPointerException ex) {
|
||||
@@ -38,6 +39,7 @@ public class Click {
|
||||
else if (e.getWhoClicked() instanceof Player) {
|
||||
// Clicks the inventory
|
||||
PlayerData data = HelperPlayer.getData((Player) e.getWhoClicked());
|
||||
if (data == null) return false;
|
||||
if (!e.getInventory().equals(data.getMenu().getInv()))
|
||||
return false;
|
||||
// Clicks their own inventory
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package me.SuperRonanCraft.BetterRTP.player.events;
|
||||
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
@@ -11,7 +12,8 @@ public class Damage {
|
||||
}
|
||||
|
||||
static boolean isInInvincibleMode(Player player) {
|
||||
return HelperPlayer.getData(player).getInvincibleEndTime() > System.currentTimeMillis();
|
||||
PlayerData data = HelperPlayer.getData(player);
|
||||
return data != null && data.getInvincibleEndTime() > System.currentTimeMillis();
|
||||
}
|
||||
|
||||
static void onEntityDamage(EntityDamageEvent event) {
|
||||
|
||||
@@ -8,7 +8,6 @@ import me.SuperRonanCraft.BetterRTP.references.messages.Message_RTP;
|
||||
import me.SuperRonanCraft.BetterRTP.references.messages.MessagesCore;
|
||||
import me.SuperRonanCraft.BetterRTP.references.web.Updater;
|
||||
import me.SuperRonanCraft.BetterRTP.references.helpers.HelperRTP;
|
||||
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
@@ -19,8 +18,9 @@ public class Join {
|
||||
|
||||
static void event(PlayerJoinEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
getPl().getPlayerDataManager().startSession(p);
|
||||
updater(p);
|
||||
AsyncHandler.async(() -> getPl().getCooldowns().loadPlayer(p));
|
||||
getPl().getCooldowns().loadPlayer(p);
|
||||
rtpOnFirstJoin(p);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package me.SuperRonanCraft.BetterRTP.player.events;
|
||||
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
|
||||
import me.SuperRonanCraft.BetterRTP.BetterRTP;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
@@ -8,6 +9,10 @@ class Leave {
|
||||
|
||||
static void event(PlayerQuitEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
HelperPlayer.unload(p);
|
||||
try {
|
||||
BetterRTP.getInstance().getRTP().getOperations().cancel(p.getUniqueId(), p);
|
||||
} finally {
|
||||
HelperPlayer.unload(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import me.SuperRonanCraft.BetterRTP.references.rtpinfo.worlds.WorldPlayer;
|
||||
public class RTP {
|
||||
|
||||
@Getter final RTPTeleport teleport = new RTPTeleport();
|
||||
@Getter private final RTPOperationTracker operations = new RTPOperationTracker();
|
||||
//Cache
|
||||
public final HashMap<String, String> overriden = new HashMap<>();
|
||||
@Getter List<String> disabledWorlds, blockList;
|
||||
@@ -82,16 +83,19 @@ public class RTP {
|
||||
private void rtp(CommandSender sendi, WorldPlayer pWorld, RTP_TYPE type) {
|
||||
//Cooldown
|
||||
Player p = pWorld.getPlayer();
|
||||
getPl().getPInfo().getRtping().put(p, true); //Cache player so they cant run '/rtp' again while rtp'ing
|
||||
if (!p.isOnline()) return;
|
||||
RTPOperationTracker.Operation operation = operations.start(p.getUniqueId(), p);
|
||||
if (operation == null) return;
|
||||
//Setup player rtp methods
|
||||
RTPPlayer rtpPlayer = new RTPPlayer(p, this, pWorld, type);
|
||||
// Delaying? Else, just go
|
||||
if (pWorld.getPlayerInfo().applyDelay && HelperRTP_Check.applyDelay(pWorld.getPlayer())) {
|
||||
new RTPDelay(sendi, rtpPlayer, delayTime, cancelOnMove, cancelOnDamage);
|
||||
} else {
|
||||
if (!teleport.beforeTeleportInstant(sendi, p))
|
||||
rtpPlayer.randomlyTeleport(sendi);
|
||||
}
|
||||
RTPPlayer rtpPlayer = new RTPPlayer(p, this, pWorld, type, operation);
|
||||
rtpPlayer.runSafely(() -> {
|
||||
if (pWorld.getPlayerInfo().applyDelay && HelperRTP_Check.applyDelay(p)) {
|
||||
new RTPDelay(sendi, rtpPlayer, delayTime, cancelOnMove, cancelOnDamage);
|
||||
} else {
|
||||
rtpPlayer.afterPreEvent(teleport.beforeTeleportInstant(sendi, p),
|
||||
() -> rtpPlayer.randomlyTeleport(sendi));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private BetterRTP getPl() {
|
||||
|
||||
+28
-14
@@ -22,15 +22,17 @@ class RTPDelay implements Listener {
|
||||
this.cancelOnMove = cancelOnMove;
|
||||
this.cancelOnDamage = cancelOnDamage;
|
||||
this.rtp = rtp;
|
||||
rtp.getOperation().onFinish(this::dispose);
|
||||
delay(sendi, delay);
|
||||
}
|
||||
|
||||
private void delay(CommandSender sendi, int delay) {
|
||||
if (!getPl().getRTP().getTeleport().beforeTeleportDelay(rtp.getPlayer(), delay)) {
|
||||
rtp.afterPreEvent(getPl().getRTP().getTeleport().beforeTeleportDelay(rtp.getPlayer(), delay), () -> {
|
||||
task = AsyncHandler.syncLater(run(sendi, this), delay * 20L);
|
||||
if (cancelOnMove || cancelOnDamage)
|
||||
Bukkit.getPluginManager().registerEvents(this, BetterRTP.getInstance());
|
||||
}
|
||||
if (!rtp.isActive()) dispose();
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
@@ -57,23 +59,35 @@ class RTPDelay implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
private void dispose() {
|
||||
dispose(task, this);
|
||||
}
|
||||
|
||||
static void dispose(WrappedTask task, Listener listener) {
|
||||
try {
|
||||
if (task != null) task.cancel();
|
||||
} finally {
|
||||
HandlerList.unregisterAll(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private void cancel() {
|
||||
if (task != null)
|
||||
task.cancel();
|
||||
HandlerList.unregisterAll(this);
|
||||
getPl().getRTP().getTeleport().cancelledTeleport(rtp.getPlayer());
|
||||
//getPl().getEco().unCharge(rtp.getPlayer(), rtp.pWorld);
|
||||
getPl().getCooldowns().removeCooldown(rtp.getPlayer(), rtp.worldPlayer.getWorld());
|
||||
getPl().getPInfo().getRtping().remove(rtp.getPlayer());
|
||||
Bukkit.getServer().getPluginManager().callEvent(new RTP_CancelledEvent(rtp.getPlayer()));
|
||||
rtp.runSafely(() -> {
|
||||
try {
|
||||
getPl().getRTP().getTeleport().cancelledTeleport(rtp.getPlayer());
|
||||
getPl().getCooldowns().removeCooldown(rtp.getPlayer(), rtp.worldPlayer.getWorld());
|
||||
} finally {
|
||||
rtp.getOperation().finish();
|
||||
}
|
||||
Bukkit.getServer().getPluginManager().callEvent(new RTP_CancelledEvent(rtp.getPlayer()));
|
||||
});
|
||||
}
|
||||
|
||||
private Runnable run(final CommandSender sendi, final RTPDelay cls) {
|
||||
return () -> {
|
||||
return () -> rtp.runSafely(() -> {
|
||||
HandlerList.unregisterAll(cls);
|
||||
if (getPl().getPInfo().getRtping().containsKey(rtp.getPlayer()))
|
||||
rtp.randomlyTeleport(sendi);
|
||||
};
|
||||
rtp.randomlyTeleport(sendi);
|
||||
});
|
||||
}
|
||||
|
||||
private BetterRTP getPl() {
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package me.SuperRonanCraft.BetterRTP.player.rtp;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Owns active requests. Identity checks prevent old callbacks from ending a newer request. */
|
||||
public final class RTPOperationTracker {
|
||||
private final Map<UUID, Operation> active = new HashMap<>();
|
||||
|
||||
public synchronized Operation start(UUID uuid, Object session) {
|
||||
if (active.containsKey(uuid)) return null;
|
||||
Operation operation = new Operation(uuid, session);
|
||||
active.put(uuid, operation);
|
||||
return operation;
|
||||
}
|
||||
|
||||
public synchronized boolean contains(UUID uuid) { return active.containsKey(uuid); }
|
||||
|
||||
public void cancel(UUID uuid, Object session) {
|
||||
Operation operation;
|
||||
synchronized (this) { operation = active.get(uuid); }
|
||||
if (operation != null && operation.session == session) operation.finish();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
List<Operation> operations;
|
||||
synchronized (this) {
|
||||
operations = new ArrayList<>(active.values());
|
||||
active.clear();
|
||||
}
|
||||
RuntimeException failure = null;
|
||||
for (Operation operation : operations) {
|
||||
try { operation.finish(); } catch (RuntimeException ex) { failure = ex; }
|
||||
}
|
||||
if (failure != null) throw failure;
|
||||
}
|
||||
|
||||
public final class Operation {
|
||||
private final UUID uuid;
|
||||
private final Object session;
|
||||
private final List<Runnable> cleanup = new ArrayList<>();
|
||||
private boolean finished;
|
||||
|
||||
private Operation(UUID uuid, Object session) { this.uuid = uuid; this.session = session; }
|
||||
|
||||
public boolean isActive() {
|
||||
synchronized (RTPOperationTracker.this) { return active.get(uuid) == this; }
|
||||
}
|
||||
|
||||
public void onFinish(Runnable action) {
|
||||
synchronized (this) {
|
||||
if (!finished) { cleanup.add(action); return; }
|
||||
}
|
||||
action.run();
|
||||
}
|
||||
|
||||
public void finish() {
|
||||
List<Runnable> actions;
|
||||
synchronized (this) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
actions = new ArrayList<>(cleanup);
|
||||
cleanup.clear();
|
||||
}
|
||||
synchronized (RTPOperationTracker.this) { active.remove(uuid, this); }
|
||||
RuntimeException failure = null;
|
||||
for (Runnable action : actions) {
|
||||
try { action.run(); } catch (RuntimeException ex) { failure = ex; }
|
||||
}
|
||||
if (failure != null) throw failure;
|
||||
}
|
||||
|
||||
/** Terminal future: cleanup also runs when result handling throws. */
|
||||
public void complete(CompletableFuture<Boolean> future, Runnable success, Runnable failure,
|
||||
Consumer<Throwable> errors) {
|
||||
future.whenComplete((result, error) -> {
|
||||
try {
|
||||
if (!isActive()) return;
|
||||
if (error != null) errors.accept(error);
|
||||
else if (Boolean.TRUE.equals(result)) success.run();
|
||||
else failure.run();
|
||||
} catch (Throwable ex) {
|
||||
errors.accept(ex);
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
-15
@@ -23,20 +23,56 @@ import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
|
||||
public class RTPPlayer {
|
||||
|
||||
@Getter private final Player player;
|
||||
@Getter private final RTPOperationTracker.Operation operation;
|
||||
private final RTP settings;
|
||||
@Getter WorldPlayer worldPlayer;
|
||||
@Getter RTP_TYPE type;
|
||||
@Getter int attempts;
|
||||
//List<Location> attemptedLocations = new ArrayList<>();
|
||||
|
||||
RTPPlayer(Player player, RTP settings, WorldPlayer worldPlayer, RTP_TYPE type) {
|
||||
RTPPlayer(Player player, RTP settings, WorldPlayer worldPlayer, RTP_TYPE type, RTPOperationTracker.Operation operation) {
|
||||
this.operation = operation;
|
||||
this.player = player;
|
||||
this.settings = settings;
|
||||
this.worldPlayer = worldPlayer;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
boolean isActive() {
|
||||
if (!player.isOnline()) operation.finish();
|
||||
return operation.isActive();
|
||||
}
|
||||
|
||||
void logError(Throwable error) {
|
||||
getPl().getLogger().log(java.util.logging.Level.WARNING, "RTP operation failed for " + player.getUniqueId(), error);
|
||||
}
|
||||
|
||||
void runSafely(Runnable action) {
|
||||
try {
|
||||
if (isActive()) action.run();
|
||||
} catch (Throwable error) {
|
||||
try { operation.finish(); } finally { logError(error); }
|
||||
}
|
||||
}
|
||||
|
||||
void afterPreEvent(boolean cancelled, Runnable continuation) {
|
||||
if (cancelled) operation.finish();
|
||||
else runSafely(continuation);
|
||||
}
|
||||
|
||||
void awaitChunk(CompletableFuture<Chunk> chunk, Runnable continuation) {
|
||||
chunk.whenComplete((result, error) -> runSafely(() -> {
|
||||
if (error != null) {
|
||||
try { operation.finish(); } finally { logError(error); }
|
||||
} else continuation.run();
|
||||
}));
|
||||
}
|
||||
|
||||
void randomlyTeleport(CommandSender sendi) {
|
||||
runSafely(() -> search(sendi));
|
||||
}
|
||||
|
||||
private void search(CommandSender sendi) {
|
||||
if (attempts >= settings.maxAttempts) //Cancel out, too many tries
|
||||
metMax(sendi, player);
|
||||
else { //Try again to find a safe location
|
||||
@@ -45,11 +81,11 @@ public class RTPPlayer {
|
||||
Bukkit.getServer().getPluginManager().callEvent(event);
|
||||
//Async Location finder
|
||||
if (event.isCancelled()) {
|
||||
randomlyTeleport(sendi);
|
||||
attempts++;
|
||||
AsyncHandler.sync(() -> randomlyTeleport(sendi));
|
||||
return;
|
||||
}
|
||||
AsyncHandler.async(() -> {
|
||||
AsyncHandler.async(() -> runSafely(() -> {
|
||||
Location loc;
|
||||
if (event.getLocation() != null) // && WorldPlayer.checkIsValid(event.getLocation(), pWorld))
|
||||
loc = event.getLocation();
|
||||
@@ -63,25 +99,21 @@ public class RTPPlayer {
|
||||
}
|
||||
attempts++; //Add an attempt
|
||||
//Load chunk and find out if safe location (asynchronously)
|
||||
AsyncHandler.sync(() -> {
|
||||
AsyncHandler.sync(() -> runSafely(() -> {
|
||||
try { //Prior to 1.12 this async chunk will NOT work
|
||||
CompletableFuture<Chunk> chunk = PaperLib.getChunkAtAsync(loc);
|
||||
chunk.thenAccept(result -> {
|
||||
//BetterRTP.debug("Checking location for " + p.getName());
|
||||
attempt(sendi, loc);
|
||||
});
|
||||
awaitChunk(chunk, () -> attempt(sendi, loc));
|
||||
} catch (IllegalStateException e) {
|
||||
//Legacy non-async support
|
||||
attempt(sendi, loc);
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
}
|
||||
});
|
||||
});
|
||||
}));
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private void attempt(CommandSender sendi, Location loc) {
|
||||
if (!isActive()) return;
|
||||
Location tpLoc;
|
||||
tpLoc = RandomLocation.getSafeLocation(worldPlayer.getWorldtype(), worldPlayer.getWorld(), loc, worldPlayer.getMinY(), worldPlayer.getMaxY(), worldPlayer.getBiomes());
|
||||
//attemptedLocations.add(loc);
|
||||
@@ -94,11 +126,11 @@ public class RTPPlayer {
|
||||
getPl().getCooldowns().add(player, worldPlayer.getWorld());
|
||||
tpLoc.setYaw(player.getLocation().getYaw());
|
||||
tpLoc.setPitch(player.getLocation().getPitch());
|
||||
AsyncHandler.sync(() -> settings.teleport.sendPlayer(sendi, player, tpLoc, worldPlayer, attempts, type));
|
||||
AsyncHandler.sync(() -> runSafely(() -> settings.teleport.sendPlayer(sendi, this, tpLoc)));
|
||||
} else {
|
||||
if (worldPlayer.getPlayerInfo().applyCooldown)
|
||||
getPl().getCooldowns().removeCooldown(player, worldPlayer.getWorld());
|
||||
getPl().getPInfo().getRtping().remove(player);
|
||||
operation.finish();
|
||||
}
|
||||
} else {
|
||||
randomlyTeleport(sendi);
|
||||
@@ -110,7 +142,7 @@ public class RTPPlayer {
|
||||
private void metMax(CommandSender sendi, Player p) {
|
||||
settings.teleport.failedTeleport(p, sendi);
|
||||
getPl().getCooldowns().removeCooldown(p, worldPlayer.getWorld());
|
||||
getPl().getPInfo().getRtping().remove(p);
|
||||
operation.finish();
|
||||
//RTP Failed Event
|
||||
Bukkit.getServer().getPluginManager().callEvent(new RTP_FailedEvent(this));
|
||||
}
|
||||
|
||||
+18
-31
@@ -5,7 +5,6 @@ import java.util.Arrays;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import io.papermc.lib.PaperLib;
|
||||
import me.SuperRonanCraft.BetterRTP.BetterRTP;
|
||||
@@ -38,37 +37,25 @@ public class RTPTeleport {
|
||||
// CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).cancel(true);
|
||||
// }
|
||||
|
||||
void sendPlayer(final CommandSender sendi, final Player p, final Location location, final WorldPlayer wPlayer,
|
||||
final int attempts, RTP_TYPE type) throws NullPointerException {
|
||||
void sendPlayer(CommandSender sendi, RTPPlayer request, Location location) {
|
||||
Player p = request.getPlayer();
|
||||
WorldPlayer wPlayer = request.getWorldPlayer();
|
||||
int attempts = request.getAttempts();
|
||||
RTP_TYPE type = request.getType();
|
||||
Location oldLoc = p.getLocation();
|
||||
loadingTeleport(p, sendi); //Send loading message to player who requested
|
||||
//List<CompletableFuture<Chunk>> asyncChunks = getChunks(location); //Get a list of chunks
|
||||
//playerLoads.put(p, asyncChunks);
|
||||
/*CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).thenRun(() -> { //Async chunk load
|
||||
new BukkitRunnable() { //Run synchronously
|
||||
@Override
|
||||
public void run() {*/
|
||||
try {
|
||||
RTP_TeleportEvent event = new RTP_TeleportEvent(p, location, wPlayer.getWorldtype());
|
||||
getPl().getServer().getPluginManager().callEvent(event);
|
||||
Location loc = event.getLocation();
|
||||
PaperLib.teleportAsync(p, loc).thenRun(new BukkitRunnable() { //Async teleport
|
||||
@Override
|
||||
public void run() {
|
||||
afterTeleport(p, loc, wPlayer, attempts, oldLoc, type);
|
||||
if (sendi != p) //Tell player who requested that the player rtp'd
|
||||
sendSuccessMsg(sendi, p.getName(), loc, wPlayer, false, attempts);
|
||||
getPl().getPInfo().getRtping().remove(p); //No longer rtp'ing
|
||||
//Save respawn location if first join
|
||||
if (type == RTP_TYPE.JOIN) //RTP Type was Join
|
||||
if (BetterRTP.getInstance().getSettings().isRtpOnFirstJoin_SetAsRespawn()) //Save as respawn is enabled
|
||||
p.setBedSpawnLocation(loc, true); //True means to force a respawn even without a valid bed
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
getPl().getPInfo().getRtping().remove(p); //No longer rtp'ing (errored)
|
||||
e.printStackTrace();
|
||||
}
|
||||
loadingTeleport(p, sendi);
|
||||
RTP_TeleportEvent event = new RTP_TeleportEvent(p, location, wPlayer.getWorldtype());
|
||||
getPl().getServer().getPluginManager().callEvent(event);
|
||||
if (!request.isActive()) return;
|
||||
Location loc = event.getLocation();
|
||||
request.getOperation().complete(PaperLib.teleportAsync(p, loc), () -> {
|
||||
if (!request.isActive()) return;
|
||||
afterTeleport(p, loc, wPlayer, attempts, oldLoc, type);
|
||||
if (sendi != p)
|
||||
sendSuccessMsg(sendi, p.getName(), loc, wPlayer, false, attempts);
|
||||
if (type == RTP_TYPE.JOIN && getPl().getSettings().isRtpOnFirstJoin_SetAsRespawn())
|
||||
p.setBedSpawnLocation(loc, true);
|
||||
}, () -> failedTeleport(p, sendi), request::logError);
|
||||
}
|
||||
|
||||
//Effects
|
||||
|
||||
+4
-1
@@ -3,6 +3,7 @@ package me.SuperRonanCraft.BetterRTP.player.rtp.effects;
|
||||
import me.SuperRonanCraft.BetterRTP.BetterRTP;
|
||||
import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
|
||||
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
@@ -52,8 +53,10 @@ public class RTPEffect_Potions { //Potions AND Invincibility
|
||||
|
||||
public void giveEffects(Player p) {
|
||||
AsyncHandler.syncAtEntity(p, () -> {
|
||||
PlayerData data = HelperPlayer.getData(p);
|
||||
if (data == null) return;
|
||||
if (invincibleEnabled)
|
||||
HelperPlayer.getData(p).setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L));
|
||||
data.setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L));
|
||||
if (potionEnabled) {
|
||||
List<PotionEffect> effects = new ArrayList<>();
|
||||
for (PotionEffectType e : potionEffects.keySet()) {
|
||||
|
||||
+52
-40
@@ -6,7 +6,7 @@ import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import me.SuperRonanCraft.BetterRTP.BetterRTP;
|
||||
@@ -41,56 +41,68 @@ public class DatabasePlayers extends SQLite {
|
||||
}
|
||||
}
|
||||
|
||||
public void setupData(PlayerData data) {
|
||||
if (data == null || data.player == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Future<?> task = SQLiteExecutor.EXECUTOR.submit(() -> {
|
||||
Connection conn = null;
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
conn = getSQLConnection();
|
||||
ps = conn.prepareStatement("SELECT * FROM " + tables.get(0) + " WHERE " + COLUMNS.UUID.name + " = ?");
|
||||
ps.setString(1, data.player.getUniqueId().toString());
|
||||
/** Immutable persistence values; never retains a Bukkit player/session. */
|
||||
public static final class Snapshot {
|
||||
public final UUID uuid;
|
||||
public final int count;
|
||||
public final long cooldown;
|
||||
|
||||
rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
long count = rs.getLong(COLUMNS.COUNT.name);
|
||||
long time = rs.getLong(COLUMNS.LAST_COOLDOWN_DATE.name);
|
||||
data.setRtpCount(Math.toIntExact(count));
|
||||
data.setGlobalCooldown(time);
|
||||
public Snapshot(UUID uuid, int count, long cooldown) {
|
||||
this.uuid = uuid;
|
||||
this.count = count;
|
||||
this.cooldown = cooldown;
|
||||
}
|
||||
|
||||
public static Snapshot capture(PlayerData data) {
|
||||
return new Snapshot(data.player.getUniqueId(), data.getRtpCount(), data.getGlobalCooldown());
|
||||
}
|
||||
}
|
||||
|
||||
/** Existing API: load into this session only while it is still current. */
|
||||
public void setupData(PlayerData data) {
|
||||
if (data == null) return;
|
||||
Snapshot stored = loadData(data.player.getUniqueId());
|
||||
if (stored != null)
|
||||
BetterRTP.getInstance().getPlayerDataManager().applyIfCurrent(data, current -> {
|
||||
current.setRtpCount(stored.count);
|
||||
current.setGlobalCooldown(stored.cooldown);
|
||||
});
|
||||
}
|
||||
|
||||
public Snapshot loadData(UUID uuid) {
|
||||
try {
|
||||
return SQLiteExecutor.EXECUTOR.submit(() -> {
|
||||
try (Connection conn = getSQLConnection();
|
||||
PreparedStatement ps = conn.prepareStatement("SELECT * FROM " + tables.get(0) + " WHERE " + COLUMNS.UUID.name + " = ?")) {
|
||||
ps.setString(1, uuid.toString());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next())
|
||||
return new Snapshot(uuid, Math.toIntExact(rs.getLong(COLUMNS.COUNT.name)),
|
||||
rs.getLong(COLUMNS.LAST_COOLDOWN_DATE.name));
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
BetterRTP.getInstance().getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
|
||||
} finally {
|
||||
close(ps, rs, conn);
|
||||
}
|
||||
});
|
||||
task.get();
|
||||
return null;
|
||||
}).get();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//Set a player Cooldown
|
||||
/** Compatibility entry point: capture before deferring database work. */
|
||||
public void setData(PlayerData data) {
|
||||
try {
|
||||
SQLiteExecutor.EXECUTOR.submit(() -> {
|
||||
String sql = "INSERT OR REPLACE INTO " + tables.get(0) + " ("
|
||||
+ COLUMNS.UUID.name + ", "
|
||||
+ COLUMNS.COUNT.name + ", "
|
||||
if (data != null) setData(Snapshot.capture(data));
|
||||
}
|
||||
|
||||
public void setData(Snapshot data) {
|
||||
SQLiteExecutor.EXECUTOR.submit(() -> {
|
||||
String sql = "INSERT OR REPLACE INTO " + tables.get(0) + " ("
|
||||
+ COLUMNS.UUID.name + ", " + COLUMNS.COUNT.name + ", "
|
||||
+ COLUMNS.LAST_COOLDOWN_DATE.name + ") VALUES(?, ?, ?)";
|
||||
List<Object> params = new ArrayList<Object>() {{
|
||||
add(data.player.getUniqueId().toString());
|
||||
add(data.getRtpCount());
|
||||
add(data.getGlobalCooldown());
|
||||
}};
|
||||
sqlUpdate(sql, params);
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
List<Object> params = java.util.Arrays.asList(data.uuid.toString(), data.count, data.cooldown);
|
||||
sqlUpdate(sql, params);
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
@@ -39,6 +39,7 @@ public class DepPlaceholderAPI extends PlaceholderExpansion {
|
||||
@Override
|
||||
public String onPlaceholderRequest(Player player, String request) {
|
||||
PlayerData data = HelperPlayer.getData(player);
|
||||
if (data == null) return null;
|
||||
if (request.equalsIgnoreCase("count")) {
|
||||
return String.valueOf(data.getRtpCount());
|
||||
} else if (request.startsWith("cooldown")) {
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ public class HelperRTP_Check {
|
||||
}
|
||||
|
||||
private static boolean isRTPing(Player player) {
|
||||
return getPl().getPInfo().getRtping().getOrDefault(player, false);
|
||||
return getPl().getRTP().getOperations().contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
public static boolean isCoolingDown(Player player, WorldPlayer pWorld) {
|
||||
|
||||
+1
@@ -37,6 +37,7 @@ public interface RTPInventory_Defaults {
|
||||
|
||||
default void cacheInv(Player p, Inventory inv, RTP_INV_SETTINGS type) {
|
||||
PlayerData info = HelperPlayer.getData(p);
|
||||
if (info == null) return;
|
||||
info.getMenu().setInv(inv);
|
||||
info.getMenu().setInvType(type);
|
||||
}
|
||||
|
||||
+1
@@ -6,6 +6,7 @@ import org.bukkit.entity.Player;
|
||||
|
||||
public class HelperPlayer {
|
||||
|
||||
@org.jetbrains.annotations.Nullable
|
||||
public static PlayerData getData(Player p) {
|
||||
return getPl().getPlayerDataManager().getData(p);
|
||||
}
|
||||
|
||||
+2
-1
@@ -12,7 +12,8 @@ import me.SuperRonanCraft.BetterRTP.references.rtpinfo.CooldownData;
|
||||
|
||||
public class PlayerData {
|
||||
|
||||
public boolean loading; //Is this players data loading?
|
||||
public volatile boolean cooldownsLoaded;
|
||||
public volatile boolean loading; //Is this players data loading?
|
||||
public final Player player;
|
||||
//Menus
|
||||
@Getter final PlayerData_Menus menu = new PlayerData_Menus();
|
||||
|
||||
+22
-3
@@ -6,14 +6,33 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class PlayerDataManager {
|
||||
|
||||
private final Map<UUID, PlayerData> playerData = new ConcurrentHashMap<>();
|
||||
|
||||
public PlayerData getData(@NonNull Player p) {
|
||||
return playerData.computeIfAbsent(p.getUniqueId(), uuid -> new PlayerData(p));
|
||||
/** Called only by join/enable/reload lifecycle handling. */
|
||||
public PlayerData startSession(@NonNull Player p) {
|
||||
PlayerData data = new PlayerData(p);
|
||||
playerData.put(p.getUniqueId(), data);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** Lookup only: a departed or replaced session must never be recreated. */
|
||||
@Nullable
|
||||
public PlayerData getData(Player p) {
|
||||
if (p == null) return null;
|
||||
PlayerData data = playerData.get(p.getUniqueId());
|
||||
return data != null && data.player == p ? data : null;
|
||||
}
|
||||
|
||||
public void applyIfCurrent(PlayerData session, Consumer<PlayerData> update) {
|
||||
playerData.computeIfPresent(session.player.getUniqueId(), (id, current) -> {
|
||||
if (current == session) update.accept(current);
|
||||
return current;
|
||||
});
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@@ -26,6 +45,6 @@ public class PlayerDataManager {
|
||||
}
|
||||
|
||||
public void clear(Player p) {
|
||||
playerData.remove(p.getUniqueId());
|
||||
playerData.computeIfPresent(p.getUniqueId(), (id, data) -> data.player == p ? null : data);
|
||||
}
|
||||
}
|
||||
+65
-48
@@ -2,7 +2,8 @@ package me.SuperRonanCraft.BetterRTP.references.rtpinfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@@ -15,6 +16,7 @@ import lombok.Getter;
|
||||
import me.SuperRonanCraft.BetterRTP.BetterRTP;
|
||||
import me.SuperRonanCraft.BetterRTP.references.database.DatabaseCooldowns;
|
||||
import me.SuperRonanCraft.BetterRTP.references.database.DatabaseHandler;
|
||||
import me.SuperRonanCraft.BetterRTP.references.database.DatabasePlayers;
|
||||
import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
|
||||
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
|
||||
@@ -26,12 +28,11 @@ public class CooldownHandler {
|
||||
@Getter boolean enabled, loaded, cooldownByWorld;
|
||||
@Getter private int defaultCooldownTime; //Global Cooldown timer
|
||||
private int lockedAfter; //Rtp's before being locked
|
||||
private final List<Player> downloading = new CopyOnWriteArrayList<>();
|
||||
|
||||
public void load() {
|
||||
FileOther.FILETYPE config = FileOther.FILETYPE.CONFIG;
|
||||
enabled = config.getBoolean("Settings.Cooldown.Enabled");
|
||||
downloading.clear();
|
||||
|
||||
loaded = false;
|
||||
if (enabled) {
|
||||
defaultCooldownTime = config.getInt("Settings.Cooldown.Time");
|
||||
@@ -62,6 +63,7 @@ public class CooldownHandler {
|
||||
public void add(Player player, World world) {
|
||||
if (!enabled) return;
|
||||
PlayerData playerData = getData(player);
|
||||
if (playerData == null) return;
|
||||
if (cooldownByWorld) {
|
||||
Map<World, CooldownData> cooldowns = playerData.getCooldowns();
|
||||
CooldownData data = cooldowns.getOrDefault(world, new CooldownData(player.getUniqueId(), 0L));
|
||||
@@ -69,7 +71,7 @@ public class CooldownHandler {
|
||||
data.setTime(System.currentTimeMillis());
|
||||
playerData.setGlobalCooldown(data.getTime());
|
||||
cooldowns.put(world, data);
|
||||
savePlayer(player, world, data, false);
|
||||
savePlayer(playerData, world, data, false);
|
||||
} else
|
||||
add(player);
|
||||
}
|
||||
@@ -77,18 +79,19 @@ public class CooldownHandler {
|
||||
private void add(Player player) {
|
||||
if (!enabled) return;
|
||||
PlayerData playerData = getData(player);
|
||||
if (playerData == null) return;
|
||||
playerData.setRtpCount(playerData.getRtpCount() + 1);
|
||||
playerData.setGlobalCooldown(System.currentTimeMillis());
|
||||
savePlayer(player, null, null, false);
|
||||
savePlayer(playerData, null, null, false);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public CooldownData get(Player p, World world) {
|
||||
PlayerData data = getData(p);
|
||||
if (data == null) return null;
|
||||
if (cooldownByWorld) {
|
||||
Map<World, CooldownData> cooldownData = getData(p).getCooldowns();
|
||||
if (data != null)
|
||||
return cooldownData.getOrDefault(world, null);
|
||||
Map<World, CooldownData> cooldownData = data.getCooldowns();
|
||||
return cooldownData.getOrDefault(world, null);
|
||||
} else if (data.getGlobalCooldown() > 0) {
|
||||
return new CooldownData(p.getUniqueId(), data.getGlobalCooldown());
|
||||
}
|
||||
@@ -102,73 +105,87 @@ public class CooldownHandler {
|
||||
}
|
||||
|
||||
public boolean locked(Player player) {
|
||||
return lockedAfter > 0 && getData(player).getRtpCount() >= lockedAfter;
|
||||
PlayerData data = getData(player);
|
||||
return lockedAfter > 0 && data != null && data.getRtpCount() >= lockedAfter;
|
||||
}
|
||||
|
||||
public void removeCooldown(Player player, World world) {
|
||||
if (!enabled) return;
|
||||
PlayerData playerData = getData(player);
|
||||
if (playerData == null) return;
|
||||
CooldownData cooldownData = playerData.getCooldowns().getOrDefault(world, null);
|
||||
if (cooldownData != null) {
|
||||
if (lockedAfter > 0) {
|
||||
if (playerData.getRtpCount() <= 0) { //Remove from file as well
|
||||
savePlayer(player, world, cooldownData, true);
|
||||
getData(player).getCooldowns().put(world, null);
|
||||
savePlayer(playerData, world, cooldownData, true);
|
||||
playerData.getCooldowns().remove(world);
|
||||
} else { //Keep the player cached
|
||||
savePlayer(player, world, cooldownData, false);
|
||||
savePlayer(playerData, world, cooldownData, false);
|
||||
}
|
||||
} else { //Remove completely
|
||||
getData(player).getCooldowns().remove(world);
|
||||
savePlayer(player, world, cooldownData, true);
|
||||
playerData.getCooldowns().remove(world);
|
||||
savePlayer(playerData, world, cooldownData, true);
|
||||
}
|
||||
} else if (!cooldownByWorld) {
|
||||
getData(player).setGlobalCooldown(0);
|
||||
savePlayer(player, null, null, true);
|
||||
playerData.setGlobalCooldown(0);
|
||||
savePlayer(playerData, null, null, true);
|
||||
}
|
||||
}
|
||||
|
||||
private void savePlayer(Player player, @Nullable World world, @Nullable CooldownData data, boolean remove) {
|
||||
AsyncHandler.async(() -> {
|
||||
if (world != null && data != null && getDatabaseWorlds() != null) { //Per World enabled?
|
||||
if (!remove)
|
||||
getDatabaseWorlds().setCooldown(world, data);
|
||||
else
|
||||
getDatabaseWorlds().removePlayer(data.getUuid(), world);
|
||||
}
|
||||
DatabaseHandler.getPlayers().setData(getData(player));
|
||||
private void savePlayer(PlayerData session, @Nullable World world, @Nullable CooldownData data, boolean remove) {
|
||||
DatabasePlayers.Snapshot snapshot = DatabasePlayers.Snapshot.capture(session);
|
||||
CooldownData cooldown = data == null ? null : new CooldownData(data.getUuid(), data.getTime());
|
||||
DatabaseCooldowns worlds = getDatabaseWorlds();
|
||||
// Submit player values now, preserving submission order and avoiding a later lookup.
|
||||
DatabaseHandler.getPlayers().setData(snapshot);
|
||||
if (world != null && cooldown != null && worlds != null) {
|
||||
AsyncHandler.async(() -> {
|
||||
if (remove) worlds.removePlayer(cooldown.getUuid(), world);
|
||||
else worlds.setCooldown(world, cooldown);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Capture the session before scheduling; completion cannot affect a reconnect. */
|
||||
public void loadPlayer(Player player) {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
if (!isEnabled()) return;
|
||||
PlayerData session = getData(player);
|
||||
if (session == null) return;
|
||||
synchronized (session) {
|
||||
if (session.loading || session.cooldownsLoaded) return;
|
||||
session.loading = true;
|
||||
}
|
||||
|
||||
PlayerData playerData = getData(player);
|
||||
if (playerData == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
downloading.add(player);
|
||||
|
||||
try {
|
||||
if (getDatabaseWorlds() != null) { //Per World enabled?
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
//Cooldowns
|
||||
CooldownData cooldown = getDatabaseWorlds().getCooldown(player.getUniqueId(), world);
|
||||
if (cooldown != null)
|
||||
playerData.getCooldowns().put(world, cooldown);
|
||||
UUID uuid = player.getUniqueId();
|
||||
List<World> worlds = Bukkit.getWorlds();
|
||||
DatabaseCooldowns databaseWorlds = getDatabaseWorlds();
|
||||
AsyncHandler.async(() -> {
|
||||
try {
|
||||
if (getData(player) != session) return;
|
||||
Map<World, CooldownData> cooldowns = new HashMap<>();
|
||||
if (databaseWorlds != null) {
|
||||
for (World world : worlds) {
|
||||
CooldownData cooldown = databaseWorlds.getCooldown(uuid, world);
|
||||
if (cooldown != null) cooldowns.put(world, cooldown);
|
||||
}
|
||||
}
|
||||
DatabasePlayers.Snapshot stored = DatabaseHandler.getPlayers().loadData(uuid);
|
||||
BetterRTP.getInstance().getPlayerDataManager().applyIfCurrent(session, current -> {
|
||||
current.getCooldowns().putAll(cooldowns);
|
||||
if (stored != null) {
|
||||
current.setRtpCount(stored.count);
|
||||
current.setGlobalCooldown(stored.cooldown);
|
||||
}
|
||||
current.cooldownsLoaded = true;
|
||||
});
|
||||
} finally {
|
||||
session.loading = false;
|
||||
}
|
||||
//Player Data
|
||||
DatabaseHandler.getPlayers().setupData(playerData);
|
||||
} finally {
|
||||
downloading.remove(player);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean loadedPlayer(Player player) {
|
||||
return !downloading.contains(player);
|
||||
PlayerData data = getData(player);
|
||||
return data != null && !data.loading;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
+86
-65
@@ -1,88 +1,109 @@
|
||||
package me.SuperRonanCraft.BetterRTP.references.web;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import java.util.Map;
|
||||
|
||||
public class LogUploader {
|
||||
public static final String KEY_URL = "https://mclo.gs/";
|
||||
private static final String UPLOAD_URL = "https://api.mclo.gs/1/log";
|
||||
private static final int MAX_LOG_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
private static final String UPLOAD_URL = "https://logs.ronanplugins.com/documents";
|
||||
public static final String KEY_URL = "https://logs.ronanplugins.com/";
|
||||
|
||||
/** Returns the validated viewing URL, or null when the upload fails. */
|
||||
@Nullable
|
||||
public static String post(List<String> requestBody) {
|
||||
try {
|
||||
URL url = new URL(UPLOAD_URL);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "text/plain");
|
||||
connection.setDoOutput(true);
|
||||
|
||||
//String requestBody = "This is the raw body of text.";
|
||||
|
||||
try (OutputStream outputStream = connection.getOutputStream()) {
|
||||
for (String str : requestBody) {
|
||||
byte[] input = (str + System.lineSeparator()).getBytes(StandardCharsets.UTF_8);
|
||||
outputStream.write(input, 0, input.length);
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder response = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
return response.toString();
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
public static String post(List<String> lines) {
|
||||
ByteArrayOutputStream content = new ByteArrayOutputStream();
|
||||
for (String line : lines) {
|
||||
byte[] bytes = (line + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
if (content.size() + bytes.length > MAX_LOG_BYTES) return null;
|
||||
content.write(bytes, 0, bytes.length);
|
||||
}
|
||||
return upload(new String(content.toByteArray(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static String post(File file) {
|
||||
// Create the connection to the server
|
||||
try {
|
||||
URL url = new URL(UPLOAD_URL);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "text/yaml");
|
||||
connection.setDoOutput(true);
|
||||
|
||||
try (OutputStream outputStream = connection.getOutputStream()) {
|
||||
Scanner scan = new Scanner(file);
|
||||
while(scan.hasNextLine()){
|
||||
String str = scan.nextLine();
|
||||
byte[] input = (str + System.lineSeparator()).getBytes(StandardCharsets.UTF_8);
|
||||
outputStream.write(input, 0, input.length);
|
||||
}
|
||||
scan.close();
|
||||
}
|
||||
|
||||
StringBuilder response = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
return response.toString();
|
||||
if (file == null || !file.isFile() || file.length() > MAX_LOG_BYTES) return null;
|
||||
try (InputStream input = new FileInputStream(file)) {
|
||||
return upload(readBounded(input, MAX_LOG_BYTES));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
//getLogger().log(Level.INFO, "Response: " + response.toString());
|
||||
}
|
||||
|
||||
private static String readBounded(InputStream input, int limit) throws IOException {
|
||||
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[8192];
|
||||
int count;
|
||||
while ((count = input.read(buffer)) != -1) {
|
||||
if (result.size() + count > limit) throw new IOException("Upload size limit exceeded");
|
||||
result.write(buffer, 0, count);
|
||||
}
|
||||
return new String(result.toByteArray(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static String upload(String content) {
|
||||
HttpURLConnection connection = null;
|
||||
try {
|
||||
connection = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setConnectTimeout(10000);
|
||||
connection.setReadTimeout(15000);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
|
||||
connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setDoOutput(true);
|
||||
byte[] body = requestBody(content);
|
||||
connection.setFixedLengthStreamingMode(body.length);
|
||||
try (OutputStream output = connection.getOutputStream()) {
|
||||
output.write(body);
|
||||
}
|
||||
int status = connection.getResponseCode();
|
||||
if (status < 200 || status >= 300) return null;
|
||||
try (InputStream input = connection.getInputStream()) {
|
||||
return viewingUrl(readBounded(input, 64 * 1024));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] requestBody(String content) {
|
||||
Map<String, String> request = new LinkedHashMap<>();
|
||||
request.put("content", content);
|
||||
request.put("source", "BetterRTP");
|
||||
return JSONObject.toJSONString(request).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
static String viewingUrl(String response) {
|
||||
try {
|
||||
Object parsed = new JSONParser().parse(response);
|
||||
if (!(parsed instanceof JSONObject)) return null;
|
||||
JSONObject json = (JSONObject) parsed;
|
||||
if (!Boolean.TRUE.equals(json.get("success")) || !(json.get("url") instanceof String)) return null;
|
||||
String url = (String) json.get("url");
|
||||
// Only show links to the mclo.gs log viewer; never render arbitrary API response text in chat.
|
||||
return url.matches("https://mclo\\.gs/[A-Za-z0-9_-]+") ? url : null;
|
||||
} catch (ParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package me.SuperRonanCraft.BetterRTP.player.rtp;
|
||||
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.Test;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class RTPOperationTest {
|
||||
private final RTPOperationTracker tracker = new RTPOperationTracker();
|
||||
private final UUID uuid = UUID.randomUUID();
|
||||
private final Object session = new Object();
|
||||
private final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
private RTPOperationTracker.Operation start() { return tracker.start(uuid, session); }
|
||||
private Runnable unexpected() { return () -> fail("Unexpected continuation"); }
|
||||
|
||||
private RTPPlayer request(RTPOperationTracker.Operation operation) {
|
||||
Player player = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class},
|
||||
(proxy, method, args) -> {
|
||||
if (method.getName().equals("isOnline")) return true;
|
||||
if (method.getName().equals("getUniqueId")) return uuid;
|
||||
throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
return new RTPPlayer(player, null, null, RTP_TYPE.JOIN, operation) {
|
||||
@Override void logError(Throwable failure) { error.set(failure); }
|
||||
};
|
||||
}
|
||||
|
||||
@Test public void cancelledPreEventDoesNotStartInstantSearch() {
|
||||
RTPOperationTracker.Operation operation = start();
|
||||
request(operation).afterPreEvent(true, unexpected());
|
||||
assertNull(error.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void cancelledPreEventDisposesDelayAndDoesNotSchedule() {
|
||||
RTPOperationTracker.Operation operation = start();
|
||||
AtomicInteger disposed = new AtomicInteger();
|
||||
operation.onFinish(disposed::incrementAndGet);
|
||||
request(operation).afterPreEvent(true, unexpected());
|
||||
assertNull(error.get());
|
||||
operation.finish();
|
||||
assertEquals(1, disposed.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void exceptionalChunkFutureEndsOperation() {
|
||||
RTPOperationTracker.Operation operation = start();
|
||||
CompletableFuture<Chunk> future = new CompletableFuture<>();
|
||||
request(operation).awaitChunk(future, unexpected());
|
||||
RuntimeException failure = new RuntimeException("chunk load failed");
|
||||
future.completeExceptionally(failure);
|
||||
assertSame(failure, error.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void exceptionInChunkContinuationEndsOperation() {
|
||||
RTPOperationTracker.Operation operation = start();
|
||||
RuntimeException failure = new RuntimeException("location check failed");
|
||||
request(operation).awaitChunk(CompletableFuture.completedFuture(null), () -> { throw failure; });
|
||||
assertSame(failure, error.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void exceptionalTeleportFutureEndsOperation() {
|
||||
RTPOperationTracker.Operation operation = start();
|
||||
CompletableFuture<Boolean> future = new CompletableFuture<>();
|
||||
operation.complete(future, unexpected(), unexpected(), error::set);
|
||||
RuntimeException failure = new RuntimeException("teleport failed");
|
||||
future.completeExceptionally(failure);
|
||||
assertSame(failure, error.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void falseTeleportRunsFailureOnly() {
|
||||
AtomicInteger failures = new AtomicInteger();
|
||||
start().complete(CompletableFuture.completedFuture(false), unexpected(), failures::incrementAndGet, error::set);
|
||||
assertEquals(1, failures.get());
|
||||
assertNull(error.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void exceptionInPostTeleportEffectsStillCleansUp() {
|
||||
RuntimeException failure = new RuntimeException("effect failed");
|
||||
start().complete(CompletableFuture.completedFuture(true), () -> { throw failure; }, unexpected(), error::set);
|
||||
assertSame(failure, error.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void successRunsOnceAndReleasesOperation() {
|
||||
AtomicInteger successes = new AtomicInteger();
|
||||
start().complete(CompletableFuture.completedFuture(true), successes::incrementAndGet, unexpected(), error::set);
|
||||
assertEquals(1, successes.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
}
|
||||
|
||||
@Test public void quitAndStaleCompletionCannotRemoveNewOperation() {
|
||||
RTPOperationTracker.Operation old = start();
|
||||
CompletableFuture<Boolean> future = new CompletableFuture<>();
|
||||
old.complete(future, unexpected(), unexpected(), error::set);
|
||||
tracker.cancel(uuid, session);
|
||||
RTPOperationTracker.Operation current = tracker.start(uuid, new Object());
|
||||
tracker.cancel(uuid, session);
|
||||
future.complete(true);
|
||||
old.finish();
|
||||
assertTrue(current.isActive());
|
||||
assertNull(error.get());
|
||||
}
|
||||
|
||||
@Test public void reloadClearsAllAndRunsEachCleanupOnce() {
|
||||
RTPOperationTracker.Operation first = start();
|
||||
RTPOperationTracker.Operation second = tracker.start(UUID.randomUUID(), new Object());
|
||||
AtomicInteger disposed = new AtomicInteger();
|
||||
first.onFinish(disposed::incrementAndGet);
|
||||
second.onFinish(disposed::incrementAndGet);
|
||||
tracker.clear();
|
||||
tracker.clear();
|
||||
assertEquals(2, disposed.get());
|
||||
assertFalse(first.isActive());
|
||||
assertFalse(second.isActive());
|
||||
first.onFinish(disposed::incrementAndGet);
|
||||
assertEquals(3, disposed.get());
|
||||
}
|
||||
|
||||
@Test public void cleanupFailureDoesNotRetainOtherOperations() {
|
||||
RTPOperationTracker.Operation first = start();
|
||||
RTPOperationTracker.Operation second = tracker.start(UUID.randomUUID(), new Object());
|
||||
AtomicInteger disposed = new AtomicInteger();
|
||||
first.onFinish(() -> { throw new IllegalStateException("task cancellation failed"); });
|
||||
first.onFinish(disposed::incrementAndGet);
|
||||
second.onFinish(disposed::incrementAndGet);
|
||||
try { tracker.clear(); fail("Expected cleanup failure"); } catch (IllegalStateException expected) { }
|
||||
assertEquals(2, disposed.get());
|
||||
assertFalse(first.isActive());
|
||||
assertFalse(second.isActive());
|
||||
}
|
||||
|
||||
@Test public void duplicateRequestCannotReplaceActiveRequest() {
|
||||
RTPOperationTracker.Operation first = start();
|
||||
assertNull(start());
|
||||
assertTrue(first.isActive());
|
||||
}
|
||||
@Test public void lifecycleCleanupUnregistersListenerEvenWhenTaskCancelThrows() {
|
||||
org.bukkit.event.HandlerList handlers = new org.bukkit.event.HandlerList();
|
||||
org.bukkit.event.Listener listener = new org.bukkit.event.Listener() {};
|
||||
org.bukkit.plugin.Plugin plugin = (org.bukkit.plugin.Plugin) Proxy.newProxyInstance(
|
||||
org.bukkit.plugin.Plugin.class.getClassLoader(), new Class<?>[]{org.bukkit.plugin.Plugin.class},
|
||||
(proxy, method, args) -> {
|
||||
if (method.getName().equals("isEnabled")) return true;
|
||||
throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
handlers.register(new org.bukkit.plugin.RegisteredListener(listener, (target, event) -> {},
|
||||
org.bukkit.event.EventPriority.NORMAL, plugin, false));
|
||||
AtomicInteger cancelled = new AtomicInteger();
|
||||
com.tcoded.folialib.wrapper.task.WrappedTask task = new com.tcoded.folialib.wrapper.task.WrappedTask() {
|
||||
public void cancel() { cancelled.incrementAndGet(); throw new IllegalStateException("cancel failed"); }
|
||||
public boolean isCancelled() { return cancelled.get() > 0; }
|
||||
public org.bukkit.plugin.Plugin getOwningPlugin() { return plugin; }
|
||||
public boolean isAsync() { return false; }
|
||||
};
|
||||
RTPOperationTracker.Operation operation = start();
|
||||
operation.onFinish(() -> RTPDelay.dispose(task, listener));
|
||||
try {
|
||||
assertEquals(1, handlers.getRegisteredListeners().length);
|
||||
try { tracker.clear(); fail("Expected task cancellation failure"); }
|
||||
catch (IllegalStateException expected) { }
|
||||
assertEquals(0, handlers.getRegisteredListeners().length);
|
||||
assertEquals(1, cancelled.get());
|
||||
assertFalse(tracker.contains(uuid));
|
||||
} finally {
|
||||
handlers.unregister(listener);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package me.SuperRonanCraft.BetterRTP.references.player.playerdata;
|
||||
|
||||
import me.SuperRonanCraft.BetterRTP.references.database.DatabasePlayers;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.Test;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.UUID;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PlayerSessionTest {
|
||||
private Player player(UUID id) {
|
||||
return (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class},
|
||||
(proxy, method, args) -> {
|
||||
if (method.getName().equals("getUniqueId")) return id;
|
||||
if (method.getName().equals("hashCode")) return System.identityHashCode(proxy);
|
||||
if (method.getName().equals("equals")) return proxy == args[0];
|
||||
throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
}
|
||||
|
||||
@Test public void deferredLookupAndLoadCannotRestoreDepartedSession() {
|
||||
PlayerDataManager manager = new PlayerDataManager();
|
||||
Player player = player(UUID.randomUUID());
|
||||
PlayerData session = manager.startSession(player);
|
||||
manager.clear(player);
|
||||
assertNull(manager.getData(player));
|
||||
manager.applyIfCurrent(session, data -> fail("Departed session was updated"));
|
||||
assertNull(manager.getData(player.getUniqueId()));
|
||||
}
|
||||
|
||||
@Test public void oldCallbacksAndQuitCannotAffectReconnect() {
|
||||
PlayerDataManager manager = new PlayerDataManager();
|
||||
UUID id = UUID.randomUUID();
|
||||
Player oldPlayer = player(id), newPlayer = player(id);
|
||||
PlayerData old = manager.startSession(oldPlayer);
|
||||
manager.clear(oldPlayer);
|
||||
PlayerData current = manager.startSession(newPlayer);
|
||||
manager.applyIfCurrent(old, data -> data.setRtpCount(99));
|
||||
manager.clear(oldPlayer);
|
||||
assertNull(manager.getData(oldPlayer));
|
||||
assertSame(current, manager.getData(newPlayer));
|
||||
assertSame(newPlayer, current.player);
|
||||
assertEquals(0, current.getRtpCount());
|
||||
}
|
||||
|
||||
@Test public void reloadInvalidatesOldLoadEvenForSamePlayerObject() {
|
||||
PlayerDataManager manager = new PlayerDataManager();
|
||||
Player player = player(UUID.randomUUID());
|
||||
PlayerData old = manager.startSession(player);
|
||||
manager.clear();
|
||||
PlayerData current = manager.startSession(player);
|
||||
manager.applyIfCurrent(old, data -> fail("Old reload generation was updated"));
|
||||
manager.applyIfCurrent(current, data -> data.setRtpCount(7));
|
||||
assertEquals(7, current.getRtpCount());
|
||||
}
|
||||
|
||||
@Test public void pendingSaveKeepsCapturedValuesAfterMutationAndQuit() {
|
||||
PlayerDataManager manager = new PlayerDataManager();
|
||||
Player player = player(UUID.randomUUID());
|
||||
PlayerData data = manager.startSession(player);
|
||||
data.setRtpCount(12);
|
||||
data.setGlobalCooldown(123456L);
|
||||
DatabasePlayers.Snapshot pending = DatabasePlayers.Snapshot.capture(data);
|
||||
data.setRtpCount(0);
|
||||
data.setGlobalCooldown(0);
|
||||
manager.clear(player);
|
||||
assertEquals(player.getUniqueId(), pending.uuid);
|
||||
assertEquals(12, pending.count);
|
||||
assertEquals(123456L, pending.cooldown);
|
||||
assertNull(manager.getData(player));
|
||||
}
|
||||
|
||||
@Test public void deferredDatabaseWriterUsesSnapshotAfterQuit() throws Exception {
|
||||
PlayerDataManager manager = new PlayerDataManager();
|
||||
Player player = player(UUID.randomUUID());
|
||||
PlayerData data = manager.startSession(player);
|
||||
data.setRtpCount(23);
|
||||
data.setGlobalCooldown(987654L);
|
||||
java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.atomic.AtomicReference<java.util.List<Object>> written =
|
||||
new java.util.concurrent.atomic.AtomicReference<>();
|
||||
DatabasePlayers database = new DatabasePlayers() {
|
||||
@Override protected boolean sqlUpdate(String sql, java.util.List<Object> params) {
|
||||
written.set(params);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
// Table setup without starting Bukkit or opening a database connection.
|
||||
java.lang.reflect.Field tables = database.getClass().getSuperclass().getSuperclass().getDeclaredField("tables");
|
||||
tables.setAccessible(true);
|
||||
tables.set(database, java.util.Collections.singletonList("Players"));
|
||||
java.util.concurrent.ExecutorService executor =
|
||||
me.SuperRonanCraft.BetterRTP.references.database.SQLiteExecutor.EXECUTOR;
|
||||
executor.submit(() -> {
|
||||
try { release.await(5, java.util.concurrent.TimeUnit.SECONDS); }
|
||||
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
});
|
||||
try {
|
||||
database.setData(data);
|
||||
data.setRtpCount(0);
|
||||
data.setGlobalCooldown(0);
|
||||
manager.clear(player);
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
executor.submit(() -> {}).get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertEquals(java.util.Arrays.asList(player.getUniqueId().toString(), 23, 987654L), written.get());
|
||||
assertNull(manager.getData(player));
|
||||
}
|
||||
|
||||
@Test public void lookupNeverCreatesSessionAndAcceptsNull() {
|
||||
PlayerDataManager manager = new PlayerDataManager();
|
||||
assertNull(manager.getData((Player) null));
|
||||
assertNull(manager.getData(player(UUID.randomUUID())));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user