Author SHA1 Message Date
ARR4NN 48f211b1ad Add support for custom lang for the update message. 2024-05-29 11:40:53 +01:00
238 changed files with 1296 additions and 3430 deletions

No files matched your search

@@ -1,37 +0,0 @@
name: Publish editor schema
on:
release:
types: [published]
permissions:
contents: write
jobs:
publish:
if: '!github.event.release.prerelease'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.release.tag_name }}
persist-credentials: false
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Prepare plugin-owned schemas
env:
SCHEMA_PATHS: BetterRTP-Core/src/main/resources/META-INF/editor-schema.json BetterRTPAddons/src/main/resources/META-INF/editor-schema.json
run: |
node --input-type=module <<'JS'
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
mkdirSync('editor-schemas');
for (const path of process.env.SCHEMA_PATHS.split(' ')) {
const bytes = readFileSync(path), meta = JSON.parse(bytes)['x-bettersync'];
if (meta?.format !== 1 || !/^[a-z0-9-]+$/.test(meta.plugin) || !/^[A-Za-z0-9._-]+$/.test(meta.schemaVersion)) throw new Error('Invalid schema identity');
writeFileSync(`editor-schemas/${meta.plugin}-${meta.schemaVersion}.schema.json`, bytes);
}
JS
- name: Attach schemas to this plugin release
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
run: gh release upload "$RELEASE_TAG" editor-schemas/*.schema.json
-79
View File
@@ -1,79 +0,0 @@
name: Release BetterRTP Maven version
on:
push:
branches: [master]
workflow_dispatch:
permissions:
contents: write
concurrency:
group: release-maven-version
cancel-in-progress: false
jobs:
release:
if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
cache: maven
- name: Read BetterRTP Maven version
id: version
shell: bash
run: |
mvn -B -q -f BetterRTP-Core/pom.xml help:evaluate -Dexpression=project.version -Doutput="$RUNNER_TEMP/version-0"
version0=$(cat "$RUNNER_TEMP/version-0")
[[ "$version0" =~ ^[0-9][A-Za-z0-9._-]*$ ]] || { echo "Invalid Maven version"; exit 1; }
[[ "$version0" != *SNAPSHOT* ]] || { echo "Snapshot versions are not released"; exit 1; }
echo "version0=$version0" >> "$GITHUB_OUTPUT"
echo "tag=v$version0" >> "$GITHUB_OUTPUT"
echo "title=BetterRTP $version0" >> "$GITHUB_OUTPUT"
- name: Check for an existing release
id: existing
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ steps.version.outputs.tag }}
run: |
# Listing errors fail the workflow; they are not mistaken for an absent release.
releases=$(gh api --paginate "repos/$GH_REPO/releases?per_page=100" --jq '.[].tag_name')
if printf '%s\n' "$releases" | grep -Fxq "$RELEASE_TAG"; then
echo "exists=true" >> "$GITHUB_OUTPUT"
echo "Release $RELEASE_TAG already exists; bump the Maven version for another release."
fi
- name: Build and test
if: steps.existing.outputs.exists != 'true'
run: |
mvn -B -pl :BetterRTP clean verify
mvn -B -f tests/editor/pom.xml verify
- name: Prepare BetterRTP JAR and editor schemas
if: steps.existing.outputs.exists != 'true'
env:
# The website still needs Addons field metadata; this does not build its JAR.
SCHEMA_PATHS: BetterRTP-Core/src/main/resources/META-INF/editor-schema.json BetterRTPAddons/src/main/resources/META-INF/editor-schema.json
run: |
mkdir release-assets
cp "dist/BetterRTP-${{ steps.version.outputs.version0 }}.jar" release-assets/
python3 - <<'PYTHON'
import json, os, pathlib, re
for path in os.environ['SCHEMA_PATHS'].split():
data = pathlib.Path(path).read_bytes()
meta = json.loads(data)['x-bettersync']
if meta['format'] != 1 or not re.fullmatch(r'[a-z0-9-]+', meta['plugin']) or not re.fullmatch(r'[A-Za-z0-9._-]+', meta['schemaVersion']):
raise ValueError('Invalid schema identity')
pathlib.Path('release-assets', f"{meta['plugin']}-{meta['schemaVersion']}.schema.json").write_bytes(data)
PYTHON
- name: Publish versioned release
if: steps.existing.outputs.exists != 'true'
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ steps.version.outputs.tag }}
RELEASE_TITLE: ${{ steps.version.outputs.title }}
run: |
gh release create "$RELEASE_TAG" release-assets/* \
--target "$GITHUB_SHA" --title "$RELEASE_TITLE" --generate-notes --latest
+1 -3
View File
@@ -18,6 +18,4 @@ jobs:
run: cp settings.xml $HOME/.m2/settings.xml run: cp settings.xml $HOME/.m2/settings.xml
- name: Build and test with Maven - name: Build and test with Maven
run: | run: mvn test
mvn -B -pl :BetterRTP verify
mvn -B -f tests/editor/pom.xml verify
-2
View File
@@ -10,5 +10,3 @@ BetterRTP.wiki/
.DS_Store .DS_Store
.vscode/ .vscode/
node_modules/ node_modules/
/dist/
-434
View File
@@ -1,434 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP</artifactId>
<packaging>jar</packaging>
<version>3.6.15</version>
<!-- Upload patches to https://repo.ronanplugins.com/#/ -->
<properties>
<bettersync.version>2.0.0</bettersync.version>
<maven.compiler.release>8</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<editor.website>https://www.minecentral.net</editor.website>
<editor.buildSuffix></editor.buildSuffix>
</properties>
<profiles>
<profile>
<id>dev</id>
<build>
<plugins>
<plugin>
<!-- Local Server Building -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<configuration>
<outputDirectory>${project.basedir}/../../../Java/plugins</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<finalName>${project.artifactId}-${project.version}${editor.buildSuffix}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<configuration>
<outputDirectory>${project.basedir}/../dist</outputDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.4</version>
</plugin>
<plugin>
<!-- Shade PaperLib into project -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml
</dependencyReducedPomLocation>
<relocations>
<relocation><pattern>com.ronanplugins.bettersync</pattern><shadedPattern>me.SuperRonanCraft.BetterRTP.lib.bettersync</shadedPattern></relocation>
<relocation>
<pattern>io.papermc.lib</pattern>
<shadedPattern>me.SuperRonanCraft.BetterRTP.lib.paperlib</shadedPattern>
</relocation>
<relocation>
<pattern>com.tcoded.folialib</pattern>
<shadedPattern>me.SuperRonanCraft.BetterRTP.lib.folialib</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<!-- Remove only Shade's unbundled backup, after the final JAR is ready. -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<filesets>
<fileset>
<directory>${project.basedir}/../dist</directory>
<includes>
<include>${project.artifactId}-*.jar</include>
<include>original-${project.artifactId}-*.jar</include>
</includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
<executions>
<execution>
<id>remove-unshaded-backup</id>
<phase>package</phase>
<goals><goal>clean</goal></goals>
<configuration>
<excludeDefaultDirectories>true</excludeDefaultDirectories>
<filesets combine.self="override">
<fileset>
<directory>${project.basedir}/../dist</directory>
<includes><include>original-${project.build.finalName}.jar</include></includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<!-- CAN BE UNCOMMENTED IF YOU HAVE ACCESS TO THE REPO -->
<!--<repository>
<id>ronanplugins-private</id>
<name>RonanPlugins Repository</name>
<url>https://repo.ronanplugins.com/private</url>
</repository>-->
<!-- GitHub based Repos -->
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<!-- FoliaLib Repo -->
<repository>
<id>tcoded-releases</id>
<url>https://repo.tcoded.com/releases</url>
</repository>
<!-- Spigot Repo -->
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<!-- PaperMC Repo -->
<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<!-- Vault Repo -->
<repository>
<id>vault-repo</id>
<url>https://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<!-- WorldGuard Repo -->
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<!-- ProjectRed Repo -->
<repository>
<id>redprotect-repo</id>
<url>https://raw.githubusercontent.com/FabioZumbi12/RedProtect/mvn-repo/</url>
</repository>
<!-- FactionsUUID Repo -->
<repository>
<id>factions-uuid</id>
<url>https://ci.ender.zone/plugin/repository/everything/</url>
</repository>
<!-- ProtocolLib Repo -->
<repository>
<id>dmulloy2-repo</id>
<url>https://repo.dmulloy2.net/nexus/repository/public/</url>
</repository>
<!-- EssentialsX Repo -->
<repository>
<id>essentials-releases</id>
<url>https://repo.essentialsx.net/releases/</url>
</repository>
<!-- PlaceholderAPI Repo -->
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<!-- MinePlots Repo -->
<repository>
<id>minecodes-repository-releases</id>
<name>mineCodes Organization Repository</name>
<url>https://repository.minecodes.pl/releases</url>
</repository>
<!-- Used by Husk plugins -->
<repository>
<id>william278-releases</id>
<url>https://repo.william278.net/releases</url>
</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>
<artifactId>BetterSync</artifactId>
<version>${bettersync.version}</version>
</dependency>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Spigot Stuff -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Vault -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<!-- Paper Library for Async Chunk/Teleport -->
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.8</version>
<scope>compile</scope>
</dependency>
<!-- WorldGuard (https://dev.bukkit.org/projects/worldguard) -->
<dependency> <!-- Saber Factions screws up if updated -->
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<!-- RedProtect (https://www.spigotmc.org/resources/redprotect.15841/) -->
<dependency>
<groupId>br.net.fabiozumbi12.RedProtect</groupId>
<artifactId>RedProtect-Core</artifactId>
<version>7.7.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>br.net.fabiozumbi12.RedProtect</groupId>
<artifactId>RedProtect-Spigot-1.13</artifactId>
<version>7.7.3</version>
<scope>provided</scope>
</dependency>
<!-- FactionsUUID (https://www.spigotmc.org/resources/factionsuuid.1035/) -->
<dependency>
<groupId>com.massivecraft</groupId>
<artifactId>Factions</artifactId>
<version>1.6.9.5-U0.6.8</version>
<scope>provided</scope>
</dependency>
<!-- Lands (https://www.spigotmc.org/resources/lands.53313/) -->
<dependency>
<groupId>com.github.angeschossen</groupId>
<artifactId>LandsAPI</artifactId>
<version>6.28.11</version>
<scope>provided</scope>
</dependency>
<!-- ProtocolLib -->
<dependency>
<groupId>com.comphenix.protocol</groupId>
<artifactId>ProtocolLib</artifactId>
<version>5.3.0</version>
<scope>provided</scope>
</dependency>
<!-- Towny (https://www.spigotmc.org/resources/towny.72694/) -->
<dependency>
<groupId>com.github.TownyAdvanced</groupId>
<artifactId>Towny</artifactId>
<version>0.98.6.6</version>
<scope>provided</scope>
</dependency>
<!-- GriefPrevention (https://www.spigotmc.org/resources/griefprevention.1884/) -->
<dependency>
<groupId>com.github.TechFortress</groupId>
<artifactId>GriefPrevention</artifactId>
<version>17.0.0</version>
<scope>provided</scope>
</dependency>
<!-- KingdomsX (https://www.spigotmc.org/resources/kingdomsx.77670/) -->
<dependency>
<groupId>com.github.cryptomorin</groupId>
<artifactId>kingdoms</artifactId>
<version>1.16.8.1.1</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- GriefDefender (https://www.spigotmc.org/resources/griefdefender.68900/) -->
<dependency>
<groupId>com.github.bloodmc</groupId>
<artifactId>GriefDefenderApi</artifactId>
<version>920a610</version>
<scope>provided</scope>
</dependency>
<!-- Peublos (https://www.spigotmc.org/resources/pueblos.91255/) -->
<dependency>
<groupId>com.github.SuperRonanCraft</groupId>
<artifactId>Pueblos</artifactId>
<version>97b96c9</version>
<scope>provided</scope>
</dependency>
<!-- Particles Library
https://github.com/ByteZ1337/ParticleLib
(https://github.com/ByteZ1337/ParticleLib/blob/master/src/main/java/xyz/xenondevs/particle/ParticleEffect.java) -->
<dependency>
<groupId>xyz.xenondevs</groupId>
<artifactId>particle</artifactId>
<version>1.8.4</version>
<scope>compile</scope>
</dependency>
<!-- Lombok Support (@Getter & @Setter)-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.38</version>
<scope>provided</scope>
</dependency>
<!-- EssentialsX -->
<dependency>
<groupId>net.essentialsx</groupId>
<artifactId>EssentialsX</artifactId>
<version>2.21.0</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Saber Factions (https://www.spigotmc.org/resources/saberfactions.69771/) (Added in 3.4.5)-->
<dependency> <!-- WorldGuard screws up if updated -->
<groupId>com.github.SaberLLC</groupId>
<artifactId>Saber-Factions</artifactId>
<version>2.4.0-RC</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- PlaceholderAPI Support (Added in 3.4.5)-->
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.6</version>
<scope>provided</scope>
</dependency>
<!-- HuskClaims (https://www.spigotmc.org/resources/huskclaims.114467/) (Added in 3.6.13)-->
<dependency>
<groupId>net.william278.huskclaims</groupId>
<artifactId>huskclaims-bukkit</artifactId>
<version>1.5.10</version>
<scope>provided</scope>
</dependency>
<!-- Husktown (https://www.spigotmc.org/resources/husktowns.92672/) (Added in 3.4.5)-->
<dependency>
<groupId>net.william278.husktowns</groupId>
<artifactId>husktowns-bukkit</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
<!-- MinePlots (https://builtbybit.com/resources/mineplots.21646/) (Added in 3.6.6 ) -->
<dependency>
<groupId>pl.minecodes.plots</groupId>
<artifactId>plugin-api</artifactId>
<version>3.4.5</version>
<scope>provided</scope>
</dependency>
<!-- FoliaLib -->
<dependency>
<groupId>com.tcoded</groupId>
<artifactId>FoliaLib</artifactId>
<version>0.5.1</version>
<scope>compile</scope>
</dependency>
<!-- FactionsBridge -->
<dependency>
<groupId>com.dansplugins.factionsystem</groupId>
<artifactId>FactionsBridge</artifactId>
<version>1.3.8</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/FactionsBridge-1.3.8.jar</systemPath>
</dependency>
<dependency>
<groupId>com.github.WhipDevelopment</groupId>
<artifactId>CrashClaim</artifactId>
<version>c697d3e9ef</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.bekvon.bukkit.residence</groupId>
<artifactId>Residence</artifactId>
<version>5.1.4.1</version>
<scope>system</scope>
<optional>true</optional>
<systemPath>${project.basedir}/../lib/Residence5.1.4.1.jar</systemPath>
</dependency>
</dependencies>
</project>
@@ -1,28 +0,0 @@
package me.SuperRonanCraft.BetterRTP.player.commands.types;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommand;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommandHelpable;
import me.SuperRonanCraft.BetterRTP.references.PermissionNode;
import me.SuperRonanCraft.BetterRTP.references.messages.MessagesHelp;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
public class CmdEditor implements RTPCommand, RTPCommandHelpable {
public String getName() { return "editor"; }
public PermissionNode permission() { return PermissionNode.EDITOR; }
public List<String> tabComplete(CommandSender sender, String[] args) {
return Collections.emptyList();
}
public void execute(CommandSender sender, String label, String[] args) {
if (args.length == 1) BetterRTP.getInstance().getEditorBridge().upload(sender);
else sender.sendMessage("Usage: /" + label + " editor");
}
@Override
public String getHelp() {
return MessagesHelp.EDITOR.get();
}
}
@@ -1,21 +0,0 @@
package me.SuperRonanCraft.BetterRTP.player.commands.types;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommand;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommandHelpable;
import me.SuperRonanCraft.BetterRTP.references.PermissionNode;
import me.SuperRonanCraft.BetterRTP.references.messages.MessagesHelp;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
public class CmdEditorSync implements RTPCommand, RTPCommandHelpable {
public String getName() { return "editorsync"; }
public PermissionNode permission() { return PermissionNode.EDITOR; }
public List<String> tabComplete(CommandSender sender, String[] args) { return Collections.emptyList(); }
public void execute(CommandSender sender, String label, String[] args) {
if (args.length == 2) BetterRTP.getInstance().getEditorBridge().redeem(sender, args[1]);
else sender.sendMessage("Usage: /" + label + " editorsync <token>");
}
public String getHelp() { return MessagesHelp.EDITOR_SYNC.get(); }
}
@@ -1,95 +0,0 @@
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();
}
});
}
}
}
@@ -1,18 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references;
import me.SuperRonanCraft.BetterRTP.references.depends.DepPerms;
import org.bukkit.command.CommandSender;
public class Permissions {
private final DepPerms depPerms = new DepPerms();
public void register() {
depPerms.register();
}
public boolean checkPerm(String str, CommandSender sendi) {
return depPerms.hasPerm(str, sendi);
}
}
@@ -1,108 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
public class DatabasePlayers extends SQLite {
public DatabasePlayers() {
super(DATABASE_TYPE.PLAYERS);
}
@Override
public List<String> getTables() {
List<String> list = new ArrayList<>();
list.add("Players");
return list;
}
public enum COLUMNS {
UUID("uuid", "varchar(32) PRIMARY KEY"),
//COOLDOWN DATA
COUNT("count", "long"),
LAST_COOLDOWN_DATE("last_rtp_date", "long"),
;
public final String name;
public final String type;
COLUMNS(String name, String type) {
this.name = name;
this.type = type;
}
}
/** 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;
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);
}
return null;
}).get();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/** Compatibility entry point: capture before deferring database work. */
public void setData(PlayerData data) {
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 = java.util.Arrays.asList(data.uuid.toString(), data.count, data.cooldown);
sqlUpdate(sql, params);
});
}
}
@@ -1,184 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references.database;
import lombok.Getter;
import lombok.NonNull;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.rtpinfo.QueueData;
import me.SuperRonanCraft.BetterRTP.references.rtpinfo.QueueGenerator;
import me.SuperRonanCraft.BetterRTP.references.rtpinfo.QueueHandler;
import me.SuperRonanCraft.BetterRTP.references.rtpinfo.worlds.RTPWorld;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
public class DatabaseQueue extends SQLite {
public DatabaseQueue() {
super(DATABASE_TYPE.QUEUE);
}
@Override
public List<String> getTables() {
List<String> list = new ArrayList<>();
list.add("Queue");
return list;
}
public enum COLUMNS {
ID("id", "integer PRIMARY KEY AUTOINCREMENT"),
//Location Data
X("x", "long"),
Z("z", "long"),
WORLD("world", "varchar(32)"),
GENERATED("generated", "long")
;
public final String name;
public final String type;
COLUMNS(String name, String type) {
this.name = name;
this.type = type;
}
}
@Override public void load() {
if (QueueHandler.isEnabled())
super.load();
}
public List<QueueData> getInRange(QueueRangeData range) {
final List<QueueData> queueDataList = new ArrayList<>();
try {
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.WORLD.name + " = '" + range.getWorld().getName() + "' AND "
+ COLUMNS.X.name + " BETWEEN " + range.getXLow() + " AND " + range.getXHigh()
+ " AND " + COLUMNS.Z.name + " BETWEEN " + range.getZLow() + " AND " + range.getZHigh()
+ " ORDER BY RANDOM() LIMIT " + (QueueGenerator.queueMax + 1)
);
rs = ps.executeQuery();
while (rs.next()) {
long x = rs.getLong(COLUMNS.X.name);
long z = rs.getLong(COLUMNS.Z.name);
String worldName = rs.getString(COLUMNS.WORLD.name);
int id = rs.getInt(COLUMNS.ID.name);
long generated = rs.getLong(COLUMNS.GENERATED.name);
World world = Bukkit.getWorld(worldName);
if (world != null) {
queueDataList.add(new QueueData(new Location(world, x, 69, z), generated, id));
}
}
} catch (SQLException ex) {
BetterRTP.getInstance().getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
close(ps, rs, conn);
}
}).get();
} catch (Exception ex) {
ex.printStackTrace();
}
return queueDataList;
}
//Set a queue to save
public QueueData addQueue(Location loc) {
try {
return SQLiteExecutor.EXECUTOR.submit(() -> {
String sql = "INSERT INTO " + tables.get(0) + " ("
+ COLUMNS.X.name + ", "
+ COLUMNS.Z.name + ", "
+ COLUMNS.WORLD.name + ", "
+ COLUMNS.GENERATED.name + ") VALUES(?, ?, ?, ?)";
List<Object> params = new ArrayList<Object>() {{
add(loc.getBlockX());
add(loc.getBlockZ());
add(loc.getWorld().getName());
add(System.currentTimeMillis());
}};
int database_id = createQueue(sql, params);
return database_id >= 0 ? new QueueData(loc, System.currentTimeMillis(), database_id) : null;
}).get();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private int createQueue(String statement, @NonNull List<Object> params) {
Connection conn = null;
PreparedStatement ps = null;
int id = -1;
try {
conn = getSQLConnection();
ps = conn.prepareStatement(statement, Statement.RETURN_GENERATED_KEYS);
Iterator<Object> it = params.iterator();
int paramIndex = 1;
while (it.hasNext()) {
ps.setObject(paramIndex, it.next());
paramIndex++;
}
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
id = rs.getInt(1);
}
} catch (SQLException ex) {
BetterRTP.getInstance().getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
close(ps, null, conn);
}
return id;
}
public boolean removeLocation(Location loc) {
try {
return SQLiteExecutor.EXECUTOR.submit(() -> {
String sql = "DELETE FROM " + tables.get(0) + " WHERE "
+ COLUMNS.X.name + " = ? AND "
+ COLUMNS.Z.name + " = ? AND "
+ COLUMNS.WORLD.name + " = ?";
List<Object> params = new ArrayList<Object>() {{
add(loc.getBlockX());
add(loc.getBlockZ());
add(loc.getWorld().getName());
}};
return sqlUpdate(sql, params);
}).get();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
@Getter
public static class QueueRangeData {
int xLow, xHigh;
int zLow, zHigh;
World world;
public QueueRangeData(RTPWorld rtpWorld) {
this.xLow = rtpWorld.getCenterX() - rtpWorld.getMaxRadius();
this.xHigh = rtpWorld.getCenterX() + rtpWorld.getMaxRadius();
this.zLow = rtpWorld.getCenterZ() - rtpWorld.getMaxRadius();
this.zHigh = rtpWorld.getCenterZ() + rtpWorld.getMaxRadius();
this.world = rtpWorld.getWorld();
}
}
}
@@ -1,8 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references.database;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SQLiteExecutor {
public static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
}
@@ -1,21 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references.depends.regionPlugins;
import net.william278.huskclaims.BukkitHuskClaims;
import net.william278.huskclaims.api.BukkitHuskClaimsAPI;
import org.bukkit.Location;
public class RTP_HuskClaims implements RegionPluginCheck {
@Override
public boolean check(Location loc) {
boolean result = true;
if (REGIONPLUGINS.HUSKCLAIMS.isEnabled()) {
try {
result = !BukkitHuskClaimsAPI.getInstance().getClaimAt(BukkitHuskClaims.Adapter.adapt(loc)).isPresent();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
@@ -1,50 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references.player.playerdata;
import lombok.NonNull;
import org.bukkit.entity.Player;
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<>();
/** 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
public PlayerData getData(UUID id) {
return playerData.get(id);
}
public void clear() {
playerData.clear();
}
public void clear(Player p) {
playerData.computeIfPresent(p.getUniqueId(), (id, data) -> data.player == p ? null : data);
}
}
@@ -1,109 +0,0 @@
package me.SuperRonanCraft.BetterRTP.references.web;
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.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.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;
/** Returns the validated viewing URL, or null when the upload fails. */
@Nullable
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) {
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) {
return null;
}
}
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;
}
}
}
@@ -1,2 +0,0 @@
# Build metadata embedded in the JAR; not a server configuration file.
website=${editor.website}
@@ -1,397 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://schemas.ronanplugins.com/betterrtp/2",
"title": "BetterRTP editor configuration",
"type": "object",
"properties": {
"Settings": {
"type": "object",
"properties": {
"Respect": {
"type": "object",
"properties": {
"MinePlots": {
"type": "boolean"
},
"WorldGuard": {
"type": "boolean"
},
"GriefPrevention": {
"type": "boolean"
},
"Towny": {
"type": "boolean"
},
"RedProtect": {
"type": "boolean"
},
"FactionsUUID": {
"type": "boolean"
},
"Lands": {
"type": "boolean"
},
"Residence": {
"type": "boolean"
},
"KingdomsX": {
"type": "boolean"
},
"hClaims": {
"type": "boolean"
},
"GriefDefender": {
"type": "boolean"
},
"UltimateClaims": {
"type": "boolean"
},
"Pueblos": {
"type": "boolean"
},
"SaberFactions": {
"type": "boolean"
},
"HuskClaims": {
"type": "boolean"
},
"HuskTowns": {
"type": "boolean"
},
"FactionsBridge": {
"type": "boolean"
},
"CrashClaim": {
"type": "boolean"
}
}
},
"Debugger": {
"type": "boolean"
},
"PreloadRadius": {
"type": "number"
},
"MaxAttempts": {
"type": "number"
},
"RtpOnFirstJoin": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"World": {
"type": "string"
},
"SetAsRespawn": {
"type": "boolean"
}
}
},
"Cooldown": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"LockAfter": {
"type": "number"
},
"Time": {
"type": "number"
},
"PerWorld": {
"type": "boolean"
}
}
},
"Delay": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"Time": {
"type": "number"
},
"CancelOnMove": {
"type": "boolean"
}
}
},
"Queue": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
}
}
},
"DisableUpdater": {
"type": "boolean"
},
"Logger": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"LogToConsole": {
"type": "boolean"
},
"Format": {
"type": "string"
}
}
}
}
},
"Default": {
"type": "object",
"properties": {
"Biomes": {
"type": "array",
"items": {
"type": "string"
}
},
"UseWorldBorder": {
"type": "boolean"
},
"MaxRadius": {
"type": "number"
},
"MinRadius": {
"type": "number"
},
"CenterX": {
"type": "number"
},
"CenterZ": {
"type": "number"
},
"Shape": {
"type": "string"
},
"MaxY": {
"type": "number"
},
"MinY": {
"type": "number"
},
"RTPOnDeath": {
"type": "boolean"
}
}
},
"Language-File": {
"type": "string",
"description": "Change the language file locally."
},
"BlacklistedBlocks": {
"type": "array",
"items": {
"type": "string"
}
},
"DisabledWorlds": {
"type": "array",
"items": {
"type": "string"
}
},
"Overrides": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"x-editor": {
"collection": "overrides"
}
},
"WorldType": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "string",
"enum": [
"NORMAL",
"NETHER"
],
"x-caseInsensitive": true
}
},
"x-editor": {
"collection": "types"
}
},
"CustomWorlds": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"UseWorldBorder": {
"type": "boolean",
"default": false
},
"MaxRadius": {
"type": "integer",
"default": 1000
},
"MinRadius": {
"type": "integer",
"default": 10
},
"CenterX": {
"type": "integer",
"default": 0
},
"CenterZ": {
"type": "integer",
"default": 0
},
"Price": {
"type": "integer",
"default": 0
},
"Shape": {
"type": "string",
"default": "square"
},
"MaxY": {
"type": "integer",
"default": 320
},
"MinY": {
"type": "integer",
"default": 0
},
"Cooldown": {
"type": "integer",
"default": 0
},
"RTPOnDeath": {
"type": "boolean",
"default": false
},
"Biomes": {
"type": "array",
"items": {
"type": "string"
}
}
},
"x-editableProperties": true,
"x-inherit": "Default"
}
},
"x-editor": {
"collection": "worlds"
}
},
"PermissionGroup": {
"type": "object",
"properties": {
"Groups": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"UseWorldBorder": {
"type": "boolean",
"default": false
},
"MaxRadius": {
"type": "integer",
"default": 1000
},
"MinRadius": {
"type": "integer",
"default": 10
},
"CenterX": {
"type": "integer",
"default": 0
},
"CenterZ": {
"type": "integer",
"default": 0
},
"Price": {
"type": "integer",
"default": 0
},
"Shape": {
"type": "string",
"default": "square"
},
"MaxY": {
"type": "integer",
"default": 320
},
"MinY": {
"type": "integer",
"default": 0
},
"Cooldown": {
"type": "integer",
"default": 0
},
"RTPOnDeath": {
"type": "boolean",
"default": false
},
"Biomes": {
"type": "array",
"items": {
"type": "string"
}
},
"Priority": {
"type": "integer",
"default": 0
}
},
"x-editableProperties": true,
"x-inherit": "Default"
}
},
"x-editor": {
"collection": "worlds"
}
}
},
"x-editor": {
"collection": "groups"
}
},
"Enabled": {
"type": "boolean"
}
}
}
},
"x-bettersync": {
"format": 1,
"plugin": "betterrtp",
"schemaVersion": "2",
"displayName": "BetterRTP"
},
"required": [
"Settings",
"Default"
]
}
@@ -1,65 +0,0 @@
# Ajude a traduzir este arquivo para mais idiomas!
Messages:
Prefix: '&7[&6BetterRTP&7] '
Success: ## Marcadores! %x% %y% e %z% são as coordenadas x, y, e z para as quais o jogador está sendo teleportado! #
Paid: '&aVocê foi teleportado para&7 x=%x% y=%y% z=%z% por &c$%price%&7!'
Bypass: '&aVocê foi teleportado para&7 x=%x% y=%y% z=%z%'
Loading: '&aLocal seguro localizado! &7Carregando chunks...'
Teleport: '&aTeleportando... &fpor favor, aguarde enquanto encontramos um local seguro!'
Failed:
Price: '&cNão foi possível teletransportar porque não há fundos suficientes! &7Você precisa de pelo menos $%price% &7para rtp!'
NotSafe: '&cNão foi possível encontrar um local seguro em %attempts% tentativas! &7Você não foi teleportado!'
Hunger: '&cNão foi possível teletransportar porque você está... &7com fome demais&c, coma algo!'
Other:
Success: '&a%player% foi teleportado para&7 x=%x% y=%y% z=%z%'
NotSafe: '&cNão foi possível encontrar um local seguro em %attempts% tentativas! &7%player% não foi teleportado!'
Biome: '&cParece que o bioma&7 %biome%&c não existe! &7Tente usar a lista de abas!'
Reload: '&eConfiguração recarregada com sucesso!'
Update: '&7Há uma atualização disponível para &6BetterRTP &7versão &e#%newVersion% &7você tem a versão &e#%currentVersion%'
NoPermission:
Basic: '&cDesculpe! &7Você não tem permissão para usar este comando! &8Permissão: %permission%'
World: '&cDesculpe! &7Você não tem permissão para rtp no mundo %world%! &8Permissão: %permission%'
DisabledWorld: '&cMundo desativado %world%! &7Não foi possível teleportar!'
Cooldown: '&cDesculpe! &7Você não pode usar rtp por mais &c%time%&7!'
Locked: '&cDesculpe! &7Você já usou todos os seus RTPs!'
Invalid: '&cArgumento inválido. Tente ''/%command% help'''
NotOnline: '&cO jogador &7%player% &cnão está online!'
Delay: '&aTeleportando em &f%time% &asegundos! Não se mova!'
Moved: '&cVocê se moveu! &7O RTP foi cancelado!'
NotExist: '&cParece que o mundo &7%world% &cnão existe!'
Already: '&cOps! &7Parece que você já está usando rtp, tenha um pouco de paciência!'
Sign: '&7Sinal de comando criado! &7O comando é... ''&f/rtp %command%&7'''
Edit:
Error: '&cErro! &7Entrada inválida fornecida!'
Set: '&bSucesso! &7%type% definido para %value%'
Remove: '&cRemovido! &7Você removeu o Mundo Personalizado %world%'
Help:
Prefix: '&e&m-----&6&l BetterRTP &8| Ajuda &e&m-----'
Main: ' &7- &e/%command% &7- Teletransporta você aleatoriamente!'
Biome: ' &7- &e/%command% biome <biome1, biome2...> &7- Teletransporta aleatoriamente dentro desses biomas'
Edit: ' &7- &e/%command% edit <default/world> [args...] &7- Edita algumas configurações do plugin'
Help: ' &7- &e/%command% help &7- Mostra a lista de ajuda'
Info: ' &7- &e/%command% info [world/particles/shapes/potion_effects] &7- Visualiza informações específicas sobre parâmetros do plugin'
Player: ' &7- &e/%command% player <player> [world] [biome1, biome2...] &7- Teletransporta outro jogador aleatoriamente'
Reload: ' &7- &e/%command% reload &7- Recarrega o plugin'
Settings: ' &7- &e/%command% settings &7- Abre uma GUI para editar algumas configurações'
Test: ' &7- &e/%command% test &7- Testa os efeitos do plugin após um teletransporte sem se mover'
Version: ' &7- &e/%command% version &7- Visualiza a versão atual em execução'
World: ' &7- &e/%command% world <world> [biome1, biome2...] &7- Teletransporta aleatoriamente em outro mundo'
Location: ' &7- &e/%command% location <location_name> &7- Teletransporta usando uma localização específica'
Usage:
Player: '&cUso&7: /%command% player <player> [world] [biome1, biome2]'
World: '&cUso&7: /%command% world <world> [biome1, biome2...]'
Biome: '&cUso&7: /%command% biome <biome1, biome2...>'
Location: '&cUso&7: /%command% location <location_name>'
Edit:
Base: '&cUso&7: /%command% edit <default/world> [args...]'
Default: '&cUso&7: /%command% edit default <max/min/useworldborder/center> <value>'
World: '&cUso&7: /%command% edit customworld <world> <max/min/useworldborder/center> <value>'
PermissionGroup: '&cUso&7: /%command% edit permission_group <group> <world> <max/min/useworldborder/center> <value>'
Location: '&cUso&7: /%command% edit location <location_name> <max/min/useworldborder/center> <value>'
Worldtype: '&cUso&7: /%command% edit world_type <world> <NETHER/NORMAL>'
Override: '&cUso&7: /%command% edit override <world> <world_to>'
BlacklistedBlocks: '&cUso&7: /%command% edit blacklistedblocks <add/remove> <block_id>'
@@ -1,180 +0,0 @@
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);
}
}
}
@@ -1,116 +0,0 @@
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())));
}
}
-16
View File
@@ -5,20 +5,6 @@
BetterRTP-Addons is a paid resource, adding optional middleware to BetterRTP to help financially support the developement of BetterRTP. BetterRTP-Addons is a paid resource, adding optional middleware to BetterRTP to help financially support the developement of BetterRTP.
But this can be compiled free of charge if you know how to compile maven resources! But this can be compiled free of charge if you know how to compile maven resources!
## Web configuration editor
[Open the BetterRTP Addons editor](https://www.minecentral.net/editor/betterrtp-addons) to start with defaults or upload config.yml. Edit addon toggles, menus, command lists, and flashback warnings. Install the matching updated BetterRTP JAR too: Addons shares its editor bridge.
1. Run `/rtp addons editor` on your server and open the private link it returns.
2. Edit the form or YAML and choose **Save and get sync command**.
3. Run `/betterrtp addons editorsync <token>` in Minecraft to apply that saved version.
Console and players with `betterrtp.addon.editor` (default: op) can use both commands. No account or premium is required for editing, downloading, or command sync. Upload links last 24 hours; each sync command works once and expires after 15 minutes. Keep links and commands private.
Sync validates config.yml, saves a backup in `editor-backups`, then replaces the file and reloads the plugin. Nothing changes until the sync command runs. If reload fails after writing, the new file remains in place and Minecraft reports the error.
Shared behavior, deployment, and verification are documented in the [webapp repository](https://github.com/RonanPlugins/BetterRTP-Webapp/blob/main/docs/web-editor.md#addons-deployment).
## Where's the Lang files?/Want to Contribute translating? ## Where's the Lang files?/Want to Contribute translating?
All language files are located [here](src/main/resources/lang) All language files are located [here](src/main/resources/lang)
feel free to fork one of the language files and help translate! feel free to fork one of the language files and help translate!
@@ -42,5 +28,3 @@ The wiki is available [here](../../../wiki)!
<br/> <br/>
<b><i><a href="https://www.spigotmc.org/resources/authors/superronancraft.13025/">Check out my other plugins!</a></i></b> <b><i><a href="https://www.spigotmc.org/resources/authors/superronancraft.13025/">Check out my other plugins!</a></i></b>
</p> </p>
Build both BetterRTP and Addons together by running `mvn clean package` from the parent BetterRTP directory. Both finished JARs are written to the parent directory’s `dist/` folder.
+14 -82
View File
@@ -7,26 +7,13 @@
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTPAddons</artifactId> <artifactId>BetterRTPAddons</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>1.8.10</version> <version>1.8.8</version>
<properties> <properties>
<editor.website>https://www.minecentral.net</editor.website>
<bettersync.version>2.0.0</bettersync.version>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<profiles>
<profile>
<id>dev</id>
<build><plugins><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration><outputDirectory>../../../Java/plugins</outputDirectory></configuration>
</plugin></plugins></build>
</profile>
</profiles>
<build> <build>
<resources> <resources>
<resource> <resource>
@@ -36,14 +23,6 @@
</resources> </resources>
<finalName>${project.artifactId}-${project.version}</finalName> <finalName>${project.artifactId}-${project.version}</finalName>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<configuration>
<outputDirectory>${project.basedir}/../dist</outputDirectory>
</configuration>
</plugin>
<plugin> <plugin>
<!-- Shade PaperLib into project --> <!-- Shade PaperLib into project -->
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
@@ -52,8 +31,6 @@
<configuration> <configuration>
<dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation> <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
<relocations> <relocations>
<relocation><pattern>com.ronanplugins.bettersync</pattern><shadedPattern>me.SuperRonanCraft.BetterRTPAddons.lib.bettersync</shadedPattern></relocation>
<relocation> <relocation>
<pattern>io.papermc.lib</pattern> <pattern>io.papermc.lib</pattern>
<shadedPattern>me.SuperRonanCraft.BetterRTPAddons.paperlib</shadedPattern> <shadedPattern>me.SuperRonanCraft.BetterRTPAddons.paperlib</shadedPattern>
@@ -69,6 +46,15 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<!-- Local Server Building -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<outputDirectory>../../../Java/plugins</outputDirectory>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
@@ -78,49 +64,10 @@
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<!-- Remove only Shade's unbundled backup, after the final JAR is ready. -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<filesets>
<fileset>
<directory>${project.basedir}/../dist</directory>
<includes>
<include>${project.artifactId}-*.jar</include>
<include>original-${project.artifactId}-*.jar</include>
</includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
<executions>
<execution>
<id>remove-unshaded-backup</id>
<phase>package</phase>
<goals><goal>clean</goal></goals>
<configuration>
<excludeDefaultDirectories>true</excludeDefaultDirectories>
<filesets combine.self="override">
<fileset>
<directory>${project.basedir}/../dist</directory>
<includes><include>original-${project.build.finalName}.jar</include></includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository>
<id>minecodes-repository-releases</id>
<url>https://repository.minecodes.pl/releases</url>
</repository>
<repository> <repository>
<id>spigot-repo</id> <id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
@@ -128,22 +75,15 @@
<!-- PaperMC Repo --> <!-- PaperMC Repo -->
<repository> <repository>
<id>papermc</id> <id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url> <url>https://papermc.io/repo/repository/maven-public/</url>
</repository> </repository>
<!-- ProtocolLib Repo --> <!-- ProtocolLib Repo -->
<repository> <repository>
<id>dmulloy2-repo</id> <id>dmulloy2-repo</id>
<url>https://repo.dmulloy2.net/nexus/repository/public/</url> <url>https://repo.dmulloy2.net/nexus/repository/public/</url>
</repository> </repository>
<repository><id>jitpack.io</id><url>https://jitpack.io</url></repository>
</repositories> </repositories>
<dependencies> <dependencies>
<!-- Download the tagged GitHub library through JitPack; bundled by Shade. -->
<dependency>
<groupId>com.github.RonanPlugins</groupId>
<artifactId>BetterSync</artifactId>
<version>${bettersync.version}</version>
</dependency>
<!--Spigot API--> <!--Spigot API-->
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
@@ -162,14 +102,14 @@
<dependency> <dependency>
<groupId>io.papermc</groupId> <groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId> <artifactId>paperlib</artifactId>
<version>1.0.8</version> <version>1.0.5</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!-- BetterRTP --> <!-- BetterRTP -->
<dependency> <dependency>
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP</artifactId> <artifactId>BetterRTP</artifactId>
<version>3.6.15</version> <version>LATEST</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- ProtocolLib --> <!-- ProtocolLib -->
@@ -178,19 +118,11 @@
<artifactId>ProtocolLib</artifactId> <artifactId>ProtocolLib</artifactId>
<version>4.5.0</version> <version>4.5.0</version>
<scope>provided</scope> <scope>provided</scope>
<exclusions>
<!-- ProtocolLib supplies its executor implementation; Addons does not use it.
Its legacy transitive snapshot is no longer available to fresh builds. -->
<exclusion>
<groupId>com.comphenix.executors</groupId>
<artifactId>BukkitExecutors</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.38</version> <version>1.18.22</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -33,14 +33,6 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
@Override @Override
public void execute(CommandSender sendi, String label, String[] args) { public void execute(CommandSender sendi, String label, String[] args) {
if (args.length >= 2 && (args[1].equalsIgnoreCase("editor") || args[1].equalsIgnoreCase("editorsync"))) {
Main plugin = Main.getInstance();
if (!plugin.canEdit(sendi)) { sendi.sendMessage("§cYou need betterrtp.addon.editor permission."); return; }
if (args[1].equalsIgnoreCase("editor") && args.length == 2) plugin.getEditorBridge().upload(sendi);
else if (args[1].equalsIgnoreCase("editorsync") && args.length == 3) plugin.getEditorBridge().redeem(sendi, args[2]);
else sendi.sendMessage("§eUsage: /" + label + " addons " + (args[1].equalsIgnoreCase("editor") ? "editor" : "editorsync <token>"));
return;
}
if (args.length == 2) { if (args.length == 2) {
for (AddonCmds cmds : AddonCmds.values()) { for (AddonCmds cmds : AddonCmds.values()) {
if (cmds.name().equalsIgnoreCase(args[1])) { if (cmds.name().equalsIgnoreCase(args[1])) {
@@ -52,7 +44,6 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
} else { } else {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
list.add(MessagesHelp.PREFIX.get()); list.add(MessagesHelp.PREFIX.get());
addEditorHelp(sendi, label, list);
for (AddonsHandler.Addons addon : Main.getInstance().getAddonsHandler().addons) { for (AddonsHandler.Addons addon : Main.getInstance().getAddonsHandler().addons) {
RTPCommand cmd = addon.getCmd(); RTPCommand cmd = addon.getCmd();
if (cmd instanceof RTPCommandHelpable) if (cmd instanceof RTPCommandHelpable)
@@ -66,10 +57,6 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
@Override @Override
public List<String> tabComplete(CommandSender sendi, String[] args) { public List<String> tabComplete(CommandSender sendi, String[] args) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
if (args.length == 2 && Main.getInstance().canEdit(sendi)) {
for (String command : new String[] { "editor", "editorsync" })
if (command.startsWith(args[1].toLowerCase(Locale.ROOT))) list.add(command);
}
if (args.length == 2) if (args.length == 2)
for (AddonCmds cmds : AddonCmds.values()) { for (AddonCmds cmds : AddonCmds.values()) {
if (cmds.name().toLowerCase().startsWith(args[1].toLowerCase())) if (cmds.name().toLowerCase().startsWith(args[1].toLowerCase()))
@@ -78,13 +65,6 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
return list; return list;
} }
public static void addEditorHelp(CommandSender sender, String label, List<String> list) {
if (Main.getInstance().canEdit(sender)) {
list.add("§7- §e/" + label + " addons editor §7- Open the Addons web editor");
list.add("§7- §e/" + label + " addons editorsync <token> §7- Apply a saved Addons config");
}
}
@Override @Override
public PermissionNode permission() { public PermissionNode permission() {
return PermissionNode.USE; return PermissionNode.USE;
@@ -30,7 +30,6 @@ public class AddonsHandler {
//addonCount++; //addonCount++;
} }
//Main.getInstance().getLogger().log(Level.INFO, addonCount + "/" + Addons.values().length + " addons were enabled!"); //Main.getInstance().getLogger().log(Level.INFO, addonCount + "/" + Addons.values().length + " addons were enabled!");
if (!BetterRTP.getInstance().getCmd().commands.contains(cmd))
HelperRTP_Command.registerCommand(cmd, false); HelperRTP_Command.registerCommand(cmd, false);
} }
@@ -1,9 +1,5 @@
package me.SuperRonanCraft.BetterRTPAddons; package me.SuperRonanCraft.BetterRTPAddons;
import com.ronanplugins.bettersync.editor.EditorClient;
import com.ronanplugins.bettersync.editor.EditorSchema;
import lombok.Getter;
import me.SuperRonanCraft.BetterRTPAddons.util.Files; import me.SuperRonanCraft.BetterRTPAddons.util.Files;
import me.SuperRonanCraft.BetterRTPAddons.util.ReloadListener; import me.SuperRonanCraft.BetterRTPAddons.util.ReloadListener;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -11,37 +7,21 @@ import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin { public class Main extends JavaPlugin {
@Getter
private static Main instance; private static Main instance;
@Getter
private final AddonsHandler addonsHandler = new AddonsHandler(); private final AddonsHandler addonsHandler = new AddonsHandler();
@Getter
private final Files files = new Files(); private final Files files = new Files();
public final AddonMessages msgs = new AddonMessages(); public final AddonMessages msgs = new AddonMessages();
private final ReloadListener reloadListener = new ReloadListener(); private final ReloadListener reloadListener = new ReloadListener();
@Getter
private EditorClient editorBridge;
public boolean canEdit(org.bukkit.command.CommandSender sender) {
return !(sender instanceof org.bukkit.entity.Player) || sender.hasPermission("betterrtp.addon.editor");
}
@Override @Override
public void onEnable() { public void onEnable() {
instance = this; instance = this;
Bukkit.getPluginManager().registerEvents(reloadListener, this); Bukkit.getPluginManager().registerEvents(reloadListener, this);
load(); load();
editorBridge = new EditorClient(
this, EditorSchema.load(this, "META-INF/editor-schema.json"),
EditorClient.website(this, "META-INF/betterrtp-addons-editor.properties"),
me.SuperRonanCraft.BetterRTP.versions.AsyncHandler::sync, sender -> load(),
this::canEdit, () -> Files.FILETYPE.CONFIG.getConfig().saveToString());
} }
@Override @Override
public void onDisable() { public void onDisable() {
if (editorBridge != null) editorBridge.close();
addonsHandler.unload(); addonsHandler.unload();
} }
@@ -50,4 +30,15 @@ public class Main extends JavaPlugin {
addonsHandler.load(); addonsHandler.load();
} }
public Files getFiles() {
return files;
}
public AddonsHandler getAddonsHandler() {
return addonsHandler;
}
public static Main getInstance() {
return instance;
}
} }
@@ -21,7 +21,6 @@ public class AddonsCommand_Help implements AddonsCommands, RTPCommandHelpable {
public void execute(CommandSender sendi, String label, String[] args) { public void execute(CommandSender sendi, String label, String[] args) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
list.add(MessagesHelp.PREFIX.get()); list.add(MessagesHelp.PREFIX.get());
AddonsCommand.addEditorHelp(sendi, label, list);
for (AddonsCommand.AddonCmds cmds : AddonsCommand.AddonCmds.values()) { for (AddonsCommand.AddonCmds cmds : AddonsCommand.AddonCmds.values()) {
if (cmds.cmd instanceof RTPCommandHelpable) if (cmds.cmd instanceof RTPCommandHelpable)
list.add(((RTPCommandHelpable) cmds.cmd).getHelp().replace("%command%", label)); list.add(((RTPCommandHelpable) cmds.cmd).getHelp().replace("%command%", label));
@@ -1,9 +1,17 @@
package me.SuperRonanCraft.BetterRTPAddons.cmds; package me.SuperRonanCraft.BetterRTPAddons.cmds;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommandHelpable;
import me.SuperRonanCraft.BetterRTP.references.messages.Message;
import me.SuperRonanCraft.BetterRTPAddons.AddonMessages;
import me.SuperRonanCraft.BetterRTPAddons.AddonsHandler;
import me.SuperRonanCraft.BetterRTPAddons.Main; import me.SuperRonanCraft.BetterRTPAddons.Main;
import me.SuperRonanCraft.BetterRTPAddons.util.Message_ADDONS; import me.SuperRonanCraft.BetterRTPAddons.util.Message_ADDONS;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class AddonsCommand_Version implements AddonsCommands { public class AddonsCommand_Version implements AddonsCommands {
@Override @Override
@@ -1 +0,0 @@
website=${editor.website}
@@ -1,245 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://schemas.ronanplugins.com/betterrtp-addons/2",
"title": "BetterRTP Addons editor configuration",
"type": "object",
"properties": {
"Flashback": {
"type": "object",
"properties": {
"Timer": {
"type": "object",
"properties": {
"Delay": {
"type": "number"
},
"Warnings": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"x-editor": {
"collection": "warnings"
}
}
}
},
"Enabled": {
"type": "boolean"
}
}
},
"Logger": {
"type": "object",
"properties": {
"Format": {
"type": "string"
},
"Enabled": {
"type": "boolean"
},
"LogToConsole": {
"type": "boolean"
}
}
},
"Portals": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"IgnoreDelay": {
"type": "boolean"
},
"IgnoreCooldown": {
"type": "boolean"
}
}
},
"ExtraEffects": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"YOffset": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"Offset": {
"type": "number"
}
}
}
}
},
"MagicStick": {
"type": "object",
"properties": {
"GiveFirstJoin": {
"type": "object",
"properties": {
"Amount": {
"type": "integer"
},
"Enabled": {
"type": "boolean"
}
}
},
"Item": {
"type": "object",
"properties": {
"Material": {
"type": "string"
},
"Name": {
"type": "string"
},
"Lore": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Enabled": {
"type": "boolean"
},
"Take": {
"type": "boolean"
}
}
},
"Commands": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"Events": {
"type": "object",
"properties": {
"Teleport": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"Commands": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Cancelled": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
},
"Commands": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
}
},
"Parties": {
"type": "object",
"properties": {
"Enabled": {
"type": "boolean"
}
}
},
"RTPMenu": {
"type": "object",
"properties": {
"Lines": {
"type": "integer"
},
"AutoRefresh": {
"type": "number"
},
"WorldList": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"Name": {
"type": "string",
"default": ""
},
"Item": {
"type": "string",
"default": "MAP"
},
"Slot": {
"type": "integer",
"default": 0
},
"Lore": {
"type": "array",
"items": {
"type": "string"
},
"default": []
}
},
"x-editableProperties": true
}
},
"x-editor": {
"collection": "menu"
}
},
"Enabled": {
"type": "boolean"
},
"Title": {
"type": "string"
},
"AutoCenter": {
"type": "boolean"
}
}
},
"Language-File": {
"type": "string",
"description": "Change the language file locally."
}
},
"x-bettersync": {
"format": 1,
"plugin": "betterrtp-addons",
"schemaVersion": "2",
"displayName": "BetterRTP Addons"
},
"required": [
"Flashback",
"Logger",
"Portals",
"ExtraEffects",
"MagicStick",
"Commands",
"Parties",
"RTPMenu"
]
}
@@ -7,9 +7,6 @@ depend: [BetterRTP]
softdepend: [ProtocolLib] softdepend: [ProtocolLib]
permissions: permissions:
betterrtp.addon.editor:
description: Open and sync the BetterRTP Addons web editor
default: op
betterrtp.addon.portals: betterrtp.addon.portals:
description: Ability to use the portals addon commands description: Ability to use the portals addon commands
+3 -81
View File
@@ -2,28 +2,8 @@
<b><a>Welcome to BetterRTP's repository!</a></b> <b><a>Welcome to BetterRTP's repository!</a></b>
</p> </p>
## Web configuration editor
[Open the BetterRTP editor](https://www.minecentral.net/editor/betterrtp) to start with defaults or upload config.yml. Edit world settings, teleport ranges, cooldowns, and supported lists.
1. Run `/rtp editor` on your server and open the private link it returns.
2. Edit the form or YAML and choose **Save and get sync command**.
3. Run `/betterrtp editorsync <token>` in Minecraft to apply that saved version.
Console and players with `betterrtp.editor` (default: op) can use both commands. No account or premium is required for editing, downloading, or command sync. Upload links last 24 hours; each sync command works once and expires after 15 minutes. Keep links and commands private.
Sync validates config.yml, saves a backup in `editor-backups`, then replaces the file and reloads the plugin. Nothing changes until the sync command runs. If reload fails after writing, the new file remains in place and Minecraft reports the error.
Shared behavior, deployment, and verification are documented in the [webapp repository](https://github.com/RonanPlugins/BetterRTP-Webapp/blob/main/docs/web-editor.md).
## Support log uploads
The logger, info, and queue upload actions share logs through `https://mclo.gs`. Uploads are manual and use the mclogs JSON API at `https://api.mclo.gs/1/log`. Files larger than 5 MiB are rejected locally. Uploads have connection/read timeouts, and failed or malformed responses show an upload error instead of a broken link.
No self-hosted log service, DNS setup, account pairing, or API key is required. Logs are uploaded to the third-party mclo.gs service only when the administrator chooses the upload action. Server owners need an updated BetterRTP JAR to use this endpoint.
## Where's the Lang files?/Want to Contribute translating? ## Where's the Lang files?/Want to Contribute translating?
All language files are located [here](BetterRTP-Core/src/main/resources/lang) All language files are located [here](src/main/resources/lang)
feel free to fork one of the language files and help translate! feel free to fork one of the language files and help translate!
## Libraries ## Libraries
@@ -35,14 +15,9 @@ BetterRTP uses and is compiled with the following libraries:
## Build instructions on Ubuntu ## Build instructions on Ubuntu
From this directory, run `mvn clean package` to build BetterRTP followed by BetterRTP Addons. Maven resolves Addons against the BetterRTP built in the same run; a separate `install` step is unnecessary. mvn clean install
- BetterRTP JAR: `dist/BetterRTP-3.6.15.jar` The file will be in the Target file.
- Addons JAR: `dist/BetterRTPAddons-1.8.10.jar`
Both server-ready JARs are collected in `dist/`. `mvn clean` removes each selected plugin’s previous JARs from this folder; intermediate build files stay in `target/`. The `dev` profile still outputs directly to its configured server plugins folder.
The root `pom.xml` aggregates both modules. Core plugin dependencies and build settings live in `BetterRTP-Core/pom.xml`; its sources live in `BetterRTP-Core/src/`. To build only the core plugin, use `mvn -pl :BetterRTP clean package`. Existing `-Deditor.website=...`, `-Deditor.buildSuffix=...`, and `-Pdev` options remain available.
## Where's the Wiki? ## Where's the Wiki?
The wiki is available [here](../../wiki)! The wiki is available [here](../../wiki)!
@@ -58,56 +33,3 @@ The wiki is available [here](../../wiki)!
<br/> <br/>
<b><i><a href="https://www.spigotmc.org/resources/authors/superronancraft.13025/">Check out my other plugins!</a></i></b> <b><i><a href="https://www.spigotmc.org/resources/authors/superronancraft.13025/">Check out my other plugins!</a></i></b>
</p> </p>
## Shared editor library
The web editor uses [BetterSync](https://github.com/RonanPlugins/BetterSync),
downloaded by Maven from JitPack as `com.github.RonanPlugins:BetterSync:2.0.0`.
No local BetterSync project or manual Maven install is required. Release `2.0.0` is published on JitPack. Update `bettersync.version` in the plugin and editor-test
POMs together when upgrading. Shade bundles and relocates the library into the
plugin JAR; server owners do not install a separate BetterSync plugin.
The plugin retains its scheduler, permissions, reload callbacks, and filtered
`editor.website` setting. Editor transport and configuration validation are
maintained in BetterSync.
### Editor schema ownership
Each plugin module owns `src/main/resources/META-INF/editor-schema.json` and packages
it in its JAR. It describes field types, lists, defaults and form collection hints.
BetterSync checks basic types and required sections; it does not enforce business
rules such as ranges, material names or relationships between fields.
When a stable GitHub release is published, `.github/workflows/publish-editor-schema.yml`
attaches the schema from that exact release tag to this repository's release. BetterRTP
publishes both Core and Addons schemas. The workflow uses the built-in GitHub token;
no cross-repository publishing secret is needed. Release tags must include the workflow
and the schema resource. Do not replace a published schema; increment `schemaVersion`
when changing field metadata.
Website builds discover this repository's latest stable release and download its schema.
No plugin checkout or local Maven install is needed. The website uses a build-only token
with Contents read access for private repositories. It must be rebuilt after the schema
publication workflow succeeds. An unsupported plugin schema version is rejected until
the corresponding website build is deployed.
Use the website's schema-version database migrations before deploying these clients.
### Automatic Maven releases
`.github/workflows/release.yml` runs on pushes to `master` (or manually from
that branch). It reads only the Core POM version, builds and verifies BetterRTP Core,
runs the editor tests, and publishes a stable GitHub release with exactly one plugin
JAR. For the current Core POM the title is `BetterRTP 3.6.15` and the tag is `v3.6.15`.
This single-JAR release is compatible with the website's GitHub release importer.
Both Core and Addons editor-schema JSON files remain attached for the website editor.
Copying Addons metadata does not compile or publish its plugin binary. GitHub's Maven
test workflow also selects Core only. Build and upload the Addons plugin manually;
do not attach its JAR to the automated BetterRTP release, which must contain one JAR.
Local root Maven builds still build both modules.
An existing release is left untouched. Bump `BetterRTP-Core/pom.xml` to publish the next
Core release. An Addons-only version bump does not create a new Core release.
SNAPSHOT versions are rejected. GitHub's built-in token needs Contents write
permission, which the workflow declares. No extra publishing token is required.
-126
View File
@@ -1,126 +0,0 @@
# BetterRTP memory-retention analysis
Reviewed 2026-11-18 at commit `04309fb`; core POM version 3.6.13. Scope: BetterRTP-Core player lifecycle, cooldown persistence, RTP execution, menus, queues, scheduling, and shutdown. Addons were screened but are not covered by the conclusions below. This is source analysis plus an isolated Java reproduction, not a production heap diagnosis. No plugin behavior was changed.
All source references below are relative to `BetterRTP-Core/src/main/java/me/SuperRonanCraft/BetterRTP/`.
## Implementation status: deferred player lookups
Finding 1 has now been addressed in the working tree. The findings below describe the original reviewed commit; the other issues remain separate work.
- Sessions are created explicitly on join and for online players during enable/reload, and cleared on quit/disable. `getData(Player)` is now a nullable, non-creating lookup that rejects a different Player instance for the same UUID. External integrations using this API must handle absent sessions.
- Cooldown loads capture the session before scheduling, avoid duplicate loads, and apply results through an atomic current-session check. Old results cannot update a replacement session or repopulate the map.
- Player saves capture immutable UUID/count/timestamp values before executor submission. Per-world saves copy the cooldown timestamp before scheduling. Deferred writers do not look up or capture PlayerData/Player.
- Core placeholder, menu, damage, and effect callers handle absent session data.
- Validation: `mvn -o -q -f BetterRTP-Core/pom.xml test` passed six regression tests, including a blocked database executor released after session mutation/quit. Quit, reconnect, reload, and non-creating reads are covered. Live Paper/Folia integration has not been exercised.
## 1. High: deferred player lookups recreate cache entries after quit
Evidence: `references/player/playerdata/PlayerDataManager.java:15`, `PlayerData.java:16`, `references/player/HelperPlayer.java:13`, `player/events/Join.java:25`, `references/rtpinfo/CooldownHandler.java:130-166`.
`getData(Player)` is a creating operation: `computeIfAbsent` installs a PlayerData containing a strong, final Player reference. Neither this method nor loadPlayer checks whether that player session remains active. Quit only removes the UUID from this map.
Two concrete sequences:
1. Join schedules async loadPlayer(p); player quits and the cache is cleared; the async task starts and getData(p) creates a new entry for the departed player.
2. A cooldown change schedules savePlayer(p); player quits; the save callback calls `DatabaseHandler.getPlayers().setData(getData(player))`, recreating the cache entry.
The entry has no expiry or offline sweep. It remains until another explicit clear for that UUID or a plugin reload. A stream of different departing players can grow the map beyond the online population. Reference path: plugin -> PlayerDataManager -> map -> PlayerData -> Player. The exact retained bytes behind Player require heap inspection; this does not establish that every loaded chunk is retained by each player.
The save race also risks overwriting persisted count/global cooldown with defaults: the callback can obtain a newly created empty PlayerData instead of the state that originally triggered the save. If the player reconnects while the stale entry exists, getData(newPlayer) returns data whose final player field still refers to the previous session. UUID keys alone do not solve this.
Important distinction: when loadPlayer obtained PlayerData before quit, updating that detached object afterward does not itself reinsert it. The problematic insertion is the creating lookup after removal. ConcurrentHashMap makes map operations safe but does not make join/quit/callback ordering correct.
Validation: compiled the actual, unmodified PlayerDataManager and PlayerData sources with minimal Bukkit/annotation/menu stubs. Simulated 1,000 join -> clear -> deferred lookup sequences: 1,000 entries remained. Reconnecting with a different Player instance and the same UUID returned the old Player reference. This validates cache semantics, not real scheduler timing or production incidence. Reproduction is in `/tmp/betterrtp-retention-2sz2g7g5/Repro.java` for this workspace session.
Recommended correction: create session state explicitly on join; separate non-creating lookup from creation; invalidate the session on quit; carry a session token through callbacks. Save immutable UUID/count/timestamp snapshots captured before scheduling, without looking up PlayerData in the writer. Apply loaded results only if the original session is still current. An isOnline check alone still leaves check/remove/insert and reconnect races.
## Implementation status: RTP operation cleanup
Finding 2 is addressed on `fix/rtp-operation-cleanup`, based on the deferred-lookup fix. The original findings below remain as historical evidence.
- Replaced the Player-keyed boolean map with a synchronized UUID-keyed operation registry. Each request has its own identity and session owner; duplicate starts are rejected, and stale completion/quit cannot remove a newer operation.
- Both pre-teleport cancellation modes end the operation. Chunk-load failures, synchronous work exceptions, unsuccessful teleport results, and exceptions in success effects also release it. Unexpected errors are logged.
- Quit, reload, and disable end active operations. Delay cleanup cancels its task and unregisters its listener, including when task cancellation throws. Cleanup is idempotent and clears resource callbacks.
- Deferred search/delay callbacks check whether their request remains active. Cancelled location-event retries increment attempts before scheduling another retry, avoiding recursive stack growth.
- Compatibility: the mutable `PlayerInfo.getRtping()` API was removed. Integrations checking activity should use `getRTP().getOperations().contains(player.getUniqueId())`; they must not independently mutate tracking state.
- Validation: `mvn -o -q -f BetterRTP-Core/pom.xml test` passed 19 tests (13 operation tests plus the existing 6 session tests). These exercise shared pre-event cancellation handling, actual chunk continuation handling, terminal future outcomes, cleanup after effect exceptions, stale completions, lifecycle cleanup, and Bukkit listener unregistration even when task cancellation fails. Full plugin event/scheduler integration on Paper/Folia has not been exercised.
- Limits: no timeout policy was added for a future that never completes while its player remains online. Logical cancellation does not guarantee cancellation of underlying chunk IO or an already-started teleport. Other menu, executor, and queue-generation findings remain separate work.
## 2. High: RTP operation map has permanent retention paths
Evidence: `player/PlayerInfo.java:19,45-59`, `player/rtp/RTP.java:82-94`, `RTPDelay.java:31-36`, `RTPPlayer.java:64-76`, `RTPTeleport.java:55-71`, and `player/events/Leave.java:9-12`.
`PlayerInfo.rtping` is a HashMap keyed by Player. RTP inserts before firing the teleport pre-event. If another plugin cancels that event, both instant and delayed paths stop without removing the entry. This is a direct persistent retention path, even without a database race. Quit does not clear it; PlayerInfo.unload and unloadAll are private and never invoked.
Additional ways to strand the entry:
- The chunk-loading continuation has no exceptional completion handler. Its surrounding catch also silently discards Throwable without cleanup.
- teleportAsync uses thenRun, so exceptional completion skips cleanup. Errors thrown by afterTeleport also skip the later removal.
- A false Boolean teleport result still runs the success path because thenRun ignores the result; this is a correctness issue separate from retention.
Ordinary completion can remove an entry; this is not a claim that every RTP leaks. The cancellation and failure paths make retention possible without a later cleanup guarantee. Player keys can retain distinct disconnected session objects across reconnects.
Recommended correction: centralize idempotent operation completion and use it for success, cancellation, exceptions, quit, reload, and disable. Scope removal to the operation/session so an old callback cannot clear a newer request. Handle both exceptional completion and unsuccessful teleport results. Use thread-safe or correctly scheduler-confined state for supported Folia execution.
## 3. High/medium: RTP keeps searching after disconnect
Evidence: `player/rtp/RTPDelay.java:72-78`, `RTPPlayer.java:38-114`, `RTPTeleport.java:40-85`, and `player/rtp/effects/RTPEffect_Potions.java:56`.
Quit does not cancel a delay or in-progress search. The delay checks rtping, which quit does not clear. Search callbacks do not verify online/session/operation state before generating locations, loading chunks, charging, adding cooldowns, or teleporting. Later cooldown and effect lookups can recreate PlayerData as in finding 1.
Ordinary failed-location retries are limited by maxAttempts, so these callbacks alone are not necessarily a permanent leak. They are avoidable post-quit work and temporary Player retention that can feed permanent caches. An unresolved chunk future can prolong retention; no application timeout exists.
A separate retry bug exists at RTPPlayer.java:46-49: when the location event is cancelled, recursive randomlyTeleport runs before attempts is incremented. Repeated cancellation can cause stack overflow instead of reaching the attempt limit. Treat this as a control-flow/resource-exhaustion bug, not proof of a growing heap cache.
Recommended correction: cancel the logical operation on quit, check its token at every async boundary and before side effects, bound its lifetime, and guarantee terminal cleanup. Do not assume cancelling a future stops underlying chunk IO. Count attempts before retrying and schedule retries without recursive stack growth.
## 4. Medium: settings menu maps retain players
Evidence: `player/PlayerInfo.java:16-17,31-36,41-66`, `references/invs/types/RTPInvCoordinates.java:18-22`, `RTPInvWorlds.java:55`, `references/invs/RTPInventories.java:22-29`.
Menu navigation writes Player keys into invWorld and invNextInv. Quit does not clear these maps. The apparent reload cleanup is ineffective: closeAll gates cleanup on playerExists, which checks the legacy invs map; its only insertion method is commented out. Offline users would be skipped by closeAll's online-player loop anyway. No InventoryCloseEvent handler performs cleanup in the core listener.
This is a source-confirmed retention path for users who navigate those settings screens. It affects fewer players than the general cooldown race, but does not require async timing.
Recommended correction: consolidate menu state into session-owned data or explicitly remove all menu references on quit and clear them on reload/disable. Close inventory cleanup must use the active menu state, not the unused legacy map.
## 5. Medium: database backlog and executor lifecycle
Evidence: `references/database/SQLiteExecutor.java:7`, `DatabasePlayers.java:49-85`, `DatabaseQueue.java:63-95`, `BetterRTP.java:78-83`.
A static single-thread executor serves player and queue work, has an unbounded pending-task queue, and is never shut down by plugin code. Writes capture PlayerData, which holds Player. Several callers block on Future.get without an application timeout while holding their own captured Player/world state. Under sustained IO slowdown, queued tasks and waiting async callers can retain an increasing population of objects. This is a conditional backlog, not proof that normal successful queries permanently leak.
After first use, the executor also leaves a worker running across plugin disable. This is a lifecycle leak risk when unloading/replacing the plugin in-process; exact classloader roots should be verified in a heap dump. It is distinct from an ordinary `/rtp reload`, which does not create a fresh static executor.
Recommended correction: own the executor in the plugin lifecycle, define a bounded pending-work policy, snapshot primitive persistence data, expose queue depth/age, and drain/shut down explicitly. Avoid blocking worker threads waiting for other workers. Shutdown must coordinate pending saves before clearing session state.
## 6. Medium/conditional: queue generation can outlive reload
Evidence: `references/rtpinfo/QueueGenerator.java:33-66,165-204`, `QueueHandler.java:48-51`.
Only the latest queueGenerator delayed task is tracked. The initial generate delay is not retained; in-flight chunk/database continuations can call queueGenerator after unload. Concurrent low-queue requests can each enter generate before generating becomes true. Reload or demand bursts can therefore leave multiple chains active and make cancellation incomplete. A request can carry WorldPlayer via RTPWorld, retaining a player through that chain.
This is a lifecycle/concurrency risk, not a demonstrated indefinitely growing in-memory location cache. DatabaseQueue queries explicitly limit results to queueMax + 1 (33). Queue contents are persisted rather than held in an unlimited core list.
Recommended correction: use a generation token and atomic single-flight admission; invalidate the generation on reload/disable and check it before each continuation schedules more work.
## Other observations and limits
- PlaceholderAPI calls creating getData before validating the request and without a null/session guard (`DepPlaceholderAPI.java:40-41`). A stale Player passed by an integration can reproduce finding 1; a null player can throw. This method itself does not issue SQL, and the core contains no active getOfflinePlayer lookup. Do not attribute automatic offline placeholder polling to this plugin without tracing the caller.
- CooldownHandler.downloading removes entries in finally. Under normal completion it is not a permanent leak, although blocked database work prolongs retention. It also allows duplicate loads.
- Most query paths explicitly close JDBC resources. SQLite.close wraps all closes in a single try, so one close failure can prevent subsequent cleanup; use independent try-with-resources. This is exception-path hardening, not evidence that every query leaks connections.
- Metrics' timer cancels when it next notices the plugin disabled, so it can retain the old plugin until that scheduled check (up to roughly 30 minutes). It is not necessarily permanent.
- Logger setup closes the prior file handler. LogUploader bounds uploaded file content. Neither supplied a stronger explanation for offline Player retention.
- No production heap, live server, or user logs were available. No full plugin integration tests were run. External libraries, BetterSync internals, and addon-specific lifecycle bugs are outside this report's validated scope.
## Fix order and validation
1. Introduce explicit session ownership/non-creating reads and snapshot-based persistence.
2. Centralize RTP completion, cancel on quit, and cover cancellation/failure/timeout branches.
3. Remove legacy menu references on quit/reload/disable.
4. Bound and close database work; invalidate queue-generation continuations on reload.
Regression scenarios should deliberately control callback ordering: quit before join-load starts; quit before save starts; reconnect before an old callback finishes; cancelled pre-event in both delay modes; exceptional chunk/teleport futures; exception during post-teleport effects; quit during delay/search; menu use then quit; reload during queue generation; database backlog then shutdown.
For production confirmation, compare retained objects after equivalent join/RTP/quit cycles and after pending work drains. Inspect strong paths from BetterRTP to PlayerDataManager.playerData, PlayerInfo.rtping/invWorld/invNextInv, executor pending tasks, and RTP callback/listener instances. Count offline Player objects in those structures, oldest operation age, database queue depth, and outstanding generation chains. A rising heap before garbage collection alone is insufficient; distinguish live retained objects from allocation churn, ordinary loaded chunks, and work that eventually drains. Expected steady state: no departed session in player/menu/operation maps and no stale callback able to recreate it.
Binary file not shown.
Binary file not shown.
+377 -10
View File
@@ -1,18 +1,385 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP-build</artifactId> <artifactId>BetterRTP</artifactId>
<version>3.6.15</version> <packaging>jar</packaging>
<packaging>pom</packaging> <version>3.6.13</version>
<modules>
<module>BetterRTP-Core</module> <!-- Upload patches to https://repo.ronanplugins.com/#/ -->
<module>BetterRTPAddons</module>
</modules> <properties>
<maven.compiler.release>8</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<profiles>
<profile>
<id>dev</id>
<build> <build>
<!-- The core plugin owns the root target directory. --> <plugins>
<directory>${project.basedir}/target/reactor</directory> <plugin>
<!-- Local Server Building -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<outputDirectory>../../Java/plugins</outputDirectory>
</configuration>
</plugin>
</plugins>
</build> </build>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<!-- Shade PaperLib into project -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml
</dependencyReducedPomLocation>
<relocations>
<relocation>
<pattern>io.papermc.lib</pattern>
<shadedPattern>me.SuperRonanCraft.BetterRTP.lib.paperlib</shadedPattern>
</relocation>
<relocation>
<pattern>com.tcoded.folialib</pattern>
<shadedPattern>me.SuperRonanCraft.BetterRTP.lib.folialib</shadedPattern>
</relocation>
<!--relocation>
<pattern>xyz.xenondevs.particle</pattern>
<shadedPattern>me.SuperRonanCraft.BetterRTP.particleLib</shadedPattern>
</relocation-->
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<!-- CAN BE UNCOMMENTED IF YOU HAVE ACCESS TO THE REPO -->
<!--<repository>
<id>ronanplugins-private</id>
<name>RonanPlugins Repository</name>
<url>https://repo.ronanplugins.com/private</url>
</repository>-->
<!-- GitHub based Repos -->
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<!-- Spigot Repo -->
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<!-- PaperMC Repo -->
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<!-- Vault Repo -->
<repository>
<id>vault-repo</id>
<url>https://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<!-- Worldguard Repo -->
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<!-- ProjectRed Repo -->
<repository>
<id>redprotect-repo</id>
<url>https://raw.githubusercontent.com/FabioZumbi12/RedProtect/mvn-repo/</url>
</repository>
<!-- FactionsUUID Repo -->
<repository>
<id>factions-uuid</id>
<url>https://ci.ender.zone/plugin/repository/everything/</url>
</repository>
<!-- ProtocolLib Repo -->
<repository>
<id>dmulloy2-repo</id>
<url>https://repo.dmulloy2.net/nexus/repository/public/</url>
</repository>
<!-- EssentialsX Repo -->
<repository>
<id>essentials-releases</id>
<url>https://repo.essentialsx.net/releases/</url>
</repository>
<!-- PlaceholderAPI Repo -->
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<!-- MinePlots Repo -->
<repository>
<id>minecodes-repository-releases</id>
<name>mineCodes Organization Repository</name>
<url>https://repository.minecodes.pl/releases</url>
</repository>
<!-- FoliaLib https://github.com/TechnicallyCoded/FoliaLib -->
<repository>
<id>devmart-other</id>
<url>https://nexuslite.gcnt.net/repos/other/</url>
</repository>
<!-- Used by FactionsBridge -->
<repository>
<id>devmart-public</id>
<url>https://nexuslite.gcnt.net/repos/public/</url>
</repository>
</repositories>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Spigot Stuff -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Vault -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<!-- Paper Library for Async Chunk/Teleport -->
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.8</version>
<scope>compile</scope>
</dependency>
<!-- Worldguard (https://dev.bukkit.org/projects/worldguard) -->
<dependency> <!-- Saber Factions screws up if updated -->
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<!-- RedProtect (https://www.spigotmc.org/resources/redprotect.15841/) -->
<dependency>
<groupId>br.net.fabiozumbi12.RedProtect</groupId>
<artifactId>RedProtect-Core</artifactId>
<version>7.7.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>br.net.fabiozumbi12.RedProtect</groupId>
<artifactId>RedProtect-Spigot-1.13</artifactId>
<version>7.7.3</version>
<scope>provided</scope>
</dependency>
<!-- FactionsUUID (https://www.spigotmc.org/resources/factionsuuid.1035/) -->
<dependency>
<groupId>com.massivecraft</groupId>
<artifactId>Factions</artifactId>
<version>1.6.9.5-U0.6.8</version>
<scope>provided</scope>
</dependency>
<!-- Lands (https://www.spigotmc.org/resources/lands.53313/) -->
<dependency>
<groupId>com.github.angeschossen</groupId>
<artifactId>LandsAPI</artifactId>
<version>6.28.11</version>
<scope>provided</scope>
</dependency>
<!-- ProtocolLib -->
<dependency>
<groupId>com.comphenix.protocol</groupId>
<artifactId>ProtocolLib</artifactId>
<version>4.8.0</version>
<scope>provided</scope>
</dependency>
<!-- Towny (https://www.spigotmc.org/resources/towny.72694/) -->
<dependency>
<groupId>com.github.TownyAdvanced</groupId>
<artifactId>Towny</artifactId>
<version>0.98.6.6</version>
<scope>provided</scope>
</dependency>
<!-- GriefPrevention (https://www.spigotmc.org/resources/griefprevention.1884/) -->
<dependency>
<groupId>com.github.TechFortress</groupId>
<artifactId>GriefPrevention</artifactId>
<version>16.18</version>
<scope>provided</scope>
</dependency>
<!-- KingdomsX v1.10.5.2 (https://www.spigotmc.org/resources/kingdomsx.77670/) -->
<dependency>
<groupId>com.github.cryptomorin</groupId>
<artifactId>kingdoms</artifactId>
<version>1.16.8.1.1</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- GriefDefender (https://www.spigotmc.org/resources/griefdefender.68900/) -->
<dependency>
<groupId>com.github.bloodmc</groupId>
<artifactId>GriefDefenderApi</artifactId>
<version>920a610</version>
<scope>provided</scope>
</dependency>
<!-- Peublos (https://www.spigotmc.org/resources/pueblos.91255/) -->
<dependency>
<groupId>com.github.SuperRonanCraft</groupId>
<artifactId>Pueblos</artifactId>
<version>97b96c9</version>
<scope>provided</scope>
</dependency>
<!-- Particles Library
https://github.com/ByteZ1337/ParticleLib
(https://github.com/ByteZ1337/ParticleLib/blob/master/src/main/java/xyz/xenondevs/particle/ParticleEffect.java) -->
<dependency>
<groupId>xyz.xenondevs</groupId>
<artifactId>particle</artifactId>
<version>1.8.4</version>
<scope>compile</scope>
</dependency>
<!-- Lombok Support (@Getter & @Setter)-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
<!-- EssentialsX -->
<dependency>
<groupId>net.essentialsx</groupId>
<artifactId>EssentialsX</artifactId>
<version>2.20.1</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Saber Factions (https://www.spigotmc.org/resources/saberfactions.69771/) (Added in 3.4.5)-->
<dependency> <!-- WorldGuard screws up if updated -->
<groupId>com.github.SaberLLC</groupId>
<artifactId>Saber-Factions</artifactId>
<version>2.4.0-RC</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- PlaceholderAPI Support (Added in 3.4.5)-->
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.2</version>
<scope>provided</scope>
</dependency>
<!-- Husktown (https://www.spigotmc.org/resources/husktowns.92672/) (Added in 3.4.5)-->
<dependency>
<groupId>net.william278</groupId>
<artifactId>HuskTowns</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- MinePlots (https://builtbybit.com/resources/mineplots.21646/) (Added in 3.6.6 ) -->
<dependency>
<groupId>pl.minecodes.plots</groupId>
<artifactId>plugin-api</artifactId>
<version>3.4.5</version>
<scope>provided</scope>
</dependency>
<!-- FoliaLib -->
<dependency>
<groupId>com.tcoded</groupId>
<artifactId>FoliaLib</artifactId>
<version>0.3.1</version>
<scope>compile</scope>
</dependency>
<!-- FactionsBridge -->
<dependency>
<groupId>com.dansplugins.factionsystem</groupId>
<artifactId>FactionsBridge</artifactId>
<version>1.3.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.WhipDevelopment</groupId>
<artifactId>CrashClaim</artifactId>
<version>-75abe3b665-1</version>
<scope>provided</scope>
</dependency>
<!-- CAN BE UNCOMMENTED IF YOU HAVE ACCESS TO THE PLUGIN -->
<!-- Private Repoed -->
<!-- This is uploaded to our private repo on https://repo.ronanplugins.com -->
<!-- hClaims (https://www.spigotmc.org/resources/90540/) -->
<!--<dependency>
<groupId>com.ronanplugins</groupId>
<artifactId>hClaims</artifactId>
<version>2.5.3</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>-->
<!-- Provided by repo: devmart-public -->
<dependency>
<groupId>com.bekvon.bukkit.residence</groupId>
<artifactId>Residence</artifactId>
<version>5.1.4.1</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
</project> </project>
@@ -1,8 +1,5 @@
package me.SuperRonanCraft.BetterRTP; package me.SuperRonanCraft.BetterRTP;
import com.ronanplugins.bettersync.editor.EditorClient;
import com.ronanplugins.bettersync.editor.EditorSchema;
import lombok.Getter; import lombok.Getter;
import me.SuperRonanCraft.BetterRTP.player.PlayerInfo; import me.SuperRonanCraft.BetterRTP.player.PlayerInfo;
import me.SuperRonanCraft.BetterRTP.player.commands.Commands; import me.SuperRonanCraft.BetterRTP.player.commands.Commands;
@@ -50,19 +47,12 @@ public class BetterRTP extends JavaPlugin {
@Getter private boolean PlaceholderAPI; @Getter private boolean PlaceholderAPI;
@Getter private final RTPLogger rtpLogger = new RTPLogger(); @Getter private final RTPLogger rtpLogger = new RTPLogger();
@Getter private final FoliaHandler foliaHandler = new FoliaHandler(); @Getter private final FoliaHandler foliaHandler = new FoliaHandler();
@Getter private EditorClient editorBridge;
@Override @Override
public void onEnable() { public void onEnable() {
instance = this; instance = this;
registerDependencies(); registerDependencies();
loadAll(); loadAll();
editorBridge = new EditorClient(
this, EditorSchema.load(this, "META-INF/editor-schema.json"),
EditorClient.website(this, "META-INF/betterrtp-editor.properties"),
me.SuperRonanCraft.BetterRTP.versions.AsyncHandler::sync, this::reload,
me.SuperRonanCraft.BetterRTP.references.PermissionNode.EDITOR::check,
() -> me.SuperRonanCraft.BetterRTP.references.file.FileOther.FILETYPE.CONFIG.getConfig().saveToString());
new Updater(this); new Updater(this);
new Metrics(this); new Metrics(this);
listener.registerEvents(this); listener.registerEvents(this);
@@ -76,9 +66,6 @@ public class BetterRTP extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
RTP.getOperations().clear();
playerDataManager.clear();
if (editorBridge != null) editorBridge.close();
invs.closeAll(); invs.closeAll();
queue.unload(); queue.unload();
rtpLogger.unload(); rtpLogger.unload();
@@ -112,11 +99,8 @@ public class BetterRTP extends JavaPlugin {
//(Re)Load all plugin systems/files/cache //(Re)Load all plugin systems/files/cache
private void loadAll() { private void loadAll() {
RTP.getOperations().clear();
foliaHandler.load(); foliaHandler.load();
playerDataManager.clear(); playerDataManager.clear();
for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
playerDataManager.startSession(player);
files.loadAll(); files.loadAll();
settings.load(); settings.load();
cooldowns.load(); cooldowns.load();
@@ -16,7 +16,7 @@ public class PlayerInfo {
@Getter private final HashMap<Player, World> invWorld = new HashMap<>(); @Getter private final HashMap<Player, World> invWorld = new HashMap<>();
@Getter private final HashMap<Player, RTP_INV_SETTINGS> invNextInv = new HashMap<>(); @Getter private final HashMap<Player, RTP_INV_SETTINGS> invNextInv = new HashMap<>();
//private final HashMap<Player, CooldownData> cooldown = 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, List<Location>> previousLocations = new HashMap<>();
//private final HashMap<Player, RTP_TYPE> rtpType = new HashMap<>(); //private final HashMap<Player, RTP_TYPE> rtpType = new HashMap<>();
@@ -48,14 +48,14 @@ public class PlayerInfo {
invWorld.clear(); invWorld.clear();
invNextInv.clear(); invNextInv.clear();
//cooldown.clear(); //cooldown.clear();
rtping.clear();
//previousLocations.clear(); //previousLocations.clear();
} }
private void unload(Player p) { private void unload(Player p) {
clearInvs(p); clearInvs(p);
//cooldown.remove(p); //cooldown.remove(p);
rtping.remove(p);
//previousLocations.remove(p); //previousLocations.remove(p);
} }
@@ -43,10 +43,7 @@ public class Commands {
//Command Event //Command Event
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
boolean editorSync = args[0].equalsIgnoreCase("editorsync") || BetterRTP.debug(sendi.getName() + " executed: /" + label + " " + String.join(" ", args));
(args[0].equalsIgnoreCase("addons") && args.length > 1 && args[1].equalsIgnoreCase("editorsync"));
BetterRTP.debug(sendi.getName() + " executed: /" + label + " " +
(editorSync ? (args[0].equalsIgnoreCase("addons") ? "addons editorsync [redacted]" : "editorsync [redacted]") : String.join(" ", args)));
cmd.execute(sendi, label, args); cmd.execute(sendi, label, args);
Bukkit.getServer().getPluginManager().callEvent(new RTP_CommandEvent_After(sendi, cmd)); Bukkit.getServer().getPluginManager().callEvent(new RTP_CommandEvent_After(sendi, cmd));
} }
@@ -5,8 +5,6 @@ import me.SuperRonanCraft.BetterRTP.player.commands.types.*;
public enum RTPCommandType { public enum RTPCommandType {
BIOME(new CmdBiome()), BIOME(new CmdBiome()),
EDIT(new CmdEdit()), EDIT(new CmdEdit()),
EDITOR(new CmdEditor()),
EDITOR_SYNC(new CmdEditorSync()),
HELP(new CmdHelp()), HELP(new CmdHelp()),
INFO(new CmdInfo()), INFO(new CmdInfo()),
LOCATION(new CmdLocation()), LOCATION(new CmdLocation()),
@@ -13,6 +13,9 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.NotNull; 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.BetterRTP;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommand; import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommand;
@@ -144,22 +147,27 @@ public class CmdInfo implements RTPCommand, RTPCommandHelpable {
if (!upload) { if (!upload) {
sendi.sendMessage(list.toArray(new String[0])); sendi.sendMessage(list.toArray(new String[0]));
if (sendi instanceof Player) { if (sendi instanceof Player) {
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &fmclo.gs")); TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &flogs.ronanplugins.com"));
component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd + " _UPLOAD_")); 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())); 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); ((Player) sendi).spigot().sendMessage(component);
} else { } else {
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://mclo.gs"); sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://logs.ronanplugins.com");
} }
} else { } else {
list.add(0, "Command: " + cmd); list.add(0, "Command: " + cmd);
list.forEach(str -> list.set(list.indexOf(str), ChatColor.stripColor(str))); list.forEach(str -> list.set(list.indexOf(str), ChatColor.stripColor(str)));
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
String url = LogUploader.post(list); String key = LogUploader.post(list);
if (url == null) { if (key == 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); Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cAn error occured attempting to upload log!")), null);
} else { } else {
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6" + url), null); 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);
}
} }
}); });
} }
@@ -13,6 +13,9 @@ import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -33,20 +36,25 @@ public class CmdLogger implements RTPCommand {
String cmd = "/" + label + " " + String.join(" ", args); String cmd = "/" + label + " " + String.join(" ", args);
if (!upload) { if (!upload) {
if (sendi instanceof Player) { if (sendi instanceof Player) {
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload log to &fmclo.gs")); TextComponent component = new TextComponent(Message.color("&7- &7Click to upload log to &flogs.ronanplugins.com"));
component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd + " _UPLOAD_")); 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())); 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); ((Player) sendi).spigot().sendMessage(component);
} else { } else {
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload log to https://mclo.gs"); sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload log to https://logs.ronanplugins.com");
} }
} else { } else {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
String url = LogUploader.post(BetterRTP.getInstance().getRtpLogger().getFile()); String key = LogUploader.post(BetterRTP.getInstance().getRtpLogger().getFile());
if (url == null) { if (key == 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); Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cAn error occured attempting to upload log!")), null);
} else { } else {
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6" + url), null); 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);
}
} }
}); });
} }
@@ -22,6 +22,9 @@ import org.bukkit.World;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -56,22 +59,27 @@ public class CmdQueue implements RTPCommand {
if (!upload) { if (!upload) {
sendi.sendMessage(list.toArray(new String[0])); sendi.sendMessage(list.toArray(new String[0]));
if (sendi instanceof Player) { if (sendi instanceof Player) {
TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &fmclo.gs")); TextComponent component = new TextComponent(Message.color("&7- &7Click to upload command log to &flogs.ronanplugins.com"));
component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd + " _UPLOAD_")); 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())); 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); ((Player) sendi).spigot().sendMessage(component);
} else { } else {
sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://mclo.gs"); sendi.sendMessage("Execute `" + cmd + " _UPLOAD_`" + " to upload command log to https://logs.ronanplugins.com");
} }
} else { } else {
list.add(0, "Command: " + cmd); list.add(0, "Command: " + cmd);
list.forEach(str -> list.set(list.indexOf(str), ChatColor.stripColor(str))); list.forEach(str -> list.set(list.indexOf(str), ChatColor.stripColor(str)));
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
String url = LogUploader.post(list); String key = LogUploader.post(list);
if (url == null) { if (key == 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); Message.sms(sendi, new ArrayList<>(Collections.singletonList("&cAn error occured attempting to upload log!")), null);
} else { } else {
Message.sms(sendi, Arrays.asList(" ", Message.getPrefix(Message_RTP.msg) + "&aLog uploaded! &fView&7: &6" + url), null); 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);
}
} }
}); });
} }
@@ -21,7 +21,6 @@ public class Click {
try { try {
Player p = (Player) e.getWhoClicked(); Player p = (Player) e.getWhoClicked();
PlayerData data = HelperPlayer.getData(p); PlayerData data = HelperPlayer.getData(p);
if (data == null) return;
RTPInventories menu = BetterRTP.getInstance().getInvs(); RTPInventories menu = BetterRTP.getInstance().getInvs();
menu.getInv(data.getMenu().getInvType()).clickEvent(e); menu.getInv(data.getMenu().getInvType()).clickEvent(e);
} catch (NullPointerException ex) { } catch (NullPointerException ex) {
@@ -39,7 +38,6 @@ public class Click {
else if (e.getWhoClicked() instanceof Player) { else if (e.getWhoClicked() instanceof Player) {
// Clicks the inventory // Clicks the inventory
PlayerData data = HelperPlayer.getData((Player) e.getWhoClicked()); PlayerData data = HelperPlayer.getData((Player) e.getWhoClicked());
if (data == null) return false;
if (!e.getInventory().equals(data.getMenu().getInv())) if (!e.getInventory().equals(data.getMenu().getInv()))
return false; return false;
// Clicks their own inventory // Clicks their own inventory
@@ -1,7 +1,6 @@
package me.SuperRonanCraft.BetterRTP.player.events; package me.SuperRonanCraft.BetterRTP.player.events;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
@@ -12,8 +11,7 @@ public class Damage {
} }
static boolean isInInvincibleMode(Player player) { static boolean isInInvincibleMode(Player player) {
PlayerData data = HelperPlayer.getData(player); return HelperPlayer.getData(player).getInvincibleEndTime() > System.currentTimeMillis();
return data != null && data.getInvincibleEndTime() > System.currentTimeMillis();
} }
static void onEntityDamage(EntityDamageEvent event) { static void onEntityDamage(EntityDamageEvent event) {
@@ -8,6 +8,7 @@ import me.SuperRonanCraft.BetterRTP.references.messages.Message_RTP;
import me.SuperRonanCraft.BetterRTP.references.messages.MessagesCore; import me.SuperRonanCraft.BetterRTP.references.messages.MessagesCore;
import me.SuperRonanCraft.BetterRTP.references.web.Updater; import me.SuperRonanCraft.BetterRTP.references.web.Updater;
import me.SuperRonanCraft.BetterRTP.references.helpers.HelperRTP; import me.SuperRonanCraft.BetterRTP.references.helpers.HelperRTP;
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
@@ -18,9 +19,10 @@ public class Join {
static void event(PlayerJoinEvent e) { static void event(PlayerJoinEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
getPl().getPlayerDataManager().startSession(p);
updater(p); updater(p);
AsyncHandler.async(() -> {
getPl().getCooldowns().loadPlayer(p); getPl().getCooldowns().loadPlayer(p);
});
rtpOnFirstJoin(p); rtpOnFirstJoin(p);
} }
@@ -40,7 +42,7 @@ public class Join {
//RTP on first join //RTP on first join
private static void rtpOnFirstJoin(Player p) { private static void rtpOnFirstJoin(Player p) {
if (getPl().getSettings().isRtpOnFirstJoin_Enabled() && !p.hasPlayedBefore()) if (getPl().getSettings().isRtpOnFirstJoin_Enabled() && !p.hasPlayedBefore())
HelperRTP.tp(p, Bukkit.getConsoleSender(), Bukkit.getWorld(getPl().getSettings().getRtpOnFirstJoin_World()), null, RTP_TYPE.JOIN, true, true); HelperRTP.tp(p, Bukkit.getConsoleSender(), Bukkit.getWorld(getPl().getSettings().getRtpOnFirstJoin_World()), null, RTP_TYPE.JOIN); //Console is sender to override delays
} }
private static BetterRTP getPl() { private static BetterRTP getPl() {
@@ -1,7 +1,6 @@
package me.SuperRonanCraft.BetterRTP.player.events; package me.SuperRonanCraft.BetterRTP.player.events;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
@@ -9,10 +8,6 @@ class Leave {
static void event(PlayerQuitEvent e) { static void event(PlayerQuitEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
try {
BetterRTP.getInstance().getRTP().getOperations().cancel(p.getUniqueId(), p);
} finally {
HelperPlayer.unload(p); HelperPlayer.unload(p);
} }
}
} }
@@ -22,7 +22,6 @@ import me.SuperRonanCraft.BetterRTP.references.rtpinfo.worlds.WorldPlayer;
public class RTP { public class RTP {
@Getter final RTPTeleport teleport = new RTPTeleport(); @Getter final RTPTeleport teleport = new RTPTeleport();
@Getter private final RTPOperationTracker operations = new RTPOperationTracker();
//Cache //Cache
public final HashMap<String, String> overriden = new HashMap<>(); public final HashMap<String, String> overriden = new HashMap<>();
@Getter List<String> disabledWorlds, blockList; @Getter List<String> disabledWorlds, blockList;
@@ -83,19 +82,16 @@ public class RTP {
private void rtp(CommandSender sendi, WorldPlayer pWorld, RTP_TYPE type) { private void rtp(CommandSender sendi, WorldPlayer pWorld, RTP_TYPE type) {
//Cooldown //Cooldown
Player p = pWorld.getPlayer(); Player p = pWorld.getPlayer();
if (!p.isOnline()) return; getPl().getPInfo().getRtping().put(p, true); //Cache player so they cant run '/rtp' again while rtp'ing
RTPOperationTracker.Operation operation = operations.start(p.getUniqueId(), p);
if (operation == null) return;
//Setup player rtp methods //Setup player rtp methods
RTPPlayer rtpPlayer = new RTPPlayer(p, this, pWorld, type, operation); RTPPlayer rtpPlayer = new RTPPlayer(p, this, pWorld, type);
rtpPlayer.runSafely(() -> { // Delaying? Else, just go
if (pWorld.getPlayerInfo().applyDelay && HelperRTP_Check.applyDelay(p)) { if (pWorld.getPlayerInfo().applyDelay && HelperRTP_Check.applyDelay(pWorld.getPlayer())) {
new RTPDelay(sendi, rtpPlayer, delayTime, cancelOnMove, cancelOnDamage); new RTPDelay(sendi, rtpPlayer, delayTime, cancelOnMove, cancelOnDamage);
} else { } else {
rtpPlayer.afterPreEvent(teleport.beforeTeleportInstant(sendi, p), if (!teleport.beforeTeleportInstant(sendi, p))
() -> rtpPlayer.randomlyTeleport(sendi)); rtpPlayer.randomlyTeleport(sendi);
} }
});
} }
private BetterRTP getPl() { private BetterRTP getPl() {
@@ -22,17 +22,15 @@ class RTPDelay implements Listener {
this.cancelOnMove = cancelOnMove; this.cancelOnMove = cancelOnMove;
this.cancelOnDamage = cancelOnDamage; this.cancelOnDamage = cancelOnDamage;
this.rtp = rtp; this.rtp = rtp;
rtp.getOperation().onFinish(this::dispose);
delay(sendi, delay); delay(sendi, delay);
} }
private void delay(CommandSender sendi, int delay) { private void delay(CommandSender sendi, int delay) {
rtp.afterPreEvent(getPl().getRTP().getTeleport().beforeTeleportDelay(rtp.getPlayer(), delay), () -> { if (!getPl().getRTP().getTeleport().beforeTeleportDelay(rtp.getPlayer(), delay)) {
task = AsyncHandler.syncLater(run(sendi, this), delay * 20L); task = AsyncHandler.syncLater(run(sendi, this), delay * 20L);
if (cancelOnMove || cancelOnDamage) if (cancelOnMove || cancelOnDamage)
Bukkit.getPluginManager().registerEvents(this, BetterRTP.getInstance()); Bukkit.getPluginManager().registerEvents(this, BetterRTP.getInstance());
if (!rtp.isActive()) dispose(); }
});
} }
@EventHandler @EventHandler
@@ -59,35 +57,23 @@ 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() { private void cancel() {
rtp.runSafely(() -> { if (task != null)
try { task.cancel();
HandlerList.unregisterAll(this);
getPl().getRTP().getTeleport().cancelledTeleport(rtp.getPlayer()); getPl().getRTP().getTeleport().cancelledTeleport(rtp.getPlayer());
//getPl().getEco().unCharge(rtp.getPlayer(), rtp.pWorld);
getPl().getCooldowns().removeCooldown(rtp.getPlayer(), rtp.worldPlayer.getWorld()); getPl().getCooldowns().removeCooldown(rtp.getPlayer(), rtp.worldPlayer.getWorld());
} finally { getPl().getPInfo().getRtping().remove(rtp.getPlayer());
rtp.getOperation().finish();
}
Bukkit.getServer().getPluginManager().callEvent(new RTP_CancelledEvent(rtp.getPlayer())); Bukkit.getServer().getPluginManager().callEvent(new RTP_CancelledEvent(rtp.getPlayer()));
});
} }
private Runnable run(final CommandSender sendi, final RTPDelay cls) { private Runnable run(final CommandSender sendi, final RTPDelay cls) {
return () -> rtp.runSafely(() -> { return () -> {
HandlerList.unregisterAll(cls); HandlerList.unregisterAll(cls);
if (getPl().getPInfo().getRtping().containsKey(rtp.getPlayer()))
rtp.randomlyTeleport(sendi); rtp.randomlyTeleport(sendi);
}); };
} }
private BetterRTP getPl() { private BetterRTP getPl() {
@@ -23,56 +23,20 @@ import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
public class RTPPlayer { public class RTPPlayer {
@Getter private final Player player; @Getter private final Player player;
@Getter private final RTPOperationTracker.Operation operation;
private final RTP settings; private final RTP settings;
@Getter WorldPlayer worldPlayer; @Getter WorldPlayer worldPlayer;
@Getter RTP_TYPE type; @Getter RTP_TYPE type;
@Getter int attempts; @Getter int attempts;
//List<Location> attemptedLocations = new ArrayList<>(); //List<Location> attemptedLocations = new ArrayList<>();
RTPPlayer(Player player, RTP settings, WorldPlayer worldPlayer, RTP_TYPE type, RTPOperationTracker.Operation operation) { RTPPlayer(Player player, RTP settings, WorldPlayer worldPlayer, RTP_TYPE type) {
this.operation = operation;
this.player = player; this.player = player;
this.settings = settings; this.settings = settings;
this.worldPlayer = worldPlayer; this.worldPlayer = worldPlayer;
this.type = type; 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) { void randomlyTeleport(CommandSender sendi) {
runSafely(() -> search(sendi));
}
private void search(CommandSender sendi) {
if (attempts >= settings.maxAttempts) //Cancel out, too many tries if (attempts >= settings.maxAttempts) //Cancel out, too many tries
metMax(sendi, player); metMax(sendi, player);
else { //Try again to find a safe location else { //Try again to find a safe location
@@ -81,11 +45,11 @@ public class RTPPlayer {
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
//Async Location finder //Async Location finder
if (event.isCancelled()) { if (event.isCancelled()) {
randomlyTeleport(sendi);
attempts++; attempts++;
AsyncHandler.sync(() -> randomlyTeleport(sendi));
return; return;
} }
AsyncHandler.async(() -> runSafely(() -> { AsyncHandler.async(() -> {
Location loc; Location loc;
if (event.getLocation() != null) // && WorldPlayer.checkIsValid(event.getLocation(), pWorld)) if (event.getLocation() != null) // && WorldPlayer.checkIsValid(event.getLocation(), pWorld))
loc = event.getLocation(); loc = event.getLocation();
@@ -99,21 +63,25 @@ public class RTPPlayer {
} }
attempts++; //Add an attempt attempts++; //Add an attempt
//Load chunk and find out if safe location (asynchronously) //Load chunk and find out if safe location (asynchronously)
AsyncHandler.sync(() -> runSafely(() -> { AsyncHandler.sync(() -> {
try { //Prior to 1.12 this async chunk will NOT work try { //Prior to 1.12 this async chunk will NOT work
CompletableFuture<Chunk> chunk = PaperLib.getChunkAtAsync(loc); CompletableFuture<Chunk> chunk = PaperLib.getChunkAtAsync(loc);
awaitChunk(chunk, () -> attempt(sendi, loc)); chunk.thenAccept(result -> {
//BetterRTP.debug("Checking location for " + p.getName());
attempt(sendi, loc);
});
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
//Legacy non-async support //Legacy non-async support
attempt(sendi, loc); attempt(sendi, loc);
} catch (Throwable ignored) {
} }
})); });
})); });
} }
} }
private void attempt(CommandSender sendi, Location loc) { private void attempt(CommandSender sendi, Location loc) {
if (!isActive()) return;
Location tpLoc; Location tpLoc;
tpLoc = RandomLocation.getSafeLocation(worldPlayer.getWorldtype(), worldPlayer.getWorld(), loc, worldPlayer.getMinY(), worldPlayer.getMaxY(), worldPlayer.getBiomes()); tpLoc = RandomLocation.getSafeLocation(worldPlayer.getWorldtype(), worldPlayer.getWorld(), loc, worldPlayer.getMinY(), worldPlayer.getMaxY(), worldPlayer.getBiomes());
//attemptedLocations.add(loc); //attemptedLocations.add(loc);
@@ -126,11 +94,11 @@ public class RTPPlayer {
getPl().getCooldowns().add(player, worldPlayer.getWorld()); getPl().getCooldowns().add(player, worldPlayer.getWorld());
tpLoc.setYaw(player.getLocation().getYaw()); tpLoc.setYaw(player.getLocation().getYaw());
tpLoc.setPitch(player.getLocation().getPitch()); tpLoc.setPitch(player.getLocation().getPitch());
AsyncHandler.sync(() -> runSafely(() -> settings.teleport.sendPlayer(sendi, this, tpLoc))); AsyncHandler.sync(() -> settings.teleport.sendPlayer(sendi, player, tpLoc, worldPlayer, attempts, type));
} else { } else {
if (worldPlayer.getPlayerInfo().applyCooldown) if (worldPlayer.getPlayerInfo().applyCooldown)
getPl().getCooldowns().removeCooldown(player, worldPlayer.getWorld()); getPl().getCooldowns().removeCooldown(player, worldPlayer.getWorld());
operation.finish(); getPl().getPInfo().getRtping().remove(player);
} }
} else { } else {
randomlyTeleport(sendi); randomlyTeleport(sendi);
@@ -142,7 +110,7 @@ public class RTPPlayer {
private void metMax(CommandSender sendi, Player p) { private void metMax(CommandSender sendi, Player p) {
settings.teleport.failedTeleport(p, sendi); settings.teleport.failedTeleport(p, sendi);
getPl().getCooldowns().removeCooldown(p, worldPlayer.getWorld()); getPl().getCooldowns().removeCooldown(p, worldPlayer.getWorld());
operation.finish(); getPl().getPInfo().getRtping().remove(p);
//RTP Failed Event //RTP Failed Event
Bukkit.getServer().getPluginManager().callEvent(new RTP_FailedEvent(this)); Bukkit.getServer().getPluginManager().callEvent(new RTP_FailedEvent(this));
} }
@@ -5,6 +5,7 @@ import java.util.Arrays;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
@@ -37,25 +38,37 @@ public class RTPTeleport {
// CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).cancel(true); // CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).cancel(true);
// } // }
void sendPlayer(CommandSender sendi, RTPPlayer request, Location location) { void sendPlayer(final CommandSender sendi, final Player p, final Location location, final WorldPlayer wPlayer,
Player p = request.getPlayer(); final int attempts, RTP_TYPE type) throws NullPointerException {
WorldPlayer wPlayer = request.getWorldPlayer();
int attempts = request.getAttempts();
RTP_TYPE type = request.getType();
Location oldLoc = p.getLocation(); Location oldLoc = p.getLocation();
loadingTeleport(p, sendi); 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()); RTP_TeleportEvent event = new RTP_TeleportEvent(p, location, wPlayer.getWorldtype());
getPl().getServer().getPluginManager().callEvent(event); getPl().getServer().getPluginManager().callEvent(event);
if (!request.isActive()) return;
Location loc = event.getLocation(); Location loc = event.getLocation();
request.getOperation().complete(PaperLib.teleportAsync(p, loc), () -> { PaperLib.teleportAsync(p, loc).thenRun(new BukkitRunnable() { //Async teleport
if (!request.isActive()) return; @Override
public void run() {
afterTeleport(p, loc, wPlayer, attempts, oldLoc, type); afterTeleport(p, loc, wPlayer, attempts, oldLoc, type);
if (sendi != p) if (sendi != p) //Tell player who requested that the player rtp'd
sendSuccessMsg(sendi, p.getName(), loc, wPlayer, false, attempts); sendSuccessMsg(sendi, p.getName(), loc, wPlayer, false, attempts);
if (type == RTP_TYPE.JOIN && getPl().getSettings().isRtpOnFirstJoin_SetAsRespawn()) getPl().getPInfo().getRtping().remove(p); //No longer rtp'ing
p.setBedSpawnLocation(loc, true); //Save respawn location if first join
}, () -> failedTeleport(p, sendi), request::logError); 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();
}
} }
//Effects //Effects
@@ -3,7 +3,6 @@ package me.SuperRonanCraft.BetterRTP.player.rtp.effects;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.file.FileOther; import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler; import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
@@ -53,10 +52,8 @@ public class RTPEffect_Potions { //Potions AND Invincibility
public void giveEffects(Player p) { public void giveEffects(Player p) {
AsyncHandler.syncAtEntity(p, () -> { AsyncHandler.syncAtEntity(p, () -> {
PlayerData data = HelperPlayer.getData(p);
if (data == null) return;
if (invincibleEnabled) if (invincibleEnabled)
data.setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L)); HelperPlayer.getData(p).setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L));
if (potionEnabled) { if (potionEnabled) {
List<PotionEffect> effects = new ArrayList<>(); List<PotionEffect> effects = new ArrayList<>();
for (PotionEffectType e : potionEffects.keySet()) { for (PotionEffectType e : potionEffects.keySet()) {
@@ -6,6 +6,8 @@ import com.comphenix.protocol.events.PacketContainer;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
public abstract class AbstractPacket { public abstract class AbstractPacket {
// The packet we will be modifying // The packet we will be modifying
protected PacketContainer handle; protected PacketContainer handle;
@@ -40,9 +42,15 @@ public abstract class AbstractPacket {
* Send the current packet to the given receiver. * Send the current packet to the given receiver.
* *
* @param receiver - the receiver. * @param receiver - the receiver.
* @throws RuntimeException If the packet cannot be sent.
*/ */
public void sendPacket(Player receiver) { public void sendPacket(Player receiver) {
ProtocolLibrary.getProtocolManager().sendServerPacket(receiver, getHandle()); try {
ProtocolLibrary.getProtocolManager().sendServerPacket(receiver,
getHandle());
} catch (InvocationTargetException e) {
throw new RuntimeException("Cannot send packet.", e);
}
} }
/** /**
@@ -63,7 +71,7 @@ public abstract class AbstractPacket {
@Deprecated @Deprecated
public void recievePacket(Player sender) { public void recievePacket(Player sender) {
try { try {
ProtocolLibrary.getProtocolManager().receiveClientPacket(sender, ProtocolLibrary.getProtocolManager().recieveClientPacket(sender,
getHandle()); getHandle());
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Cannot recieve packet.", e); throw new RuntimeException("Cannot recieve packet.", e);
@@ -78,7 +86,7 @@ public abstract class AbstractPacket {
*/ */
public void receivePacket(Player sender) { public void receivePacket(Player sender) {
try { try {
ProtocolLibrary.getProtocolManager().receiveClientPacket(sender, ProtocolLibrary.getProtocolManager().recieveClientPacket(sender,
getHandle()); getHandle());
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Cannot receive packet.", e); throw new RuntimeException("Cannot receive packet.", e);
@@ -49,10 +49,9 @@ public interface PermissionCheck {
String getNode(); String getNode();
@Getter
class PermissionResult { class PermissionResult {
private final boolean passed; @Getter private final boolean passed;
private final String string; @Getter private final String string;
PermissionResult(String string, boolean passed) { PermissionResult(String string, boolean passed) {
this.passed = passed; this.passed = passed;
this.string = string; this.string = string;
@@ -2,7 +2,6 @@ package me.SuperRonanCraft.BetterRTP.references;
import lombok.Getter; import lombok.Getter;
@Getter
public enum PermissionNode implements PermissionCheck { public enum PermissionNode implements PermissionCheck {
ADMIN("admin"), ADMIN("admin"),
@@ -22,12 +21,11 @@ public enum PermissionNode implements PermissionCheck {
SIGN_CREATE("sign"), SIGN_CREATE("sign"),
VERSION("version"), VERSION("version"),
EDIT("edit"), EDIT("edit"),
EDITOR("editor"),
LOCATION("location"), LOCATION("location"),
DEVELOPER("DEVELOPER_PERM"), DEVELOPER("DEVELOPER_PERM"),
; ;
private final String node; @Getter private final String node;
PermissionNode(String node) { PermissionNode(String node) {
this.node = PermissionCheck.getPrefix() + node; this.node = PermissionCheck.getPrefix() + node;
@@ -0,0 +1,108 @@
package me.SuperRonanCraft.BetterRTP.references;
import me.SuperRonanCraft.BetterRTP.references.depends.DepPerms;
import org.bukkit.command.CommandSender;
public class Permissions {
private final DepPerms depPerms = new DepPerms();
public void register() {
depPerms.register();
}
public boolean checkPerm(String str, CommandSender sendi) {
return depPerms.hasPerm(str, sendi);
}
}
//Moved to PermissionNode.NODE
/*private final String pre = "betterrtp.";
public boolean getUse(CommandSender sendi) {
return checkPerm(pre + "use", sendi);
}
public boolean getBypassEconomy(CommandSender sendi) {
return checkPerm(pre + "bypass.economy", sendi);
}
public boolean getBypassHunger(CommandSender sendi) {
return checkPerm(pre + "bypass.hunger", sendi);
}
public boolean getBypassCooldown(CommandSender sendi) {
return checkPerm(pre + "bypass.cooldown", sendi);
}
public boolean getBypassDelay(CommandSender sendi) {
return checkPerm(pre + "bypass.delay", sendi);
}
public boolean getReload(CommandSender sendi) {
return checkPerm(pre + "reload", sendi);
}
public boolean getSettings(CommandSender sendi) {
return checkPerm(pre + "settings", sendi);
}
public boolean getInfo(CommandSender sendi) {
return checkPerm(pre + "info", sendi);
}
public boolean getUpdate(CommandSender sendi) {
return checkPerm(pre + "updater", sendi);
}
public boolean getRtpOther(CommandSender sendi) {
return checkPerm(pre + "player", sendi);
}
public boolean getBiome(CommandSender sendi) {
return checkPerm(pre + "biome", sendi);
}
public boolean getWorld(CommandSender sendi) {
return checkPerm(pre + "world", sendi);
}
public boolean getSignCreate(CommandSender sendi) {
return checkPerm(pre + "sign", sendi);
}
public boolean getTest(CommandSender sendi) {
return checkPerm(pre + "test", sendi);
}
public boolean getVersion(CommandSender sendi) {
return checkPerm(pre + "version", sendi);
}
public boolean getAWorld(CommandSender sendi, String world) {
if (checkPerm(pre + "world.*", sendi))
return true;
else if (world == null) {
for (World w : Bukkit.getWorlds())
if (checkPerm(pre + "world." + w.getName(), sendi))
return true;
} else
return checkPerm(pre + "world." + world, sendi);
return false;
}
public boolean getEdit(CommandSender sendi) {
return checkPerm(pre + "edit", sendi);
}
public boolean getLocation(CommandSender sendi) {
return checkPerm(pre + "location", sendi);
}
public boolean getLocation(CommandSender sendi, String location) {
return checkPerm(pre + "location." + location, sendi);
}
public boolean getPermissionGroup(CommandSender sendi, String group) {
return checkPerm(pre + "group." + group, sendi);
}*/
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff. Show more