DuneRealms V2 clean baseline

Owner-authorised history reset; current source tree preserved exactly.
This commit is contained in:
Dev 2026-11-13 00:05:14 +01:00
commit 6deb4a2e7d
1996 changed files with 65043 additions and 0 deletions

View file

@ -0,0 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
test('feature branch CI never invokes production deployment',()=>{
const workflow=readFileSync(new URL('../workflows/web-deploy.yml',import.meta.url),'utf8');
assert.match(workflow,/- name: Trigger deployment after successful CI\r?\n\s+if: github\.ref == 'refs\/heads\/main'/);
});

View file

@ -0,0 +1,59 @@
name: DuneRealms Web CI
on:
push:
branches:
- main
paths:
- 'website/**'
- '.forgejo/workflows/web-deploy.yml'
workflow_dispatch:
jobs:
web:
runs-on: dune-ci
steps:
- name: Checkout
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
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/MC.git "$GITHUB_SHA"
git checkout --detach FETCH_HEAD
- name: Install Node 22
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Verify deployment policy
run: node --test .forgejo/tests/web-deploy.test.mjs
- name: Build and test website
working-directory: website
run: |
corepack enable
corepack pnpm install --frozen-lockfile
corepack pnpm build
corepack pnpm test
- name: Upload website build
uses: actions/upload-artifact@v3
with:
name: DuneRealms-Website
path: website/dist/
if-no-files-found: error
- name: Trigger deployment after successful CI
if: github.ref == 'refs/heads/main'
shell: bash
env:
DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }}
run: |
install -m 700 -d ~/.ssh
printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
printf '%s\n' '162.55.87.104 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILy1N6Eo+BMRgstSpYc90ZHDQtm+8iTYiNMTI3XMVi5h root@Debian-bookworm-latest-amd64-base' >> ~/.ssh/known_hosts
ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes dunedeploy@162.55.87.104 "$GITHUB_SHA"
rm -f ~/.ssh/deploy_key

3
.gitattributes vendored Normal file
View file

@ -0,0 +1,3 @@
*.pdf binary
*.png binary
*.zip binary

221
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,221 @@
name: Build DuneCore, DuneNPC, DuneEss, and DuneTerrain
on:
workflow_dispatch:
push:
branches: [main, "feature/native-gui-1.21.8"]
jobs:
build-website:
runs-on: ubuntu-latest
defaults:
run:
working-directory: website
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install website server dependencies
run: npm install --omit=dev --no-audit --no-fund
- name: Build the illustrated website and API
run: node scripts/build.mjs
- name: Test feeds and compiled pages
run: node --test tests/*.test.mjs
- name: Test inventory ownership and private market bridge
run: node --test ../control-panel-inventory/tests/*.test.mjs
- name: Upload website build
uses: actions/upload-artifact@v4
with:
name: Project-Dune-Website
path: website/dist/
include-hidden-files: true
if-no-files-found: error
build-core:
runs-on: ubuntu-latest
defaults:
run:
working-directory: DuneRealms-minecraft-only
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- name: Compile DuneCore
run: gradle clean build
- name: Upload compiled JAR
uses: actions/upload-artifact@v4
with:
name: DuneCore-Plugin
path: DuneRealms-minecraft-only/build/libs/*.jar
if-no-files-found: error
build-terrain:
runs-on: ubuntu-latest
defaults:
run:
working-directory: DuneTerrain
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- name: Compile DuneTerrain
run: gradle clean build
- name: Upload compiled JAR
uses: actions/upload-artifact@v4
with:
name: DuneTerrain-Plugin
path: DuneTerrain/build/libs/*.jar
if-no-files-found: error
build-ess:
runs-on: ubuntu-latest
defaults:
run:
working-directory: DuneEss
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- name: Compile DuneEss
run: gradle clean build
- name: Upload compiled JAR
uses: actions/upload-artifact@v4
with:
name: DuneEss-Plugin
path: DuneEss/build/libs/*.jar
if-no-files-found: error
build-npc:
runs-on: ubuntu-latest
defaults:
run:
working-directory: DuneNPC
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- name: Compile and test DuneNPC
run: gradle clean build
- name: Upload compiled JAR
uses: actions/upload-artifact@v4
with:
name: DuneNPC-Plugin
path: DuneNPC/build/libs/*.jar
if-no-files-found: error
build-lobby:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- run: gradle -p DuneLobby clean build
- uses: actions/upload-artifact@v4
with:
name: DuneLobby-Plugin
path: DuneLobby/build/libs/*.jar
if-no-files-found: error
package-server:
runs-on: ubuntu-latest
needs: [build-core, build-ess, build-terrain, build-npc, build-lobby]
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Download all plugin JARs
uses: actions/download-artifact@v4
with:
pattern: Dune*-Plugin
path: DuneRealms-Server-Package
merge-multiple: true
- name: Download verified crossplay plugins
run: python3 tools/download-crossplay.py DuneRealms-Server-Package/crossplay
- name: Add resource pack and install instructions
run: |
curl --fail --location --silent --show-error \
https://github.com/Foulest/Vault/releases/download/2.5.0/Vault-2.5.0.jar \
--output DuneRealms-Server-Package/Vault-2.5.0.jar
echo "3efb1c893d35807c0f3945068858a96af0f131020eee37545bdddb330044b2d9 DuneRealms-Server-Package/Vault-2.5.0.jar" | sha256sum --check --strict
curl --fail --location --silent --show-error \
https://raw.githubusercontent.com/Foulest/Vault/2.5.0/LICENSE \
--output DuneRealms-Server-Package/Vault-LICENSE.txt
cp DuneResourcePack.zip DuneRealms-Server-Package/
cp docs/Dune-User-Manual.pdf DuneRealms-Server-Package/
cp docs/Dune-Complete-Illustrated-Manual.pdf DuneRealms-Server-Package/
cp docs/posters/*.png DuneRealms-Server-Package/
cp docs/Native-GUI.md DuneRealms-Server-Package/Native-GUI.md
cp README.md DuneRealms-Server-Package/Project-README.md
cp website/DISCORD-FEEDS.md DuneRealms-Server-Package/DiscordSRV-Website-Setup.md
cat > DuneRealms-Server-Package/README.txt <<'EOF'
DuneRealms Paper server package
Contents: Vault 2.5.0, all five Dune plugins, and verified Geyser, Floodgate, ViaVersion JARs.
See Native-GUI.md for platform-specific plugin placement.
The illustrated user manual and Project-README.md are included for players and administrators.
Install the applicable plugin JARs in the Paper server's plugins/ folder and restart the server.
Install the included resource pack on vanilla or Fabric 1.21.4 clients for sandworm, haunted Fremen, and spice textures.
On Fabric, put the ZIP in .minecraft/resourcepacks and enable it in Options > Resource Packs; do not put it in mods/.
DuneEss provides the Solaris economy through the included Vault API plugin.
Vault 2.5.0 is the GPL-3.0 licensed Foulest/MilkBowl Vault project; its license is included here.
Its source is available at https://github.com/Foulest/Vault/tree/2.5.0.
Compatible GUI build target: Paper 1.21.8, Java 21.
See https://github.com/thomasv6545-glitch/MC for setup and configuration details.
EOF
- name: ZIP every server plugin JAR together
run: zip -r DuneRealms-All-Server-Jars.zip DuneRealms-Server-Package
- name: Upload one downloadable server package
uses: actions/upload-artifact@v4
with:
name: DuneRealms-Server-Package
path: DuneRealms-All-Server-Jars.zip
if-no-files-found: error
retention-days: 90

28
.github/workflows/lobby.yml vendored Normal file
View file

@ -0,0 +1,28 @@
name: Build Guild Lobby companion
on:
workflow_dispatch:
push:
branches: [main, beta]
paths: ['DuneLobby/**', 'worlds/**', '.github/workflows/lobby.yml', 'gui-common/**']
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- run: gradle -p DuneLobby build
- uses: actions/upload-artifact@v4
with:
name: Dune-Guild-Lobby
path: |
DuneLobby/build/libs/*.jar
worlds/Dune-Guild-Lobby-1.1.0.zip
DuneLobby/README.md
DuneLobby/VALIDATION.md
if-no-files-found: error

25
.github/workflows/network-preflight.yml vendored Normal file
View file

@ -0,0 +1,25 @@
name: Network configuration preflight
on:
push:
paths:
- 'network/**'
- 'DuneTerrain/src/main/resources/config.yml'
- '.github/workflows/network-preflight.yml'
workflow_dispatch:
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Check inventory and build world config ZIPs
run: python3 network/preflight.py --check-worlds
- name: Simulate 1000 chunks of planetary ore attempts
run: python3 network/simulate-ores.py
- name: Upload world configuration packages
uses: actions/upload-artifact@v4
with:
name: dune-world-configs
path: network/generated-worlds/*-world-config.zip

52
.github/workflows/network.yml vendored Normal file
View file

@ -0,0 +1,52 @@
name: Package DuneRealms Velocity Network
on:
workflow_dispatch:
push:
branches: [main, "feature/native-gui-1.21.8"]
paths:
- 'network/**'
- 'gui-common/**'
- 'tools/**'
- 'DuneLobby/**'
- 'DuneTerrain/**'
- 'DuneEss/**'
- 'DuneNPC/**'
- 'DuneRealms-minecraft-only/**'
- '.github/workflows/network.yml'
jobs:
package:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- name: Build plugins
run: |
set -e
mkdir -p built-plugins
for project in DuneRealms-minecraft-only DuneTerrain DuneNPC DuneEss DuneLobby; do
(cd "$project" && gradle clean build)
done
cp DuneRealms-minecraft-only/build/libs/*.jar built-plugins/DuneCore.jar
cp DuneTerrain/build/libs/*.jar built-plugins/DuneTerrain.jar
cp DuneNPC/build/libs/*.jar built-plugins/DuneNPC.jar
cp DuneEss/build/libs/*.jar built-plugins/DuneRealms-Essentials.jar
cp DuneLobby/build/libs/*.jar built-plugins/DuneLobby.jar
- name: Download verified crossplay plugins
run: |
python3 tools/download-crossplay.py built-crossplay
curl --fail --location --silent --show-error https://github.com/Foulest/Vault/releases/download/2.5.0/Vault-2.5.0.jar --output built-crossplay/universal/Vault-2.5.0.jar
echo "3efb1c893d35807c0f3945068858a96af0f131020eee37545bdddb330044b2d9 built-crossplay/universal/Vault-2.5.0.jar" | sha256sum --check --strict
curl --fail --location --silent --show-error https://raw.githubusercontent.com/Foulest/Vault/2.5.0/LICENSE --output built-crossplay/Vault-LICENSE.txt
- name: Package six servers and Velocity config
run: python3 network/package.py
- uses: actions/upload-artifact@v4
with:
name: DuneRealms-Velocity-Network
path: DuneRealms-Velocity-Network.zip
if-no-files-found: error

16
.gitignore vendored Normal file
View file

@ -0,0 +1,16 @@
.gradle/
build/
# Manual render and conversion intermediates
tmp/
__pycache__/
# Generated release packages and credentials in fresh-install network templates
/built-plugins/
/built-crossplay/
/DuneRealms-Velocity-Network/
/DuneRealms-Velocity-Network.zip
# Private database credentials and manual profile recovery snapshots
/network/database/.env
**/inventory-recovery/

30
DuneEss/EXCHANGE.md Normal file
View file

@ -0,0 +1,30 @@
# CHOAM exchange — DuneEss 1.0.4
Install matching DuneRealms-Core.jar (1.0.12) and DuneRealms-Essentials.jar (1.0.4), with Vault and existing modules on Java 21 / Paper 1.21.8. Stop all planetary servers, back up SQL/player data, replace only these plugin JARs and configure the shared PostgreSQL database on every backend before starting. Preserve all worlds/configurations. See [database setup](../network/database/README.md).
## Player controls
- `/exchange` (`/choam`, `/market`): native Java/Bedrock exchange menu.
- `/exchange sell <amount> <price-each>`: list 1–64 held items, up to 1,000,000 Solari per item, two decimal places. Items are escrowed with names, enchantments, Dune metadata and item data. Administrative items are rejected.
- `/exchange buy <id>`: inspect and confirm the purchase of one item.
- `/exchange mine`: browse your listings and reclaim unsold stock.
- `/exchange cancel <id>`: confirm cancellation of your own listing.
- `/exchange admin`: operator inspection and database check. Ownership rules still apply.
Filters, pagination, capacity checks, stale-confirmation handling and self-purchase rejection remain supported. Missing/incompatible shared Core profiles refuse to trade; lobby inventories never enter the planetary exchange.
## Transactions and history
Every actual player trade runs through Core's owned profile connection. Listing escrow, buyer debit, seller credit, stock changes, the resulting authoritative player inventory checkpoint, and any completed sale history commit together. A normal SQL failure restores the in-memory inventory and rolls back all SQL. If the commit outcome is uncertain, the profile is quarantined and ordinary quit saving is suppressed until manual recovery. Excess item delivery aborts the transaction instead of dropping items into the world.
The sales ledger `dune_exchange_sales` retains a row per completed unit purchase, including seller/buyer names and UUIDs, item/material, quantity, exact unit/total price, origin and timestamp. Cancelling or failing a trade creates no sale. Earlier sales cannot be reconstructed retroactively. Configured shared economy deposits/withdrawals now use atomic SQL arithmetic and do not fall back to stale local balances during SQL outages.
General gameplay/container changes outside these exchange transactions still rely on autosaves and unclean-session recovery. This is not an exactly-once guarantee for every Minecraft/plugin interaction. Ender chests remain local. SQL remains synchronous with bounded timeouts; profile capacity and staging tests are documented in the database guide.
## Account page and website
[control-panel-inventory](../control-panel-inventory/README.md) contains the account-page armor mannequin, saved inventory and **History of sales**, plus authenticated read-only API handlers, a private market listings bridge, integration instructions and a self-contained demo preview. The CP source is not in MC, so live wiring/deployment is a handoff task. Purchases remain in-game. Existing public website demo offers remain labelled until its operator enables the supplied live bridge.
## Validation
Run `gradle build` in Core and DuneEss and `node --test tests/*.test.mjs` in control-panel-inventory. Core tests use mocked JDBC/Paper and exchange SQL tests use H2 PostgreSQL compatibility mode, including concurrency, rollback, sales ledger and externally owned transactions. Live PostgreSQL/Paper/Velocity/Bedrock validation is pending.

40
DuneEss/build.gradle.kts Normal file
View file

@ -0,0 +1,40 @@
plugins { java }
group = "com.example"
version = "1.0.4"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://jitpack.io")
}
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
compileOnly("com.github.MilkBowl:VaultAPI:1.7") {
exclude(group = "org.bukkit", module = "bukkit")
}
implementation("org.postgresql:postgresql:42.7.4")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testImplementation("com.h2database:h2:2.3.232")
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
testImplementation("org.mockito:mockito-core:5.15.2")
testImplementation("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") }
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.jar {
archiveBaseName.set("DuneEss")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
}
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
tasks.test { useJUnitPlatform() }
repositories { maven("https://repo.opencollab.dev/main/") }
dependencies { compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") }
sourceSets.main { java.srcDir("../gui-common/src/main/java") }
tasks.jar { archiveFileName.set("DuneRealms-Essentials.jar") }
// Explicit test instrumentation works on Java 21 without dynamic self-attachment.
val mockitoAgent by configurations.creating
dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } }
tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") }

View file

@ -0,0 +1 @@
rootProject.name = "DuneEss"

View file

@ -0,0 +1,73 @@
package com.example.duneess;
import com.google.gson.*;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;
/** Authenticated website bridge; rewards are always credited by the UUID/month ledger. */
final class CommunityCodes implements CommandExecutor,TabCompleter {
private final DuneEss plugin;
private final HttpClient http=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
private final Set<UUID> busy=new HashSet<>();
private final Map<UUID,Long> cooldown=new HashMap<>();
private final String endpoint,secret;
private boolean syncing;
CommunityCodes(DuneEss plugin){
this.plugin=plugin;
File file=new File(plugin.getDataFolder(),"website-bridge.yml");if(!file.exists())plugin.saveResource("website-bridge.yml",false);
YamlConfiguration settings=YamlConfiguration.loadConfiguration(file);endpoint=settings.getString("origin","https://cp.dunerealms.com");secret=settings.getString("secret","");
for(String name:List.of("communitycode","linkwebsite")){PluginCommand command=Objects.requireNonNull(plugin.getCommand(name));command.setExecutor(this);command.setTabCompleter(this);}
Bukkit.getScheduler().runTaskTimer(plugin,this::syncReceipts,200L,1200L);
}
private JsonObject post(String path,JsonObject body) throws Exception {
if(secret.length()<32||!endpoint.equals("https://cp.dunerealms.com"))throw new IllegalStateException("Website bridge is not configured");
HttpRequest request=HttpRequest.newBuilder(URI.create(endpoint+path)).timeout(Duration.ofSeconds(10)).header("Authorization","Bearer "+secret).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(body.toString())).build();
HttpResponse<String> response=http.send(request,HttpResponse.BodyHandlers.ofString());
if(response.body().length()>16384)throw new IllegalStateException("Unexpected bridge response");
JsonObject data=JsonParser.parseString(response.body()).getAsJsonObject();
if(response.statusCode()!=200)throw new IllegalStateException(data.has("message")?data.get("message").getAsString():"Website unavailable");return data;
}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){
if(!(sender instanceof Player player)){sender.sendMessage(com.example.dunegui.PublicNames.text("Players only."));return true;}
boolean linking=command.getName().equals("linkwebsite");
if(args.length!=1){player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Generate a private link command at https://cp.dunerealms.com":"Public community codes: https://www.dunerealms.com/donate.html | Personal codes: https://cp.dunerealms.com | /communitycode CODE"));return true;}
String code=linking?args[0].toLowerCase(Locale.ROOT):args[0].toUpperCase(Locale.ROOT);
if(!(linking?code.matches("[a-f0-9]{32}"):code.matches("[A-Z0-9-]{4,48}"))){player.sendMessage(com.example.dunegui.PublicNames.text("Invalid code format."));return true;}
UUID uuid=player.getUniqueId();long now=System.currentTimeMillis();cooldown.entrySet().removeIf(entry->now-entry.getValue()>60000);
if(busy.contains(uuid)||now-cooldown.getOrDefault(uuid,0L)<3000){player.sendMessage(com.example.dunegui.PublicNames.text("Please wait a few seconds before trying again."));return true;}
cooldown.put(uuid,now);busy.add(uuid);
JsonObject body=new JsonObject();body.addProperty("uuid",uuid.toString());body.addProperty("name",player.getName());body.addProperty("code",code);
player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Verifying website link…":"Checking community reward…"));
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{try{
JsonObject response=post(linking?"/api/game-link/consume":"/api/community/game/prepare",body);
Bukkit.getScheduler().runTask(plugin,()->{try{
if(linking){player.sendMessage(com.example.dunegui.PublicNames.text("Website account linked to your Minecraft UUID. Refresh the account panel."));return;}
if(response.has("delivered")&&response.get("delivered").getAsBoolean()){player.sendMessage("This Minecraft UUID has already received that month's reward.");return;}
String month=response.get("month").getAsString(),receipt=response.get("receipt").getAsString();int amount=response.get("amount").getAsInt();
boolean granted=((DuneEconomy)plugin.economy()).grantCommunity(uuid,month,amount,receipt);
player.sendMessage(com.example.dunegui.PublicNames.text(granted?"Community reward credited: "+amount+" Dunemarks. Thank you, everyone!":"This UUID has already claimed that month's reward. No duplicate currency credited."));
syncReceipts();
}catch(Exception error){plugin.getLogger().warning("Community reward could not be committed: "+error.getClass().getSimpleName());player.sendMessage(com.example.dunegui.PublicNames.text("The reward could not be confirmed. Your code remains available; try again later."));}finally{busy.remove(uuid);}});
}catch(Exception error){Bukkit.getScheduler().runTask(plugin,()->{busy.remove(uuid);player.sendMessage(com.example.dunegui.PublicNames.text("Website request failed. Check the account panel or public code page and try again later."));});}});
return true;
}
private void syncReceipts(){
if(syncing||secret.length()<32)return;
Map<UUID,List<String>> pending;try{pending=((DuneEconomy)plugin.economy()).pendingCommunityReceipts();}catch(Exception error){return;}
if(pending.isEmpty())return;syncing=true;
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{List<Map.Entry<UUID,String>> confirmed=new ArrayList<>();
try{for(var player:pending.entrySet())for(String receipt:player.getValue()){
JsonObject body=new JsonObject();body.addProperty("uuid",player.getKey().toString());body.addProperty("receipt",receipt);
try{post("/api/community/game/ack",body);confirmed.add(Map.entry(player.getKey(),receipt));}catch(Exception unavailable){return;}
}}finally{Bukkit.getScheduler().runTask(plugin,()->{try{for(var row:confirmed)((DuneEconomy)plugin.economy()).acknowledgeCommunity(row.getKey(),row.getValue());}catch(Exception error){plugin.getLogger().warning("Community receipts will retry on the next sync.");}finally{syncing=false;}});}
});
}
@Override public List<String> onTabComplete(CommandSender sender,Command command,String alias,String[] args){return List.of();}
}

View file

@ -0,0 +1,341 @@
package com.example.duneess;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** DuneEss's Solaris ledger and Vault economy service. */
@SuppressWarnings("deprecation")
final class DuneEconomy implements Economy {
private final DuneEss plugin;
private final Map<UUID, Double> balances = new HashMap<>();
private final File file;
private final YamlConfiguration data;
private final boolean allowNegative;
private final String singular, plural;
private String jdbcUrl = "", dbUser = "", dbPassword = "";
private boolean databaseEnabled;
private boolean sharedDatabaseRequested;
DuneEconomy(DuneEss plugin) {
this.plugin = plugin;
this.file = new File(plugin.getDataFolder(), "balances.yml");
this.data = YamlConfiguration.loadConfiguration(file);
this.allowNegative = plugin.getConfig().getBoolean("currency.allow-negative-balances", true);
String configuredSingular = plugin.getConfig().getString("currency.singular", "Dunemark");
this.singular = configuredSingular.equalsIgnoreCase("Solaris") ? "Dunemark" : configuredSingular;
String configuredPlural = plugin.getConfig().getString("currency.plural", "Dunemarks");
this.plural = configuredPlural.equalsIgnoreCase("Solaris") ? "Dunemarks" : configuredPlural;
loadDatabaseSettings();
loadBalances();
}
private void loadDatabaseSettings() {
if (!plugin.getConfig().getBoolean("database.use-core-database", true)) return;
File coreConfig = new File(plugin.getDataFolder().getParentFile(), "DuneCore/config.yml");
if (!coreConfig.isFile()) return;
YamlConfiguration core = YamlConfiguration.loadConfiguration(coreConfig);
if (!core.getBoolean("database.enabled", false)) return;
sharedDatabaseRequested = true;
jdbcUrl = core.getString("database.jdbc-url", "");
dbUser = core.getString("database.username", "");
dbPassword = core.getString("database.password", "");
databaseEnabled = !jdbcUrl.isBlank();
}
boolean sharedDatabaseReady() { return databaseEnabled; }
private Connection connect() throws SQLException {
try { Class.forName("org.postgresql.Driver"); }
catch (ClassNotFoundException ex) { throw new SQLException("PostgreSQL driver unavailable", ex); }
java.util.Properties settings=new java.util.Properties();
settings.setProperty("user",dbUser);settings.setProperty("password",dbPassword);
settings.setProperty("connectTimeout","5");settings.setProperty("socketTimeout","10");
return DriverManager.getConnection(jdbcUrl,settings);
}
private void loadBalances() {
try { file.getParentFile().mkdirs(); } catch (Exception ignored) { }
for (String key : data.getKeys(false)) {
try { balances.put(UUID.fromString(key), money(data.getDouble(key))); }
catch (IllegalArgumentException ignored) { }
}
importLegacyFile();
if (databaseEnabled) {
try (Connection c = connect(); Statement s = c.createStatement()) {
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_economy_balances (uuid UUID PRIMARY KEY, balance NUMERIC(20,2) NOT NULL DEFAULT 0)");
boolean empty;
try (ResultSet rows = s.executeQuery("SELECT NOT EXISTS (SELECT 1 FROM dune_economy_balances)")) {
empty = rows.next() && rows.getBoolean(1);
}
if (empty) {
importLegacyDatabase(c);
importLocalBalances(c);
}
try (ResultSet rows = s.executeQuery("SELECT uuid,balance FROM dune_economy_balances")) {
while (rows.next()) balances.put(rows.getObject(1, UUID.class), money(rows.getDouble(2)));
}
} catch (SQLException ex) {
plugin.getLogger().severe("Shared Solaris database unavailable; network transactions remain disabled until it recovers: " + ex.getMessage());
}
}
saveLocal();
}
private void importLegacyFile() {
if (!balances.isEmpty()) return;
File old = new File(plugin.getDataFolder().getParentFile(), "DuneCore/players.yml");
if (!old.isFile()) old = new File(plugin.getDataFolder().getParentFile(), "DuneRealms/players.yml");
if (!old.isFile()) return;
YamlConfiguration legacy = YamlConfiguration.loadConfiguration(old);
for (String key : legacy.getKeys(false)) try {
UUID id = UUID.fromString(key);
if (legacy.contains(key + ".solaris")) balances.put(id, money(legacy.getDouble(key + ".solaris")));
} catch (IllegalArgumentException ignored) { }
if (!balances.isEmpty()) plugin.getLogger().info("Imported " + balances.size() + " Solaris balances from the previous Dune data file.");
}
private void importLegacyDatabase(Connection c) {
try (Statement s = c.createStatement(); ResultSet rows = s.executeQuery("SELECT uuid,solaris FROM dune_players WHERE solaris<>0")) {
try (PreparedStatement insert = c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) {
while (rows.next()) {
insert.setObject(1, rows.getObject(1, UUID.class));
insert.setBigDecimal(2, BigDecimal.valueOf(rows.getDouble(2)));
insert.addBatch();
}
insert.executeBatch();
}
plugin.getLogger().info("Imported legacy Solaris balances from the shared Dune player table.");
} catch (SQLException ignored) {
// Older installations may not have enabled the shared player database.
}
}
private void importLocalBalances(Connection c) {
if (balances.isEmpty()) return;
try (PreparedStatement insert = c.prepareStatement(
"INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) {
for (Map.Entry<UUID, Double> entry : balances.entrySet()) {
insert.setObject(1, entry.getKey());
insert.setBigDecimal(2, BigDecimal.valueOf(entry.getValue()));
insert.addBatch();
}
insert.executeBatch();
plugin.getLogger().info("Migrated local Solaris balances into the shared economy database.");
} catch (SQLException ex) {
plugin.getLogger().warning("Could not migrate local Solaris balances to PostgreSQL: " + ex.getMessage());
}
}
private static double money(double amount) {
if (!Double.isFinite(amount)) return 0;
return BigDecimal.valueOf(amount).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
private synchronized void saveLocal() {
for (Map.Entry<UUID, Double> entry : balances.entrySet()) data.set(entry.getKey().toString(), entry.getValue());
try { writeCommunitySnapshot(data); }
catch (Exception ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); }
}
private synchronized double balance(UUID id) {
if (databaseEnabled) {
try (Connection c = connect(); PreparedStatement q = c.prepareStatement("SELECT balance FROM dune_economy_balances WHERE uuid=?")) {
q.setObject(1, id);
try (ResultSet row = q.executeQuery()) {
if (row.next()) {
double value = money(row.getDouble(1));
balances.put(id, value);
return value;
}
}
} catch (SQLException ex) { plugin.getLogger().warning("Solaris balance read failed: " + ex.getMessage()); }
return 0; // Never authorize a network payment against stale local cache.
}
return balances.getOrDefault(id, 0.0);
}
private synchronized void set(UUID id, double value) {
value = money(value);
balances.put(id, value);
if (databaseEnabled) {
try (Connection c = connect(); PreparedStatement q = c.prepareStatement(
"INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO UPDATE SET balance=EXCLUDED.balance")) {
q.setObject(1, id); q.setBigDecimal(2, BigDecimal.valueOf(value)); q.executeUpdate();
} catch (SQLException ex) { plugin.getLogger().severe("Solaris database save failed: " + ex.getMessage()); }
}
saveLocal();
}
synchronized void add(UUID id, double amount) { change(id, amount); }
synchronized void subtract(UUID id, double amount) { change(id, -amount); }
private synchronized EconomyResponse change(UUID id, double delta) {
if (!Double.isFinite(delta)) return response(0, 0, EconomyResponse.ResponseType.FAILURE, "Invalid amount.");
if (sharedDatabaseRequested && !databaseEnabled) return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable.");
if (!databaseEnabled) {
double next=money(balance(id)+delta);
if (!allowNegative && next<0) return response(Math.abs(delta),balance(id),EconomyResponse.ResponseType.FAILURE,"Insufficient funds.");
set(id,next); return response(Math.abs(delta),next,EconomyResponse.ResponseType.SUCCESS,null);
}
try (Connection c=connect()) {
c.setAutoCommit(false);
try {
try (PreparedStatement create=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,0) ON CONFLICT(uuid) DO NOTHING")) {
create.setObject(1,id);create.executeUpdate();
}
double updated;
try (PreparedStatement q=c.prepareStatement("UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=? AND (? OR balance+?>=0) RETURNING balance")) {
BigDecimal amount=BigDecimal.valueOf(money(delta));
q.setBigDecimal(1,amount);q.setObject(2,id);q.setBoolean(3,allowNegative);q.setBigDecimal(4,amount);
try (ResultSet row=q.executeQuery()) {
if (!row.next()) {c.rollback();return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Insufficient funds.");}
updated=row.getDouble(1);
}
}
c.commit();balances.put(id,updated);saveLocal();
return response(Math.abs(delta),updated,EconomyResponse.ResponseType.SUCCESS,null);
} catch(SQLException ex) {c.rollback();throw ex;}
} catch(SQLException ex) {
plugin.getLogger().warning("Shared Solaris transaction failed: "+ex.getSQLState());
return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable.");
}
}
/** One durable credit per UUID/month. A failed shared ledger never falls back to a second ledger. */
synchronized boolean grantCommunity(UUID id,String month,int amount,String receipt) throws Exception {
if(!month.matches("20\\d\\d-(0[1-9]|1[0-2])")||amount<1||amount>10000||!receipt.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("Invalid community grant");
if(sharedDatabaseRequested&&!databaseEnabled)throw new IOException("Shared economy is unavailable");
String key="community-claims."+id+"."+month;
if(databaseEnabled){
try(Connection c=connect()){
try(Statement s=c.createStatement()){s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))");}
c.setAutoCommit(false);
try{
int inserted;
try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_community_claims(uuid,month,receipt,amount) VALUES(?,?,?,?) ON CONFLICT(uuid,month) DO NOTHING")){s.setObject(1,id);s.setString(2,month);s.setString(3,receipt);s.setInt(4,amount);inserted=s.executeUpdate();}
if(inserted==0){try(PreparedStatement s=c.prepareStatement("SELECT receipt,amount FROM dune_community_claims WHERE uuid=? AND month=?")){s.setObject(1,id);s.setString(2,month);try(ResultSet r=s.executeQuery()){if(!r.next()||!receipt.equals(r.getString(1))||amount!=r.getInt(2))throw new IOException("Community receipt mismatch");}}c.commit();return false;}
double updated;
try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES(?,?) ON CONFLICT(uuid) DO UPDATE SET balance=dune_economy_balances.balance+EXCLUDED.balance RETURNING balance")){s.setObject(1,id);s.setBigDecimal(2,BigDecimal.valueOf(amount));try(ResultSet r=s.executeQuery()){r.next();updated=r.getDouble(1);}}
c.commit();balances.put(id,money(updated));saveLocal();return true;
}catch(Exception error){c.rollback();throw error;}
}
}
if(data.contains(key+".receipt")){if(!receipt.equals(data.getString(key+".receipt"))||amount!=data.getInt(key+".amount"))throw new IOException("Community receipt mismatch");return false;}
YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString());
double updated=money(balances.getOrDefault(id,0.0)+amount);
next.set(id.toString(),updated);next.set(key+".receipt",receipt);next.set(key+".amount",amount);next.set(key+".acked",false);
writeCommunitySnapshot(next);balances.put(id,updated);return true;
}
private void writeCommunitySnapshot(YamlConfiguration next) throws Exception {
java.nio.file.Path target=file.toPath(),temporary=target.resolveSibling("balances.yml.community-tmp");
java.nio.file.Files.createDirectories(target.getParent());
byte[] bytes=next.saveToString().getBytes(java.nio.charset.StandardCharsets.UTF_8);
try(java.nio.channels.FileChannel channel=java.nio.channels.FileChannel.open(temporary,java.nio.file.StandardOpenOption.CREATE,java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,java.nio.file.StandardOpenOption.WRITE)){java.nio.ByteBuffer buffer=java.nio.ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);}
java.nio.file.Files.move(temporary,target,java.nio.file.StandardCopyOption.ATOMIC_MOVE,java.nio.file.StandardCopyOption.REPLACE_EXISTING);
data.loadFromString(next.saveToString());
}
synchronized Map<UUID,List<String>> pendingCommunityReceipts() throws Exception {
Map<UUID,List<String>> pending=new HashMap<>();
if(sharedDatabaseRequested&&!databaseEnabled)return pending;
if(databaseEnabled){try(Connection c=connect();Statement s=c.createStatement()){
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))");
try(ResultSet r=s.executeQuery("SELECT uuid,receipt FROM dune_community_claims WHERE acked=FALSE LIMIT 100")){while(r.next())pending.computeIfAbsent(r.getObject(1,UUID.class),ignored->new ArrayList<>()).add(r.getString(2));}
}return pending;}
var section=data.getConfigurationSection("community-claims");if(section==null)return pending;
for(String uuid:section.getKeys(false)){var months=section.getConfigurationSection(uuid);if(months==null)continue;for(String month:months.getKeys(false)){String key=uuid+"."+month;if(!section.getBoolean(key+".acked"))pending.computeIfAbsent(UUID.fromString(uuid),ignored->new ArrayList<>()).add(section.getString(key+".receipt"));}}
return pending;
}
synchronized void acknowledgeCommunity(UUID id,String receipt) throws Exception {
if(databaseEnabled){try(Connection c=connect();PreparedStatement s=c.prepareStatement("UPDATE dune_community_claims SET acked=TRUE WHERE uuid=? AND receipt=?")){s.setObject(1,id);s.setString(2,receipt);s.executeUpdate();}return;}
YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString());var months=next.getConfigurationSection("community-claims."+id);if(months==null)return;
for(String month:months.getKeys(false))if(receipt.equals(months.getString(month+".receipt")))months.set(month+".acked",true);
writeCommunitySnapshot(next);
}
private EconomyResponse response(double amount, double balance, EconomyResponse.ResponseType type, String message) {
return new EconomyResponse(amount, balance, type, message);
}
private EconomyResponse deposit(OfflinePlayer player, double amount) {
if (amount < 0 || !Double.isFinite(amount)) return response(amount, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative.");
return change(player.getUniqueId(), amount);
}
private EconomyResponse withdraw(OfflinePlayer player, double amount) {
double current = getBalance(player);
if (amount < 0 || !Double.isFinite(amount)) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative.");
if (!allowNegative && current < amount) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Insufficient funds.");
return change(player.getUniqueId(), -amount);
}
@Override public boolean isEnabled() { return plugin.isEnabled(); }
@Override public String getName() { return "DuneEss"; }
@Override public boolean hasBankSupport() { return false; }
@Override public int fractionalDigits() { return 2; }
@Override public String format(double amount) { return String.format(java.util.Locale.US, "%,.2f %s", amount, Math.abs(amount) == 1 ? singular : plural); }
@Override public String currencyNamePlural() { return plural; }
@Override public String currencyNameSingular() { return singular; }
@Override public boolean hasAccount(String name) { return hasAccount(Bukkit.getOfflinePlayer(name)); }
@Override public boolean hasAccount(OfflinePlayer player) { return balances.containsKey(player.getUniqueId()) || player.hasPlayedBefore() || player.isOnline(); }
@Override public boolean hasAccount(String name, String world) { return hasAccount(name); }
@Override public boolean hasAccount(OfflinePlayer player, String world) { return hasAccount(player); }
@Override public double getBalance(String name) { return getBalance(Bukkit.getOfflinePlayer(name)); }
@Override public double getBalance(OfflinePlayer player) { return balance(player.getUniqueId()); }
@Override public double getBalance(String name, String world) { return getBalance(name); }
@Override public double getBalance(OfflinePlayer player, String world) { return getBalance(player); }
@Override public boolean has(String name, double amount) { return has(Bukkit.getOfflinePlayer(name), amount); }
@Override public boolean has(OfflinePlayer player, double amount) { return amount >= 0 && getBalance(player) >= amount; }
@Override public boolean has(String name, String world, double amount) { return has(name, amount); }
@Override public boolean has(OfflinePlayer player, String world, double amount) { return has(player, amount); }
@Override public EconomyResponse withdrawPlayer(String name, double amount) { return withdraw(Bukkit.getOfflinePlayer(name), amount); }
@Override public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { return withdraw(player, amount); }
@Override public EconomyResponse withdrawPlayer(String name, String world, double amount) { return withdrawPlayer(name, amount); }
@Override public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double amount) { return withdraw(player, amount); }
@Override public EconomyResponse depositPlayer(String name, double amount) { return deposit(Bukkit.getOfflinePlayer(name), amount); }
@Override public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { return deposit(player, amount); }
@Override public EconomyResponse depositPlayer(String name, String world, double amount) { return depositPlayer(name, amount); }
@Override public EconomyResponse depositPlayer(OfflinePlayer player, String world, double amount) { return deposit(player, amount); }
@Override public EconomyResponse createBank(String name, String player) { return unsupported(); }
@Override public EconomyResponse createBank(String name, OfflinePlayer player) { return unsupported(); }
@Override public EconomyResponse deleteBank(String name) { return unsupported(); }
@Override public EconomyResponse bankBalance(String name) { return unsupported(); }
@Override public EconomyResponse bankHas(String name, double amount) { return unsupported(); }
@Override public EconomyResponse bankWithdraw(String name, double amount) { return unsupported(); }
@Override public EconomyResponse bankDeposit(String name, double amount) { return unsupported(); }
@Override public EconomyResponse isBankOwner(String name, String player) { return unsupported(); }
@Override public EconomyResponse isBankOwner(String name, OfflinePlayer player) { return unsupported(); }
@Override public EconomyResponse isBankMember(String name, String player) { return unsupported(); }
@Override public EconomyResponse isBankMember(String name, OfflinePlayer player) { return unsupported(); }
@Override public List<String> getBanks() { return new ArrayList<>(); }
@Override public boolean createPlayerAccount(String name) { return createPlayerAccount(Bukkit.getOfflinePlayer(name)); }
@Override public boolean createPlayerAccount(OfflinePlayer player) {
UUID id = player.getUniqueId();
if (databaseEnabled) {
try (Connection c=connect();PreparedStatement q=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) {
q.setObject(1,id);q.setBigDecimal(2,BigDecimal.valueOf(money(plugin.getConfig().getDouble("currency.starting-balance",0))));q.executeUpdate();return true;
} catch(SQLException ex) {return false;}
}
if (!balances.containsKey(id)) set(id, money(plugin.getConfig().getDouble("currency.starting-balance", 0)));
return true;
}
@Override public boolean createPlayerAccount(String name, String world) { return createPlayerAccount(name); }
@Override public boolean createPlayerAccount(OfflinePlayer player, String world) { return createPlayerAccount(player); }
private EconomyResponse unsupported() { return response(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "DuneEss does not provide bank accounts."); }
}

View file

@ -0,0 +1,597 @@
package com.example.duneess;
import net.milkbowl.vault.economy.Economy;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.*;
public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCompleter, Listener {
private static final List<String> PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv", "spacing_guild");
private DuneEconomy economy;
String balanceLabel(Player player) { return economy.format(economy.getBalance(player)); }
private ExchangeMenu exchangeMenu;
private EssentialsBasics basics;
private String jdbcUrl = "", dbUser = "", dbPassword = "";
private boolean networkEnabled;
private String localPlanet;
private NamespacedKey spiceKey;
private NamespacedKey helpPageKey, helpActionKey;
private final Map<UUID, Integer> helpPageByPlayer = new HashMap<>();
private static final String HELP_TITLE = ChatColor.DARK_RED + "Dune Field Guide";
private static final List<List<HelpEntry>> HELP_PAGES = List.of(
List.of(
new HelpEntry("/duneess balance", "Check your Dunemarks wallet.", Material.GOLD_INGOT),
new HelpEntry("/duneess sell", "Sell all tagged spice in your inventory.", Material.ORANGE_DYE),
new HelpEntry("/duneess travel", "Open the Vaerkring planet selector.", Material.ENDER_PEARL),
new HelpEntry("/duneess travel arrakis", "Pay the fare and travel to Arrakis.", Material.MAP),
new HelpEntry("/dune", "Open the Dune Navigator menu.", Material.NETHER_STAR)
),
List.of(
new HelpEntry("/dune choose fremen", "Choose Vrijduin; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER),
new HelpEntry("/dune kit", "Receive your faction stillsuit and spice shovel.", Material.NETHERITE_SHOVEL),
new HelpEntry("/dune elytra", "Upgrade a worn stillsuit chestplate with an Elytra.", Material.ELYTRA),
new HelpEntry("/dune politics status", "View the Vaerkring Trust, leaders, and Landsraad appointments.", Material.WRITABLE_BOOK),
new HelpEntry("/dune water status", "View your Arrakis water-trading career.", Material.WATER_BUCKET)
),
List.of(
new HelpEntry("/dune serverjobs", "Browse hourly Koopkring spice contracts.", Material.EMERALD),
new HelpEntry("/dune job", "Browse player-posted spice contracts.", Material.BOOK),
new HelpEntry("/dune job post 100", "Post a 100-spice contract; change the amount to suit your listing.", Material.PAPER),
new HelpEntry("/dune water sell", "Sell water collected on Arrakis.", Material.BUCKET),
new HelpEntry("/dune exchange", "Open the spice exchange menu.", Material.CHEST)
),
List.of(
new HelpEntry("/duneess admin solari player amount", "Grant Dunemarks to an online player.", Material.GOLD_INGOT),
new HelpEntry("/duneess admin teleport arrakis", "Force yourself to Arrakis spawn.", Material.COMPASS),
new HelpEntry("/duneess admin teleport sietch", "Teleport yourself to a generated sietch.", Material.CHEST),
new HelpEntry("/duneess admin teleport spiceblow", "Teleport yourself to a generated spice blow.", Material.MAGMA_BLOCK),
new HelpEntry("/duneess admin spicebloom", "Place an untriggered bloom about 50 blocks ahead of you.", Material.GLOWSTONE),
new HelpEntry("/dune summon sandworm", "Admin: summon on Arrakis; optionally supply x y z.", Material.HUSK_SPAWN_EGG),
new HelpEntry("/dune guireload", "Reload DuneCore's configurable Navigator menu.", Material.COMPARATOR)
)
);
private record HelpEntry(String command, String description, Material icon) {}
@Override public void onEnable() {
saveDefaultConfig();
loadCoreSettings();
spiceKey = new NamespacedKey("dunerealms", "item");
helpPageKey = new NamespacedKey(this, "help_page");
helpActionKey = new NamespacedKey(this, "help_action");
economy = new DuneEconomy(this);
new CommunityCodes(this);
getServer().getServicesManager().register(Economy.class, economy, this, ServicePriority.Highest);
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
PluginCommand command = Objects.requireNonNull(getCommand("duneess"));
command.setExecutor(this);
command.setTabCompleter(this);
getServer().getPluginManager().registerEvents(this, this);
basics=new EssentialsBasics(this);
basics.register();
exchangeMenu = new ExchangeMenu(this);
exchangeMenu.register();
for (Player player : Bukkit.getOnlinePlayers()) economy.createPlayerAccount(player);
getLogger().info("DuneRealms Essentials enabled as the Dunemarks Vault provider.");
}
@Override public void onDisable() {
getServer().getServicesManager().unregister(Economy.class, economy);
}
public Economy economy() { return economy; }
/** Free faction selection arrival, routed through DuneEss so Core owns no player-facing teleport command logic. */
public void factionArrival(Player player, String planet) {
planet = planet.toLowerCase(Locale.ROOT);
if (!PLANETS.contains(planet)) return;
if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) {
player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized.");
return;
}
if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) {
String server = getConfig().getString("network.servers." + planet, "");
if (server.isBlank()) server = YamlConfiguration.loadConfiguration(
new File(getDataFolder().getParentFile(), "DuneCore/config.yml")).getString("network.servers." + planet, "");
if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; }
sendToServer(player, server, planet);
return;
}
World world = Bukkit.getWorld(planet);
if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; }
if (player.teleport(world.getSpawnLocation())) {
player.sendMessage(ChatColor.AQUA + "Faction arrival: " + planet);
if (planet.equals("arrakis")) callCoreArrakisArrival(player);
}
}
private void loadCoreSettings() {
File coreFile = new File(getDataFolder().getParentFile(), "DuneCore/config.yml");
YamlConfiguration core = YamlConfiguration.loadConfiguration(coreFile);
if (getConfig().getBoolean("database.use-core-database", true) && core.getBoolean("database.enabled", false)) {
jdbcUrl = core.getString("database.jdbc-url", "");
dbUser = core.getString("database.username", "");
dbPassword = core.getString("database.password", "");
}
boolean useCore = getConfig().getBoolean("network.use-core-settings", true);
networkEnabled = useCore ? core.getBoolean("network.enabled", getConfig().getBoolean("network.enabled", false)) : getConfig().getBoolean("network.enabled", false);
localPlanet = useCore ? core.getString("network.local-planet", getConfig().getString("network.local-planet", "arrakis")) : getConfig().getString("network.local-planet", "arrakis");
}
String localPlanet() { return localPlanet; }
Connection connectEconomyDatabase() throws java.sql.SQLException {
if (jdbcUrl.isBlank() || !economy.sharedDatabaseReady())
throw new java.sql.SQLException("No shared economy database configured");
Properties properties = new Properties();
properties.setProperty("user", dbUser);
properties.setProperty("password", dbPassword);
properties.setProperty("connectTimeout", "5");
properties.setProperty("socketTimeout", "5");
return DriverManager.getConnection(jdbcUrl, properties);
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(args.length==0 && sender instanceof Player player) { basics.menu(player); return true; }
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
int page = 1;
if (args.length > 1 && args[1].equalsIgnoreCase("menu")) {
if (sender instanceof Player player) openHelpMenu(player, 1);
else sender.sendMessage("The visual guide is available in-game: /duneess help menu");
return true;
}
if (args.length > 1) {
if (args[1].equalsIgnoreCase("next")) page = (sender instanceof Player p ? helpPageByPlayer.getOrDefault(p.getUniqueId(), 1) : 1) + 1;
else if (args[1].equalsIgnoreCase("previous") || args[1].equalsIgnoreCase("prev")) page = (sender instanceof Player p ? helpPageByPlayer.getOrDefault(p.getUniqueId(), 1) : 1) - 1;
else try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { }
}
if (sender instanceof Player player) sendHelpPage(player, page);
else help(sender, page);
return true;
}
String root = args[0].toLowerCase(Locale.ROOT);
if (root.equals("balance")) {
Player target = args.length > 1 && sender.hasPermission("dune.admin") ? Bukkit.getPlayerExact(args[1]) : sender instanceof Player p ? p : null;
if (target == null) { sender.sendMessage("Usage: /duneess balance [online player]"); return true; }
sender.sendMessage(ChatColor.GOLD + target.getName() + " has " + economy.format(economy.getBalance(target)) + ".");
return true;
}
if (root.equals("sell")) { if (sender instanceof Player player) sellSpice(player); else sender.sendMessage("Run this command in-game."); return true; }
if (root.equals("travel")) {
if (!(sender instanceof Player player)) { sender.sendMessage("Run this command in-game."); return true; }
if (args.length == 1) { openTravelMenu(player); return true; }
travel(player, args[1]); return true;
}
if (root.equals("admin")) return admin(sender, args);
sender.sendMessage(ChatColor.YELLOW + "Use /duneess help.");
return true;
}
private void help(CommandSender sender, int page) {
int index = Math.max(0, Math.min(HELP_PAGES.size() - 1, page - 1));
sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+");
sendBoxLine(sender, ChatColor.GOLD + "DUNE FIELD GUIDE" + ChatColor.GRAY + " PAGE " + (index + 1) + " OF " + HELP_PAGES.size());
sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+");
for (HelpEntry entry : HELP_PAGES.get(index)) {
sendBoxLine(sender, ChatColor.YELLOW + entry.command());
for (String descriptionLine : wrap(entry.description(), 50))
sendBoxLine(sender, ChatColor.GRAY + " " + descriptionLine);
sendBoxLine(sender, " ");
}
sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+");
sendBoxLine(sender, ChatColor.GRAY + "Use /duneess help menu for the visual guide.");
sendBoxLine(sender, ChatColor.GRAY + "DuneEss: Dunemarks and Vaerkring travel");
sendBoxLine(sender, ChatColor.GRAY + "DuneCore: factions and Arrakis");
sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+");
if (sender instanceof Player player) {
helpPageByPlayer.put(player.getUniqueId(), index + 1);
TextComponent nav = new TextComponent("§8[ " + (index == 0 ? "§8Previous Page" : "§ePrevious Page") + " §8] ");
if (index > 0) nav.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/duneess help previous"));
TextComponent next = new TextComponent("§8[ " + (index == HELP_PAGES.size() - 1 ? "§8Next Page" : "§eNext Page") + " §8]");
if (index < HELP_PAGES.size() - 1) next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/duneess help next"));
TextComponent pages = new TextComponent("§7 (page " + (index + 1) + "/" + HELP_PAGES.size() + ")");
player.spigot().sendMessage(nav, next, pages);
} else {
sender.sendMessage(ChatColor.GRAY + "Page " + (index + 1) + " of " + HELP_PAGES.size() + " - /duneess help previous or next");
}
}
private void sendHelpPage(Player player, int page) {
int boundedPage = Math.max(1, Math.min(HELP_PAGES.size(), page));
help(player, boundedPage);
}
private void sendBoxLine(CommandSender sender, String text) {
String plain = ChatColor.stripColor(text);
if (plain.length() > 56) plain = plain.substring(0, 53) + "...";
String padding = " ".repeat(Math.max(0, 56 - plain.length()));
sender.sendMessage(ChatColor.DARK_RED + "| " + text + padding + " " + ChatColor.DARK_RED + "|");
}
private List<String> wrap(String text, int width) {
List<String> lines = new ArrayList<>();
StringBuilder line = new StringBuilder();
for (String word : text.split("\\s+")) {
if (line.length() > 0 && line.length() + 1 + word.length() > width) {
lines.add(line.toString());
line.setLength(0);
}
if (line.length() > 0) line.append(' ');
line.append(word);
}
if (line.length() > 0) lines.add(line.toString());
return lines;
}
private void openHelpMenu(Player player, int page) {
int index = Math.max(0, Math.min(HELP_PAGES.size() - 1, page - 1));
Inventory menu = Bukkit.createInventory(null, 54, HELP_TITLE + ChatColor.DARK_GRAY + " Page " + (index + 1) + " of " + HELP_PAGES.size());
ItemStack frame = helpItem(Material.BLACK_STAINED_GLASS_PANE, ChatColor.DARK_GRAY + " ", null);
for (int slot = 0; slot < 9; slot++) { menu.setItem(slot, frame); menu.setItem(45 + slot, frame); }
for (int row = 1; row <= 4; row++) { menu.setItem(row * 9, frame); menu.setItem(row * 9 + 8, frame); }
ItemStack heading = helpItem(Material.WRITABLE_BOOK, ChatColor.GOLD + "Dune Field Guide",
List.of(ChatColor.GRAY + "Page " + (index + 1) + " of " + HELP_PAGES.size(), ChatColor.DARK_GRAY + "Click a command to run it."));
menu.setItem(4, heading);
int[] slots = {10, 12, 14, 16, 28, 30, 32};
int n = 0;
for (HelpEntry entry : HELP_PAGES.get(index)) {
ItemStack item = helpItem(entry.icon(), ChatColor.YELLOW + entry.command(),
List.of(ChatColor.GRAY + entry.description(), ChatColor.GREEN + "Click to run"));
ItemMeta itemMeta = item.getItemMeta();
if (!entry.command().endsWith(" player amount") && !entry.command().contains("["))
itemMeta.getPersistentDataContainer().set(helpActionKey, PersistentDataType.STRING, entry.command());
item.setItemMeta(itemMeta);
menu.setItem(slots[n++], item);
}
ItemStack previous = helpItem(index == 0 ? Material.GRAY_STAINED_GLASS_PANE : Material.BOOK,
ChatColor.YELLOW + "Previous page", List.of(ChatColor.GRAY + (index == 0 ? "You are on the first page." : "Go to page " + index)));
ItemMeta previousMeta = previous.getItemMeta();
previousMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index);
previous.setItemMeta(previousMeta);
menu.setItem(45, previous);
menu.setItem(49, helpItem(Material.BARRIER, ChatColor.RED + "Close", List.of(ChatColor.GRAY + "Close this guide.")));
ItemStack next = helpItem(index == HELP_PAGES.size() - 1 ? Material.GRAY_STAINED_GLASS_PANE : Material.WRITABLE_BOOK,
ChatColor.YELLOW + "Next page", List.of(ChatColor.GRAY + (index == HELP_PAGES.size() - 1 ? "You are on the last page." : "Go to page " + (index + 2))));
ItemMeta nextMeta = next.getItemMeta();
nextMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index + 2);
next.setItemMeta(nextMeta);
menu.setItem(53, next);
java.util.Map<Integer,Runnable> actions=new java.util.HashMap<>();
actions.put(45,()->openHelpMenu(player,index));
actions.put(53,()->openHelpMenu(player,index+2));
actions.put(49,player::closeInventory);
for(int slot:slots) {
ItemStack entry=menu.getItem(slot);
if(entry==null) continue;
String command=entry.getItemMeta().getPersistentDataContainer().get(helpActionKey,PersistentDataType.STRING);
if(command!=null) actions.put(slot,()->player.performCommand(command.substring(1)));
}
com.example.dunegui.NativeMenus.inventory(this,player,"Dune Field Guide · "+(index+1),menu,actions);
}
private ItemStack helpItem(Material material, String name, List<String> lore) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
if (lore != null) meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
@EventHandler public void onHelpMenuClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().startsWith(HELP_TITLE)) return;
event.setCancelled(true);
ItemStack clicked = event.getCurrentItem();
if (clicked == null || !clicked.hasItemMeta()) return;
ItemMeta meta = clicked.getItemMeta();
Integer page = meta.getPersistentDataContainer().get(helpPageKey, PersistentDataType.INTEGER);
if (page != null) { openHelpMenu(player, page); return; }
if (clicked.getType() == Material.BARRIER) { player.closeInventory(); return; }
String action = meta.getPersistentDataContainer().get(helpActionKey, PersistentDataType.STRING);
if (action != null) { player.closeInventory(); player.performCommand(action.substring(1)); }
}
@EventHandler public void onHelpMenuDrag(org.bukkit.event.inventory.InventoryDragEvent event) {
if (event.getView().getTitle().startsWith(HELP_TITLE)) event.setCancelled(true);
}
@EventHandler public void onPlayerJoin(PlayerJoinEvent event) {
economy.createPlayerAccount(event.getPlayer());
}
@EventHandler(ignoreCancelled=true)
public void spiceSeller(org.bukkit.event.player.PlayerInteractEntityEvent event) {
if(!event.getRightClicked().getPersistentDataContainer().has(new NamespacedKey("dunerealms","spice-seller"),PersistentDataType.BYTE))return;
event.setCancelled(true);
if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;
Player player=event.getPlayer();
Inventory menu=Bukkit.createInventory(null,9,"Spice Seller");
int quantity=16;
double price=java.math.BigDecimal.valueOf(Math.max(1,getConfig().getInt("currency.spice-price",15)))
.multiply(new java.math.BigDecimal("1.35")).multiply(java.math.BigDecimal.valueOf(quantity)).doubleValue();
ItemStack offer=new ItemStack(Material.ORANGE_DYE,quantity); ItemMeta meta=offer.getItemMeta();
meta.setDisplayName("Buy 16 spice · "+economy.format(price));
meta.setLore(List.of("35% above standard spice price", "Confirm purchase"));offer.setItemMeta(meta);menu.setItem(4,offer);
Map<Integer,Runnable> actions=new HashMap<>();
actions.put(4,()->{
// Recheck proximity and capacity at confirmation; never charge for undeliverable goods.
if(!event.getRightClicked().isValid() || !player.getWorld().equals(event.getRightClicked().getWorld())
|| player.getLocation().distanceSquared(event.getRightClicked().getLocation())>64)return;
ItemStack spice=new ItemStack(Material.ORANGE_DYE,quantity);ItemMeta sm=spice.getItemMeta();
sm.setDisplayName(ChatColor.GOLD+"Melange Spice");sm.getPersistentDataContainer().set(spiceKey,PersistentDataType.STRING,"spice");spice.setItemMeta(sm);
if(player.getInventory().firstEmpty()<0){player.sendMessage("Make an empty inventory slot first.");return;}
if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Dunemarks, or economy unavailable.");return;}
player.getInventory().addItem(spice);player.sendMessage(ChatColor.GOLD+"Bought 16 spice for "+economy.format(price)+".");
});
com.example.dunegui.NativeMenus.inventory(this,player,"Spice Seller · +35%",menu,actions);
}
private void sellSpice(Player player) {
int amount = 0;
for (ItemStack item : player.getInventory().getStorageContents()) {
if (isSpice(item)) { amount += item.getAmount(); item.setAmount(0); }
}
if (amount == 0) { player.sendMessage(ChatColor.RED + "You have no tagged spice to sell."); return; }
int price = Math.max(1, getConfig().getInt("currency.spice-price", 15));
int gross = Math.multiplyExact(amount, price);
int net = callCoreSaleAdjustment(player, gross);
economy.depositPlayer(player, net);
player.sendMessage(ChatColor.GOLD + "Sold " + amount + " spice for " + economy.format(net) + ".");
}
private boolean isSpice(ItemStack item) {
return item != null && item.hasItemMeta()
&& "spice".equals(item.getItemMeta().getPersistentDataContainer().get(spiceKey, PersistentDataType.STRING));
}
private int callCoreSaleAdjustment(Player player, int gross) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return gross;
try {
Method method = core.getClass().getMethod("processSpiceSale", Player.class, int.class);
Object value = method.invoke(core, player, gross);
if (value instanceof Number n) return Math.max(0, n.intValue());
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not apply DuneCore spice trade rules: " + ex.getMessage()); }
return gross;
}
private void openTravelMenu(Player player) {
Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Vaerkring Travel");
for (int i = 0; i < PLANETS.size(); i++) {
String planet = PLANETS.get(i);
ItemStack item = new ItemStack(Material.ENDER_PEARL);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + com.example.dunegui.PlanetSigils.label(planet) + " — " + getConfig().getInt("currency.travel-price", 100) + " Dunemarks");
meta.getPersistentDataContainer().set(new NamespacedKey(this, "planet"), PersistentDataType.STRING, planet);
item.setItemMeta(meta);
inventory.setItem(i, com.example.dunegui.PlanetSigils.apply(item,planet));
}
java.util.Map<Integer,Runnable> actions=new java.util.HashMap<>();
for(int i=0;i<PLANETS.size();i++) { String planet=PLANETS.get(i); actions.put(i,()->travel(player,planet)); }
com.example.dunegui.NativeMenus.inventory(this,player,"Vaerkring Travel",inventory,actions);
}
@EventHandler public void onTravelMenuClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Vaerkring Travel")) return;
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
if (item == null || !item.hasItemMeta()) return;
String planet = item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey(this, "planet"), PersistentDataType.STRING);
if (planet == null) return;
player.closeInventory();
travel(player, planet);
}
private void travel(Player player, String planet) {
planet = planet.toLowerCase(Locale.ROOT);
if (!PLANETS.contains(planet)) { player.sendMessage(ChatColor.RED + "Unknown planet."); return; }
if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) { player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized."); return; }
if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) {
String server = getConfig().getString("network.servers." + planet, "");
if (server.isBlank()) {
YamlConfiguration core = YamlConfiguration.loadConfiguration(new File(getDataFolder().getParentFile(), "DuneCore/config.yml"));
server = core.getString("network.servers." + planet, "");
}
if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; }
int fare = travelFare(player, planet);
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; }
if (fare > 0) economy.withdrawPlayer(player, fare);
if (!sendToServer(player, server, planet) && fare > 0) economy.depositPlayer(player, fare);
return;
}
World world = Bukkit.getWorld(planet);
if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; }
int fare = travelFare(player, planet);
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; }
if (fare > 0) economy.withdrawPlayer(player, fare);
if (!player.teleport(world.getSpawnLocation())) {
if (fare > 0) economy.depositPlayer(player, fare);
player.sendMessage(ChatColor.RED + "Vaerkring travel failed. Your fare was returned.");
} else {
player.sendMessage(ChatColor.AQUA + "Vaerkring arrival: " + planet);
if (planet.equals("arrakis")) callCoreArrakisArrival(player);
}
}
private boolean sendToServer(Player player, String server, String planet) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
data.writeUTF("Connect"); data.writeUTF(server);
player.sendPluginMessage(this, "BungeeCord", bytes.toByteArray());
player.sendMessage(ChatColor.AQUA + "Vaerkring transfer requested: " + planet);
return true;
} catch (Exception ex) {
player.sendMessage(ChatColor.RED + "Guild transfer failed. Your fare was returned.");
return false;
}
}
private boolean callCoreArrakisAuthorization(Player player) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return true;
try {
Method method = core.getClass().getMethod("authorizeArrakisTravel", Player.class);
return Boolean.TRUE.equals(method.invoke(core, player));
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not authorize Arrakis travel with DuneCore: " + ex.getMessage()); return false; }
}
private void callCoreArrakisArrival(Player player) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return;
try { core.getClass().getMethod("enforceArrakisArrival", Player.class).invoke(core, player); }
catch (ReflectiveOperationException ex) { getLogger().warning("Could not enforce Arrakis arrival rules: " + ex.getMessage()); }
}
private int travelFare(Player player, String planet) {
if (planet.equals("arrakis")) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core != null && core.isEnabled()) try {
Method method = core.getClass().getMethod("hasFreeArrakisTravel", Player.class);
if (Boolean.TRUE.equals(method.invoke(core, player))) return 0;
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not check Arrakis travel rights: " + ex.getMessage()); }
}
return Math.max(0, getConfig().getInt("currency.travel-price", 100));
}
private boolean admin(CommandSender sender, String[] args) {
if (!sender.hasPermission("dune.admin")) { sender.sendMessage(ChatColor.RED + "Admin only."); return true; }
if (args.length < 2) { sender.sendMessage("Usage: /duneess admin <solari|teleport|spicebloom> ..."); return true; }
if (args[1].equalsIgnoreCase("solari")) {
if (args.length != 4) { sender.sendMessage("Usage: /duneess admin solari <player> <amount>"); return true; }
Player target = Bukkit.getPlayerExact(args[2]);
if (target == null) { sender.sendMessage(ChatColor.RED + "That player must be online."); return true; }
try {
double amount = Double.parseDouble(args[3]);
if (amount <= 0 || !Double.isFinite(amount)) throw new NumberFormatException();
economy.depositPlayer(target, amount);
sender.sendMessage(ChatColor.GREEN + "Added " + economy.format(amount) + " to " + target.getName() + ".");
target.sendMessage(ChatColor.GOLD + "An admin added " + economy.format(amount) + " to your balance.");
} catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Dunemarks amount."); }
return true;
}
if (args[1].equalsIgnoreCase("spicebloom")) {
Player bloomTarget = args.length > 2 ? Bukkit.getPlayerExact(args[2]) : sender instanceof Player p ? p : null;
if (bloomTarget == null) { sender.sendMessage("Usage: /duneess admin spicebloom [online player]"); return true; }
World arrakisWorld = Bukkit.getWorld("arrakis");
if (arrakisWorld == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; }
spawnSpiceBloom(sender, bloomTarget, arrakisWorld);
return true;
}
if (!args[1].equalsIgnoreCase("teleport")) { sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]"); return true; }
if (args.length < 3) { sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]"); return true; }
Player target = args.length > 3 ? Bukkit.getPlayerExact(args[3]) : sender instanceof Player p ? p : null;
if (target == null) { sender.sendMessage(ChatColor.RED + "Specify an online player from console."); return true; }
World arrakis = Bukkit.getWorld("arrakis");
if (arrakis == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; }
switch (args[2].toLowerCase(Locale.ROOT)) {
case "arrakis" -> finishTeleport(sender, target, arrakis.getSpawnLocation(), "Arrakis spawn");
case "sietch" -> teleportToSietch(sender, target, arrakis);
case "spiceblow" -> teleportToSpiceBlow(sender, target, arrakis);
default -> sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]");
}
return true;
}
private void finishTeleport(CommandSender sender, Player target, Location location, String label) {
if (target.teleport(location)) { target.sendMessage(ChatColor.AQUA + "An admin sent you to " + label + "."); sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to " + label + "."); }
else sender.sendMessage(ChatColor.RED + "Teleport failed.");
}
private void teleportToSietch(CommandSender sender, Player target, World world) {
Location origin = target.getWorld().equals(world) ? target.getLocation() : world.getSpawnLocation();
for (long[] c : candidates(origin, 0x534945544348L)) {
int x=(int)c[0], z=(int)c[1];
world.getChunkAt(x >> 4, z >> 4).load(true);
int chestX=x, chestZ=z-10, estimate=world.getHighestBlockYAt(x+12,z+12);
for (int y=Math.max(world.getMinHeight()+1,estimate-80); y<=Math.min(world.getMaxHeight()-1,estimate+5); y++) {
Block b=world.getBlockAt(chestX,y,chestZ);
if (b.getType()==Material.CHEST && b.getState() instanceof org.bukkit.block.Chest chest && "Personal Sietch Cache".equals(chest.getCustomName())) {
finishTeleport(sender,target,new Location(world,x+.5,y+14,z+.5),"a sietch"); return;
}
}
}
sender.sendMessage(ChatColor.RED+"No generated sietch was found nearby. Explore new Arrakis terrain, then retry.");
}
private void teleportToSpiceBlow(CommandSender sender, Player target, World world) {
for (long[] c : candidates(target.getWorld().equals(world)?target.getLocation():world.getSpawnLocation(),0x5350494345424c4fL)) {
int x=(int)c[0],z=(int)c[1]; world.getChunkAt(x>>4,z>>4).load(true);
int top=world.getHighestBlockYAt(x,z); Material marker=world.getBlockAt(x,top,z).getType();
if(marker==Material.MAGMA_BLOCK||marker==Material.GLOWSTONE) {
int sx=x+4,sz=z+4; finishTeleport(sender,target,new Location(world,sx+.5,world.getHighestBlockYAt(sx,sz)+1,sz+.5),"a spice blow"); return;
}
}
sender.sendMessage(ChatColor.RED+"No spice blow was found nearby. Explore new Arrakis terrain, then retry.");
}
private List<long[]> candidates(Location origin,long salt) {
int spacing=2000; long gx0=Math.floorDiv(origin.getBlockX(),spacing),gz0=Math.floorDiv(origin.getBlockZ(),spacing);
List<long[]> points=new ArrayList<>();
for(long gx=gx0-2;gx<=gx0+2;gx++)for(long gz=gz0-2;gz<=gz0+2;gz++){
long h1=mix64(gx*0x9E3779B97F4A7C15L^gz*0xC2B2AE3D27D4EB4FL^salt);
long h2=mix64(gz*0x165667B19E3779F9L^gx*0x85EBCA77C2B2AE63L^~salt);
long x=gx*spacing+8+Math.floorMod(h1,spacing-16),z=gz*spacing+8+Math.floorMod(h2,spacing-16);
long dx=x-origin.getBlockX(),dz=z-origin.getBlockZ();points.add(new long[]{x,z,dx*dx+dz*dz});
}
points.sort(Comparator.comparingLong(point->point[2]));return points;
}
private static long mix64(long value){value=(value^(value>>>30))*0xBF58476D1CE4E5B9L;value=(value^(value>>>27))*0x94D049BB133111EBL;return value^(value>>>31);}
private void spawnSpiceBloom(CommandSender sender, Player target, World world) {
if(!target.getWorld().equals(world)){sender.sendMessage(ChatColor.RED+"The target must be on Arrakis.");return;}
double base=Math.toRadians(90.0-target.getLocation().getYaw()); Block center=null;
for(int offset=-12;offset<=12;offset++){
double angle=base+Math.toRadians(offset*15.0);int x=target.getLocation().getBlockX()+(int)Math.round(Math.cos(angle)*50),z=target.getLocation().getBlockZ()+(int)Math.round(Math.sin(angle)*50),y=world.getHighestBlockYAt(x,z);boolean ok=true;
for(int dx=-1;dx<=1&&ok;dx++)for(int dz=-1;dz<=1;dz++){Block b=world.getBlockAt(x+dx,y,z+dz);if((b.getType()!=Material.SAND&&b.getType()!=Material.RED_SAND)||!world.getBlockAt(x+dx,y+1,z+dz).isPassable()){ok=false;break;}}
if(ok&&world.getBlockAt(x,y+2,z).isPassable()){center=world.getBlockAt(x,y,z);break;}
}
if(center==null){sender.sendMessage(ChatColor.RED+"No clear sand patch was found 50 blocks ahead.");return;}
int x=center.getX(),y=center.getY(),z=center.getZ();for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++)world.getBlockAt(x+dx,y,z+dz).setType(Material.MAGMA_BLOCK,false);world.getBlockAt(x,y+1,z).setType(Material.MAGMA_BLOCK,false);
org.bukkit.plugin.Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core != null && core.isEnabled()) try {
Location bloom = new Location(world, x, y + 1, z);
core.getClass().getMethod("announceArrakisEvent", String.class, Location.class, String.class)
.invoke(core, "spicebloom", bloom, "bloom:" + world.getUID() + ":" + x + ":" + (y + 1) + ":" + z);
} catch (ReflectiveOperationException ex) { getLogger().warning("Spice bloom announcement failed: " + ex.getMessage()); }
sender.sendMessage(ChatColor.GREEN+"Placed a spice bloom near "+x+", "+z+".");target.sendMessage(ChatColor.GOLD+"A spice bloom appeared about 50 blocks ahead.");
}
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if(args.length==1)return complete(List.of("help","balance","sell","travel","admin"),args[0]);
if(args[0].equalsIgnoreCase("help")&&args.length==2)return complete(List.of("1","2","3","4","next","previous","menu"),args[1]);
if(args[0].equalsIgnoreCase("travel")&&args.length==2)return complete(PLANETS,args[1]);
if(args[0].equalsIgnoreCase("admin")&&sender.hasPermission("dune.admin")){
if(args.length==2)return complete(List.of("solari","teleport","spicebloom"),args[1]);
if(args[1].equalsIgnoreCase("teleport")&&args.length==3)return complete(List.of("arrakis","sietch","spiceblow"),args[2]);
if(args[1].equalsIgnoreCase("spicebloom")&&args.length==3)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[2]);
if((args[1].equalsIgnoreCase("teleport")||args[1].equalsIgnoreCase("solari"))&&args.length==4)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[3]);
}
if(args[0].equalsIgnoreCase("balance")&&args.length==2&&sender.hasPermission("dune.admin"))return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[1]);
return List.of();
}
private List<String> complete(Collection<String> options,String prefix){return options.stream().filter(s->s.toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT))).sorted(String.CASE_INSENSITIVE_ORDER).toList();}
}

View file

@ -0,0 +1,138 @@
package com.example.duneess;
import com.example.dunegui.NativeMenus;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.player.PlayerQuitEvent;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/** Deliberately small essentials command surface; vanilla owns bed/anchor respawns. */
final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener {
private final DuneEss plugin;
private final File file;
private YamlConfiguration homes;
private final Map<UUID,Request> requests=new HashMap<>();
private record Request(UUID sender,long expires) {}
EssentialsBasics(DuneEss plugin) {
this.plugin=plugin;
file=new File(plugin.getDataFolder(),"homes.yml");
homes=YamlConfiguration.loadConfiguration(file);
}
void register() {
for(String name:List.of("home","sethome","delhome","homes","tpa","tpaccept","tpdeny","spawn","server","essentials")) {
PluginCommand command=Objects.requireNonNull(plugin.getCommand(name));
command.setExecutor(this); command.setTabCompleter(this);
}
Bukkit.getPluginManager().registerEvents(this,plugin);
}
static String homeName(String[] args) {
String name=args.length==0?"home":args[0].toLowerCase(Locale.ROOT);
if(args.length>1 || !name.matches("[a-z0-9_-]{1,24}")) throw new IllegalArgumentException("Use a home name with 1–24 letters, numbers, underscores or hyphens.");
return name;
}
private String key(Player p,String name) { return p.getUniqueId()+"."+name; }
private Set<String> names(Player p) {
var section=homes.getConfigurationSection(p.getUniqueId().toString());
return section==null?Set.of():section.getKeys(false);
}
private void save() throws IOException {
Path target=file.toPath(), temp=target.resolveSibling("homes.yml.tmp");
Files.createDirectories(target.getParent());
Files.writeString(temp,homes.saveToString());
try { Files.move(temp,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); }
catch(AtomicMoveNotSupportedException ex) { Files.move(temp,target,StandardCopyOption.REPLACE_EXISTING); }
}
private void teleport(Player p,Location location) {
// Local essentials never bypass interplanetary permits, fares, or arrival rules.
if(location==null || location.getWorld()==null) { p.sendMessage("That destination is unavailable on this server."); return; }
if(!p.getWorld().equals(location.getWorld())) { p.sendMessage("Use /server to travel between worlds, then /home at your destination."); return; }
if(!location.getWorld().getWorldBorder().isInside(location) || location.getY()<location.getWorld().getMinHeight() || location.getY()>=location.getWorld().getMaxHeight()) {
p.sendMessage("That destination is outside the world's playable bounds."); return;
}
p.teleportAsync(location).thenAccept(success->{ if(!success) p.sendMessage("Teleportation failed. Try again."); });
}
void menu(Player p) {
List<NativeMenus.Choice> choices=new ArrayList<>();
choices.add(new NativeMenus.Choice("Set home","Save your current position as home.",()->p.performCommand("sethome")));
choices.add(new NativeMenus.Choice("Homes","Choose a saved home on this backend.",()->homeMenu(p)));
choices.add(new NativeMenus.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn")));
choices.add(new NativeMenus.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel")));
choices.add(new NativeMenus.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance")));
choices.add(new NativeMenus.Choice("Koopkring Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange")));
choices.add(new NativeMenus.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu")));
NativeMenus.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices);
}
private void homeMenu(Player p) {
List<NativeMenus.Choice> choices=names(p).stream().sorted().map(name->new NativeMenus.Choice(name,"Teleport to this saved home.",()->p.performCommand("home "+name))).toList();
if(choices.isEmpty()) p.sendMessage("You have no homes. Use /sethome [name].");
else NativeMenus.show(plugin,p,"Your homes",choices);
}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
if(!(sender instanceof Player p)) { sender.sendMessage("Use this command in-game."); return true; }
String action=command.getName();
if(!p.hasPermission("duneess.basics")) { p.sendMessage("You do not have permission to use essentials."); return true; }
try {
switch(action) {
case "essentials" -> menu(p);
case "homes" -> homeMenu(p);
case "sethome" -> {
String name=homeName(args), path=key(p,name);
if(!homes.contains(path) && names(p).size()>=Math.max(1,plugin.getConfig().getInt("essentials.max-homes",3))) throw new IllegalArgumentException("Your home limit has been reached.");
homes.set(path,p.getLocation()); save(); p.sendMessage("Home saved: "+name);
}
case "home" -> teleport(p,homes.getLocation(key(p,homeName(args))));
case "delhome" -> {
String name=homeName(args),path=key(p,name);
if(!homes.contains(path)) throw new IllegalArgumentException("That home does not exist.");
homes.set(path,null); save(); p.sendMessage("Home removed: "+name);
}
case "spawn" -> teleport(p,p.getWorld().getSpawnLocation());
case "server" -> plugin.onCommand(p,Objects.requireNonNull(plugin.getCommand("duneess")),"duneess",args.length==0?new String[]{"travel"}:new String[]{"travel",args[0]});
case "tpa" -> {
if(args.length!=1) throw new IllegalArgumentException("Usage: /tpa <online player>");
Player target=Bukkit.getPlayerExact(args[0]);
if(target==null || target.equals(p) || !p.canSee(target)) throw new IllegalArgumentException("Choose another online player on this server.");
if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Vaerkring travel to reach that player's world first.");
requests.put(target.getUniqueId(),new Request(p.getUniqueId(),System.nanoTime()+60_000_000_000L));
target.sendMessage(p.getName()+" requests to teleport to you. /tpaccept or /tpdeny (60 seconds).");
p.sendMessage("Teleport request sent.");
}
case "tpaccept","tpdeny" -> {
Request request=requests.remove(p.getUniqueId());
if(request==null || request.expires()<System.nanoTime()) throw new IllegalArgumentException("No active teleport request.");
Player requester=Bukkit.getPlayer(request.sender());
if(requester==null || !requester.isOnline()) throw new IllegalArgumentException("That player is offline.");
if(action.equals("tpaccept")) teleport(requester,p.getLocation());
else requester.sendMessage("Your teleport request was declined.");
}
default -> { return false; }
}
} catch(IllegalArgumentException ex) { p.sendMessage(ex.getMessage()); }
catch(IOException ex) {
homes=YamlConfiguration.loadConfiguration(file);
plugin.getLogger().warning("Could not persist homes: "+ex.getMessage());
p.sendMessage("Could not save your homes. No change was committed.");
}
return true;
}
@Override public List<String> onTabComplete(CommandSender sender,Command command,String alias,String[] args) {
if(!(sender instanceof Player p) || args.length!=1) return List.of();
Collection<String> values=switch(command.getName()) {
case "home","delhome" -> names(p);
case "tpa" -> Bukkit.getOnlinePlayers().stream().filter(p::canSee).map(Player::getName).toList();
case "server" -> List.of("arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv","spacing_guild");
default -> List.of();
};
return values.stream().filter(v->v.toLowerCase(Locale.ROOT).startsWith(args[0].toLowerCase(Locale.ROOT))).toList();
}
@EventHandler public void quit(PlayerQuitEvent event) {
UUID id=event.getPlayer().getUniqueId();
requests.remove(id); requests.values().removeIf(request->request.sender().equals(id));
}
}

View file

@ -0,0 +1,320 @@
package com.example.duneess;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
/** Native menus share the existing SQL-backed trading operations. */
@SuppressWarnings("deprecation")
final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
private static final List<String> CATEGORIES=List.of("ores","spice","building","equipment","farming","misc");
private static final List<String> PLANETS=List.of("all","arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv");
private static final List<Material> ICONS=List.of(Material.IRON_PICKAXE,Material.ORANGE_DYE,Material.BRICKS,Material.IRON_SWORD,Material.WHEAT,Material.CHEST);
private final DuneEss plugin;
private final ExchangeStore store;
private final Map<UUID,String> planets=new HashMap<>();
private boolean ready;
static final class Screen implements InventoryHolder {
final UUID owner;
final Map<Integer,Runnable> actions=new HashMap<>();
Inventory inventory;
String title;
Screen(UUID owner) { this.owner=owner; }
@Override public Inventory getInventory() { return inventory; }
}
ExchangeMenu(DuneEss plugin) {
this.plugin=plugin;
this.store=new ExchangeStore(plugin::connectEconomyDatabase);
}
void register() {
PluginCommand command=Objects.requireNonNull(plugin.getCommand("exchange"));
command.setExecutor(this); command.setTabCompleter(this);
Bukkit.getPluginManager().registerEvents(this,plugin);
try { store.initialize(); ready=true; }
catch(SQLException ex) { plugin.getLogger().warning("Koopkring is offline until the shared PostgreSQL economy is connected."); }
}
private boolean connected(Player p) {
// Retry after a transient startup outage; never trade against a fallback local wallet.
if(!ready) try { store.initialize(); ready=true; } catch(SQLException ignored) { }
if(!ready) p.sendMessage(ChatColor.YELLOW+"Koopkring is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Dunemarks were taken.");
return ready;
}
private String faction(Player p) {
Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore");
if(core!=null) try {
String house=String.valueOf(core.getClass().getMethod("factionOf",Player.class).invoke(core,p));
if(List.of("Fremen","Atreides","Harkonnen","Corrino","Ordos").contains(house)) return house;
} catch(ReflectiveOperationException ignored) { }
return "Vaerkring";
}
private ChatColor tint(Player p) {
return switch(faction(p)) {
case "Atreides" -> ChatColor.AQUA;
case "Harkonnen" -> ChatColor.RED;
case "Corrino" -> ChatColor.GOLD;
case "Fremen" -> ChatColor.YELLOW;
case "Ordos" -> ChatColor.GREEN;
default -> ChatColor.LIGHT_PURPLE;
};
}
private ItemStack icon(Material material,String name,String... lore) {
ItemStack item=new ItemStack(material); ItemMeta meta=item.getItemMeta();
meta.setDisplayName(name); meta.setLore(Arrays.asList(lore)); item.setItemMeta(meta); return item;
}
private Screen screen(Player p,String title) {
Screen s=new Screen(p.getUniqueId());
s.title="Koopkring | "+title;
s.inventory=Bukkit.createInventory(s,54,tint(p)+"Koopkring | "+title);
Material glass=switch(faction(p)) {
case "Atreides" -> Material.CYAN_STAINED_GLASS_PANE;
case "Harkonnen" -> Material.RED_STAINED_GLASS_PANE;
case "Corrino" -> Material.YELLOW_STAINED_GLASS_PANE;
case "Ordos" -> Material.GREEN_STAINED_GLASS_PANE;
case "Fremen" -> Material.ORANGE_STAINED_GLASS_PANE;
default -> Material.PURPLE_STAINED_GLASS_PANE;
};
for(int i=0;i<54;i++) if(i<9||i>=45||i%9==0||i%9==8)
s.inventory.setItem(i,icon(glass," "));
s.inventory.setItem(47,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Dunemarks",List.of(ChatColor.GRAY+"Wallet: "+plugin.balanceLabel(p),ChatColor.GRAY+"Display icon only; balances stay in the ledger.")));
button(s,49,Material.BARRIER,"Back to Exchange",()->home(p)); return s;
}
private void button(Screen s,int slot,Material material,String title,Runnable action,String... lore) {
s.inventory.setItem(slot,icon(material,ChatColor.GOLD+title,lore)); s.actions.put(slot,action);
}
private void home(Player p) {
Screen s=screen(p,faction(p));
for(int i=0;i<CATEGORIES.size();i++) {
String category=CATEGORIES.get(i);
button(s,10+i,ICONS.get(i),category.toUpperCase(Locale.ROOT),()->browse(p,category,0,false,false));
}
s.inventory.setItem(29,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Buy / All Items",List.of(ChatColor.GRAY+"Pay with Dunemarks from your wallet.")));
s.actions.put(29,()->browse(p,"all",0,false,false));
button(s,31,Material.CHEST,"Sell Held Item",()->{
p.closeInventory(); p.sendMessage(ChatColor.YELLOW+"Hold the item to list, then /exchange sell <amount> <price-each>. Example: /exchange sell 16 25");
},"Tagged Dune items and their attributes are preserved.","Price is for ONE item.");
button(s,33,Material.BOOK,"My Listings",()->browse(p,"all",0,true,false),"Cancel and reclaim your unsold items.");
button(s,40,Material.COMPASS,"Planet: "+planets.getOrDefault(p.getUniqueId(),"all"),()->planetMenu(p));
button(s,38,Material.PAPER,"Trading Guide",()->{
p.sendMessage(ChatColor.YELLOW+"/exchange sell <amount> <price> · /exchange buy <id> · /exchange cancel <id> · /exchange mine");
p.sendMessage(ChatColor.GRAY+"Purchases buy one item. Listings reserve the offered items. Website demo offers cannot be purchased.");
});
if(p.hasPermission("dune.admin")) button(s,42,Material.COMMAND_BLOCK,"Exchange Administration",()->admin(p));
button(s,49,Material.BARRIER,"Close",p::closeInventory);
com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions);
}
private void planetMenu(Player p) {
Screen s=screen(p,"Planet Filter");
for(int i=0;i<PLANETS.size();i++) {
String planet=PLANETS.get(i);
button(s,11+i,Material.COMPASS,planet,()->{planets.put(p.getUniqueId(),planet); browse(p,"all",0,false,false);});
}
com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions);
}
private void admin(Player p) {
if(!p.hasPermission("dune.admin")) return;
Screen s=screen(p,"Administration");
button(s,20,Material.BOOK,"All Listings",()->browse(p,"all",0,false,true),"All planets. Read-only inspection; normal ownership rules apply.");
button(s,24,Material.REDSTONE,"Check Database",()->{
if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared Koopkring database connected.");
});
com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions);
}
private ItemStack decode(ExchangeStore.Listing offer) {
ItemStack item;
if(offer.payload()!=null&&!offer.payload().isBlank()) item=ItemStack.deserializeBytes(Base64.getDecoder().decode(offer.payload()));
else {
Material material=Material.matchMaterial(offer.material());
if(material==null||material.isAir()||!material.isItem()) throw new IllegalArgumentException("This item is unsupported on this server; contact an operator.");
item=new ItemStack(material);
}
item.setAmount(1); return item;
}
private void browse(Player p,String category,int page,boolean mine,boolean admin) {
if(admin&&!p.hasPermission("dune.admin")) return;
if(!connected(p)) return;
execute(p,()->{
int current=Math.max(0,page);
String planet=mine||admin?"all":planets.getOrDefault(p.getUniqueId(),"all");
List<ExchangeStore.Listing> rows=store.browse(category,planet,mine?p.getUniqueId():null,current);
Screen s=screen(p,(mine?"My Listings":admin?"All Listings":category)+" · "+(current+1));
int slot=10;
for(ExchangeStore.Listing row:rows.subList(0,Math.min(28,rows.size()))) {
while(slot%9==0||slot%9==8) slot++;
ItemStack item;
try { item=decode(row); } catch(RuntimeException ex) { item=new ItemStack(Material.PAPER); }
ItemMeta meta=item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD+"#"+row.id()+" "+(row.displayName()==null?row.material():row.displayName()));
meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Dunemarks","Seller: "+row.sellerName(),"Planet: "+row.origin(),
row.seller().equals(p.getUniqueId())?"Click to reclaim unsold items":"Click to review purchase"));
item.setItemMeta(meta); s.inventory.setItem(slot,item);
s.actions.put(slot,()->confirm(p,row.id(),row.seller().equals(p.getUniqueId()))); slot++;
}
if(rows.isEmpty()) s.inventory.setItem(22,icon(Material.PAPER,"No matching listings","Try another planet or list a held item."));
if(current>0) button(s,45,Material.ARROW,"Previous",()->browse(p,category,current-1,mine,admin));
if(rows.size()>28) button(s,53,Material.ARROW,"Next",()->browse(p,category,current+1,mine,admin));
com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions);
});
}
private void confirm(Player p,long id,boolean reclaim) {
execute(p,()->{
ExchangeStore.Listing row=store.find(id);
if(reclaim&&!row.seller().equals(p.getUniqueId())) throw new IllegalArgumentException("You can reclaim only your own listings.");
Screen s=screen(p,reclaim?"Reclaim Listing":"Confirm Purchase");
s.inventory.setItem(22,icon(decode(row).getType(),"#"+id+" "+(row.displayName()==null?row.material():row.displayName()),
"Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Dunemarks"));
button(s,30,Material.LIME_CONCRETE,reclaim?"Confirm Reclaim":"Confirm Purchase",()->{
p.closeInventory(); if(reclaim) cancel(p,id); else buy(p,id);
});
button(s,32,Material.RED_CONCRETE,"Never Mind",()->home(p)); com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions);
});
}
private boolean fits(Player p,ItemStack item,int amount) {
int remaining=amount;
for(ItemStack slot:p.getInventory().getStorageContents()) {
if(slot==null||slot.getType().isAir()) remaining-=item.getMaxStackSize();
else if(slot.isSimilar(item)) remaining-=Math.max(0,item.getMaxStackSize()-slot.getAmount());
if(remaining<=0) return true;
}
return false;
}
private void deliver(Player p,ItemStack item,int amount) {
item.setAmount(amount);
Map<Integer,ItemStack> excess=p.getInventory().addItem(item);
// Capacity is checked immediately before the transaction on this same server thread.
if (!excess.isEmpty()) throw new IllegalArgumentException("Inventory changed; the trade was rolled back. Make room and retry.");
}
private void sell(Player p,int amount,BigDecimal price) throws SQLException {
ExchangeStore.validate(amount,price);
ItemStack held=p.getInventory().getItemInMainHand();
if(held.getType().isAir()||amount>held.getAmount()) throw new IllegalArgumentException("Hold at least that many items in your main hand.");
// Never let operator tools become tradeable through the public exchange.
if(held.hasItemMeta()) for(NamespacedKey key:held.getItemMeta().getPersistentDataContainer().getKeys())
if(key.getKey().contains("admin")) throw new IllegalArgumentException("Administrative tools cannot be listed.");
ItemStack unit=held.clone(); unit.setAmount(1);
String name=unit.hasItemMeta()&&unit.getItemMeta().hasDisplayName()?ChatColor.stripColor(unit.getItemMeta().getDisplayName()):unit.getType().name();
if(name.length()>120) name=name.substring(0,120);
final String displayName=name;
atomic(p, scoped -> {
scoped.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price,
Base64.getEncoder().encodeToString(unit.serializeAsBytes()),displayName);
held.setAmount(held.getAmount()-amount);
});
p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Dunemarks each.");
}
private String origin(Player p) {
String world=p.getWorld().getName().toLowerCase(Locale.ROOT).replace('-','_');
for(String planet:PLANETS) if(!planet.equals("all")&&world.contains(planet)) return planet;
return plugin.localPlanet();
}
static String category(ItemStack item) {
if(item.hasItemMeta()) {
String kind=item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING);
if(kind!=null&&kind.toLowerCase(Locale.ROOT).contains("spice")) return "spice";
}
String n=item.getType().name();
if(n.contains("ORE")||n.contains("INGOT")||n.contains("DEBRIS")||n.contains("DIAMOND")||n.contains("EMERALD")||n.contains("COAL")||n.contains("REDSTONE")||n.contains("RAW_")||n.contains("LAPIS")||n.contains("QUARTZ")) return "ores";
if(n.contains("SWORD")||n.contains("PICKAXE")||n.endsWith("AXE")||n.contains("HELMET")||n.contains("CHESTPLATE")||n.contains("LEGGINGS")||n.contains("BOOTS")||n.contains("ELYTRA")||n.contains("BOW")||n.contains("SHOVEL")||n.contains("HOE")||n.equals("SHIELD")||n.equals("TRIDENT")||n.equals("FISHING_ROD")||n.equals("ENCHANTED_BOOK")) return "equipment";
if(item.getType().isEdible()||n.contains("WHEAT")||n.contains("SEED")||n.contains("SAPLING")) return "farming";
return item.getType().isBlock()?"building":"misc";
}
private void buy(Player p,long id) {
if(!connected(p)) return;
execute(p,()->{
ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before);
if(!fits(p,item,1)) throw new IllegalArgumentException("Make room in your inventory first.");
atomic(p, scoped -> {
scoped.buy(p.getUniqueId(),p.getName(),id);
deliver(p,item,1);
});
p.sendMessage(ChatColor.GREEN+"Purchased one item for "+before.price()+" Dunemarks.");
});
}
private void cancel(Player p,long id) {
if(!connected(p)) return;
execute(p,()->{
ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before);
if(!fits(p,item,before.quantity())) throw new IllegalArgumentException("Make room for all "+before.quantity()+" items first.");
atomic(p, scoped -> {
ExchangeStore.Listing cancelled=scoped.cancel(p.getUniqueId(),id);
deliver(p,item,cancelled.quantity());
});
p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned.");
});
}
private interface Trade { void run(ExchangeStore scoped) throws SQLException; }
private void atomic(Player p, Trade trade) throws SQLException {
Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore");
if (core==null) throw new SQLException("DuneCore network profiles are required");
try {
java.util.function.Consumer<java.sql.Connection> work = connection -> {
try { trade.run(ExchangeStore.bound(connection)); }
catch (SQLException ex) { throw new java.util.concurrent.CompletionException(ex); }
};
core.getClass().getMethod("transactNetworkInventory",Player.class,java.util.function.Consumer.class).invoke(core,p,work);
} catch (ReflectiveOperationException ex) {
Throwable cause=ex instanceof java.lang.reflect.InvocationTargetException ? ex.getCause() : ex;
if (cause instanceof java.util.concurrent.CompletionException && cause.getCause()!=null) cause=cause.getCause();
if (cause instanceof IllegalArgumentException invalid) throw invalid;
if (cause instanceof SQLException sql) throw sql;
throw new SQLException("Network inventory transaction unavailable; install matching Core and Essentials",cause);
}
}
private interface Operation { void run() throws SQLException; }
private void execute(Player p,Operation action) {
try { action.run(); }
catch(IllegalArgumentException ex) { p.sendMessage(ChatColor.YELLOW+ex.getMessage()); }
catch(SQLException ex) {
ready=false; plugin.getLogger().warning("Koopkring SQL operation failed: "+ex.getSQLState());
p.sendMessage(ChatColor.RED+"The market database is unavailable. Please try again later.");
}
}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
if(!(sender instanceof Player p)) { sender.sendMessage("Open the Koopkring exchange in-game with /exchange."); return true; }
if(args.length==0) { home(p); return true; }
String action=args[0].toLowerCase(Locale.ROOT);
if(action.equals("admin")) { if(p.hasPermission("dune.admin")) admin(p); else p.sendMessage(ChatColor.RED+"Operators only."); return true; }
if(action.equals("help")) { home(p); return true; }
if(!connected(p)) return true;
execute(p,()->{
try {
switch(action) {
case "sell" -> { if(args.length!=3) throw new IllegalArgumentException("/exchange sell <amount> <price-each>"); sell(p,Integer.parseInt(args[1]),new BigDecimal(args[2])); }
case "buy","cancel" -> { if(args.length!=2) throw new IllegalArgumentException("/exchange "+action+" <listing-id>"); long id=Long.parseLong(args[1]); if(id<1) throw new IllegalArgumentException("Listing IDs are positive numbers."); confirm(p,id,action.equals("cancel")); }
case "mine" -> browse(p,"all",0,true,false);
default -> p.sendMessage(ChatColor.YELLOW+"Use /exchange, /exchange sell <amount> <price>, /exchange buy <id>, /exchange cancel <id>, or /exchange mine.");
}
} catch(NumberFormatException ex) { throw new IllegalArgumentException("Enter a valid amount, price and listing ID."); }
});
return true;
}
@Override public List<String> onTabComplete(CommandSender sender,Command command,String alias,String[] args) {
if(args.length!=1) return List.of();
return List.of("help","sell","buy","cancel","mine","admin").stream()
.filter(s->!s.equals("admin")||sender.hasPermission("dune.admin"))
.filter(s->s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList();
}
@EventHandler public void click(InventoryClickEvent e) {
if(!(e.getView().getTopInventory().getHolder() instanceof Screen screen)) return;
e.setCancelled(true);
if(!(e.getWhoClicked() instanceof Player p)||!screen.owner.equals(p.getUniqueId())
||e.getClickedInventory()!=e.getView().getTopInventory()||e.getClick()==ClickType.DOUBLE_CLICK) return;
Runnable action=screen.actions.get(e.getRawSlot());
if(action!=null) Bukkit.getScheduler().runTask(plugin,()->{
if(p.isOnline()&&p.getOpenInventory().getTopInventory()==screen.inventory) action.run();
});
}
@EventHandler public void drag(InventoryDragEvent e) {
if(e.getView().getTopInventory().getHolder() instanceof Screen) e.setCancelled(true);
}
@EventHandler public void quit(PlayerQuitEvent e) { planets.remove(e.getPlayer().getUniqueId()); }
}

View file

@ -0,0 +1,129 @@
package com.example.duneess;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
/** SQL escrow and wallet changes share one transaction. Bukkit inventory work stays on its server thread. */
final class ExchangeStore {
interface Connections { Connection open() throws SQLException; }
record Listing(long id, UUID seller, String sellerName, String origin, String category,
String material, int quantity, BigDecimal price, String payload, String displayName) {}
private final Connections connections;
ExchangeStore(Connections connections) { this.connections = connections; }
/** Reuse the Core profile transaction; only Core may commit, roll back or close it. */
static ExchangeStore bound(Connection connection) {
Connection scoped = (Connection) java.lang.reflect.Proxy.newProxyInstance(
ExchangeStore.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> {
if (Set.of("close", "commit", "rollback", "setAutoCommit").contains(method.getName())) return null;
try { return method.invoke(connection, args); }
catch (java.lang.reflect.InvocationTargetException ex) { throw ex.getCause(); }
});
return new ExchangeStore(() -> scoped);
}
void initialize() throws SQLException {
try (Connection c = connections.open(); Statement s = c.createStatement()) {
s.setQueryTimeout(5);
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_listings (id BIGSERIAL PRIMARY KEY, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, origin VARCHAR(48) NOT NULL, category VARCHAR(24) NOT NULL, material VARCHAR(80) NOT NULL, quantity INT NOT NULL CHECK(quantity>0), price NUMERIC(20,2) NOT NULL CHECK(price>0))");
s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS payload TEXT");
s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS display_name VARCHAR(120)");
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_sales (id BIGSERIAL PRIMARY KEY, listing_id BIGINT NOT NULL, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, buyer UUID NOT NULL, buyer_name VARCHAR(32) NOT NULL, material VARCHAR(80) NOT NULL, display_name VARCHAR(120), quantity INTEGER NOT NULL CHECK(quantity>0), unit_price NUMERIC(20,2) NOT NULL CHECK(unit_price>0), total_price NUMERIC(20,2) NOT NULL CHECK(total_price>0), origin VARCHAR(48) NOT NULL, sold_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP)");
s.executeUpdate("CREATE INDEX IF NOT EXISTS dune_exchange_sales_seller_id ON dune_exchange_sales(seller,id DESC)");
}
}
private PreparedStatement prepare(Connection c, String sql) throws SQLException {
PreparedStatement q = c.prepareStatement(sql); q.setQueryTimeout(5); return q;
}
static void validate(int amount, BigDecimal price) {
if (amount < 1 || amount > 64 || price == null || price.signum() <= 0 || price.scale() > 2
|| price.compareTo(new BigDecimal("1000000")) > 0)
throw new IllegalArgumentException("Use 1–64 items and a price from 0.01 to 1,000,000 Solaris (two decimals maximum).");
}
void list(UUID seller, String name, String origin, String category, String material,
int amount, BigDecimal price, String payload, String displayName) throws SQLException {
validate(amount, price);
try (Connection c = connections.open(); PreparedStatement q = prepare(c,
"INSERT INTO dune_exchange_listings(seller,seller_name,origin,category,material,quantity,price,payload,display_name) VALUES(?,?,?,?,?,?,?,?,?)")) {
q.setObject(1,seller); q.setString(2,name); q.setString(3,origin); q.setString(4,category);
q.setString(5,material); q.setInt(6,amount); q.setBigDecimal(7,price); q.setString(8,payload); q.setString(9,displayName);
q.executeUpdate();
}
}
List<Listing> browse(String category, String planet, UUID owner, int page) throws SQLException {
String sql = "SELECT * FROM dune_exchange_listings WHERE 1=1";
if (!category.equals("all")) sql += " AND category=?";
if (!planet.equals("all")) sql += " AND origin=?";
if (owner != null) sql += " AND seller=?";
sql += " ORDER BY id DESC LIMIT 29 OFFSET ?";
try (Connection c = connections.open(); PreparedStatement q = prepare(c,sql)) {
int k=1;
if (!category.equals("all")) q.setString(k++,category);
if (!planet.equals("all")) q.setString(k++,planet);
if (owner!=null) q.setObject(k++,owner);
q.setInt(k,Math.max(0,page)*28);
try (ResultSet r=q.executeQuery()) {
List<Listing> rows=new ArrayList<>(); while(r.next()) rows.add(read(r)); return rows;
}
}
}
Listing find(long id) throws SQLException {
try(Connection c=connections.open(); PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=?")) {
q.setLong(1,id); try(ResultSet r=q.executeQuery()) {
if(!r.next()) throw new IllegalArgumentException("That listing has already been sold or cancelled.");
return read(r);
}
}
}
private Listing read(ResultSet r) throws SQLException {
return new Listing(r.getLong("id"),r.getObject("seller",UUID.class),r.getString("seller_name"),
r.getString("origin"),r.getString("category"),r.getString("material"),r.getInt("quantity"),
r.getBigDecimal("price"),r.getString("payload"),r.getString("display_name"));
}
/** On SQL failure, no wallet or listing changes survive. Never set quantity to zero under CHECK(quantity>0). */
Listing buy(UUID buyer, long id) throws SQLException { return buy(buyer, "Unknown", id); }
Listing buy(UUID buyer, String buyerName, long id) throws SQLException {
try(Connection c=connections.open()) {
c.setAutoCommit(false);
try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? FOR UPDATE")) {
q.setLong(1,id);
try(ResultSet r=q.executeQuery()) {
if(!r.next()) throw new IllegalArgumentException("Listing unavailable.");
Listing offer=read(r);
if(offer.seller().equals(buyer)) throw new IllegalArgumentException("Use My Listings to reclaim your own offer.");
try(PreparedStatement debit=prepare(c,"UPDATE dune_economy_balances SET balance=balance-? WHERE uuid=? AND balance>=?");
PreparedStatement credit=prepare(c,"UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=?");
PreparedStatement stock=prepare(c,offer.quantity()==1?"DELETE FROM dune_exchange_listings WHERE id=?":"UPDATE dune_exchange_listings SET quantity=quantity-1 WHERE id=?")) {
debit.setBigDecimal(1,offer.price()); debit.setObject(2,buyer); debit.setBigDecimal(3,offer.price());
if(debit.executeUpdate()!=1) throw new IllegalArgumentException("Insufficient Solaris or shared wallet unavailable.");
credit.setBigDecimal(1,offer.price()); credit.setObject(2,offer.seller());
if(credit.executeUpdate()!=1) throw new IllegalArgumentException("Seller wallet unavailable; no payment taken.");
stock.setLong(1,id); if(stock.executeUpdate()!=1) throw new SQLException("Listing changed.");
try (PreparedStatement sale = prepare(c, "INSERT INTO dune_exchange_sales(listing_id,seller,seller_name,buyer,buyer_name,material,display_name,quantity,unit_price,total_price,origin) VALUES(?,?,?,?,?,?,?,1,?,?,?)")) {
sale.setLong(1, id); sale.setObject(2, offer.seller()); sale.setString(3, offer.sellerName());
sale.setObject(4, buyer); sale.setString(5, buyerName);
sale.setString(6, offer.material()); sale.setString(7, offer.displayName());
sale.setBigDecimal(8, offer.price()); sale.setBigDecimal(9, offer.price()); sale.setString(10, offer.origin());
sale.executeUpdate();
}
c.commit(); return offer;
}
}
} catch(SQLException|RuntimeException ex) { c.rollback(); throw ex; }
}
}
Listing cancel(UUID owner, long id) throws SQLException {
try(Connection c=connections.open()) {
c.setAutoCommit(false);
try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? AND seller=? FOR UPDATE")) {
q.setLong(1,id); q.setObject(2,owner);
try(ResultSet r=q.executeQuery()) {
if(!r.next()) throw new IllegalArgumentException("This listing is unavailable or belongs to another player.");
Listing offer=read(r);
try(PreparedStatement d=prepare(c,"DELETE FROM dune_exchange_listings WHERE id=?")) {
d.setLong(1,id); d.executeUpdate(); c.commit(); return offer;
}
}
} catch(SQLException|RuntimeException ex) { c.rollback(); throw ex; }
}
}
}

View file

@ -0,0 +1,24 @@
currency:
singular: Dunemark
plural: Dunemarks
spice-price: 15
travel-price: 100
starting-balance: 0
allow-negative-balances: true
# DuneEss automatically reuses DuneCore's existing PostgreSQL settings when enabled.
# Set use-core-database to false to use local balances.yml storage instead.
database:
use-core-database: true
network:
use-core-settings: true
enabled: true
local-planet: arrakis
servers: {}
worlds: [arrakis, giedi_prime, kaitain, caladan, sigma_draconis_iv]
# Homes are local to each backend. Vanilla bed/anchor respawns remain authoritative.
essentials:
max-homes: 3

View file

@ -0,0 +1,58 @@
name: DuneEss
version: 1.0.4
main: com.example.duneess.DuneEss
api-version: '1.21.8'
depend: [Vault]
softdepend: [floodgate, ViaVersion, DuneCore, DuneTerrain]
prefix: DuneRealms Essentials
description: DuneRealms Essentials - Dunemarks economy, Vault provider, spice sales, and Arrakduin travel
commands:
communitycode:
description: Claim one community currency reward per UUID and monthly goal
usage: /communitycode <code>
linkwebsite:
description: Verify your Minecraft UUID for a website account
usage: /linkwebsite <private-code>
exchange:
description: CHOAM interplanetary player marketplace
usage: /exchange
aliases: [choam, market]
duneess:
description: Solaris, travel, and Arrakis administration
usage: /duneess help
aliases: [dess]
essentials:
description: Open DuneRealms Essentials
permission: duneess.basics
home:
description: Teleport to a saved home
permission: duneess.basics
sethome:
description: Save a named home
permission: duneess.basics
delhome:
description: Remove a named home
permission: duneess.basics
homes:
description: Choose a saved home
permission: duneess.basics
tpa:
description: Request player teleportation
permission: duneess.basics
tpaccept:
description: Accept a teleport request
permission: duneess.basics
tpdeny:
description: Decline a teleport request
permission: duneess.basics
spawn:
description: Return to world spawn
permission: duneess.basics
server:
description: Open Guild server travel
permission: duneess.basics
permissions:
duneess.basics:
default: true
dune.admin:
default: op

View file

@ -0,0 +1,3 @@
origin: https://cp.dunerealms.com
# Operator secret shared with the account panel. Never publish or put it in command arguments.
secret: ''

Some files were not shown because too many files have changed in this diff Show more