From c37b65af5273a08f2196fcdfdf8e4184b9b3fe1e Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:18:35 +0100 Subject: [PATCH] Integrate DuneGroups with explicit backend activation --- .forgejo/workflows/dunegroups.yml | 41 ++++ DuneGroups/README.md | 53 +++++ DuneGroups/build.gradle.kts | 14 ++ DuneGroups/settings.gradle.kts | 1 + .../com/example/dunegroups/DuneGroups.java | 148 ++++++++++++++ .../com/example/dunegroups/HomeRegistry.java | 171 +++++++++++++++++ .../com/example/dunegroups/PvpListener.java | 67 +++++++ .../com/example/dunegroups/PvpPolicy.java | 19 ++ DuneGroups/src/main/resources/config.yml | 4 + DuneGroups/src/main/resources/plugin.yml | 15 ++ .../example/dunegroups/HomeRegistryTest.java | 101 ++++++++++ .../com/example/dunegroups/PvpPolicyTest.java | 23 +++ .../jarvis/CentralClanDirectory.java | 19 ++ .../com/dunerealms/jarvis/ClanDirectory.java | 19 ++ .../jarvis/DuneGroupsKeyWorker.java | 181 ++++++++++++++++++ .../jarvis/FactionClanDirectory.java | 32 ++++ .../com/dunerealms/jarvis/ImperialRaid.java | 45 ++--- .../dunerealms/jarvis/ImperialRaidWorker.java | 4 +- .../dunerealms/jarvis/JarvisTranslator.java | 14 +- .../dunerealms/jarvis/NativeKeyWorker.java | 6 +- .../com/dunerealms/jarvis/NativeKeys.java | 10 + .../jarvis/OrganisationDirectory.java | 108 +++++++++++ JarvisConnector/src/main/resources/plugin.yml | 2 +- .../jarvis/OrganisationDirectoryTest.java | 69 +++++++ 24 files changed, 1124 insertions(+), 42 deletions(-) create mode 100644 .forgejo/workflows/dunegroups.yml create mode 100644 DuneGroups/README.md create mode 100644 DuneGroups/build.gradle.kts create mode 100644 DuneGroups/settings.gradle.kts create mode 100644 DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java create mode 100644 DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java create mode 100644 DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java create mode 100644 DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java create mode 100644 DuneGroups/src/main/resources/config.yml create mode 100644 DuneGroups/src/main/resources/plugin.yml create mode 100644 DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java create mode 100644 DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/CentralClanDirectory.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/ClanDirectory.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/DuneGroupsKeyWorker.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/FactionClanDirectory.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeys.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/OrganisationDirectory.java create mode 100644 JarvisConnector/src/test/java/com/dunerealms/jarvis/OrganisationDirectoryTest.java diff --git a/.forgejo/workflows/dunegroups.yml b/.forgejo/workflows/dunegroups.yml new file mode 100644 index 00000000..179a90e9 --- /dev/null +++ b/.forgejo/workflows/dunegroups.yml @@ -0,0 +1,41 @@ +name: DuneGroups Replacement Build +on: + workflow_dispatch: + push: + branches: ['feat/dunegroups-replacement-*'] + +jobs: + dunegroups: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and test both replacement plugins + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + gradle --no-daemon -p DuneGroups test jar + mkdir dunegroups-artifacts + cp JarvisConnector/build/libs/jarvistranslator.jar DuneGroups/build/libs/DuneGroups.jar dunegroups-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > dunegroups-artifacts/SOURCE_COMMIT + (cd dunegroups-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-DuneGroups-Replacement + path: dunegroups-artifacts/ + if-no-files-found: error diff --git a/DuneGroups/README.md b/DuneGroups/README.md new file mode 100644 index 00000000..5a6eeca9 --- /dev/null +++ b/DuneGroups/README.md @@ -0,0 +1,53 @@ +# DuneGroups: replaces Towny and Medieval Factions + +Built from canonical plugins main `5d727d7f59e6af26fba07a3878fd79035a5923ce`. Web main `8c25f491...` was not touched or needed. Nothing is pushed to DuneGit. `/plot` and wilderness drafts are not included. + +## Switch +`JarvisConnector config.yml: native.backend: legacy | dunegroups` (default `legacy`). +- `legacy`: unchanged behaviour. If DuneGroups is installed it is told to deactivate, so the jar alone changes nothing. +- `dunegroups`: JARVIS activates DuneGroups. If DuneGroups or WorldGuard is missing, JARVIS logs SEVERE and disables itself instead of running without Home Block and WorldGuard projection. +Rollback: set `legacy`, restart. DuneGroups drops every rule and its in-memory projection. Its `homes.yml` is kept for the next activation. + +## What replaced what +| Before | Now | +|---|---| +| Towny town home block / Factions home claim | DuneGroups home chunk registry (clans, companies, protected offices, expanded estate chunks, claim revisions) | +| Towny `setPVP(false)` | DuneGroups: nobody can hurt anybody on a company or protected-office home chunk (melee, projectiles, TNT, tamed pets, fire, splash, lingering clouds). Clans stay PvP. Only ever cancels; never clears another plugin's cancellation | +| NativeWorldGuard estate regions | Unchanged class, now also run by the new worker for clans, companies and offices, with wars | +| Home NPCs, Kaitain Emperor NPC | Same code, driven by the new worker | +| Faction roster/roles/neutrality/parents/wars | `OrganisationDirectory`: central projection persisted in `organisation-directory.json` | +| ImperialRaid asking MedievalFactions | `ClanDirectory` (central projection). Paid receipt validation, spawn checks, journal recovery and refunds are unchanged. New: the target claim revision must match the permit | +| Faction AT_WAR/LIEGE edges, Towny nations, mayor/caretaker, power | Retired. No consumer outside the old worker was found. `WarCampaignWorker` is untouched | + +## Relocation cleanup +Acknowledged only after verified absence of: DuneGroups claims, WorldGuard regions, the Home NPC, and any legacy Towny/Factions projection (if those plugins are still installed). The cleanup is written to `dunegroups-worker.yml` before the original requestId/keyId is acknowledged, and an unacknowledged one is re-sent first after a restart. No block is ever removed. + +## Bank +No bank, balance or Vault code was added or touched. Native roles grant nothing. The shared-inventory SQL (`ExchangeInventory`) is untouched. + +## Verified (CI, unimatrixgit/mcdune-backup branch claude/menus-ci) +- DuneGroups builds; 12 unit tests: chunk maths, conflicts, malformed UUID/world/coordinates/revision, stale revision, unresolved vs archived, storage round trip, PvP policy. +- JarvisConnector compiles with all changes; OrganisationDirectoryTest (rosters, roles, neutrality, parents, wars, review retention, duplicate war key, storage); existing TerrainAuthority/NativeCommandPolicy tests pass. + +## NOT verified (needs a server) +Reflection into Paper and WorldGuard, the PvP listener on real events, WorldGuard region writes, Home NPC placement, relocation and restart recovery end to end, paid travel, a real raid, and running with both vendor jars absent. Run the canary below before removing either plugin. + +## Canary checklist (one planet, vendor jars removed, vendor data kept) +1. Start with `legacy`, confirm normal. Switch to `dunegroups`, restart: expect `DuneGroups active`, no SEVERE. +2. `/jarvis status`: clans/companies/offices/wars/home chunks counts match the website. +3. `/dunegroups here` on a clan, company and office home chunk; hit a player from outside and inside a company chunk; throw a harmful splash and lingering potion. +4. WorldGuard: outsider cannot build in an estate; member can. +5. Home NPC present for a clan and a company. Kaitain: Emperor NPC. +6. Relocate a clan home: old chunk, region and NPC gone, then acknowledged once. Kill the server between persist and ack: after restart it acknowledges once. +7. Break `homes.yml` write permission: sync must fail loudly and keep the old projection. +8. Raid: paid order accepted, spawn checks pass, refund path on a stale revision. +9. Switch back to `legacy`: DuneGroups rules stop immediately. + +## Open items found by the audit (not changed) +- `tools/install-plugin-fleet.py:277` still requires a reviewed MedievalFactions runtime. Fleet install fails without it. +- `tools/allow-giedi-nether-pearl.py` and `tools/disable-unused-vendor-settings.*` configure Towny; Giedi Prime's Ender Pearl rule lives in Towny's unclaimed-zone settings and disappears with Towny. +- `DuneTerrain/trails/*-config.yml` carry Towny path settings; harmless without Towny. +- `NativeCommandPolicy` still intercepts `/town`, `/f`, `/mf` etc.; harmless but now redundant. +- Company PvP has no exemption for active war campaigns. If wars on company land must allow PvP, say so. +- Claim revision is read from `homeBlock.claimRevision` (fallback `claimRevision`); confirm the website uses that field. +- The Towny nation/office tree is not reproduced anywhere; only protected neutrality and parents are kept as data. diff --git a/DuneGroups/build.gradle.kts b/DuneGroups/build.gradle.kts new file mode 100644 index 00000000..35991453 --- /dev/null +++ b/DuneGroups/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { java } +group = "com.example" +version = "1.0.0" +repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneGroups.jar") } diff --git a/DuneGroups/settings.gradle.kts b/DuneGroups/settings.gradle.kts new file mode 100644 index 00000000..a3cc54fe --- /dev/null +++ b/DuneGroups/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneGroups" diff --git a/DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java b/DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java new file mode 100644 index 00000000..31290b53 --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java @@ -0,0 +1,148 @@ +package com.example.dunegroups; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.*; + +/** + * Home blocks for JARVIS clans, companies and protected offices. JARVIS stays the source of truth and calls + * {@link #activate()}, {@link #sync(String)}, {@link #claimCount(String, String)} and {@link #deactivate()} by reflection. + * Installing the jar alone changes nothing: until JARVIS activates it there are no rules and no cached projection in force. + */ +public final class DuneGroups extends JavaPlugin implements CommandExecutor { + private final HomeRegistry registry = new HomeRegistry(); + private volatile boolean active; + private boolean fresh; + private File cache; + private Set pvpFreeKinds = Set.of("company", "protected"); + private String pvpFreeMessage = "PvP is disabled on company land."; + + @Override public void onEnable() { + saveDefaultConfig(); + cache = new File(getDataFolder(), "homes.yml"); + loadConfigValues(); + getServer().getPluginManager().registerEvents(new PvpListener(this), this); + var cmd = getCommand("dunegroups"); + if (cmd != null) cmd.setExecutor(this); + getLogger().info("DuneGroups installed and inactive. It starts only when JARVIS uses native.backend: dunegroups."); + } + + @Override public void onDisable() { deactivate(); } + + private void loadConfigValues() { + reloadConfig(); + Set kinds = new HashSet<>(); + for (String k : getConfig().getStringList("pvp-free-kinds")) kinds.add(k.toLowerCase(Locale.ROOT)); + pvpFreeKinds = kinds; + pvpFreeMessage = getConfig().getString("pvp-free-message", pvpFreeMessage); + } + + boolean active() { return active; } + + /** Starts the rules and loads the last stored projection. Throws if the stored projection is unreadable. */ + public synchronized void activate() { + if (active) return; + if (!fresh) throw new IllegalStateException("Waiting for fresh central state"); + active = true; + getLogger().info("DuneGroups active with " + registry.size() + " home chunk(s)."); + } + + private void readCache() throws IOException { + if (cache.exists()) { + try (var in = Files.newBufferedReader(cache.toPath())) { + Object raw = new Yaml().load(in); + if (raw instanceof Map m) registry.install(HomeRegistry.fromMap((Map) m.get("chunks")), String.valueOf(m.get("state") == null ? "" : m.get("state"))); + } catch (RuntimeException broken) { throw new IOException("homes.yml is unreadable: " + broken.getMessage(), broken); } + } + } + + /** Stops every rule at once and forgets the in-memory projection. The stored file is kept for the next activation. */ + public synchronized void deactivate() { + if (!active && !fresh && registry.size() == 0) return; + active = false; + fresh = false; + registry.install(Map.of(), ""); + getLogger().info("DuneGroups deactivated; no rules are in force."); + } + + private void store(Map next, String state) throws IOException { + Files.createDirectories(cache.toPath().getParent()); + String text = new Yaml().dump(Map.of("state", state, "chunks", HomeRegistry.toMap(next))); + File tmp = new File(getDataFolder(), "homes.yml.tmp"); + Files.writeString(tmp.toPath(), text); + try { Files.move(tmp.toPath(), cache.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } + catch (java.nio.file.AtomicMoveNotSupportedException unsupported) { Files.move(tmp.toPath(), cache.toPath(), StandardCopyOption.REPLACE_EXISTING); } + } + + private static JsonArray rows(JsonObject o, String field) { + JsonElement e = o.get(field); + return e == null || e.isJsonNull() ? null : e.getAsJsonArray(); + } + + /** + * Payload: {"stateId":"...","clans":[],"companies":[],"offices":[],"unresolved":[{"kind":"clan","id":"..."}]}. + * Replaces every home chunk atomically. Throws on malformed or conflicting data (the last valid projection stays) and on + * any storage failure (nothing is swapped in). Returns the number of home chunks now registered. + */ + public synchronized int sync(String json) throws IOException { + if (!fresh) readCache(); + JsonObject o = JsonParser.parseString(json).getAsJsonObject(); + Map by = new HashMap<>(); + by.put("clan", rows(o, "clans")); by.put("company", rows(o, "companies")); by.put("protected", rows(o, "offices")); + List unresolved = new ArrayList<>(); + if (o.has("unresolved") && o.get("unresolved").isJsonArray()) + for (JsonElement v : o.getAsJsonArray("unresolved")) { + JsonObject r = v.getAsJsonObject(); + unresolved.add(new HomeRegistry.Ref(r.get("kind").getAsString(), r.get("id").getAsString())); + } + String state = o.has("stateId") ? o.get("stateId").getAsString() : ""; + Map next = HomeRegistry.parse(by, unresolved, registry.snapshot()); + if (!next.equals(registry.snapshot()) || !state.equals(registry.stateId())) { + store(next, state); + registry.install(next, state); + } + fresh = true; + return registry.size(); + } + + /** Number of home chunks currently owned by this group. Zero proves the old claim is gone. */ + public long claimCount(String kind, String id) { return registry.claimCount(kind, id); } + + HomeRegistry.Entry ownerAt(Location at) { + if (!active || at == null || at.getWorld() == null) return null; + return registry.at(at.getWorld().getUID().toString(), Math.floorDiv(at.getBlockX(), 16), Math.floorDiv(at.getBlockZ(), 16)); + } + + boolean pvpFree(Location at) { var e = ownerAt(at); return e != null && pvpFreeKinds.contains(e.kind()); } + String pvpFreeMessage() { return pvpFreeMessage; } + + @Override public boolean onCommand(CommandSender s, Command c, String l, String[] a) { + String sub = a.length == 0 ? "here" : a[0].toLowerCase(Locale.ROOT); + switch (sub) { + case "here" -> { + if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; } + var e = ownerAt(p.getLocation()); + s.sendMessage(!active ? "DuneGroups is inactive." : e == null ? "This block is not a home block." + : "Home block of " + e.kind() + " " + e.name() + (e.tag().isBlank() ? "" : " [" + e.tag() + "]") + (pvpFree(p.getLocation()) ? " (PvP-free)." : ".")); + } + case "list" -> { if (!s.hasPermission("dunegroups.admin")) s.sendMessage("No permission."); else s.sendMessage((active ? "Active, " : "Inactive, ") + registry.size() + " home chunk(s)."); } + case "reload" -> { if (!s.hasPermission("dunegroups.admin")) s.sendMessage("No permission."); else { loadConfigValues(); s.sendMessage("DuneGroups config reloaded."); } } + default -> s.sendMessage("/dunegroups "); + } + return true; + } +} diff --git a/DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java b/DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java new file mode 100644 index 00000000..f80800ee --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java @@ -0,0 +1,171 @@ +package com.example.dunegroups; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.*; + +/** + * Which central clan, company or protected office owns which home chunk. Pure logic, no Bukkit types. + * A bad or conflicting payload is rejected as a whole so the last valid projection stays in force. + */ +final class HomeRegistry { + static final Set KINDS = Set.of("clan", "company", "protected"); + private static final int MAX_CHUNKS_PER_GROUP = 10_000, MAX_ROWS = 2_000; + private static final int CHUNK_LIMIT = 1_875_000; // world border 30,000,000 blocks / 16 + + record Entry(String kind, String id, String name, String tag, long revision) {} + record Ref(String kind, String id) {} + + /** Thrown for malformed rows, conflicting ownership and stale revisions. Never applied partially. */ + static final class Rejected extends IllegalArgumentException { + Rejected(String message) { super(message); } + } + + private volatile Map chunks = Map.of(); + private volatile String stateId = ""; + + static String key(String world, int chunkX, int chunkZ) { return world + ":" + chunkX + ":" + chunkZ; } + + Entry at(String world, int chunkX, int chunkZ) { return chunks.get(key(world, chunkX, chunkZ)); } + int size() { return chunks.size(); } + Map snapshot() { return chunks; } + String stateId() { return stateId; } + + long claimCount(String kind, String id) { + return chunks.values().stream().filter(e -> e.kind().equals(kind) && e.id().equals(id)).count(); + } + + void install(Map next, String state) { chunks = Map.copyOf(next); stateId = state == null ? "" : state; } + + // ---- parsing ---- + private static String str(JsonObject o, String f) { + JsonElement e = o.get(f); + return e == null || e.isJsonNull() || !e.isJsonPrimitive() ? "" : e.getAsString(); + } + + private static int integer(JsonObject o, String f, String what) { + JsonElement e = o.get(f); + if (e == null || !e.isJsonPrimitive() || !e.getAsJsonPrimitive().isNumber()) throw new Rejected(what + " is not a number"); + double d = e.getAsDouble(); + if (d != Math.rint(d) || Math.abs(d) > 30_000_000) throw new Rejected(what + " is out of range"); + return (int) d; + } + + private static boolean uuid(String s) { + try { UUID.fromString(s); return true; } catch (IllegalArgumentException bad) { return false; } + } + + private static boolean bool(JsonObject o, String f) { + JsonElement e = o.get(f); + return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isBoolean() && e.getAsBoolean(); + } + + private static void chunk(int cx, int cz, String what) { + if (Math.abs(cx) > CHUNK_LIMIT || Math.abs(cz) > CHUNK_LIMIT) throw new Rejected(what + " chunk is out of range"); + } + + /** + * Builds the next chunk map. Lifecycle {@code active} projects. {@code archived} or {@code retired}, hidden rows and ids + * that vanished from the payload are dropped. Any other lifecycle, and every id in {@code unresolved}, keeps whatever + * it owned before: an unresolved record is never treated as an absence. + */ + static Map parse(Map rowsByKind, Collection unresolved, Map previous) { + Map out = new HashMap<>(); + Set keep = new HashSet<>(unresolved); + int rows = 0; + for (var group : new TreeMap<>(rowsByKind).entrySet()) { + String kind = group.getKey(); + if (!KINDS.contains(kind)) throw new Rejected("Unknown group kind " + kind); + if (group.getValue() == null) continue; + TreeMap sorted = new TreeMap<>(); + for (JsonElement v : group.getValue()) { + if (!v.isJsonObject()) throw new Rejected("Row is not an object"); + JsonObject r = v.getAsJsonObject(); + String id = str(r, "id"); + if (!uuid(id)) throw new Rejected("Invalid " + kind + " id"); + if (sorted.put(id, r) != null) throw new Rejected("Duplicate " + kind + " " + id); + if (++rows > MAX_ROWS) throw new Rejected("Too many rows"); + } + for (JsonObject r : sorted.values()) { + String id = str(r, "id"), life = str(r, "lifecycle"); + if (life.equals("archived") || life.equals("retired") || bool(r, "hidden")) continue; + if (!life.equals("active")) { keep.add(new Ref(kind, id)); continue; } + project(out, kind, id, r, previous); + } + } + for (var entry : previous.entrySet()) { + Entry e = entry.getValue(); + if (!keep.contains(new Ref(e.kind(), e.id()))) continue; + Entry now = out.get(entry.getKey()); + if (now != null && !(now.kind().equals(e.kind()) && now.id().equals(e.id()))) + throw new Rejected("Chunk " + entry.getKey() + " is claimed by an active record while " + e.kind() + " " + e.id() + " is unresolved"); + out.putIfAbsent(entry.getKey(), e); + } + return out; + } + + private static void project(Map out, String kind, String id, JsonObject r, Map previous) { + if (!r.has("homeBlock") || !r.get("homeBlock").isJsonObject()) return; + JsonObject home = r.getAsJsonObject("homeBlock"); + if (!"minecraft".equals(str(home, "source"))) return; + String world = str(home, "worldUuid"); + if (!uuid(world)) throw new Rejected(kind + " " + id + " has an invalid world"); + if (!home.has("position") || !home.get("position").isJsonObject()) throw new Rejected(kind + " " + id + " has no position"); + JsonObject pos = home.getAsJsonObject("position"); + int x = integer(pos, "x", "x"), z = integer(pos, "z", "z"); + long revision = 0; + JsonElement rev = home.has("revision") ? home.get("revision") : r.get("claimRevision"); + if (rev != null && !rev.isJsonNull()) { + if (!rev.isJsonPrimitive() || !rev.getAsJsonPrimitive().isNumber() || rev.getAsDouble() < 0 || rev.getAsDouble() != Math.rint(rev.getAsDouble())) + throw new Rejected(kind + " " + id + " has an invalid claim revision"); + revision = rev.getAsLong(); + if (home.has("revision") && r.has("claimRevision") && (!r.get("claimRevision").isJsonPrimitive() || r.get("claimRevision").getAsLong() != revision)) + throw new Rejected(kind + " " + id + " claim revisions disagree"); + } + for (Entry old : previous.values()) + if (old.kind().equals(kind) && old.id().equals(id) && old.revision() > revision) + throw new Rejected(kind + " " + id + " claim revision " + revision + " is older than the applied " + old.revision()); + Entry entry = new Entry(kind, id, str(r, "name"), str(r, "tag"), revision); + Set mine = new LinkedHashSet<>(); + mine.add(key(world, Math.floorDiv(x, 16), Math.floorDiv(z, 16))); + if (r.has("claimedChunks") && r.get("claimedChunks").isJsonArray()) { + JsonArray c = r.getAsJsonArray("claimedChunks"); + if (c.size() > MAX_CHUNKS_PER_GROUP) throw new Rejected(kind + " " + id + " exceeds the estate bound"); + for (JsonElement v : c) { + if (!v.isJsonObject()) throw new Rejected(kind + " " + id + " has a malformed chunk"); + JsonObject o = v.getAsJsonObject(); + int cx = integer(o, "x", "chunk x"), cz = integer(o, "z", "chunk z"); + chunk(cx, cz, kind + " " + id); + mine.add(key(world, cx, cz)); + } + } + for (String k : mine) { + Entry other = out.get(k); + if (other != null && !(other.kind().equals(kind) && other.id().equals(id))) + throw new Rejected("Chunk " + k + " is claimed by both " + other.kind() + " " + other.id() + " and " + kind + " " + id); + out.put(k, entry); + } + } + + // ---- storage ---- + static Map toMap(Map m) { + Map out = new LinkedHashMap<>(); + new TreeMap<>(m).forEach((k, e) -> out.put(k, Map.of("kind", e.kind(), "id", e.id(), "name", e.name(), "tag", e.tag(), "revision", e.revision()))); + return out; + } + + static Map fromMap(Map raw) { + Map out = new HashMap<>(); + if (raw == null) return out; + raw.forEach((k, v) -> { + if (!(v instanceof Map o)) throw new Rejected("Cached entry is malformed"); + String kind = String.valueOf(o.get("kind")), id = String.valueOf(o.get("id")); + if (!KINDS.contains(kind) || !uuid(id)) throw new Rejected("Cached entry is malformed"); + long rev = o.get("revision") instanceof Number n ? n.longValue() : 0; + out.put(String.valueOf(k), new Entry(kind, id, String.valueOf(o.get("name")), String.valueOf(o.get("tag")), rev)); + }); + return out; + } +} diff --git a/DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java b/DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java new file mode 100644 index 00000000..8f440e98 --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java @@ -0,0 +1,67 @@ +package com.example.dunegroups; + +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.*; +import org.bukkit.potion.PotionEffect; + +import java.util.Collection; + +/** Cancels player-versus-player harm on PvP-free home blocks. Uses ignoreCancelled and never clears a cancellation. */ +final class PvpListener implements Listener { + private final DuneGroups plugin; + + PvpListener(DuneGroups plugin) { this.plugin = plugin; } + + /** The player a damage source belongs to, or null. Covers arrows, tridents, snowballs, TNT, clouds and tamed pets. */ + static Player attribution(Entity source) { + if (source instanceof Player p) return p; + if (source instanceof Projectile pr && pr.getShooter() instanceof Player p) return p; + if (source instanceof TNTPrimed tnt && tnt.getSource() instanceof Player p) return p; + if (source instanceof AreaEffectCloud cloud && cloud.getSource() instanceof Player p) return p; + if (source instanceof Tameable pet && pet.getOwner() instanceof Player p) return p; + return null; + } + + private boolean blocked(Player attacker, Player victim) { + return plugin.active() && PvpPolicy.blocked(attacker == victim, plugin.pvpFree(attacker.getLocation()), plugin.pvpFree(victim.getLocation())); + } + + private static boolean harmful(Collection effects) { + for (PotionEffect e : effects) if (PvpPolicy.harmful(e.getType().getKey().getKey())) return true; + return false; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamage(EntityDamageByEntityEvent e) { + if (!(e.getEntity() instanceof Player victim)) return; + Player attacker = attribution(e.getDamager()); + if (attacker == null || !blocked(attacker, victim)) return; + e.setCancelled(true); + attacker.sendMessage(plugin.pvpFreeMessage()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCombust(EntityCombustByEntityEvent e) { + if (e.getEntity() instanceof Player victim && attribution(e.getCombuster()) instanceof Player attacker && blocked(attacker, victim)) e.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSplash(PotionSplashEvent e) { + if (!(e.getEntity().getShooter() instanceof Player thrower) || !harmful(e.getPotion().getEffects())) return; + for (LivingEntity hit : e.getAffectedEntities()) + if (hit instanceof Player victim && blocked(thrower, victim)) e.setIntensity(victim, 0); + } + + /** Lingering potions: remove protected players from the cloud's current hit list. */ + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCloud(AreaEffectCloudApplyEvent e) { + if (!(e.getEntity().getSource() instanceof Player thrower)) return; + AreaEffectCloud cloud = e.getEntity(); + boolean bad = harmful(cloud.getCustomEffects()) || cloud.getBasePotionType() != null && harmful(cloud.getBasePotionType().getPotionEffects()); + if (!bad) return; + e.getAffectedEntities().removeIf(hit -> hit instanceof Player victim && blocked(thrower, victim)); + } +} diff --git a/DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java b/DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java new file mode 100644 index 00000000..c6f8bbfe --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java @@ -0,0 +1,19 @@ +package com.example.dunegroups; + +import java.util.Set; + +/** Pure rules for the company protection. Only ever decides to cancel; never to re-allow. */ +final class PvpPolicy { + private PvpPolicy() {} + + /** Potion effect keys (namespaced path names) that harm or hinder the target. */ + static final Set HARMFUL = Set.of("poison", "instant_damage", "weakness", "slowness", "wither", "blindness", + "hunger", "mining_fatigue", "nausea", "levitation", "darkness", "infested", "oozing", "weaving", "wind_charged", "bad_omen", "raid_omen"); + + static boolean harmful(String effectKey) { return HARMFUL.contains(effectKey == null ? "" : effectKey); } + + /** Players in a PvP-free chunk can neither hurt nor be hurt, whoever stands outside. Self damage is untouched. */ + static boolean blocked(boolean sameActor, boolean attackerInFree, boolean victimInFree) { + return !sameActor && (attackerInFree || victimInFree); + } +} diff --git a/DuneGroups/src/main/resources/config.yml b/DuneGroups/src/main/resources/config.yml new file mode 100644 index 00000000..25058fc0 --- /dev/null +++ b/DuneGroups/src/main/resources/config.yml @@ -0,0 +1,4 @@ +# DuneGroups only projects JARVIS home blocks. It has no claims, build protection or commands that create groups. +# Kinds that are PvP-free on their home chunk: company, protected (offices). Clans stay PvP. +pvp-free-kinds: [company, protected] +pvp-free-message: "PvP is disabled on company land." diff --git a/DuneGroups/src/main/resources/plugin.yml b/DuneGroups/src/main/resources/plugin.yml new file mode 100644 index 00000000..91c765c1 --- /dev/null +++ b/DuneGroups/src/main/resources/plugin.yml @@ -0,0 +1,15 @@ +name: DuneGroups +version: 1.0.0 +main: com.example.dunegroups.DuneGroups +api-version: '1.21.8' +load: STARTUP +description: Home blocks for JARVIS clans and companies. Companies are PvP-free on their home block. Replaces Towny and Medieval Factions. +commands: + dunegroups: + description: Show who owns the home block you stand on, or reload + usage: /dunegroups +permissions: + dunegroups.here: + default: true + dunegroups.admin: + default: op diff --git a/DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java b/DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java new file mode 100644 index 00000000..75931f53 --- /dev/null +++ b/DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java @@ -0,0 +1,101 @@ +package com.example.dunegroups; + +import com.google.gson.JsonArray; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; + +class HomeRegistryTest { + private static final String W = "11111111-1111-1111-1111-111111111111"; + private static final String A = "aaaaaaaa-0000-0000-0000-000000000001", B = "bbbbbbbb-0000-0000-0000-000000000002", C = "cccccccc-0000-0000-0000-000000000003"; + + private static JsonArray rows(String... json) { return JsonParser.parseString("[" + String.join(",", json) + "]").getAsJsonArray(); } + + private static String row(String id, String life, boolean hidden, int x, int z, String claims, String revision) { + return "{\"id\":\"" + id + "\",\"name\":\"N" + id.charAt(0) + "\",\"tag\":\"T\",\"lifecycle\":\"" + life + "\",\"hidden\":" + hidden + + ",\"homeBlock\":{\"source\":\"minecraft\",\"worldUuid\":\"" + W + "\",\"position\":{\"x\":" + x + ",\"y\":64,\"z\":" + z + "}" + revision + "},\"claimedChunks\":" + claims + "}"; + } + + private static Map parse(JsonArray clans, JsonArray companies, JsonArray offices, List unresolved, Map previous) { + Map by = new HashMap<>(); + by.put("clan", clans); by.put("company", companies); by.put("protected", offices); + return HomeRegistry.parse(by, unresolved, previous); + } + + private static Map parse(JsonArray clans, JsonArray companies) { return parse(clans, companies, null, List.of(), Map.of()); } + + @Test void negativeCoordinatesUseFloorDivisionAndExpandedChunksAreIncluded() { + var m = parse(null, rows(row(A, "active", false, -1, -17, "[{\"x\":3,\"z\":4}]", ""))); + assertEquals("company", m.get(HomeRegistry.key(W, -1, -2)).kind()); + assertNotNull(m.get(HomeRegistry.key(W, 3, 4))); + assertEquals(2, m.size()); + } + + @Test void archivedHiddenAndNonMinecraftAreDropped() { + var m = parse(rows(row(A, "archived", false, 0, 0, "[]", ""), row(B, "active", true, 100, 100, "[]", "")), rows( + "{\"id\":\"" + C + "\",\"lifecycle\":\"active\",\"hidden\":false,\"homeBlock\":{\"source\":\"discord\"}}")); + assertTrue(m.isEmpty()); + } + + @Test void overlappingOwnershipRejectsTheWholePayload() { + var ex = assertThrows(HomeRegistry.Rejected.class, () -> parse(rows(row(A, "active", false, 0, 0, "[]", "")), rows(row(B, "active", false, 5, 5, "[]", "")))); + assertTrue(ex.getMessage().contains("claimed by both")); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", ""), row(B, "active", false, 0, 0, "[{\"x\":0,\"z\":0}]", "")))); + } + + @Test void malformedRowsAreRejected() { + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row("not-a-uuid", "active", false, 0, 0, "[]", "")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", "").replace(W, "bad-world")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 99_999_999, 0, "[]", "")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[{\"x\":\"a\",\"z\":1}]", "")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", ",\"claimRevision\":-3")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(rows(row(A, "active", false, 0, 0, "[]", ""), row(A, "active", false, 50, 50, "[]", "")), null)); + } + + @Test void aStaleClaimRevisionIsRejectedAndKeepsTheOldProjection() { + var first = parse(null, rows(row(A, "active", false, 0, 0, "[]", ",\"claimRevision\":5"))); + assertEquals(5, first.values().iterator().next().revision()); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 200, 200, "[]", ",\"claimRevision\":4")), null, List.of(), first)); + var newer = parse(null, rows(row(A, "active", false, 200, 200, "[]", ",\"claimRevision\":6")), null, List.of(), first); + assertNull(newer.get(HomeRegistry.key(W, 0, 0)), "old home chunk is released"); + assertNotNull(newer.get(HomeRegistry.key(W, 12, 12))); + } + + @Test void unresolvedRecordsKeepWhatTheyOwnedAndMissingOnesDoNot() { + var before = parse(rows(row(A, "active", false, 0, 0, "[]", ""), row(B, "active", false, 100, 100, "[]", "")), null); + assertEquals(2, before.size()); + // A is under review (listed unresolved and absent from rows); B vanished and is not in review. + var after = parse(rows(), null, null, List.of(new HomeRegistry.Ref("clan", A)), before); + assertEquals(1, after.size()); + assertEquals(A, after.values().iterator().next().id()); + // A row with an unknown lifecycle counts as unresolved too. + var odd = parse(rows(row(A, "pending-review", false, 0, 0, "[]", "")), null, null, List.of(), before); + assertNotNull(odd.get(HomeRegistry.key(W, 0, 0))); + } + + @Test void anUnresolvedRecordCannotHoldAChunkAnActiveRecordNowClaims() { + var before = parse(rows(row(A, "active", false, 0, 0, "[]", "")), null); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(B, "active", false, 0, 0, "[]", "")), null, List.of(new HomeRegistry.Ref("clan", A)), before)); + } + + @Test void officesProjectAsProtectedAndStorageRoundTrips() { + var m = parse(null, null, rows(row(A, "active", false, 0, 0, "[]", ",\"claimRevision\":7")), List.of(), Map.of()); + assertEquals("protected", m.values().iterator().next().kind()); + assertEquals(m, HomeRegistry.fromMap(HomeRegistry.toMap(m))); + var r = new HomeRegistry(); + r.install(m, "s1"); + assertEquals(1, r.claimCount("protected", A)); + assertEquals(0, r.claimCount("clan", A)); + assertEquals("s1", r.stateId()); + r.install(Map.of(), ""); + assertEquals(0, r.claimCount("protected", A)); + } + + @Test void aCorruptCacheEntryIsRejected() { + assertThrows(HomeRegistry.Rejected.class, () -> HomeRegistry.fromMap(Map.of("k", Map.of("kind", "wizard", "id", A)))); + assertThrows(HomeRegistry.Rejected.class, () -> HomeRegistry.fromMap(Map.of("k", "oops"))); + } +} diff --git a/DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java b/DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java new file mode 100644 index 00000000..e8f04aa8 --- /dev/null +++ b/DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java @@ -0,0 +1,23 @@ +package com.example.dunegroups; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PvpPolicyTest { + @Test void insideTheChunkNobodyCanHurtAnybodyAndOutsidersAreIncluded() { + assertTrue(PvpPolicy.blocked(false, false, true), "outsider hits someone standing on company land"); + assertTrue(PvpPolicy.blocked(false, true, false), "someone on company land shoots out"); + assertTrue(PvpPolicy.blocked(false, true, true)); + } + + @Test void outsideCompanyLandNothingChangesAndSelfDamageIsLeftAlone() { + assertFalse(PvpPolicy.blocked(false, false, false)); + assertFalse(PvpPolicy.blocked(true, true, true)); + } + + @Test void harmfulEffectsCoverPotionsAndClouds() { + for (String k : new String[]{"poison", "instant_damage", "slowness", "weakness", "wither", "levitation", "blindness"}) assertTrue(PvpPolicy.harmful(k), k); + for (String k : new String[]{"speed", "regeneration", "instant_health", "fire_resistance", "", null}) assertFalse(PvpPolicy.harmful(k), String.valueOf(k)); + } +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/CentralClanDirectory.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/CentralClanDirectory.java new file mode 100644 index 00000000..57b9d18e --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/CentralClanDirectory.java @@ -0,0 +1,19 @@ +package com.dunerealms.jarvis; + +import java.util.*; +import java.util.function.Supplier; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +/** ClanDirectory over the current central projection. */ +final class CentralClanDirectory implements ClanDirectory { + private final Supplier source; + CentralClanDirectory(Supplier source){this.source=source;} + @Override public String clanOf(UUID player){return source.get().clanOfPlayer(player);} + @Override public String name(String id){var g=source.get().clan(id);return g==null?null:g.name();} + @Override public String idByName(String name){for(var g:source.get().clans())if(g.name().equalsIgnoreCase(name))return g.id();return null;} + @Override public List names(){var out=new ArrayList();for(var g:source.get().clans())out.add(g.name());return out;} + @Override public Location home(String id){var g=source.get().clan(id);if(g==null||g.home()==null)return null;World w=Bukkit.getWorld(g.home().world());return w==null?null:new Location(w,g.home().x(),g.home().y(),g.home().z());} + @Override public long homeRevision(String id){var g=source.get().clan(id);return g==null||g.home()==null?-1:g.home().revision();} +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ClanDirectory.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ClanDirectory.java new file mode 100644 index 00000000..feda5b58 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ClanDirectory.java @@ -0,0 +1,19 @@ +package com.dunerealms.jarvis; + +import java.util.List; +import java.util.UUID; +import org.bukkit.Location; + +/** What Imperial Raid needs to know about clans. Backed by the central projection, or by MedievalFactions in legacy mode. */ +interface ClanDirectory { + /** Central clan id of the player's clan, or null. */ + String clanOf(UUID player); + /** Clan display name, or null when the id is unknown. */ + String name(String clanId); + String idByName(String name); + List names(); + /** Registered Home Block position, or null when the clan has none or its world is not loaded. */ + Location home(String clanId); + /** Claim revision of that Home Block, or -1 when the source does not carry one. */ + long homeRevision(String clanId); +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/DuneGroupsKeyWorker.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/DuneGroupsKeyWorker.java new file mode 100644 index 00000000..582483b2 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/DuneGroupsKeyWorker.java @@ -0,0 +1,181 @@ +package com.dunerealms.jarvis; + +import com.google.gson.*; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.security.MessageDigest; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; + +/** + * Projects central clan, company and protected-office records without Towny or MedievalFactions: Home Blocks and the + * company PvP rule in DuneGroups, estate regions in WorldGuard, Home NPCs, the Kaitain Emperor NPC, and the organisation + * directory used by Imperial Raid. Deeds, rosters and banks stay central. Selected with native.backend: dunegroups. + * Construction fails when DuneGroups or WorldGuard is unavailable so the caller can stop JARVIS instead of running blind. + */ +final class DuneGroupsKeyWorker implements NativeKeys { + private final JavaPlugin plugin;private final SharedGameApi api;private final Plugin groups;private final Method activate,deactivate,sync,claimCount; + private final NativeWorldGuard guards;private final OrganisationHomeNpcs homeNpcs;private final AtomicBoolean busy=new AtomicBoolean(); + private final Path stateFile,directoryFile;private final BukkitTask task;private final CentralClanDirectory clanView; + private final FactionsAdapter legacyFactions;private final TownyAdapter legacyTowns; + private final boolean legacyFactionsPresent,legacyTownyPresent; + private final Set ownedClans=new TreeSet<>(),ownedCompanies=new TreeSet<>(),ownedOffices=new TreeSet<>(); + private final List pendingAcks=new ArrayList<>(); + private volatile OrganisationDirectory directory=OrganisationDirectory.EMPTY; + private volatile boolean closed,homeNpcPending;private volatile String status="Waiting for central organisation keys"; + private String previousFailure="",appliedState=""; + + DuneGroupsKeyWorker(JavaPlugin plugin,SharedGameApi api)throws Exception { + this.plugin=plugin;this.api=api; + groups=Bukkit.getPluginManager().getPlugin("DuneGroups"); + if(groups==null||!groups.isEnabled())throw new IllegalStateException("DuneGroups unavailable"); + activate=groups.getClass().getMethod("activate");deactivate=groups.getClass().getMethod("deactivate"); + sync=groups.getClass().getMethod("sync",String.class);claimCount=groups.getClass().getMethod("claimCount",String.class,String.class); + guards=new NativeWorldGuard(plugin); // throws when WorldGuard is unavailable: WorldGuard stays the build-protection authority + homeNpcs=new OrganisationHomeNpcs(plugin); + stateFile=plugin.getDataFolder().toPath().resolve("dunegroups-worker.yml");directoryFile=plugin.getDataFolder().toPath().resolve("organisation-directory.json"); + load(); + clanView=new CentralClanDirectory(()->directory); + // During migration the old vendors may still be installed. Their projections must be gone before cleanup is acknowledged. + var mf=Bukkit.getPluginManager().getPlugin("MedievalFactions");var towny=Bukkit.getPluginManager().getPlugin("Towny"); + FactionsAdapter f=null;TownyAdapter t=null; + if(mf!=null&&mf.isEnabled())try{f=new FactionsAdapter(mf,new HashSet<>());}catch(ReflectiveOperationException|RuntimeException unverifiable){plugin.getLogger().warning("Legacy MedievalFactions cannot be verified; relocation acknowledgements will wait.");} + if(towny!=null&&towny.isEnabled())try{t=new TownyAdapter(towny,new HashSet<>(),new HashSet<>());}catch(ReflectiveOperationException|RuntimeException unverifiable){plugin.getLogger().warning("Legacy Towny cannot be verified; relocation acknowledgements will wait.");} + legacyFactions=f;legacyTowns=t;legacyFactionsPresent=mf!=null;legacyTownyPresent=towny!=null; + task=Bukkit.getScheduler().runTaskTimerAsynchronously(plugin,this::refresh,60L,300L); + } + + private static Object invokeOn(Method m,Object target,Object... args)throws Exception{ + try{return m.invoke(target,args);}catch(InvocationTargetException e){Throwable c=e.getCause();if(c instanceof Exception x)throw x;throw e;} + } + private Object invoke(Method m,Object... args)throws Exception{return invokeOn(m,groups,args);} + + @Override public String status(){return status;} + @Override public void request(){Bukkit.getScheduler().runTaskAsynchronously(plugin,this::refresh);} + @Override public ClanDirectory clans(){return clanView;} + + // ---- durable worker state: owned ids (so vanished records can be retired) and acknowledgements not yet delivered ---- + private void load()throws IOException { + var yml=YamlConfiguration.loadConfiguration(stateFile.toFile()); + ownedClans.addAll(yml.getStringList("clans"));ownedCompanies.addAll(yml.getStringList("companies"));ownedOffices.addAll(yml.getStringList("offices")); + pendingAcks.addAll(yml.getStringList("pendingAcks")); + if(Files.exists(directoryFile))try{storedDirectory=OrganisationDirectory.fromJson(JsonParser.parseString(Files.readString(directoryFile)).getAsJsonObject());} + catch(RuntimeException unreadable){plugin.getLogger().warning("Stored organisation directory is unreadable; waiting for the next central state.");} + } + private OrganisationDirectory storedDirectory=OrganisationDirectory.EMPTY; + private void save(OrganisationDirectory next,List acknowledgements)throws IOException { + Files.createDirectories(stateFile.getParent());var yml=new YamlConfiguration(); + yml.set("clans",new ArrayList<>(ownedClans));yml.set("companies",new ArrayList<>(ownedCompanies));yml.set("offices",new ArrayList<>(ownedOffices));yml.set("pendingAcks",acknowledgements); + atomic(directoryFile,next.toJson().toString());atomic(stateFile,yml.saveToString()); + } + private static void atomic(Path target,String text)throws IOException { + if(Files.exists(target)&&Files.readString(target).equals(text))return; + Path temp=target.resolveSibling(target.getFileName()+".tmp");Files.writeString(temp,text); + Files.move(temp,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); + } + + private static JsonArray array(JsonObject state,String field){ + var e=state.get(field);if(e==null||!e.isJsonArray())throw new IllegalStateException("Native state is missing "+field);return e.getAsJsonArray(); + } + private static Set ids(JsonArray rows){var out=new TreeSet();for(var v:rows)out.add(v.getAsJsonObject().get("id").getAsString());return out;} + private static Set reviewIds(JsonArray review,String kind){ + var out=new TreeSet();if(review!=null)for(var v:review){var r=v.getAsJsonObject();if(kind.equals(r.get("kind").getAsString()))out.add(r.get("id").getAsString());}return out; + } + /** Rows plus archived stubs for ids we projected earlier that vanished and are not under review, so their regions are removed. */ + private static JsonArray withRetired(JsonArray rows,Set owned,Set review){ + var records=rows.deepCopy();for(String id:NativeProjectionScope.retired(owned,ids(rows),review)){var stub=new JsonObject();stub.addProperty("id",id);stub.addProperty("lifecycle","archived");records.add(stub);}return records; + } + private static Set activeIds(JsonArray rows){ + var out=new TreeSet();for(var v:rows){var r=v.getAsJsonObject();if("active".equals(r.get("lifecycle").getAsString())&&!(r.has("hidden")&&r.get("hidden").getAsBoolean()))out.add(r.get("id").getAsString());}return out; + } + private static String digest(String text)throws Exception { + var hash=MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));var out=new StringBuilder();for(byte b:hash)out.append(String.format("%02x",b));return out.toString(); + } + + private void deliverPending()throws Exception { + for(String text:List.copyOf(pendingAcks)){ + api.homeCleanup(JsonParser.parseString(text).getAsJsonObject()); + var remaining=new ArrayList<>(pendingAcks);remaining.remove(text); + save(storedDirectory,remaining);pendingAcks.remove(text); + } + } + + private void refresh(){ + if(closed||!busy.compareAndSet(false,true))return; + try{ + String folder=plugin.getDataFolder().getAbsoluteFile().getParentFile().getParentFile().getName().replace('_','-'); + String server=plugin.getConfig().getString("native.server-key",folder); + if(!Set.of("lobby","caladan","giedi-prime","kaitain","sigma-draconis-iv","arrakis").contains(server))throw new IllegalStateException("Native server key is not configured"); + deliverPending(); // an earlier cleanup that was persisted but not acknowledged goes first, with its original request and key + var state=api.nativeState(server);if(closed)return; + JsonArray clans=array(state,"clans"),companies=array(state,"companies"),offices=array(state,"offices"),wars=array(state,"wars"); + if(clans.size()>512||companies.size()>512||offices.size()>512||wars.size()>1000)throw new IllegalStateException("Native inventory invalid"); + var review=state.has("review")&&!state.get("review").isJsonNull()?state.getAsJsonArray("review"):null; + var relocations=state.has("relocations")&&!state.get("relocations").isJsonNull()?state.getAsJsonArray("relocations"):new JsonArray(); + String desired=clans.toString()+companies+offices+wars+relocations+(review==null?"":review)+(state.has("imperialAppearance")?state.get("imperialAppearance"):""); + if(server.equals("kaitain")){var appearance=state.has("imperialAppearance")&&!state.get("imperialAppearance").isJsonNull()?state.getAsJsonObject("imperialAppearance"):null;Bukkit.getScheduler().runTask(plugin,()->{try{var gui=Bukkit.getPluginManager().getPlugin("DunerealmsGUI");if(gui!=null&&gui.isEnabled())gui.getClass().getMethod("updateImperialQuestNpc",UUID.class,String.class,String.class).invoke(gui,appearance==null?null:UUID.fromString(appearance.get("uuid").getAsString()),appearance==null?null:appearance.get("name").getAsString(),appearance==null?null:appearance.get("term").getAsString());}catch(ReflectiveOperationException|IllegalArgumentException ignored){}});} + if(desired.equals(appliedState)&&!homeNpcPending)return; + var nextDirectory=storedDirectory.next(state); // validates UUIDs and duplicate war keys before anything is applied + var clanRecords=withRetired(clans,ownedClans,reviewIds(review,"clan")); + var companyRecords=withRetired(companies,ownedCompanies,reviewIds(review,"company")); + var officeRecords=withRetired(offices,ownedOffices,reviewIds(review,"protected")); + var payload=new JsonObject();payload.addProperty("stateId",digest(desired));payload.add("clans",clanRecords);payload.add("companies",companyRecords);payload.add("offices",officeRecords); + var unresolved=new JsonArray();if(review!=null)for(var v:review){var r=v.getAsJsonObject();var u=new JsonObject();u.add("kind",r.get("kind"));u.add("id",r.get("id"));unresolved.add(u);}payload.add("unresolved",unresolved); + var nextClans=new TreeSet<>(activeIds(clans));nextClans.addAll(reviewIds(review,"clan")); + var nextCompanies=new TreeSet<>(activeIds(companies));nextCompanies.addAll(reviewIds(review,"company")); + var nextOffices=new TreeSet<>(activeIds(offices));nextOffices.addAll(reviewIds(review,"protected")); + var done=new CompletableFuture();var cleanupReady=new ArrayList(); + Bukkit.getScheduler().runTask(plugin,()->{try{ + if(closed)throw new IllegalStateException("Translator stopped"); + int count=(Integer)invoke(sync,payload.toString()); // throws on a conflict or a failed write; the last valid projection stays + guards.reconcile(clanRecords,"clan",wars);guards.reconcile(companyRecords,"company",wars);guards.reconcile(officeRecords,"protected",wars); + boolean npcs=plugin.getConfig().getBoolean("pol-home-npcs-enabled",true); + if(npcs)try{homeNpcPending=!homeNpcs.reconcile(clanRecords,companies,nextClans,nextCompanies,review);}catch(Exception pending){homeNpcPending=true;plugin.getLogger().warning("Home NPC projection awaiting retry; Home Blocks and estate regions remain intact.");} + for(var entry:relocations){var op=entry.getAsJsonObject();String kind=op.get("kind").getAsString(),id=op.get("id").getAsString(); + if(!Set.of("clan","company").contains(kind))throw new IllegalStateException("Relocation cleanup is not complete"); + if((Long)invoke(claimCount,kind,id)!=0)throw new IllegalStateException("Relocation cleanup is not complete: Home Block claim remains"); + if(!guards.absent(kind,id))throw new IllegalStateException("Relocation cleanup is not complete: WorldGuard region remains"); + boolean legacyGone=kind.equals("clan") + ?!legacyFactionsPresent||legacyFactions!=null&&legacyFactions.absent(id) + :!legacyTownyPresent||legacyTowns!=null&&legacyTowns.absent(id); + if(!legacyGone){homeNpcPending=true;continue;} + if(npcs&&!homeNpcs.absent(kind,id)){homeNpcPending=true;continue;} + cleanupReady.add(op);} + done.complete(count);}catch(Exception failure){done.completeExceptionally(failure);}}); + int chunks=done.get(20,TimeUnit.SECONDS); + ownedClans.clear();ownedClans.addAll(nextClans);ownedCompanies.clear();ownedCompanies.addAll(nextCompanies);ownedOffices.clear();ownedOffices.addAll(nextOffices); + var stagedAcks=new ArrayList<>(pendingAcks); + for(var op:cleanupReady){var ack=new JsonObject();ack.addProperty("server",server);ack.add("requestId",op.get("requestId"));ack.add("keyId",op.get("keyId"));stagedAcks.add(ack.toString());} + save(nextDirectory,stagedAcks); + storedDirectory=nextDirectory;directory=nextDirectory; + pendingAcks.clear();pendingAcks.addAll(stagedAcks); + var activated=new CompletableFuture(); + Bukkit.getScheduler().runTask(plugin,()->{ + try{if(closed)throw new IllegalStateException("Translator stopped");invoke(activate);activated.complete(null);} + catch(Exception failure){activated.completeExceptionally(failure);} + }); + activated.get(20,TimeUnit.SECONDS); + deliverPending(); // then the original request and key are acknowledged + appliedState=desired; + long active=nextDirectory.wars().stream().filter(OrganisationDirectory.War::active).count(); + status="Central keys connected; "+nextClans.size()+" clans, "+nextCompanies.size()+" companies, "+nextOffices.size()+" offices, "+active+" wars, "+chunks+" home chunks"; + if(!previousFailure.isEmpty())plugin.getLogger().info(status);previousFailure=""; + }catch(Exception failure){ + status="DuneGroups processing pending: "+failure.getClass().getSimpleName(); + String reason=failure.getClass().getSimpleName()+":"+failure.getMessage(); + if(!reason.equals(previousFailure)){plugin.getLogger().warning(status+" ("+failure.getMessage()+")");previousFailure=reason;} + }finally{busy.set(false);} + } + + @Override public void close(){closed=true;task.cancel();try{invoke(deactivate);}catch(Exception ignored){}} +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/FactionClanDirectory.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/FactionClanDirectory.java new file mode 100644 index 00000000..d1d1ad76 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/FactionClanDirectory.java @@ -0,0 +1,32 @@ +package com.dunerealms.jarvis; + +import static com.dunerealms.jarvis.NativeReflection.call; + +import java.util.*; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.plugin.Plugin; + +/** Legacy ClanDirectory over MedievalFactions. Used only while native.backend is legacy. */ +final class FactionClanDirectory implements ClanDirectory { + private final Object factions; + FactionClanDirectory(Plugin mf)throws ReflectiveOperationException{ + if(mf==null||!mf.isEnabled())throw new IllegalStateException("MedievalFactions unavailable"); + factions=call(call(mf,"getServices"),"getFactionService"); + } + private String id(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getId"));} + private String nm(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getName"));} + @Override public String clanOf(UUID player){try{Object f=call(factions,"getFactionByPlayerId",player.toString());return f==null?null:id(f);}catch(ReflectiveOperationException|RuntimeException unknown){return null;}} + @Override public String name(String id){try{Object f=call(factions,"getFactionByFactionId",id);return f==null?null:nm(f);}catch(ReflectiveOperationException|RuntimeException unknown){return null;}} + @Override public String idByName(String name){try{for(Object f:(List)call(factions,"getFactions"))if(nm(f).equalsIgnoreCase(name))return id(f);}catch(ReflectiveOperationException|RuntimeException unknown){}return null;} + @Override public List names(){try{var out=new ArrayList();for(Object f:(List)call(factions,"getFactions"))out.add(nm(f));return out;}catch(ReflectiveOperationException|RuntimeException unavailable){return List.of();}} + @Override public Location home(String clanId){ + try{Object f=call(factions,"getFactionByFactionId",clanId);if(f==null)return null;Object position=call(f,"getHome");if(position==null)return null; + Object world=position.getClass().getMethod("getWorldId").invoke(position);World w=Bukkit.getWorld(UUID.fromString(String.valueOf(world)));if(w==null)return null; + double x=((Number)position.getClass().getMethod("getX").invoke(position)).doubleValue(),y=((Number)position.getClass().getMethod("getY").invoke(position)).doubleValue(),z=((Number)position.getClass().getMethod("getZ").invoke(position)).doubleValue(); + return new Location(w,x,y,z); + }catch(ReflectiveOperationException|RuntimeException unavailable){return null;} + } + @Override public long homeRevision(String clanId){return -1;} +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaid.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaid.java index 06e802fb..27ff0cb2 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaid.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaid.java @@ -33,7 +33,7 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter { private java.util.function.BiConsumer pendingRequest; private final File store; private final Map raids=new HashMap<>(); // keyed by raid id - private final Object factions; + private final ClanDirectory clans; private int task=-1; private final RaidWorldGuard protection; @@ -50,11 +50,8 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter { Location home(){World w=Bukkit.getWorld(world);return w==null?null:new Location(w,x,y,z);} } - ImperialRaid(JavaPlugin plugin,java.util.function.Consumer stamp)throws ReflectiveOperationException,java.io.IOException{ - this.plugin=plugin;this.stamp=Objects.requireNonNull(stamp); - var mf=Bukkit.getPluginManager().getPlugin("MedievalFactions"); - if(mf==null||!mf.isEnabled())throw new IllegalStateException("MedievalFactions unavailable"); - factions=call(call(mf,"getServices"),"getFactionService"); + ImperialRaid(JavaPlugin plugin,java.util.function.Consumer stamp,ClanDirectory clans)throws ReflectiveOperationException,java.io.IOException{ + this.plugin=plugin;this.stamp=Objects.requireNonNull(stamp);this.clans=Objects.requireNonNull(clans); protection=new RaidWorldGuard(); raidKey=new NamespacedKey(plugin,"imperial_raid");ordererKey=new NamespacedKey(plugin,"imperial_raid_orderer");captainKey=new NamespacedKey(plugin,"imperial_raid_captain"); settings=ImperialRaidPlan.Settings.defaults(); @@ -82,33 +79,14 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter { } - // ---- clan lookups (native MedievalFactions roster, mirrored by JARVIS) ---- - private Object factionOf(UUID player)throws ReflectiveOperationException{return call(factions,"getFactionByPlayerId",player.toString());} - private String idOf(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getId"));} - private String nameOf(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getName"));} - private Object factionByName(String name)throws ReflectiveOperationException{ - for(Object f:(List)call(factions,"getFactions"))if(nameOf(f).equalsIgnoreCase(name))return f; - return null; - } - private List factionNames(){ - try{var out=new ArrayList();for(Object f:(List)call(factions,"getFactions"))out.add(nameOf(f));return out;}catch(ReflectiveOperationException|RuntimeException unavailable){return List.of();} - } - /** Home Block position, or null when the clan has none or its world is not loaded. */ - private Location homeOf(Object faction)throws ReflectiveOperationException{ - Object position=call(faction,"getHome");if(position==null)return null; - Object world=position.getClass().getMethod("getWorldId").invoke(position); - World w=Bukkit.getWorld(UUID.fromString(String.valueOf(world)));if(w==null)return null; - double x=((Number)position.getClass().getMethod("getX").invoke(position)).doubleValue(),y=((Number)position.getClass().getMethod("getY").invoke(position)).doubleValue(),z=((Number)position.getClass().getMethod("getZ").invoke(position)).doubleValue(); - return new Location(w,x,y,z); - } - private boolean inClan(Player player,String clanId){ - try{Object f=factionOf(player.getUniqueId());return f!=null&&clanId.equals(idOf(f));}catch(ReflectiveOperationException|RuntimeException unknown){return false;} - } + // ---- clan lookups (central organisation projection; MedievalFactions only in legacy mode) ---- + private boolean inClan(Player player,String clanId){return clanId.equals(clans.clanOf(player.getUniqueId()));} private boolean allowedVictim(Player player,String orderer){ if(orderer==null||orderer.isBlank()||!player.isOnline()||player.getGameMode()==GameMode.CREATIVE||player.getGameMode()==GameMode.SPECTATOR)return false; - try{Object faction=factionOf(player.getUniqueId());return faction==null||!orderer.equals(idOf(faction));}catch(ReflectiveOperationException|RuntimeException unavailable){return false;} + return !orderer.equals(clans.clanOf(player.getUniqueId())); } private List onlineOf(String clanId){var out=new ArrayList();for(var p:Bukkit.getOnlinePlayers())if(inClan(p,clanId))out.add(p);return out;} + private List factionNames(){return clans.names();} // ---- ordering ---- /** An authenticated paid bridge receipt is the only production entry. No native bank mutation. */ @@ -116,9 +94,9 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter { boolean preflight(Order order){ if(!Bukkit.isPrimaryThread())throw new IllegalStateException("Native preflight requires the server thread"); if(order.ordererId().equals(order.targetId())||order.retaliationLevel()<0||order.retaliationLevel()>3)return false; - try{Object target=call(factions,"getFactionByFactionId",order.targetId());if(target==null)return false;Location home=homeOf(target); + try{if(clans.name(order.targetId())==null)return false;Location home=clans.home(order.targetId()); return home!=null&&home.getWorld().getUID().equals(order.world())&&home.getBlockX()==(int)Math.floor(order.x())&&home.getBlockY()==(int)Math.floor(order.y())&&home.getBlockZ()==(int)Math.floor(order.z())&&home.getWorld().isChunkLoaded(home.getBlockX()>>4,home.getBlockZ()>>4)&&spawnPoints(home,order.targetId()).size()>=ImperialRaidPlan.raiderCount(settings,onlineOf(order.targetId()).size()); - }catch(ReflectiveOperationException|RuntimeException unavailable){return false;} + }catch(RuntimeException unavailable){return false;} } void accepted(Order order,com.google.gson.JsonObject authoritativePaidReceipt)throws java.io.IOException{ var previous=journal.get(order.id()); @@ -185,10 +163,11 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter { } com.google.gson.JsonObject preflightEvidence(ImperialRaidPermit permit){ if(!preflight(new Order(permit.id(),permit.orderingClan().toString(),permit.targetClan().toString(),permit.orderingName(),permit.targetName(),permit.world(),permit.x(),permit.y(),permit.z(),0,permit.retaliation())))throw new IllegalStateException("Travel to the target's registered world and load its safe home area first"); + long knownRevision=clans.homeRevision(permit.targetClan().toString());if(knownRevision>=0&&knownRevision!=permit.claimRevision())throw new IllegalStateException("The target clan's claim revision has changed"); var result=new com.google.gson.JsonObject();result.addProperty("worldUuid",permit.world().toString());var p=new com.google.gson.JsonObject();p.addProperty("x",permit.x());p.addProperty("y",permit.y());p.addProperty("z",permit.z());result.add("position",p);result.addProperty("claimRevision",permit.claimRevision());result.addProperty("defendersOnline",onlineOf(permit.targetClan().toString()).size());result.addProperty("spawnable",true);result.addProperty("protected",false);result.addProperty("observedAt",System.currentTimeMillis());return result; } - UUID clanOf(Player player)throws ReflectiveOperationException{Object clan=factionOf(player.getUniqueId());return clan==null?null:UUID.fromString(idOf(clan));} - UUID clanNamed(String name)throws ReflectiveOperationException{Object clan=factionByName(name);return clan==null?null:UUID.fromString(idOf(clan));} + UUID clanOf(Player player)throws ReflectiveOperationException{String clan=clans.clanOf(player.getUniqueId());return clan==null?null:UUID.fromString(clan);} + UUID clanNamed(String name)throws ReflectiveOperationException{String clan=clans.idByName(name);return clan==null?null:UUID.fromString(clan);} private Raider spawn(Raid raid,Location at,ImperialRaidPlan.Slot slot){ Class type=slot.ranged()?Pillager.class:Vindicator.class; diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaidWorker.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaidWorker.java index 50d6eb44..c856a2f6 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaidWorker.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ImperialRaidWorker.java @@ -15,10 +15,10 @@ final class ImperialRaidWorker implements AutoCloseable { private final JavaPlugin plugin;private final SharedGameApi api;private final String server;private final ImperialRaid raid; private final ImperialRaidRequests requests;private final AtomicBoolean busy=new AtomicBoolean();private final Set ordering=java.util.concurrent.ConcurrentHashMap.newKeySet(),acknowledged=java.util.concurrent.ConcurrentHashMap.newKeySet(); private final BukkitTask poll;private volatile boolean closed;private String lastError="";private final long bootAt=System.currentTimeMillis(); - ImperialRaidWorker(JavaPlugin plugin,SharedGameApi api,String server,Consumer stamp)throws Exception{ + ImperialRaidWorker(JavaPlugin plugin,SharedGameApi api,String server,Consumer stamp,ClanDirectory clans)throws Exception{ this.plugin=plugin;this.api=api;this.server=server;if(server.equals("lobby"))throw new IllegalArgumentException("Travel to a planet to order a raid"); requests=new ImperialRaidRequests(plugin.getDataFolder().toPath().resolve("imperial-raid-requests.json")); - raid=new ImperialRaid(plugin,stamp);raid.orderRequests(this::order);raid.pendingRequests(this::resolve); + raid=new ImperialRaid(plugin,stamp,clans);raid.orderRequests(this::order);raid.pendingRequests(this::resolve); poll=Bukkit.getScheduler().runTaskTimerAsynchronously(plugin,this::refresh,40,100); } private static UUID event(UUID order,String kind){return UUID.nameUUIDFromBytes(("imperial-raid:"+order+":"+kind).getBytes(StandardCharsets.UTF_8));} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java index c476ee41..322173ef 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java @@ -16,7 +16,7 @@ import org.bukkit.event.server.BroadcastMessageEvent; public final class JarvisTranslator extends JavaPlugin implements Listener { private SharedGameApi api; private NativeActions actions; - private NativeKeyWorker nativeKeys; + private NativeKeys nativeKeys; private WarCampaignWorker warCampaigns; private ImperialRaidWorker imperialRaids; private SpiceRaiderMining spiceRaiderMining; @@ -176,9 +176,17 @@ public final class JarvisTranslator extends JavaPlugin implements Listener { if(nativeKeys!=null)sender.sendMessage(nativeKeys.status()); return true; }); - try {nativeKeys=new NativeKeyWorker(this,api);}catch(ReflectiveOperationException|RuntimeException unavailable){getLogger().warning("Native clan adapter unavailable: "+unavailable.getClass().getSimpleName());} + // native.backend: "legacy" keeps Towny and Medieval Factions. "dunegroups" replaces both and fails closed. + if("dunegroups".equalsIgnoreCase(getConfig().getString("native.backend","legacy"))){ + try {nativeKeys=new DuneGroupsKeyWorker(this,api);} + catch(Exception unavailable){getLogger().severe("native.backend dunegroups failed ("+unavailable.getClass().getSimpleName()+": "+unavailable.getMessage()+"). Stopping JARVIS instead of running without Home Block and WorldGuard projection.");getServer().getPluginManager().disablePlugin(this);return;} + } else { + var groupsPlugin=Bukkit.getPluginManager().getPlugin("DuneGroups"); // rollback: its rules must not stay in force + if(groupsPlugin!=null)try{groupsPlugin.getClass().getMethod("deactivate").invoke(groupsPlugin);}catch(ReflectiveOperationException ignored){} + try {nativeKeys=new NativeKeyWorker(this,api);}catch(ReflectiveOperationException|RuntimeException unavailable){getLogger().warning("Native clan adapter unavailable: "+unavailable.getClass().getSimpleName());} + } if(!serverKey.equals("lobby"))try{warCampaigns=new WarCampaignWorker(this,api,serverKey);}catch(Exception unavailable){getLogger().warning("War roster projection unavailable: "+unavailable.getClass().getSimpleName());} - if(!serverKey.equals("lobby"))try{imperialRaids=new ImperialRaidWorker(this,api,serverKey,item->itemMetadata.stamp(item));}catch(Exception unavailable){getLogger().warning("Imperial raids unavailable: "+unavailable.getClass().getSimpleName());} + if(!serverKey.equals("lobby"))try{imperialRaids=new ImperialRaidWorker(this,api,serverKey,item->itemMetadata.stamp(item),nativeKeys!=null&&nativeKeys.clans()!=null?nativeKeys.clans():new FactionClanDirectory(Bukkit.getPluginManager().getPlugin("MedievalFactions")));}catch(Exception unavailable){getLogger().warning("Imperial raids unavailable: "+unavailable.getClass().getSimpleName());} if(serverKey.equals("arrakis"))try{spiceRaiderMining=new SpiceRaiderMining(this,item->itemMetadata.stamp(item));}catch(Exception unavailable){getLogger().warning("Spice-raider mining unavailable: "+unavailable.getClass().getSimpleName());} if(imperialRaids==null&&getCommand("clanraid")!=null)getCommand("clanraid").setExecutor((sender,command,label,args)->{sender.sendMessage("Imperial raids require the target planet and the current clan-bank service. No new order was submitted.");return true;}); java.util.Objects.requireNonNull(getCommand("capturedeed")).setExecutor((sender,command,label,args)->{ diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeyWorker.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeyWorker.java index aa11eb71..e3676719 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeyWorker.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeyWorker.java @@ -13,7 +13,7 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; /** One shared central key reader. Both initial records and changes use the same native handlers. */ -final class NativeKeyWorker implements AutoCloseable { +final class NativeKeyWorker implements NativeKeys { private final JavaPlugin plugin;private final SharedGameApi api;private final FactionsAdapter factions; private final Set owned=new HashSet<>();private final AtomicBoolean busy=new AtomicBoolean(); private final Set towns=new HashSet<>(),nations=new HashSet<>();private final TownyAdapter towny; @@ -39,8 +39,8 @@ final class NativeKeyWorker implements AutoCloseable { towny=new TownyAdapter(townyPlugin,towns,nations); task=Bukkit.getScheduler().runTaskTimerAsynchronously(plugin,this::refresh,60L,300L); } - String status(){return status;} - void request(){Bukkit.getScheduler().runTaskAsynchronously(plugin,this::refresh);} + @Override public String status(){return status;} + @Override public void request(){Bukkit.getScheduler().runTaskAsynchronously(plugin,this::refresh);} private void refresh(){ if(closed||!busy.compareAndSet(false,true))return; try{ diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeys.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeys.java new file mode 100644 index 00000000..a6337f91 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKeys.java @@ -0,0 +1,10 @@ +package com.dunerealms.jarvis; + +/** The central-key projection worker: the legacy Towny/Medieval Factions worker or the DuneGroups worker. */ +interface NativeKeys extends AutoCloseable { + String status(); + void request(); + /** Clan lookups backed by the central projection, or null when this worker has none (legacy). */ + default ClanDirectory clans(){return null;} + @Override void close(); +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/OrganisationDirectory.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/OrganisationDirectory.java new file mode 100644 index 00000000..bcfd40e0 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/OrganisationDirectory.java @@ -0,0 +1,108 @@ +package com.dunerealms.jarvis; + +import com.google.gson.*; +import java.util.*; + +/** + * Immutable copy of the central organisation records the game needs: clan, company and protected-office rosters with + * owner/officer/member roles, protected neutrality, parent relations, Home Blocks and active/ended wars. + * Central JARVIS stays the authority; this is only its last valid projection. Pure data, no Bukkit types. + */ +final class OrganisationDirectory { + record Home(UUID world,int x,int y,int z,long revision){} + record Group(String kind,String id,String name,String tag,boolean neutral,String parentKind,String parentId,SortedMap members,Home home){} + record War(String keyId,String attackerId,String defenderId,boolean active){} + + static final OrganisationDirectory EMPTY=new OrganisationDirectory(Map.of(),Map.of(),Map.of(),List.of()); + private final Map clans,companies,offices;private final List wars; + + private OrganisationDirectory(Map clans,Map companies,Map offices,List wars){ + this.clans=Map.copyOf(clans);this.companies=Map.copyOf(companies);this.offices=Map.copyOf(offices);this.wars=List.copyOf(wars); + } + + private static String str(JsonObject o,String f){JsonElement e=o==null?null:o.get(f);return e==null||e.isJsonNull()||!e.isJsonPrimitive()?"":e.getAsString();} + private static boolean bool(JsonObject o,String f){JsonElement e=o==null?null:o.get(f);return e!=null&&e.isJsonPrimitive()&&e.getAsJsonPrimitive().isBoolean()&&e.getAsBoolean();} + private static UUID uuid(String s,String what){try{return UUID.fromString(s);}catch(IllegalArgumentException bad){throw new IllegalArgumentException("Invalid "+what);}} + + private static Home home(JsonObject row){ + if(!row.has("homeBlock")||!row.get("homeBlock").isJsonObject())return null; + JsonObject h=row.getAsJsonObject("homeBlock");if(!"minecraft".equals(str(h,"source")))return null; + UUID world=uuid(str(h,"worldUuid"),"world");JsonObject p=h.getAsJsonObject("position"); + JsonElement rev=h.has("revision")?h.get("revision"):row.get("claimRevision"); + if(h.has("revision")&&row.has("claimRevision")&&(!row.get("claimRevision").isJsonPrimitive()||rev.getAsLong()!=row.get("claimRevision").getAsLong()))throw new IllegalArgumentException("Claim revisions disagree"); + return new Home(world,p.get("x").getAsInt(),p.get("y").getAsInt(),p.get("z").getAsInt(),rev==null||rev.isJsonNull()?-1:rev.getAsLong()); + } + + private static Group group(String kind,JsonObject row){ + String id=uuid(str(row,"id"),kind+" id").toString();var members=new TreeMap(); + if(row.has("members")&&row.get("members").isJsonArray())for(var v:row.getAsJsonArray("members")){var m=v.getAsJsonObject();members.put(uuid(str(m,"uuid"),"member"),str(m,"role").isBlank()?"member":str(m,"role"));} + if(row.has("managers")&&row.get("managers").isJsonArray())for(var v:row.getAsJsonArray("managers")){var m=v.getAsJsonObject();members.putIfAbsent(uuid(str(m,"uuid"),"manager"),"officer");} + if(row.has("leader")&&row.get("leader").isJsonObject())members.put(uuid(str(row.getAsJsonObject("leader"),"uuid"),"leader"),"owner"); + JsonObject parent=row.has("parent")&&row.get("parent").isJsonObject()?row.getAsJsonObject("parent"):null; + return new Group(kind,id,str(row,"name"),str(row,"tag"),kind.equals("protected")||bool(row,"protected"),parent==null?"":str(parent,"kind"),parent==null?"":str(parent,"id"),members,home(row)); + } + + private static Map read(String kind,JsonArray rows,Map before,Set review){ + var out=new TreeMap(); + if(rows!=null)for(var v:rows){ + JsonObject row=v.getAsJsonObject();String life=str(row,"lifecycle"),id=uuid(str(row,"id"),kind+" id").toString(); + if(life.equals("archived")||life.equals("retired")||bool(row,"hidden"))continue; + if(!life.equals("active")){var old=before.get(id);if(old!=null)out.put(id,old);continue;} + if(out.put(id,group(kind,row))!=null)throw new IllegalArgumentException("Duplicate "+kind+" "+id); + } + for(String key:review)if(key.startsWith(kind+":")){String id=key.substring(kind.length()+1);var old=before.get(id);if(old!=null)out.putIfAbsent(id,old);} + return out; + } + + /** Builds the next projection from a central native-state response. Unresolved (review) records keep their previous data. */ + OrganisationDirectory next(JsonObject state){ + var review=new HashSet(); + if(state.has("review")&&state.get("review").isJsonArray())for(var v:state.getAsJsonArray("review")){var r=v.getAsJsonObject();review.add(str(r,"kind")+":"+str(r,"id"));} + var newWars=new ArrayList();var keys=new HashSet(); + if(state.has("wars")&&state.get("wars").isJsonArray())for(var v:state.getAsJsonArray("wars")){var w=v.getAsJsonObject(); + String key=uuid(str(w,"keyId"),"war key").toString();if(!keys.add(key))throw new IllegalStateException("Duplicate native war key"); + newWars.add(new War(key,uuid(str(w,"attackerId"),"attacker").toString(),uuid(str(w,"defenderId"),"defender").toString(),bool(w,"active")));} + return new OrganisationDirectory( + read("clan",state.has("clans")?state.getAsJsonArray("clans"):null,clans,review), + read("company",state.has("companies")?state.getAsJsonArray("companies"):null,companies,review), + read("protected",state.has("offices")?state.getAsJsonArray("offices"):null,offices,review),newWars); + } + + Group clan(String id){return clans.get(id);} + Group company(String id){return companies.get(id);} + Group office(String id){return offices.get(id);} + Collection clans(){return clans.values();} + Collection companies(){return companies.values();} + Collection offices(){return offices.values();} + List wars(){return wars;} + String clanOfPlayer(UUID player){for(Group g:clans.values())if(g.members().containsKey(player))return g.id();return null;} + String role(String clanId,UUID player){var g=clans.get(clanId);return g==null?null:g.members().get(player);} + /** True when an active war exists between the two ids, in either direction. */ + boolean atWar(String a,String b){for(War w:wars)if(w.active()&&(w.attackerId().equals(a)&&w.defenderId().equals(b)||w.attackerId().equals(b)&&w.defenderId().equals(a)))return true;return false;} + + // ---- storage ---- + private static JsonObject json(Group g){ + var o=new JsonObject();o.addProperty("kind",g.kind());o.addProperty("id",g.id());o.addProperty("name",g.name());o.addProperty("tag",g.tag());o.addProperty("neutral",g.neutral()); + o.addProperty("parentKind",g.parentKind());o.addProperty("parentId",g.parentId());var m=new JsonObject();g.members().forEach((k,v)->m.addProperty(k.toString(),v));o.add("members",m); + if(g.home()!=null){var h=new JsonObject();h.addProperty("world",g.home().world().toString());h.addProperty("x",g.home().x());h.addProperty("y",g.home().y());h.addProperty("z",g.home().z());h.addProperty("revision",g.home().revision());o.add("home",h);} + return o; + } + private static Group read(JsonObject o){ + var members=new TreeMap();o.getAsJsonObject("members").entrySet().forEach(e->members.put(UUID.fromString(e.getKey()),e.getValue().getAsString())); + Home home=null;if(o.has("home")){var h=o.getAsJsonObject("home");home=new Home(UUID.fromString(str(h,"world")),h.get("x").getAsInt(),h.get("y").getAsInt(),h.get("z").getAsInt(),h.get("revision").getAsLong());} + return new Group(str(o,"kind"),str(o,"id"),str(o,"name"),str(o,"tag"),bool(o,"neutral"),str(o,"parentKind"),str(o,"parentId"),members,home); + } + JsonObject toJson(){ + var out=new JsonObject();out.addProperty("schema",1); + for(var set:Map.of("clans",clans,"companies",companies,"offices",offices).entrySet()){var a=new JsonArray();new TreeMap<>(set.getValue()).values().forEach(g->a.add(json(g)));out.add(set.getKey(),a);} + var w=new JsonArray();for(War war:wars){var o=new JsonObject();o.addProperty("keyId",war.keyId());o.addProperty("attackerId",war.attackerId());o.addProperty("defenderId",war.defenderId());o.addProperty("active",war.active());w.add(o);} + out.add("wars",w);return out; + } + static OrganisationDirectory fromJson(JsonObject o){ + if(o.get("schema").getAsInt()!=1)throw new IllegalArgumentException("Unsupported directory schema"); + Map> sets=new HashMap<>(); + for(String key:List.of("clans","companies","offices")){var m=new TreeMap();for(var v:o.getAsJsonArray(key)){var g=read(v.getAsJsonObject());m.put(g.id(),g);}sets.put(key,m);} + var wars=new ArrayList();for(var v:o.getAsJsonArray("wars")){var w=v.getAsJsonObject();wars.add(new War(str(w,"keyId"),str(w,"attackerId"),str(w,"defenderId"),bool(w,"active")));} + return new OrganisationDirectory(sets.get("clans"),sets.get("companies"),sets.get("offices"),wars); + } +} diff --git a/JarvisConnector/src/main/resources/plugin.yml b/JarvisConnector/src/main/resources/plugin.yml index 925656cb..e6dda145 100644 --- a/JarvisConnector/src/main/resources/plugin.yml +++ b/JarvisConnector/src/main/resources/plugin.yml @@ -3,7 +3,7 @@ main: com.dunerealms.jarvis.JarvisTranslator version: 0.5.39-rawspice1 api-version: '1.21.8' description: Shared J.A.R.V.I.S. website API and native server action translator. -softdepend: [Citizens, Citizens, CoreProtect, SCore, ExecutableItems, ExecutableCrafting, DuneEss, ImageFrame, DecentHolograms, MedievalFactions, Towny, WorldGuard] +softdepend: [Citizens, Citizens, CoreProtect, SCore, ExecutableItems, ExecutableCrafting, DuneEss, ImageFrame, DecentHolograms, MedievalFactions, Towny, WorldGuard, DuneGroups] commands: clanraid: description: Order an Imperial raid through the authorised clan bank diff --git a/JarvisConnector/src/test/java/com/dunerealms/jarvis/OrganisationDirectoryTest.java b/JarvisConnector/src/test/java/com/dunerealms/jarvis/OrganisationDirectoryTest.java new file mode 100644 index 00000000..a388365d --- /dev/null +++ b/JarvisConnector/src/test/java/com/dunerealms/jarvis/OrganisationDirectoryTest.java @@ -0,0 +1,69 @@ +package com.dunerealms.jarvis; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class OrganisationDirectoryTest { + private static final String C1="aaaaaaaa-0000-0000-0000-000000000001",C2="aaaaaaaa-0000-0000-0000-000000000002",K1="bbbbbbbb-0000-0000-0000-000000000001",O1="cccccccc-0000-0000-0000-000000000001"; + private static final String P1="11111111-0000-0000-0000-000000000001",P2="11111111-0000-0000-0000-000000000002",P3="11111111-0000-0000-0000-000000000003",W="99999999-0000-0000-0000-000000000009"; + private static JsonObject state(String clans,String companies,String offices,String wars,String review){ + return JsonParser.parseString("{\"clans\":["+clans+"],\"companies\":["+companies+"],\"offices\":["+offices+"],\"wars\":["+wars+"],\"review\":["+review+"]}").getAsJsonObject(); + } + private static String clan(String id,String life,boolean protectedClan,String parent){ + return "{\"id\":\""+id+"\",\"name\":\"Clan "+id.substring(id.length()-1)+"\",\"tag\":\"T\",\"lifecycle\":\""+life+"\",\"hidden\":false,\"protected\":"+protectedClan+(parent.isEmpty()?"":",\"parent\":"+parent) + +",\"members\":[{\"uuid\":\""+P1+"\",\"role\":\"owner\"},{\"uuid\":\""+P2+"\",\"role\":\"officer\"},{\"uuid\":\""+P3+"\",\"role\":\"member\"}]," + +"\"homeBlock\":{\"source\":\"minecraft\",\"worldUuid\":\""+W+"\",\"position\":{\"x\":10,\"y\":70,\"z\":-5},\"revision\":4}}"; + } + private static String war(String key,String a,String d,boolean active){return "{\"keyId\":\""+key+"\",\"attackerId\":\""+a+"\",\"defenderId\":\""+d+"\",\"active\":"+active+"}";} + private static final String WK1="dddddddd-0000-0000-0000-000000000001",WK2="dddddddd-0000-0000-0000-000000000002"; + + @Test void rostersRolesNeutralityParentsAndHomesAreKept(){ + var d=OrganisationDirectory.EMPTY.next(state(clan(C1,"active",true,"{\"kind\":\"protected\",\"id\":\""+O1+"\"}")+","+clan(C2,"active",false,""), + "{\"id\":\""+K1+"\",\"name\":\"Spice Co\",\"lifecycle\":\"active\",\"hidden\":false,\"leader\":{\"uuid\":\""+P1+"\"},\"managers\":[{\"uuid\":\""+P2+"\"}],\"members\":[{\"uuid\":\""+P3+"\",\"role\":\"member\"}]}", + "{\"id\":\""+O1+"\",\"name\":\"Throne\",\"lifecycle\":\"active\",\"hidden\":false,\"members\":[]}","","")); + var g=d.clan(C1); + assertEquals("owner",g.members().get(UUID.fromString(P1)));assertEquals("officer",g.members().get(UUID.fromString(P2)));assertEquals("member",g.members().get(UUID.fromString(P3))); + assertTrue(g.neutral());assertFalse(d.clan(C2).neutral()); + assertEquals("protected",g.parentKind());assertEquals(O1,g.parentId()); + assertEquals(4,g.home().revision());assertEquals(10,g.home().x());assertEquals(-5,g.home().z()); + assertEquals("owner",d.company(K1).members().get(UUID.fromString(P1)));assertEquals("officer",d.company(K1).members().get(UUID.fromString(P2))); + assertTrue(d.office(O1).neutral()); + assertEquals(C1,d.clanOfPlayer(UUID.fromString(P3))); + } + + @Test void activeAndEndedWarsAreSeparate(){ + var d=OrganisationDirectory.EMPTY.next(state("","","",war(WK1,C1,C2,true)+","+war(WK2,C2,K1,false),"")); + assertTrue(d.atWar(C1,C2));assertTrue(d.atWar(C2,C1));assertFalse(d.atWar(C2,K1),"ended war"); + assertEquals(2,d.wars().size()); + } + + @Test void duplicateWarKeysAreRejected(){ + assertThrows(IllegalStateException.class,()->OrganisationDirectory.EMPTY.next(state("","","",war(WK1,C1,C2,true)+","+war(WK1,C1,C2,true),""))); + } + + @Test void archivedAndHiddenDropButUnresolvedKeepTheirPreviousRecord(){ + var first=OrganisationDirectory.EMPTY.next(state(clan(C1,"active",false,"")+","+clan(C2,"active",false,""),"","","","")); + assertNotNull(first.clan(C1));assertNotNull(first.clan(C2)); + // C1 is archived, C2 is only listed for review and absent from the rows. + var second=first.next(state(clan(C1,"archived",false,""),"","","","{\"kind\":\"clan\",\"id\":\""+C2+"\"}")); + assertNull(second.clan(C1));assertNotNull(second.clan(C2),"unresolved ownership is never erased"); + assertEquals(C2,second.clanOfPlayer(UUID.fromString(P1))); + // Without a review entry the vanished record is gone. + assertNull(second.next(state("","","","","")).clan(C2)); + } + + @Test void malformedUuidsAreRejected(){ + assertThrows(IllegalArgumentException.class,()->OrganisationDirectory.EMPTY.next(state(clan("not-a-uuid","active",false,""),"","","",""))); + } + + @Test void storageRoundTripKeepsEverything(){ + var d=OrganisationDirectory.EMPTY.next(state(clan(C1,"active",true,"{\"kind\":\"protected\",\"id\":\""+O1+"\"}"),"","","" +war(WK1,C1,C2,true),"")); + var back=OrganisationDirectory.fromJson(JsonParser.parseString(d.toJson().toString()).getAsJsonObject()); + assertEquals(d.toJson(),back.toJson()); + assertEquals(C1,back.clanOfPlayer(UUID.fromString(P2)));assertEquals("officer",back.role(C1,UUID.fromString(P2)));assertTrue(back.atWar(C1,C2)); + } +}