mirror of
https://github.com/RonanPlugins/BetterRTP.git
synced 2026-11-27 00:05:07 +00:00
bettersync lib
This commit is contained in:
1 parent
6eca1c5c73
commit
ab9911605c
10 files changed
+54
-523
No files matched your search
@@ -12,6 +12,7 @@
|
||||
<!-- Upload patches to https://repo.ronanplugins.com/#/ -->
|
||||
|
||||
<properties>
|
||||
<bettersync.version>1.0.1</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>
|
||||
@@ -68,6 +69,8 @@
|
||||
<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>
|
||||
@@ -209,6 +212,12 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
<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-->
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package me.SuperRonanCraft.BetterRTP;
|
||||
|
||||
import com.ronanplugins.bettersync.editor.EditorClient;
|
||||
import com.ronanplugins.bettersync.editor.EditorProfile;
|
||||
|
||||
import lombok.Getter;
|
||||
import me.SuperRonanCraft.BetterRTP.player.PlayerInfo;
|
||||
import me.SuperRonanCraft.BetterRTP.player.commands.Commands;
|
||||
@@ -47,15 +50,17 @@ public class BetterRTP extends JavaPlugin {
|
||||
@Getter private boolean PlaceholderAPI;
|
||||
@Getter private final RTPLogger rtpLogger = new RTPLogger();
|
||||
@Getter private final FoliaHandler foliaHandler = new FoliaHandler();
|
||||
@Getter private me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge editorBridge;
|
||||
@Getter private EditorClient editorBridge;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
registerDependencies();
|
||||
loadAll();
|
||||
editorBridge = new me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge(
|
||||
this, me.SuperRonanCraft.BetterRTP.versions.AsyncHandler::sync, this::reload,
|
||||
editorBridge = new EditorClient(
|
||||
this, EditorProfile.BETTERRTP,
|
||||
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);
|
||||
|
||||
-213
@@ -1,213 +0,0 @@
|
||||
package me.SuperRonanCraft.BetterRTP.references.web.editor;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** Independent config uploads; HTTP runs on a dedicated worker. No editor lifecycle. */
|
||||
public final class EditorBridge {
|
||||
private static final String WEBSITE = loadWebsite();
|
||||
|
||||
private static String loadWebsite() {
|
||||
Properties metadata = new Properties();
|
||||
try (InputStream input = EditorBridge.class.getResourceAsStream("/META-INF/betterrtp-editor.properties")) {
|
||||
if (input == null) throw new IllegalStateException("Missing editor build metadata");
|
||||
metadata.load(input);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot read editor build metadata", e);
|
||||
}
|
||||
String website = metadata.getProperty("website");
|
||||
return website;
|
||||
}
|
||||
private final JavaPlugin plugin;
|
||||
private final String editorPlugin;
|
||||
private final String editorName;
|
||||
private final Consumer<Runnable> sync;
|
||||
private final Consumer<CommandSender> reload;
|
||||
private final Predicate<CommandSender> allowed;
|
||||
private final Supplier<String> loadedConfig;
|
||||
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread thread = new Thread(r, "BetterRTP-editor"); thread.setDaemon(true); return thread;
|
||||
});
|
||||
private volatile boolean applying;
|
||||
private volatile boolean stopped;
|
||||
|
||||
public EditorBridge(JavaPlugin plugin, Consumer<Runnable> sync, Consumer<CommandSender> reload,
|
||||
Predicate<CommandSender> allowed, Supplier<String> loadedConfig) {
|
||||
this(plugin, sync, reload, allowed, loadedConfig, "betterrtp");
|
||||
}
|
||||
public EditorBridge(JavaPlugin plugin, Consumer<Runnable> sync, Consumer<CommandSender> reload,
|
||||
Predicate<CommandSender> allowed, Supplier<String> loadedConfig, String editorPlugin) {
|
||||
if (!Arrays.asList("betterrtp", "betterrtp-addons").contains(editorPlugin)) throw new IllegalArgumentException("Unknown editor plugin");
|
||||
this.editorPlugin = editorPlugin;
|
||||
this.editorName = editorPlugin.equals("betterrtp") ? "BetterRTP" : "BetterRTP Addons";
|
||||
this.plugin = plugin;
|
||||
this.sync = sync;
|
||||
this.reload = reload;
|
||||
this.allowed = allowed;
|
||||
this.loadedConfig = loadedConfig;
|
||||
// Saved versions are fetched only by an explicit editorsync command.
|
||||
}
|
||||
public void close() { stopped = true; worker.shutdownNow(); }
|
||||
|
||||
public void upload(CommandSender sender) {
|
||||
if (!allowed.test(sender)) return;
|
||||
try {
|
||||
byte[] bytes = EditorConfig.read(configPath());
|
||||
String content = new String(bytes, StandardCharsets.UTF_8); EditorConfig.parse(content);
|
||||
Upload upload = new Upload(sender instanceof Player ? ((Player) sender).getUniqueId() : null);
|
||||
// Snapshot loaded worlds on the command thread, before starting HTTP work.
|
||||
List<String> worlds = new ArrayList<>();
|
||||
for (org.bukkit.World world : Bukkit.getWorlds()) worlds.add(world.getName());
|
||||
sender.sendMessage("§7Uploading a private " + editorName + " editor config…");
|
||||
worker.execute(() -> {
|
||||
try {
|
||||
JsonObject body = new JsonObject(); body.addProperty("protocol", 4);
|
||||
body.addProperty("playerId", upload.player == null ? null : upload.player.toString());
|
||||
body.addProperty("configFile", "config.yml");
|
||||
body.addProperty("plugin", editorPlugin);
|
||||
JsonArray availableWorlds = new JsonArray();
|
||||
for (String world : worlds) availableWorlds.add(new JsonPrimitive(world));
|
||||
body.add("worlds", availableWorlds);
|
||||
body.addProperty("version", plugin.getDescription().getVersion()); body.addProperty("content", content);
|
||||
JsonObject result = request("POST", "/api/editor/tokens", body, null);
|
||||
String browserToken = result.get("token").getAsString();
|
||||
if (!browserToken.matches("[A-Za-z0-9_-]{8}")) throw new IOException("Invalid relay response.");
|
||||
if (stopped) return;
|
||||
sync.accept(() -> {
|
||||
if (stopped) return;
|
||||
CommandSender recipient = recipient(upload);
|
||||
if (recipient == null || !allowed.test(recipient)) return;
|
||||
String url = WEBSITE + "/editor/" + editorPlugin + "?token=" + browserToken;
|
||||
recipient.sendMessage("§ePrivate editor link: expires in 24 hours. Save online, then run the sync command here. Do not share it.");
|
||||
if (recipient instanceof Player) {
|
||||
TextComponent link = new TextComponent("§a[Open " + editorName + " editor]");
|
||||
link.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
|
||||
((Player) recipient).spigot().sendMessage(link);
|
||||
} else recipient.sendMessage(url);
|
||||
});
|
||||
} catch (Exception error) {
|
||||
plugin.getLogger().warning("Editor upload failed (" + error.getClass().getSimpleName() + "). Check website/database availability.");
|
||||
message(upload, "Could not upload the editor config. " + safeError(error));
|
||||
}
|
||||
});
|
||||
} catch (Exception error) { sender.sendMessage("§cEditor: " + error.getMessage()); }
|
||||
}
|
||||
|
||||
private Path configPath() { return plugin.getDataFolder().toPath().resolve("config.yml"); }
|
||||
private CommandSender recipient(Upload upload) { return upload.player == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(upload.player); }
|
||||
private void message(Upload upload, String text) {
|
||||
if (!stopped) sync.accept(() -> {
|
||||
CommandSender sender = recipient(upload); if (sender != null) sender.sendMessage("§eEditor: " + text);
|
||||
});
|
||||
}
|
||||
private void message(UUID playerId, String text) {
|
||||
if (!stopped) sync.accept(() -> {
|
||||
CommandSender player = playerId == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(playerId);
|
||||
if (player != null) player.sendMessage("§eEditor: " + text);
|
||||
});
|
||||
}
|
||||
public void redeem(CommandSender sender, String token) {
|
||||
if (!allowed.test(sender)) return;
|
||||
if (!token.matches("[A-Za-z0-9_-]{8}")) { sender.sendMessage("§cInvalid sync token. Copy the command from the editor."); return; }
|
||||
if (applying) { sender.sendMessage("§eAn editor sync is already in progress."); return; }
|
||||
final UUID executor = sender instanceof Player ? ((Player) sender).getUniqueId() : null;
|
||||
applying = true;
|
||||
sender.sendMessage("§7Downloading your saved configuration…");
|
||||
worker.execute(() -> {
|
||||
try {
|
||||
JsonObject response = request("GET", "/api/editor/sync", null, token);
|
||||
if (!"config.yml".equals(response.get("configFile").getAsString())) throw new IOException("Invalid sync target.");
|
||||
String edited = response.get("content").getAsString();
|
||||
long expires = response.get("expiresAt").getAsLong();
|
||||
// Public commands can come from any editor; validate against this server, not a browser baseline.
|
||||
String original = new String(EditorConfig.read(configPath()), StandardCharsets.UTF_8);
|
||||
EditorConfig.validate(original, edited);
|
||||
sync.accept(() -> apply(original, edited, expires, executor));
|
||||
} catch (Exception error) {
|
||||
applying = false;
|
||||
message(executor, "Sync failed: " + safeError(error) + " Save online again for a new command if this token was consumed.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static String safeError(Exception error) {
|
||||
// Do not log URLs, headers, raw responses, tokens, or config contents.
|
||||
if (error instanceof IOException && error.getMessage() != null && error.getMessage().startsWith("Relay HTTP "))
|
||||
return error.getMessage();
|
||||
return "Request or validation failed (" + error.getClass().getSimpleName() + ").";
|
||||
}
|
||||
|
||||
private void apply(String original, String edited, long tokenExpires, UUID executor) {
|
||||
try {
|
||||
if (stopped) return;
|
||||
if (System.currentTimeMillis() >= tokenExpires) throw new IOException("Sync token expired before apply.");
|
||||
CommandSender sender = executor == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(executor);
|
||||
if (sender == null || !allowed.test(sender)) throw new IOException("The syncing player must be online and still have editor permission.");
|
||||
Path backup = EditorConfig.apply(configPath(), original.getBytes(StandardCharsets.UTF_8), edited, () -> {
|
||||
reload.accept(sender);
|
||||
String loaded = loadedConfig.get();
|
||||
String persisted = new String(EditorConfig.read(configPath()), StandardCharsets.UTF_8);
|
||||
if (!EditorConfig.equivalent(persisted, loaded))
|
||||
throw new IOException("Loaded configuration does not match the saved settings.");
|
||||
});
|
||||
sender.sendMessage("§aEditor changes applied and reloaded. Backup: " + backup.getFileName());
|
||||
} catch (EditorConfig.ReloadFailure error) {
|
||||
message(executor, "Configuration saved, but reload failed. The new file remains in place. Check the console and reload the plugin.");
|
||||
plugin.getLogger().warning("Editor config was written but reload failed; no rollback was performed.");
|
||||
} catch (Exception error) {
|
||||
message(executor, "Sync not applied: " + error.getMessage());
|
||||
} finally { applying = false; }
|
||||
}
|
||||
|
||||
private JsonObject request(String method, String path, JsonObject body, String syncToken) throws IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(WEBSITE + path).openConnection();
|
||||
connection.setConnectTimeout(5000); connection.setReadTimeout(10000); connection.setInstanceFollowRedirects(false);
|
||||
connection.setRequestMethod(method); connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setRequestProperty("X-Editor-Actor", "plugin");
|
||||
connection.setRequestProperty("User-Agent", "BetterRTP-Editor/4");
|
||||
connection.setRequestProperty("X-Editor-Protocol", "4");
|
||||
connection.setRequestProperty("X-Editor-Plugin", editorPlugin);
|
||||
if (syncToken != null) {
|
||||
connection.setRequestProperty("X-Editor-Sync-Token", syncToken);
|
||||
}
|
||||
try {
|
||||
if (body != null) {
|
||||
byte[] bytes = body.toString().getBytes(StandardCharsets.UTF_8);
|
||||
connection.setDoOutput(true); connection.setFixedLengthStreamingMode(bytes.length);
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
try (OutputStream out = connection.getOutputStream()) { out.write(bytes); }
|
||||
}
|
||||
int status = connection.getResponseCode();
|
||||
if (status < 200 || status >= 300) throw new IOException("Relay HTTP " + status);
|
||||
try (InputStream in = connection.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
|
||||
byte[] chunk = new byte[8192]; int count;
|
||||
while ((count = in.read(chunk)) != -1) {
|
||||
if (buffer.size() + count > EditorConfig.MAX_BYTES * 6 + 4096) throw new IOException("Relay response too large.");
|
||||
buffer.write(chunk, 0, count);
|
||||
}
|
||||
return new JsonParser().parse(new String(buffer.toByteArray(), StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
}
|
||||
} finally { connection.disconnect(); }
|
||||
}
|
||||
private static final class Upload {
|
||||
final UUID player;
|
||||
Upload(UUID player) { this.player = player; }
|
||||
}
|
||||
}
|
||||
-300
@@ -1,300 +0,0 @@
|
||||
package me.SuperRonanCraft.BetterRTP.references.web.editor;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Fixed settings retain their schema; supported collections allow typed named entries. */
|
||||
public final class EditorConfig {
|
||||
public static final int MAX_BYTES = 128 * 1024;
|
||||
private static final Pattern TOKENS = Pattern.compile("(^|[\\s\\[\\]{},])[!&*]", Pattern.MULTILINE);
|
||||
private EditorConfig() { }
|
||||
|
||||
private static String withoutQuotedScalars(String text) {
|
||||
// Only complete, single-line quoted scalars: Minecraft color codes are text, not YAML anchors.
|
||||
return text.replaceAll("\"(?:\\\\[^\\r\\n]|[^\"\\\\\\r\\n])*\"|'(?:''|[^'\\r\\n])*'", "quoted");
|
||||
}
|
||||
|
||||
public static YamlConfiguration parse(String text) throws Exception {
|
||||
// Bukkit supports object deserialization through the reserved == key. Reject equals
|
||||
// and encoded character escapes before invoking its parser, not only after parsing.
|
||||
if (text.indexOf("==") >= 0 || Pattern.compile("\\\\[xuU]").matcher(text).find())
|
||||
throw new IOException("Object serialization markers and encoded character escapes are not supported.");
|
||||
if (text.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES || TOKENS.matcher(withoutQuotedScalars(text)).find())
|
||||
throw new IOException("Configuration too large, or YAML tags/anchors/aliases present.");
|
||||
int lines = 0, flow = 0;
|
||||
for (String line : text.split("\\n")) {
|
||||
if (++lines > 4000 || line.matches("^ {65}.*")) throw new IOException("Configuration is too complex.");
|
||||
for (char c : line.toCharArray()) if (c == '[' || c == '{') flow++;
|
||||
}
|
||||
if (flow > 128) throw new IOException("Too many flow collections.");
|
||||
YamlConfiguration parsed = new YamlConfiguration();
|
||||
parsed.loadFromString(text);
|
||||
if (parsed.isConfigurationSection("Flashback")) {
|
||||
for (String section : Arrays.asList("Flashback", "Logger", "Portals", "ExtraEffects", "MagicStick", "Commands", "Parties", "RTPMenu"))
|
||||
if (!parsed.isConfigurationSection(section)) throw new IOException("Missing addon section: " + section);
|
||||
} else if (!parsed.isConfigurationSection("Settings") || !parsed.isConfigurationSection("Default"))
|
||||
throw new IOException("Missing Settings or Default section.");
|
||||
return parsed;
|
||||
}
|
||||
|
||||
public static void validate(String original, String edited) throws Exception {
|
||||
YamlConfiguration before = parse(original), after = parse(edited);
|
||||
if (!Objects.equals(before.get("Language-File"), after.get("Language-File")))
|
||||
throw new IOException("Change Language-File locally, not through the web editor.");
|
||||
compare(before, after, "config", 0, (Map<?, ?>) normalize(after.get(after.isConfigurationSection("Flashback") ? "RTPMenu" : "Default")));
|
||||
if (after.isConfigurationSection("Flashback")) {
|
||||
new java.text.SimpleDateFormat(after.getString("Logger.Format"));
|
||||
org.bukkit.Material.valueOf(after.getString("MagicStick.Item.Material").toUpperCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
|
||||
private static Object normalize(Object value) {
|
||||
return value instanceof ConfigurationSection ? ((ConfigurationSection) value).getValues(false) : value;
|
||||
}
|
||||
|
||||
private static void compare(Object oldValue, Object newValue, String path, int depth, Map<?, ?> defaults) throws IOException {
|
||||
if (depth > 32) throw new IOException("Configuration nesting is too deep.");
|
||||
oldValue = normalize(oldValue); newValue = normalize(newValue);
|
||||
if (path.equals("config.RTPMenu.WorldList") || path.equals("config.Flashback.Timer.Warnings")) {
|
||||
addonEntries(oldValue, newValue, path, depth, defaults); return;
|
||||
}
|
||||
if (Arrays.asList("config.BlacklistedBlocks", "config.DisabledWorlds", "config.Default.Biomes").contains(path)) {
|
||||
stringList(newValue, path); return;
|
||||
}
|
||||
if (Arrays.asList("config.Overrides", "config.WorldType", "config.CustomWorlds", "config.PermissionGroup.Groups").contains(path)) {
|
||||
String kind = path.equals("config.Overrides") ? "overrides" : path.equals("config.WorldType") ? "types" : path.equals("config.CustomWorlds") ? "worlds" : "groups";
|
||||
named(oldValue, newValue, path, kind, depth, defaults); return;
|
||||
}
|
||||
if (oldValue instanceof Map) {
|
||||
if (!(newValue instanceof Map)) throw new IOException("Expected section: " + path);
|
||||
Map<?, ?> oldMap = (Map<?, ?>) oldValue, newMap = (Map<?, ?>) newValue;
|
||||
if (!oldMap.keySet().equals(newMap.keySet())) throw new IOException("Keep existing setting names: " + path);
|
||||
for (Object key : oldMap.keySet()) compare(oldMap.get(key), newMap.get(key), path + "." + key, depth + 1, defaults);
|
||||
checkRange(newMap, "MinRadius", "MaxRadius", path, true);
|
||||
checkRange(newMap, "MinY", "MaxY", path, false);
|
||||
} else if (oldValue instanceof List) {
|
||||
if (!(newValue instanceof List)) throw new IOException("Expected list: " + path);
|
||||
List<?> oldList = (List<?>) oldValue, newList = (List<?>) newValue;
|
||||
if (newList.size() > 1000) throw new IOException("List too long: " + path);
|
||||
boolean structured = oldList.stream().anyMatch(v -> normalize(v) instanceof Map);
|
||||
if (structured && oldList.size() != newList.size()) throw new IOException("Keep existing world/group entries: " + path);
|
||||
for (int i = 0; i < newList.size(); i++) {
|
||||
Object baseline = structured ? oldList.get(i) : oldList.isEmpty() ? "" : oldList.get(0);
|
||||
compare(baseline, newList.get(i), path + "[" + i + "]", depth + 1, defaults);
|
||||
}
|
||||
} else if (oldValue instanceof Number) {
|
||||
if (!(newValue instanceof Number)) throw new IOException("Expected number: " + path);
|
||||
double n = ((Number) newValue).doubleValue();
|
||||
if (!Double.isFinite(n) || n < Integer.MIN_VALUE || n > Integer.MAX_VALUE ||
|
||||
((oldValue instanceof Integer || oldValue instanceof Long) && n != Math.rint(n)))
|
||||
throw new IOException("Invalid number: " + path);
|
||||
if (path.equals("config.RTPMenu.Lines") && (n < 1 || n > 6)) throw new IOException("Menu lines must be 1–6.");
|
||||
if (Arrays.asList("config.RTPMenu.AutoRefresh", "config.Flashback.Timer.Delay").contains(path) && n < 0) throw new IOException("Negative time: " + path);
|
||||
if (path.equals("config.MagicStick.GiveFirstJoin.Amount") && (n < 1 || n > 64)) throw new IOException("Stick amount must be 1–64.");
|
||||
if (path.endsWith("Radius") && (n < 0 || n > 30000000)) throw new IOException("Invalid radius: " + path);
|
||||
if ((path.endsWith(".Time") || path.endsWith(".LockAfter")) && n < 0) throw new IOException("Negative time: " + path);
|
||||
if (path.endsWith(".PreloadRadius") && (n < 0 || n > 16)) throw new IOException("PreloadRadius must be 0–16.");
|
||||
if (path.endsWith(".MaxAttempts") && (n < 1 || n > 10000)) throw new IOException("MaxAttempts must be 1–10000.");
|
||||
} else if (oldValue instanceof Boolean) {
|
||||
if (!(newValue instanceof Boolean)) throw new IOException("Expected boolean: " + path);
|
||||
} else if (oldValue instanceof String) {
|
||||
if (!(newValue instanceof String)) throw new IOException("Expected text: " + path);
|
||||
if (path.endsWith(".Shape") && !Arrays.asList("square", "circle").contains(((String) newValue).toLowerCase(Locale.ROOT)))
|
||||
throw new IOException("Shape must be square or circle.");
|
||||
} else if (!Objects.equals(oldValue, newValue)) throw new IOException("Unsupported setting: " + path);
|
||||
}
|
||||
|
||||
private static void addonEntries(Object before, Object after, String path, int depth, Map<?, ?> defaults) throws IOException {
|
||||
boolean warnings = path.endsWith("Warnings");
|
||||
Map<String, Object> old = addonMap(before, path), next = addonMap(after, path);
|
||||
for (Map.Entry<String, Object> entry : next.entrySet()) {
|
||||
String key = entry.getKey(); Object value = normalize(entry.getValue());
|
||||
if (warnings) {
|
||||
try {
|
||||
if (!key.matches("[0-9]+") || Long.parseLong(key) > Integer.MAX_VALUE || !(value instanceof String))
|
||||
throw new IOException("Invalid warning: " + key);
|
||||
} catch (NumberFormatException e) { throw new IOException("Invalid warning time."); }
|
||||
} else {
|
||||
if (!(value instanceof Map)) throw new IOException("Expected menu world settings.");
|
||||
Map<?, ?> settings = (Map<?, ?>) value;
|
||||
Object previousValue = normalize(old.get(key));
|
||||
Map<?, ?> previous = previousValue instanceof Map ? (Map<?, ?>) previousValue : Collections.emptyMap();
|
||||
Map<String, Object> schema = new LinkedHashMap<>();
|
||||
schema.put("Name", ""); schema.put("Item", "MAP"); schema.put("Slot", 0); schema.put("Lore", Collections.emptyList());
|
||||
for (Map.Entry<?, ?> field : settings.entrySet()) {
|
||||
String name = String.valueOf(field.getKey());
|
||||
if (!schema.containsKey(name) && !previous.containsKey(name)) throw new IOException("Unknown menu setting: " + name);
|
||||
compare(schema.containsKey(name) ? schema.get(name) : previous.get(name), field.getValue(), path + "." + key + "." + name, depth + 1, defaults);
|
||||
}
|
||||
for (Object name : previous.keySet())
|
||||
if (!schema.containsKey(name) && !settings.containsKey(name)) throw new IOException("Keep existing menu setting: " + name);
|
||||
Object slot = settings.containsKey("Slot") ? settings.get("Slot") : 0;
|
||||
if (!(slot instanceof Number) || ((Number) slot).intValue() < 0 || ((Number) slot).intValue() >= ((Number) defaults.get("Lines")).intValue() * 9)
|
||||
throw new IOException("Menu slot must fit within the configured lines.");
|
||||
if (settings.containsKey("Item")) {
|
||||
try { org.bukkit.Material.valueOf(((String) settings.get("Item")).toUpperCase(Locale.ROOT)); }
|
||||
catch (IllegalArgumentException e) { throw new IOException("Unknown menu material."); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> addonMap(Object value, String path) throws IOException {
|
||||
if (!(value instanceof List) || ((List<?>) value).size() > 1000) throw new IOException("Expected named list: " + path);
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
for (Object item : (List<?>) value) {
|
||||
item = normalize(item);
|
||||
if (!(item instanceof Map) || ((Map<?, ?>) item).isEmpty()) throw new IOException("Expected named entry: " + path);
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) item).entrySet()) {
|
||||
String key = String.valueOf(entry.getKey());
|
||||
if (!validName(key) || result.containsKey(key)) throw new IOException("Invalid or duplicate name: " + path);
|
||||
result.put(key, entry.getValue());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static boolean validName(String value) {
|
||||
return !value.trim().isEmpty() && value.equals(value.trim()) && value.length() <= 100 && !Pattern.compile("[\\x00-\\x1f]").matcher(value).find();
|
||||
}
|
||||
|
||||
private static void stringList(Object value, String path) throws IOException {
|
||||
if (!(value instanceof List) || ((List<?>) value).size() > 1000) throw new IOException("Expected text list: " + path);
|
||||
for (Object item : (List<?>) value)
|
||||
if (!(item instanceof String) || ((String) item).trim().isEmpty()) throw new IOException("Expected non-empty text: " + path);
|
||||
}
|
||||
|
||||
private static Map<String, Object> entries(Object value, String path) throws IOException {
|
||||
if (!(value instanceof List) || ((List<?>) value).size() > 1000) throw new IOException("Expected named list: " + path);
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
for (Object item : (List<?>) value) {
|
||||
item = normalize(item);
|
||||
if (!(item instanceof Map) || ((Map<?, ?>) item).isEmpty()) throw new IOException("Expected named entry: " + path);
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) item).entrySet()) {
|
||||
if (!(entry.getKey() instanceof String) || !validName((String) entry.getKey()) || result.containsKey(entry.getKey()))
|
||||
throw new IOException("Invalid or duplicate name: " + path);
|
||||
result.put((String) entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Map<String, Object> worldSettings(boolean group) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
for (String name : Arrays.asList("MaxRadius", "MinRadius", "CenterX", "CenterZ", "Price", "MaxY", "MinY", "Cooldown")) result.put(name, 0);
|
||||
result.put("UseWorldBorder", false); result.put("RTPOnDeath", false);
|
||||
result.put("Shape", "square"); result.put("Biomes", Collections.emptyList());
|
||||
if (group) result.put("Priority", 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void named(Object before, Object after, String path, String kind, int depth, Map<?, ?> defaults) throws IOException {
|
||||
if (depth > 32) throw new IOException("Configuration nesting is too deep.");
|
||||
Map<String, Object> old = entries(before, path), next = entries(after, path);
|
||||
for (Map.Entry<String, Object> entry : next.entrySet()) {
|
||||
String key = entry.getKey(), at = path + "." + key;
|
||||
Object value = normalize(entry.getValue());
|
||||
if (kind.equals("overrides")) {
|
||||
if (!(value instanceof String) || !validName((String) value)) throw new IOException("Invalid target world: " + at);
|
||||
} else if (kind.equals("types")) {
|
||||
if (!(value instanceof String) || !Arrays.asList("NORMAL", "NETHER").contains(((String) value).toUpperCase(Locale.ROOT)))
|
||||
throw new IOException("World type must be NORMAL or NETHER: " + at);
|
||||
} else if (kind.equals("groups")) {
|
||||
named(old.containsKey(key) ? old.get(key) : Collections.emptyList(), value, at, "groupWorlds", depth + 1, defaults);
|
||||
} else {
|
||||
if (!(value instanceof Map)) throw new IOException("Expected world settings: " + at);
|
||||
Map<?, ?> settings = (Map<?, ?>) value;
|
||||
Object previousValue = normalize(old.get(key));
|
||||
Map<?, ?> previous = previousValue instanceof Map ? (Map<?, ?>) previousValue : Collections.emptyMap();
|
||||
Map<String, Object> allowed = worldSettings(kind.equals("groupWorlds"));
|
||||
for (Map.Entry<?, ?> field : settings.entrySet()) {
|
||||
if (!(field.getKey() instanceof String)) throw new IOException("Invalid setting name: " + at);
|
||||
String name = (String) field.getKey(); Object val = field.getValue();
|
||||
if (name.equals("Biomes")) stringList(val, at + ".Biomes");
|
||||
else if (allowed.containsKey(name)) {
|
||||
compare(allowed.get(name), val, at + "." + name, depth + 1, defaults);
|
||||
if (name.equals("Cooldown") && ((Number) val).doubleValue() < 0) throw new IOException("Negative cooldown: " + at);
|
||||
} else if (previous.containsKey(name)) compare(previous.get(name), val, at + "." + name, depth + 1, defaults);
|
||||
else throw new IOException("Unsupported world setting: " + at + "." + name);
|
||||
}
|
||||
for (Object name : previous.keySet())
|
||||
if (!allowed.containsKey(name) && !settings.containsKey(name)) throw new IOException("Keep existing setting: " + at + "." + name);
|
||||
Map<Object, Object> effective = new LinkedHashMap<>(); effective.putAll(defaults); effective.putAll(settings);
|
||||
checkRange(effective, "MinRadius", "MaxRadius", at, true);
|
||||
checkRange(effective, "MinY", "MaxY", at, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkRange(Map<?, ?> map, String min, String max, String path, boolean strict) throws IOException {
|
||||
if (map.get(min) instanceof Number && map.get(max) instanceof Number) {
|
||||
double a = ((Number) map.get(min)).doubleValue(), b = ((Number) map.get(max)).doubleValue();
|
||||
if (strict ? a >= b : a > b) throw new IOException("Invalid " + min + "/" + max + " range: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Reload { void run() throws Exception; }
|
||||
|
||||
public static Path apply(Path file, byte[] snapshot, String edited, Reload reload) throws Exception {
|
||||
validate(new String(snapshot, StandardCharsets.UTF_8), edited);
|
||||
Path backups = file.getParent().resolve("editor-backups");
|
||||
Files.createDirectories(backups);
|
||||
Path backup = backups.resolve("config-" + System.currentTimeMillis() + "-" + UUID.randomUUID() + ".yml");
|
||||
// Back up the current file, but intentionally allow intervening local changes.
|
||||
Files.write(backup, read(file), StandardOpenOption.CREATE_NEW);
|
||||
replace(file, edited.getBytes(StandardCharsets.UTF_8));
|
||||
try {
|
||||
reload.run();
|
||||
if (!equivalent(edited, new String(read(file), StandardCharsets.UTF_8)))
|
||||
throw new IOException("Saved configuration does not match the submission.");
|
||||
} catch (Exception failure) {
|
||||
throw new ReloadFailure(failure);
|
||||
}
|
||||
return backup;
|
||||
}
|
||||
|
||||
public static final class ReloadFailure extends IOException {
|
||||
public ReloadFailure(Exception cause) { super("Configuration written, but reload failed. No rollback was performed.", cause); }
|
||||
}
|
||||
|
||||
public static boolean equivalent(String expected, String actual) throws Exception {
|
||||
return tree(parse(expected)).equals(tree(parse(actual)));
|
||||
}
|
||||
|
||||
private static Object tree(Object value) {
|
||||
value = normalize(value);
|
||||
if (value instanceof Map) {
|
||||
Map<Object, Object> result = new LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) result.put(entry.getKey(), tree(entry.getValue()));
|
||||
return result;
|
||||
}
|
||||
if (value instanceof List) {
|
||||
List<Object> result = new ArrayList<>();
|
||||
for (Object item : (List<?>) value) result.add(tree(item));
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static byte[] read(Path file) throws IOException {
|
||||
if (Files.size(file) > MAX_BYTES) throw new IOException("config.yml exceeds 128 KiB.");
|
||||
byte[] result = Files.readAllBytes(file);
|
||||
if (result.length > MAX_BYTES) throw new IOException("config.yml exceeds 128 KiB.");
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void replace(Path file, byte[] bytes) throws IOException {
|
||||
Path temp = Files.createTempFile(file.getParent(), ".editor-", ".tmp");
|
||||
try {
|
||||
Files.write(temp, bytes);
|
||||
// Fail closed if this filesystem cannot atomically replace the configuration.
|
||||
Files.move(temp, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@
|
||||
<version>1.8.10</version>
|
||||
|
||||
<properties>
|
||||
<editor.website>https://www.minecentral.net</editor.website>
|
||||
<bettersync.version>1.0.1</bettersync.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@@ -50,6 +52,8 @@
|
||||
<configuration>
|
||||
<dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
|
||||
<relocations>
|
||||
<relocation><pattern>com.ronanplugins.bettersync</pattern><shadedPattern>me.SuperRonanCraft.BetterRTPAddons.lib.bettersync</shadedPattern></relocation>
|
||||
|
||||
<relocation>
|
||||
<pattern>io.papermc.lib</pattern>
|
||||
<shadedPattern>me.SuperRonanCraft.BetterRTPAddons.paperlib</shadedPattern>
|
||||
@@ -131,8 +135,15 @@
|
||||
<id>dmulloy2-repo</id>
|
||||
<url>https://repo.dmulloy2.net/nexus/repository/public/</url>
|
||||
</repository>
|
||||
<repository><id>jitpack.io</id><url>https://jitpack.io</url></repository>
|
||||
</repositories>
|
||||
<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-->
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package me.SuperRonanCraft.BetterRTPAddons;
|
||||
|
||||
import com.ronanplugins.bettersync.editor.EditorClient;
|
||||
import com.ronanplugins.bettersync.editor.EditorProfile;
|
||||
|
||||
import lombok.Getter;
|
||||
import me.SuperRonanCraft.BetterRTPAddons.util.Files;
|
||||
import me.SuperRonanCraft.BetterRTPAddons.util.ReloadListener;
|
||||
@@ -18,7 +21,7 @@ public class Main extends JavaPlugin {
|
||||
private final ReloadListener reloadListener = new ReloadListener();
|
||||
|
||||
@Getter
|
||||
private me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge editorBridge;
|
||||
private EditorClient editorBridge;
|
||||
|
||||
public boolean canEdit(org.bukkit.command.CommandSender sender) {
|
||||
return !(sender instanceof org.bukkit.entity.Player) || sender.hasPermission("betterrtp.addon.editor");
|
||||
@@ -29,9 +32,11 @@ public class Main extends JavaPlugin {
|
||||
instance = this;
|
||||
Bukkit.getPluginManager().registerEvents(reloadListener, this);
|
||||
load();
|
||||
editorBridge = new me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge(
|
||||
this, me.SuperRonanCraft.BetterRTP.versions.AsyncHandler::sync, sender -> load(),
|
||||
this::canEdit, () -> Files.FILETYPE.CONFIG.getConfig().saveToString(), "betterrtp-addons");
|
||||
editorBridge = new EditorClient(
|
||||
this, EditorProfile.BETTERRTP_ADDONS,
|
||||
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
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
website=${editor.website}
|
||||
@@ -52,3 +52,15 @@ The wiki is available [here](../../wiki)!
|
||||
<br/>
|
||||
<b><i><a href="https://www.spigotmc.org/resources/authors/superronancraft.13025/">Check out my other plugins!</a></i></b>
|
||||
</p>
|
||||
|
||||
## Shared editor library
|
||||
|
||||
The web editor uses [BetterSync](https://github.com/RonanPlugins/BetterSync),
|
||||
downloaded by Maven from JitPack as `com.github.RonanPlugins:BetterSync:1.0.1`.
|
||||
No local BetterSync project or manual Maven install is required. Release `1.0.1` 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.
|
||||
@@ -1,9 +1,10 @@
|
||||
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>me.SuperRonanCraft</groupId><artifactId>betterrtp-editor-tests</artifactId><version>1.0</version>
|
||||
<properties><maven.compiler.release>8</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<repositories><repository><id>spigot</id><url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url></repository></repositories>
|
||||
<properties><bettersync.version>1.0.1</bettersync.version><maven.compiler.release>8</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<repositories><repository><id>spigot</id><url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url></repository><repository><id>jitpack.io</id><url>https://jitpack.io</url></repository></repositories>
|
||||
<dependencies>
|
||||
<dependency><groupId>com.github.RonanPlugins</groupId><artifactId>BetterSync</artifactId><version>${bettersync.version}</version></dependency>
|
||||
<dependency><groupId>org.spigotmc</groupId><artifactId>spigot-api</artifactId><version>1.8.8-R0.1-SNAPSHOT</version><exclusions><exclusion><groupId>net.md-5</groupId><artifactId>bungeecord-chat</artifactId></exclusion></exclusions></dependency>
|
||||
<dependency><groupId>net.md-5</groupId><artifactId>bungeecord-chat</artifactId><version>1.16-R0.4</version></dependency>
|
||||
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import me.SuperRonanCraft.BetterRTP.references.web.editor.EditorConfig;
|
||||
import com.ronanplugins.bettersync.editor.betterrtp.EditorConfig;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import java.nio.file.*;
|
||||
|
||||
Reference in new issue
Block a user