forked from unimatrix/web
Keep web repository website-only and retain signed HQ item metadata
This commit is contained in:
parent
af8c0e463f
commit
207002b48a
2785 changed files with 2717 additions and 68345 deletions
|
|
@ -58,7 +58,6 @@ jobs:
|
|||
corepack pnpm install --frozen-lockfile
|
||||
corepack pnpm build
|
||||
corepack pnpm test
|
||||
node --test --test-concurrency=1 ../tools/tests/*.test.mjs
|
||||
|
||||
- name: Upload website build
|
||||
if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main'
|
||||
|
|
|
|||
221
.github/workflows/build.yml
vendored
221
.github/workflows/build.yml
vendored
|
|
@ -1,221 +0,0 @@
|
|||
|
||||
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
28
.github/workflows/lobby.yml
vendored
|
|
@ -1,28 +0,0 @@
|
|||
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
25
.github/workflows/network-preflight.yml
vendored
|
|
@ -1,25 +0,0 @@
|
|||
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
52
.github/workflows/network.yml
vendored
|
|
@ -1,52 +0,0 @@
|
|||
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
|
||||
125
AGENTS.md
125
AGENTS.md
|
|
@ -1,105 +1,40 @@
|
|||
# DuneRealms default working instructions
|
||||
# DuneRealms website working instructions
|
||||
|
||||
These are the user's default preferences for future DuneRealms work. Apply them unless the user changes them.
|
||||
## Repository ownership
|
||||
|
||||
## Production release rules
|
||||
- `unimatrix/web:main` owns the website, control panels, web APIs and their deployment configuration.
|
||||
- `unimatrix/plugins:main` owns Minecraft plugins, resource packs, game-server configuration and worlds. Do not import or deploy those components from this repository.
|
||||
- `dev/MC` is a historical development reference. Check actual subtree hashes before importing anything: the latest website, item cards and cookbook were already present on web/main when the repositories were separated on 29 November 2026.
|
||||
- The GitHub `unimatrixgit/mcdune-backup` repository is a recovery backup. Its existence does not authorise a rollback or replacement of newer work.
|
||||
|
||||
- Owner direction, 29 November 2026: `unimatrix/web:main` is website-only production; `unimatrix/plugins:main` owns plugins, resource packs and game-server deployment. This supersedes the historical combined-repository instruction. `dev/MC` remains a development reference until separately migrated. Preserve uncommitted work when reconciling checkouts.
|
||||
- Keep at most one open pull request per repository. Reuse it for follow-up commits. Direct pushes to main are prohibited. Merge completed changes only after successful CI and explicit owner authorization.
|
||||
- Every plugin change goes through a build from a recorded Git commit. Record each JAR filename, plugin version and SHA-256 in the release manifest. Roll out the exact tested artifacts and verify their hashes against the installed JARs.
|
||||
- Treat any mismatch between the production source, the build manifest and the installed plugins as release drift. Reconcile the source and retest before a replacement rollout. Avoid manual edits or class overlays on live JARs.
|
||||
## Changes and review
|
||||
|
||||
## Tools and access
|
||||
- Code and test locally, commit to a task branch and push a pull request. Do not push directly to main or merge unrelated branches.
|
||||
- Preserve unrelated work and game/account data. Never change identity, permissions, balances or progression as a workaround.
|
||||
- Use the current owner instructions as authoritative. Historical combined-repository plans and role resets are superseded.
|
||||
- Merge only the exact reviewed commit after required checks and owner approval. Do not bypass an automatic approval rejection through another tool or Git command.
|
||||
- Keep the current website PR focused and coordinate overlapping changes before editing another chat's files.
|
||||
|
||||
- Prefer the connected Composio Gitea/Forgejo integration for DuneGit repository reads, pull requests, workflow dispatch, CI status, and deployment actions.
|
||||
- Discover the actual tools and schemas before use. Do not assume that a GitHub tool targets DuneGit.
|
||||
- Use local Git for local edits, diffs, commits, and efficient pushes of tested local changes. This does not require SSH access to the server.
|
||||
- Use direct SSH only for server operations that repository/CI tools cannot perform. Keep SSH use minimal. Do not require Gateway when it is unavailable or its quota is exhausted.
|
||||
- Never save passwords, private keys, tokens, or credential-bearing URLs in instructions, commits, logs, or PR descriptions.
|
||||
## Build inputs and checks
|
||||
|
||||
## Small batches through CI
|
||||
- Website source and required data live under `website/`. Cookbook inputs live under `website/data/cookbook`, with recorded source hashes.
|
||||
- Website item-design export utilities live in `website/scripts`. `tools/README.md` is a temporary compatibility input for the previously installed staging command; no plugin tooling belongs there.
|
||||
- Use Node22 and the locked pnpm dependencies. Run `pnpm build` and `pnpm test` from `website/`.
|
||||
- Run `.forgejo/tests/web-deploy.test.mjs` with Node and `website/ops/test_*.py` with Python on Linux. The Linux deployment checks require `fcntl` and cannot pass natively on Windows.
|
||||
- Tests that create local HTTP servers need permission for loopback connections. Report environmental failures accurately and rerun with the needed permission; do not weaken production code to hide them.
|
||||
- Required release evidence includes the commit, actual checks, CI run, generated artifact and live serving revision. A build or artifact upload is not proof of deployment.
|
||||
|
||||
- Implement, check, commit, and publish small coherent batches as work progresses. Do not hold all completed work until the entire feature is finished.
|
||||
- Reuse existing infrastructure, permissions, audit records, and payment/voting mechanisms wherever possible.
|
||||
- Run checks appropriate to each batch. Fix failures caused by the change before publishing. Report any existing unrelated failures accurately.
|
||||
- Push changes to the current development branch. Update the existing pull request until the agreed scope is complete.
|
||||
- Deploy verified batches through the established website CI and deployment pipeline. A workflow dispatch being accepted, or an artifact being uploaded, does not establish that production is updated.
|
||||
- Follow CI and deployment through completion, then verify the live release and affected behavior before claiming it is live.
|
||||
- If a dispatch reports an error after HTTP 204, or a write times out, inspect the resulting run/remote state before retrying. Avoid duplicate writes or deployments.
|
||||
## Access and server changes
|
||||
|
||||
## Protect existing progress
|
||||
- Prefer Composio for DuneGit metadata, pull requests and CI actions. Local HTTPS Git is authorised for code, commits and pushes.
|
||||
- Server SSH is restricted to the owner's designated coordinating web/scope chat for resolving blockers. Other agents/chats must not use SSH without a later explicit owner change.
|
||||
- Any necessary server alteration must also be reflected in source or deployment configuration and committed, with verification, so later builds retain the fix. Do not leave undocumented hot patches.
|
||||
- Never write credentials, private keys, tokens or credential-bearing URLs to source, commits, logs or ordinary artifacts.
|
||||
|
||||
- Inspect the working tree and remote branch heads before changing branches or publishing. Preserve unrelated edits and work in progress.
|
||||
- Explicitly fetch the intended remote branch ref into its tracking ref when needed, and verify it matches the remote head. Do not assume a plain fetch refreshed an old tracking branch.
|
||||
- Never restore an old release, force-push, hard-reset, replace live files from an old backup, or resolve conflicts by discarding newer work merely to make deployment pass.
|
||||
- Stop and diagnose unexpected ancestry, missing files, or modify/delete conflicts. Preserve the current state; do not force a merge or push.
|
||||
- Keep backups outside the source tree and do not copy credentials into ordinary build artifacts.
|
||||
- Do not run broad cleanup, destructive migrations, or financial transactions unless the user has authorized the actual action.
|
||||
## Product behavior
|
||||
|
||||
## Collaboration and product behavior
|
||||
|
||||
- Continue authorized work without repeated permission questions or handoffs. Do not switch to Work mode.
|
||||
- Give concise progress updates describing results, blockers, and the next useful step.
|
||||
- Preserve existing working voting and banking behavior. Personal voting rights are absolute; organisation voting changes must not transfer personal votes.
|
||||
- Place new features in the existing navigation structure when an item already exists. Avoid duplicate menus.
|
||||
- Use the established CP design, readable colors, gold framing, and appropriate original Dune/Minecraft-inspired artwork. Company CP uses the Vaerkring/Spacing Guild-inspired palette.
|
||||
- Clearly mark unfinished features as coming soon. Do not display invented records, offers, payments, or completed actions.
|
||||
|
||||
## J.A.R.V.I.S. data-operation workflow (2026-11-18)
|
||||
|
||||
- Use Git, reviewed batches and CI for changes to files, code, schemas and action implementations.
|
||||
- Perform supported user/domain data changes through validated J.A.R.V.I.S. actions and instruments. Do not use ad hoc SQL/manual database editing as an operational shortcut.
|
||||
- Special dev keys are server/CLI-only overrides bound to an exact action manifest, environment, authorised developer identity and short validity. Never expose their issuance, secrets or execution through website routes, dropdowns or web APIs, including Big 4 accounts.
|
||||
- An ordinary code is not authority. Revalidate identity, action scope and domain conditions on execution. Keep irreversible actions explicit in the manifest.
|
||||
- Record issuance ID/hash, actor, manifest hash, each result, failures and completion; never log a secret key. Enforce once-only execution and safe retries/rollback.
|
||||
- Existing supported data actions require no PR/deployment per execution. New action logic still requires tests, Git and publication.
|
||||
- Never call a verifier-only test a successful live operation. Report local, simulated, staged and executed states accurately.
|
||||
- Seasonal changes use an explicit versioned dev batch. Preserve/reset decisions are per-season configuration, not automatic consequences of every deploy.
|
||||
- Honour the approved reset exclusions: official/protected organisations and the owner's clan/company rosters; no broader reset unless explicitly requested. No Minecraft code or deployment in this web/backend batch.
|
||||
|
||||
Current priority: implement and test the server-only dev-key executor, starting with the authorised clan-reset batch. Keep special dev tools outside the website package.
|
||||
|
||||
## Masterkey reuse before new code
|
||||
|
||||
- Before implementing a page or action, read `website/control-panel/public/jarvis-master-keys.mjs` and its existing domain adapter. Reuse an existing action rather than duplicating its flow.
|
||||
- Register every new key-backed action in that catalogue in the same change, with version, typed fields, domain rules, authority and execution status. Never claim a catalogue entry is executable before its adapter is connected.
|
||||
- The website generator cannot generate or modify developer keys, including for owner/Big 4 accounts. This is a fixed server boundary, not an assignable permission. An issued devkey can only be used through its separately permitted execution route. Developer issuance remains outside the website package.
|
||||
|
||||
## Chat-requested keys must update web keygen
|
||||
|
||||
- Whenever the user requests a key here in the development chat, find its mastertemplate and execution flow first. If absent, add the versioned template, typed fields and validated domain adapter, then update/publish the web generator as part of fulfilling that request. Reuse existing flows when present.
|
||||
- This trigger is a chat request, not website-submitted arbitrary flow code. The website cannot create new execution logic from user input.
|
||||
- Developer keys remain an absolute exception to web issuance: keygen must never generate or modify them, including for owner/Big 4. Devticket requests may collect a requested action and approval; developer issuance remains in the separately authorised development flow.
|
||||
|
||||
## Developer keys are the last resort
|
||||
|
||||
- For every requested operation, first search the masterkey catalogue and existing domain actions for a normal scoped key that achieves the same authorised result. Prefer it over a developer key.
|
||||
- Do not broaden an ordinary key, bypass its permission checks, or disguise developer capabilities as a normal template to avoid this boundary. If no suitable ordinary flow exists, a separately approved developer ticket/key may be considered through the developer-only route.
|
||||
|
||||
## User-requested batch tracking (24 November 2026)
|
||||
|
||||
- Before starting each implementation batch, create one Development task ticket through the existing validated private support workflow. The user explicitly authorises automatic approval of these batch tickets.
|
||||
- Group at least three genuine user requests in a batch; do not count individual technical edits as separate requests. War is one request, POL missions and POL decisions are the other two requests in the current batch.
|
||||
- Include the scope checklist, verification plan, PR/commit and actual live-release evidence in that ticket. Update its progress and complete it only when its stated scope is actually live and verified.
|
||||
- Placeholder pages must be explicitly marked as previews and include all appropriate DuneRealms artwork. Preserve working actions while the remaining consumers are built.
|
||||
|
||||
## Latest owner direction: portal and control-panel redesign (24 November 2026)
|
||||
|
||||
- The owner said “negeer tickets”: skip ticket creation; it must not block work.
|
||||
- Current priority is the public portal preview before further CP redesign. The owner explicitly wants to keep the current site if unsatisfied: do not replace the live homepage before design acceptance.
|
||||
- Use the supplied green/gold portal image as inspiration, not an immutable layout. Preserve the existing logo, seals, awards and avatars. Other layouts, menus and artwork may be redesigned, including the CPs.
|
||||
- Reduce the number of control panels and unify their design, but do not cram everything into one panel. Personal services, organisation management and staff need distinct, understandable workspaces.
|
||||
- The POL backend can retain its existing service contracts independently of presentation changes. The tested political-war backend batch remains on PR 563, separate from this design preview.
|
||||
- Existing hostnames are sufficient for this preview. Discuss a new hostname only if implementation actually needs it.
|
||||
|
||||
## Accepted full-site scope (24 November 2026)
|
||||
|
||||
- Portal design accepted. Apply the approved shared style throughout the site, Exchange and control panels, then finish the backend.
|
||||
- User comfort takes priority: short navigation, readable labels, accessible mobile controls and clear back paths.
|
||||
- Consolidate clan/company/POL presentation in an organisation workspace; personal and staff remain separate. Preserve all domain permissions and deep links.
|
||||
- Latest bans and appeals belong on a separate Community page. Keep original logos, seals, awards, avatars and the approved travel picker.
|
||||
|
||||
## Backend integration after design acceptance
|
||||
|
||||
- Preserve the accepted site redesign. Continue the authorised war, POL missions and POL decisions through their existing service contracts.
|
||||
- Ticket creation remains skipped by the explicit owner override.
|
||||
- Preserve the accepted DuneRealms design and reuse existing navigation, services and domain permissions.
|
||||
- DuneForge is the existing `#forge/git-workspace` workspace; the root DuneGit register is `/git/`.
|
||||
- Item cards display authoritative metadata from native Bukkit items or a verified signed HQ design. Do not invent quality, marks, lore, enchantments or stats from material names.
|
||||
- Preserve real voting, banking and item-issuance boundaries. Public presentation must not expose serialized items, signatures or service credentials.
|
||||
- Describe what is coded, tested, merged and deployed separately. Mark unavailable features honestly.
|
||||
|
|
|
|||
|
|
@ -1,30 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
plugins { java }
|
||||
group = "com.example"
|
||||
version = "1.0.12"
|
||||
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}") }
|
||||
|
|
@ -1 +0,0 @@
|
|||
rootProject.name = "DuneEss"
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
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();}
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
package com.example.duneess;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
|
||||
final class DuneCommands implements TabExecutor {
|
||||
private static final Map<String, String> ROUTES = Map.ofEntries(
|
||||
Map.entry("home", "duneess:home"), Map.entry("sethome", "duneess:sethome"),
|
||||
Map.entry("homes", "duneess:homes"), Map.entry("delhome", "duneess:delhome"),
|
||||
Map.entry("spawn", "duneess:spawn"), Map.entry("server", "duneess:server"),
|
||||
Map.entry("tpa", "duneess:tpa"), Map.entry("tpaccept", "duneess:tpaccept"),
|
||||
Map.entry("tpdeny", "duneess:tpdeny"), Map.entry("essentials", "duneess:essentials"),
|
||||
Map.entry("link", "duneess:linkwebsite"), Map.entry("linkwebsite", "duneess:linkwebsite"),
|
||||
Map.entry("communitycode", "duneess:communitycode"),
|
||||
Map.entry("condense", "duneess:condense"), Map.entry("fix", "duneess:fix"),
|
||||
Map.entry("pay", "jarvistranslator:pay"), Map.entry("invite", "jarvistranslator:invite"),
|
||||
Map.entry("accept", "jarvistranslator:accept"), Map.entry("join", "jarvistranslator:join"),
|
||||
Map.entry("leave", "jarvistranslator:leave"), Map.entry("redeem", "jarvistranslator:redeem"),
|
||||
Map.entry("jarvis", "jarvistranslator:jarvistranslator"),
|
||||
Map.entry("faction", "dunemenus:house"), Map.entry("house", "dunemenus:house"),
|
||||
Map.entry("start", "dunemenus:start"), Map.entry("mentat", "dunemenus:mentat"),
|
||||
Map.entry("exchange", "dunemenus:exchange"), Map.entry("spice", "dunemenus:spice"),
|
||||
Map.entry("sell", "dunemenus:sellall"), Map.entry("sellall", "dunemenus:sellall"),
|
||||
Map.entry("clan", "dunemenus:clan"),
|
||||
Map.entry("company", "dunemenus:company"), Map.entry("office", "dunemenus:politics"),
|
||||
Map.entry("scoreboard", "dunemenus:scoreboard"), Map.entry("menu", "dunemenus:dm"),
|
||||
Map.entry("guildtravel", "dunemenus:guildtravel"), Map.entry("warmuster", "dunemenus:warmuster"),
|
||||
Map.entry("rosterkey", "dunemenus:rosterkey"), Map.entry("lobby", "dunelobby:lobby"),
|
||||
Map.entry("lobbyadmin", "dunelobby:dunelobby"), Map.entry("npc", "dunenpc:dunenpc"),
|
||||
Map.entry("protect", "duneprotect:duneprotect"), Map.entry("ban", "duneban:duneban"),
|
||||
Map.entry("unban", "duneban:duneunban"));
|
||||
|
||||
private static final List<String> CORE = List.of("admin", "adminitem", "summon", "choose",
|
||||
"smuggle", "bounty", "npcadmin", "elytra", "kit", "politics", "trust", "water",
|
||||
"gui", "guireload", "menuitem", "serverjobs", "job", "guildnpc", "givespice");
|
||||
private static final List<String> ESSENTIALS = List.of("balance", "travel", "help");
|
||||
private static final List<String> ESSENTIALS_ADMIN = List.of("solari", "teleport", "spicebloom");
|
||||
private static final List<String> CLAN_ACTIONS = List.of("invite", "accept", "join", "leave");
|
||||
private static final List<String> STAFF = List.of("admin", "adminitem", "summon", "npcadmin",
|
||||
"guireload", "guildnpc", "givespice", "lobbyadmin", "npc", "protect", "ban", "unban",
|
||||
"jarvis", "condense", "fix");
|
||||
|
||||
private final DuneEss plugin;
|
||||
|
||||
private record Route(String target, String[] args, String label) {}
|
||||
|
||||
static void register(DuneEss plugin) {
|
||||
var router = new DuneCommands(plugin);
|
||||
var command = Objects.requireNonNull(plugin.getCommand("dune"));
|
||||
command.setExecutor(router);
|
||||
command.setTabCompleter(router);
|
||||
}
|
||||
|
||||
private DuneCommands(DuneEss plugin) { this.plugin = plugin; }
|
||||
|
||||
private static Route route(String[] args) {
|
||||
String root = args[0].toLowerCase(Locale.ROOT);
|
||||
if (root.equals("clan") && args.length > 1 && CLAN_ACTIONS.contains(args[1].toLowerCase(Locale.ROOT))) {
|
||||
return new Route(ROUTES.get(args[1].toLowerCase(Locale.ROOT)), Arrays.copyOfRange(args, 2, args.length), "dune clan " + args[1]);
|
||||
}
|
||||
if (ESSENTIALS.contains(root) || (root.equals("admin") && args.length > 1
|
||||
&& ESSENTIALS_ADMIN.contains(args[1].toLowerCase(Locale.ROOT)))) {
|
||||
return new Route("duneess:duneess", args, "dune");
|
||||
}
|
||||
if (CORE.contains(root)) return new Route("dunecore:dune", args, "dune");
|
||||
String target = ROUTES.get(root);
|
||||
return target == null ? null : new Route(target, Arrays.copyOfRange(args, 1, args.length), "dune " + root);
|
||||
}
|
||||
|
||||
private PluginCommand target(Route route) {
|
||||
if (route == null) return null;
|
||||
PluginCommand target = plugin.getServer().getPluginCommand(route.target());
|
||||
return target != null && target.getPlugin().isEnabled() ? target : null;
|
||||
}
|
||||
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 0 || (args.length == 1 && args[0].equalsIgnoreCase("help"))) {
|
||||
help(sender);
|
||||
return true;
|
||||
}
|
||||
Route route = route(args);
|
||||
if (route == null) {
|
||||
sender.sendMessage("Unknown Dune command. Use /dune help.");
|
||||
return true;
|
||||
}
|
||||
PluginCommand target = target(route);
|
||||
if (target == null) {
|
||||
sender.sendMessage("This Dune command is unavailable on this server.");
|
||||
return true;
|
||||
}
|
||||
target.execute(sender, route.label(), route.args());
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean available(CommandSender sender, String name) {
|
||||
PluginCommand target = target(route(new String[]{name}));
|
||||
return target != null && target.testPermissionSilent(sender);
|
||||
}
|
||||
|
||||
private void help(CommandSender sender) {
|
||||
sender.sendMessage("DuneRealms commands · /dune <action>");
|
||||
if (available(sender, "pay")) sender.sendMessage("/dune pay <player> <amount> <description>");
|
||||
if (available(sender, "invite")) sender.sendMessage("/dune clan invite <player> · /dune clan join [tag] · /dune clan leave");
|
||||
helpLine(sender, "Homes and travel", "home", "sethome", "homes", "delhome", "spawn", "tpa", "tpaccept", "tpdeny", "travel", "lobby");
|
||||
helpLine(sender, "Clans and House", "clan", "invite", "accept", "join", "leave", "company", "faction", "mentat", "office");
|
||||
helpLine(sender, "Bank and trade", "pay", "balance", "exchange", "spice", "sellall");
|
||||
helpLine(sender, "Quests and wars", "start", "bounty", "warmuster", "rosterkey", "scoreboard", "menu");
|
||||
helpLine(sender, "Account and services", "link", "redeem", "communitycode", "guildtravel", "essentials", "server");
|
||||
helpLine(sender, "Arrakis and politics", "smuggle", "elytra", "kit", "politics", "trust", "water", "job", "serverjobs");
|
||||
if (sender.hasPermission("dune.admin")) helpLine(sender, "Staff", STAFF.toArray(String[]::new));
|
||||
}
|
||||
|
||||
private void helpLine(CommandSender sender, String name, String... commands) {
|
||||
var visible = Arrays.stream(commands).filter(action -> available(sender, action)).toList();
|
||||
if (!visible.isEmpty()) sender.sendMessage(name + " · " + String.join(", ", visible));
|
||||
}
|
||||
|
||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
if (args.length <= 1) {
|
||||
String prefix = args.length == 0 ? "" : args[0].toLowerCase(Locale.ROOT);
|
||||
return java.util.stream.Stream.concat(java.util.stream.Stream.of("help"),
|
||||
java.util.stream.Stream.concat(ROUTES.keySet().stream(), java.util.stream.Stream.concat(CORE.stream(), ESSENTIALS.stream())))
|
||||
.distinct().filter(name -> name.startsWith(prefix))
|
||||
.filter(name -> !STAFF.contains(name) || sender.hasPermission("dune.admin"))
|
||||
.filter(name -> name.equals("help") || available(sender, name)).sorted().toList();
|
||||
}
|
||||
if (args.length == 2 && args[0].equalsIgnoreCase("clan")) {
|
||||
String prefix = args[1].toLowerCase(Locale.ROOT);
|
||||
return CLAN_ACTIONS.stream().filter(action -> action.startsWith(prefix) && available(sender, action)).toList();
|
||||
}
|
||||
Route route = route(args);
|
||||
PluginCommand target = target(route);
|
||||
if (target == null || !target.testPermissionSilent(sender)) return List.of();
|
||||
return target.tabComplete(sender, route.label(), route.args());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,341 +0,0 @@
|
|||
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."); }
|
||||
}
|
||||
|
|
@ -1,599 +0,0 @@
|
|||
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();
|
||||
StaffItemTools.start(this);
|
||||
exchangeMenu = new ExchangeMenu(this);
|
||||
exchangeMenu.register();
|
||||
DuneCommands.register(this);
|
||||
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.MenuPresentation.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.MenuPresentation.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.MenuPresentation.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();}
|
||||
}
|
||||
|
|
@ -1,168 +0,0 @@
|
|||
package com.example.duneess;
|
||||
|
||||
import com.example.dunegui.MenuPresentation;
|
||||
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 PersonalHomeTravel homeTravel;
|
||||
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() {
|
||||
homeTravel=new PersonalHomeTravel(plugin);
|
||||
for(String name:List.of("home","rescue","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 record HomeAddress(String name,boolean explicitWorld) {}
|
||||
private static HomeAddress address(Player player,String[] args){
|
||||
if(args.length!=2)return new HomeAddress(homeName(args),false);
|
||||
if(!player.getWorld().getName().equalsIgnoreCase(args[0])){
|
||||
throw new IllegalArgumentException("Use the Spacing Guild Navigator to reach "+args[0]+" first.");
|
||||
}
|
||||
return new HomeAddress(homeName(new String[]{args[1]}),true);
|
||||
}
|
||||
private String worldKey(Player player,String name){
|
||||
return "worldHomes."+player.getUniqueId()+"."+player.getWorld().getUID()+"."+name;
|
||||
}
|
||||
private Location location(Player player,String name){
|
||||
Location current=homes.getLocation(worldKey(player,name));
|
||||
return current!=null?current:homes.getLocation(key(player,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());
|
||||
var world=homes.getConfigurationSection("worldHomes."+p.getUniqueId()+"."+p.getWorld().getUID());
|
||||
Set<String> result=new TreeSet<>();
|
||||
if(section!=null)result.addAll(section.getKeys(false));
|
||||
if(world!=null)result.addAll(world.getKeys(false));
|
||||
return result;
|
||||
}
|
||||
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<MenuPresentation.Choice> choices=new ArrayList<>();
|
||||
choices.add(new MenuPresentation.Choice("Set home","Save your current position as home.",()->p.performCommand("sethome")));
|
||||
choices.add(new MenuPresentation.Choice("Homes","Choose a saved home on this backend.",()->homeMenu(p)));
|
||||
choices.add(new MenuPresentation.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn")));
|
||||
choices.add(new MenuPresentation.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel")));
|
||||
choices.add(new MenuPresentation.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance")));
|
||||
choices.add(new MenuPresentation.Choice("Koopkring Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange")));
|
||||
choices.add(new MenuPresentation.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu")));
|
||||
MenuPresentation.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices);
|
||||
}
|
||||
private void homeMenu(Player p) {
|
||||
List<MenuPresentation.Choice> choices=names(p).stream().sorted().map(name->new MenuPresentation.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 MenuPresentation.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" -> {
|
||||
HomeAddress address=address(p,args);String name=address.name(),path=address.explicitWorld()?worldKey(p,name):key(p,name);
|
||||
if(!names(p).contains(name) && 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 "rescue" -> {if(args.length!=0)throw new IllegalArgumentException("Use /rescue for emergency travel.");homeTravel.rescue(p,location(p,"home"));}
|
||||
case "home" -> {
|
||||
HomeAddress address=address(p,args);
|
||||
Location destination=location(p,address.name());
|
||||
if(address.explicitWorld()||homes.contains(worldKey(p,address.name())))homeTravel.worldHome(p,destination);
|
||||
else homeTravel.begin(p,destination);
|
||||
}
|
||||
case "delhome" -> {
|
||||
HomeAddress address=address(p,args);String name=address.name(),scoped=worldKey(p,name),path=address.explicitWorld()||homes.contains(scoped)?scoped: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))return List.of();
|
||||
if(args.length==2&&Set.of("home","delhome").contains(command.getName())&&p.getWorld().getName().equalsIgnoreCase(args[0]))return names(p).stream().filter(n->n.startsWith(args[1].toLowerCase(Locale.ROOT))).toList();
|
||||
if(args.length!=1)return List.of();
|
||||
Collection<String> values=switch(command.getName()) {
|
||||
case "home","delhome" -> {var choices=new TreeSet<>(names(p));choices.add(p.getWorld().getName());yield choices;}
|
||||
case "sethome" -> List.of(p.getWorld().getName());
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,320 +0,0 @@
|
|||
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.MenuPresentation.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.MenuPresentation.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.MenuPresentation.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.MenuPresentation.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.MenuPresentation.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()); }
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
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 origin<>'jarvis-hq'";
|
||||
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=? AND origin<>'jarvis-hq'")) {
|
||||
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=? AND origin<>'jarvis-hq' 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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
package com.example.duneess;
|
||||
|
||||
import com.google.gson.*;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import java.nio.file.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/** Same-world home travel. The existing connector owns central banking; this journal owns delivery. */
|
||||
final class PersonalHomeTravel implements Listener {
|
||||
private final JavaPlugin plugin;private final Path file;private YamlConfiguration journal;
|
||||
private final Map<UUID,UUID> waiting=new HashMap<>();private final Set<String> busy=new HashSet<>();
|
||||
PersonalHomeTravel(JavaPlugin plugin){
|
||||
this.plugin=plugin;file=plugin.getDataFolder().toPath().resolve("home-journeys.yml");journal=YamlConfiguration.loadConfiguration(file.toFile());
|
||||
Bukkit.getPluginManager().registerEvents(this,plugin);
|
||||
Bukkit.getScheduler().runTaskTimer(plugin,this::recover,40,100);
|
||||
}
|
||||
static boolean valid(Location location){return location!=null&&location.getWorld()!=null&&Double.isFinite(location.getX())&&Double.isFinite(location.getY())&&Double.isFinite(location.getZ())&&location.getWorld().getWorldBorder().isInside(location)&&location.getY()>=location.getWorld().getMinHeight()&&location.getY()<location.getWorld().getMaxHeight();}
|
||||
private void save()throws Exception{
|
||||
Files.createDirectories(file.getParent());Path temp=file.resolveSibling("home-journeys.yml.tmp");
|
||||
try(var channel=java.nio.channels.FileChannel.open(temp,StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE)){
|
||||
var bytes=StandardCharsets.UTF_8.encode(journal.saveToString());while(bytes.hasRemaining())channel.write(bytes);channel.force(true);
|
||||
}
|
||||
try{Files.move(temp,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}catch(AtomicMoveNotSupportedException e){Files.move(temp,file,StandardCopyOption.REPLACE_EXISTING);}
|
||||
}
|
||||
private boolean persist(){try{save();return true;}catch(Exception e){journal=YamlConfiguration.loadConfiguration(file.toFile());plugin.getLogger().warning("Home delivery journal could not be saved; no new travel will be started.");return false;}}
|
||||
void begin(Player p,Location destination){begin(p,destination,"");}
|
||||
void worldHome(Player p,Location destination){begin(p,destination,"world");}
|
||||
void rescue(Player p,Location destination){
|
||||
if(destination==null||!p.getWorld().equals(destination.getWorld())||!safe(destination)){
|
||||
destination=p.getWorld().getSpawnLocation();
|
||||
}
|
||||
if(!safe(destination)){p.sendMessage("No safe rescue destination is available on this world.");return;}
|
||||
begin(p,destination,"rescue");
|
||||
}
|
||||
private static boolean safe(Location at){
|
||||
if(!valid(at)||!at.getWorld().isChunkLoaded(at.getBlockX()>>4,at.getBlockZ()>>4))return false;
|
||||
var feet=at.getBlock();
|
||||
var head=feet.getRelative(org.bukkit.block.BlockFace.UP);
|
||||
var floor=feet.getRelative(org.bukkit.block.BlockFace.DOWN);
|
||||
return feet.getType().isAir()&&head.getType().isAir()&&floor.getType().isSolid()&&
|
||||
!Set.of(Material.MAGMA_BLOCK,Material.CACTUS,Material.CAMPFIRE,Material.SOUL_CAMPFIRE).contains(floor.getType());
|
||||
}
|
||||
private void begin(Player p,Location destination,String mode){
|
||||
boolean rescue=mode.equals("rescue");
|
||||
if(!valid(destination)){p.sendMessage("That saved home is unavailable or outside the world's playable bounds.");return;}
|
||||
if(!p.getWorld().equals(destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;}
|
||||
String id=p.getUniqueId().toString();if(waiting.containsKey(p.getUniqueId())||journal.contains(id)){p.sendMessage("Your home journey is already being completed.");return;}
|
||||
var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){p.sendMessage("Central home travel is unavailable. No payment was made.");return;}
|
||||
UUID token=UUID.randomUUID(),world=p.getWorld().getUID();waiting.put(p.getUniqueId(),token);Location target=destination.clone();
|
||||
if(!rescue)p.sendMessage(mode.equals("world")?"World home travel in 5 seconds · Spacing Guild tariff · 24-hour cooldown.":"Home travel in 5 seconds · 25 DM · 15 minute cooldown.");
|
||||
Runnable reserve=()->{
|
||||
if(!token.equals(waiting.remove(p.getUniqueId()))||!p.isOnline())return;
|
||||
if(!world.equals(p.getWorld().getUID())||p.isDead()||!valid(target)){p.sendMessage("Home travel cancelled. No payment was made.");return;}
|
||||
journal.set(id+".requestId",token.toString());journal.set(id+".destination",target);journal.set(id+".stage","reserve");journal.set(id+".mode",mode);
|
||||
try{journal.set(id+".destinationHash",HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest((target.getWorld().getUID()+":"+target.getX()+":"+target.getY()+":"+target.getZ()+":"+target.getYaw()+":"+target.getPitch()).getBytes(StandardCharsets.UTF_8))));}catch(Exception e){throw new IllegalStateException(e);}
|
||||
if(persist())attempt(id);
|
||||
};
|
||||
if(rescue)reserve.run();else Bukkit.getScheduler().runTaskLater(plugin,reserve,100);
|
||||
}
|
||||
private void recover(){for(String id:new HashSet<>(journal.getKeys(false)))attempt(id);}
|
||||
private void stage(String id,String value){journal.set(id+".stage",value);persist();}
|
||||
private void attempt(String id){
|
||||
if(!busy.add(id))return;
|
||||
String mode=journal.getString(id+".mode","");
|
||||
boolean rescue=mode.equals("rescue");
|
||||
String stage=journal.getString(id+".stage");Player player=Bukkit.getPlayer(UUID.fromString(id));
|
||||
// Keep a pre-payment instruction after a lost reply; retry it with exactly the same reference.
|
||||
var input=new JsonObject();input.addProperty("action",stage);input.addProperty("requestId",journal.getString(id+".requestId"));input.addProperty("destinationHash",journal.getString(id+".destinationHash"));if(!mode.isEmpty())input.addProperty("mode",mode);
|
||||
var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){busy.remove(id);return;}
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{
|
||||
JsonObject result=null;try{result=JsonParser.parseString((String)connector.getClass().getMethod("requestHome",UUID.class,String.class).invoke(connector,UUID.fromString(id),input.toString())).getAsJsonObject();}catch(Exception ignored){}
|
||||
JsonObject response=result;Bukkit.getScheduler().runTask(plugin,()->{
|
||||
boolean teleporting=false;
|
||||
try{
|
||||
if(response==null)return; // Unknown outcome stays durable and retries, never creates another payment.
|
||||
if(response.has("rejectedStatus")){
|
||||
int status=response.get("rejectedStatus").getAsInt();
|
||||
// Only a definitive reserve refusal has no accepted liability. Settlement failures retain the journal.
|
||||
if(stage.equals("reserve")&&response.has("unreserved")&&response.get("unreserved").getAsBoolean()){
|
||||
if(player!=null&&player.isOnline())player.sendMessage(response.has("message")?response.get("message").getAsString():"Home travel was refused.");journal.set(id,null);persist();
|
||||
}return;
|
||||
}
|
||||
String state=response.get("state").getAsString();
|
||||
if(!state.equals("pending")){journal.set(id,null);persist();return;}
|
||||
if(!stage.equals("reserve"))return;
|
||||
Player current=Bukkit.getPlayer(UUID.fromString(id));Location target=journal.getLocation(id+".destination");
|
||||
if(current==null||!current.isOnline()||current.isDead()||!valid(target)||rescue&&!safe(target)||!current.getWorld().equals(target.getWorld())){stage(id,"cancel");return;}
|
||||
// Keep the busy latch until the actual native result. Crash recovery re-delivers the same destination.
|
||||
current.teleportAsync(target).whenComplete((success,failure)->Bukkit.getScheduler().runTask(plugin,()->{
|
||||
boolean arrived=Boolean.TRUE.equals(success)&&failure==null;
|
||||
stage(id,arrived?"arrive":"cancel");busy.remove(id);
|
||||
if(arrived&&rescue&¤t.isOnline()&&!current.isDead()){
|
||||
var health=current.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH);
|
||||
if(health!=null)current.setHealth(health.getValue());
|
||||
current.setFireTicks(0);current.setFallDistance(0);
|
||||
}
|
||||
if(current.isOnline())current.sendMessage(arrived&&mode.equals("world")?"World home reached · "+String.format(Locale.ROOT,"%.2f DM",response.get("fareMinor").getAsLong()/100.0)+" · 24-hour cooldown.":arrived?(rescue?"Emergency rescue complete · 1,000 DM · 24-hour cooldown.":"Home reached · 25 DM · 15 minute cooldown."):"Teleport failed. Your reservation will be released.");attempt(id);
|
||||
}));
|
||||
teleporting=true;
|
||||
return;
|
||||
}finally{
|
||||
if(!teleporting)busy.remove(id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@EventHandler public void quit(PlayerQuitEvent event){waiting.remove(event.getPlayer().getUniqueId());}
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
package com.example.duneess;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import java.sql.Connection;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/** Staff conveniences using current native recipes and the shared inventory checkpoint. */
|
||||
public final class StaffItemTools implements CommandExecutor {
|
||||
private final JavaPlugin plugin;
|
||||
public static void start(JavaPlugin plugin){var tools=new StaffItemTools(plugin);for(String name:List.of("condense","fix"))Objects.requireNonNull(plugin.getCommand(name)).setExecutor(tools);}
|
||||
private StaffItemTools(JavaPlugin plugin){this.plugin=plugin;}
|
||||
private record Compression(ItemStack result,int cost){}
|
||||
private static List<RecipeChoice> ingredients(Recipe recipe){
|
||||
if(recipe instanceof ShapedRecipe r){String[] rows=r.getShape();if(rows.length!=2&&rows.length!=3||Arrays.stream(rows).anyMatch(row->row.length()!=rows.length||row.contains(" ")))return List.of();var list=new ArrayList<RecipeChoice>();for(String row:rows)for(char c:row.toCharArray())list.add(r.getChoiceMap().get(c));return list;}
|
||||
if(recipe instanceof ShapelessRecipe r)return r.getChoiceList();return List.of();
|
||||
}
|
||||
private static boolean matches(RecipeChoice choice,ItemStack stack){return choice!=null&&choice.test(stack);}
|
||||
private Compression compression(ItemStack item)throws Exception{
|
||||
var data=item.getItemMeta().getPersistentDataContainer();String custom=data.get(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING),legacy=data.get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING);
|
||||
var jarvis=Bukkit.getPluginManager().getPlugin("JarvisTranslator");
|
||||
if("spice".equals(legacy)||"spice".equals(custom)||"smuggled_spice".equals(custom)){var result=(ItemStack)jarvis.getClass().getMethod("compressedSpice",ItemStack.class).invoke(jarvis,item);return result==null?null:new Compression(result,9);}
|
||||
if(custom!=null||legacy!=null||data.has(new NamespacedKey("dunerealms","preview_only")))return null;
|
||||
var all=new ArrayList<Recipe>();Bukkit.recipeIterator().forEachRemaining(all::add);
|
||||
for(int cost:new int[]{9,4})for(var recipe:all){
|
||||
if(!(recipe instanceof Keyed keyed)||!keyed.getKey().getNamespace().equals("minecraft"))continue;
|
||||
var inputs=ingredients(recipe);var result=recipe.getResult();
|
||||
if(inputs.size()!=cost||result.getAmount()!=1||result.getType()==item.getType()||inputs.stream().anyMatch(c->!matches(c,item)))continue;
|
||||
// Only reversible storage recipes: never silently turn wood into workbenches.
|
||||
boolean reverse=all.stream().anyMatch(r->{var parts=ingredients(r);return parts.size()==1&&matches(parts.getFirst(),result)&&r.getResult().getType()==item.getType()&&r.getResult().getAmount()==cost;});
|
||||
if(reverse){var output=result.clone();if(jarvis!=null)jarvis.getClass().getMethod("markCreatedItem",ItemStack.class).invoke(jarvis,output);return new Compression(output,cost);}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private int condense(Player p)throws Exception{
|
||||
var inventory=p.getInventory();var contents=inventory.getStorageContents();var seen=new ArrayList<ItemStack>();int blocks=0;
|
||||
for(var sample:contents){if(sample==null||sample.isEmpty()||seen.stream().anyMatch(i->i.isSimilar(sample)))continue;seen.add(sample.clone());var rule=compression(sample);if(rule==null)continue;
|
||||
int count=Arrays.stream(contents).filter(i->i!=null&&i.isSimilar(sample)).mapToInt(ItemStack::getAmount).sum(),made=count/rule.cost();if(made==0)continue;
|
||||
var temporary=Bukkit.createInventory(null,36);temporary.setContents(Arrays.stream(contents).map(i->i==null?null:i.clone()).toArray(ItemStack[]::new));int remaining=made*rule.cost();
|
||||
for(int slot=0;slot<36&&remaining>0;slot++){var item=temporary.getItem(slot);if(item==null||!item.isSimilar(sample))continue;int take=Math.min(item.getAmount(),remaining);item.setAmount(item.getAmount()-take);temporary.setItem(slot,item.isEmpty()?null:item);remaining-=take;}
|
||||
var output=rule.result().clone();output.setAmount(made);if(!temporary.addItem(output).isEmpty())continue;
|
||||
contents=temporary.getContents();blocks+=made;
|
||||
}
|
||||
inventory.setStorageContents(contents);return blocks;
|
||||
}
|
||||
private static int repair(Player p){int count=0;for(int slot=0;slot<p.getInventory().getSize();slot++){var item=p.getInventory().getItem(slot);if(item==null)continue;var meta=item.getItemMeta();if(meta instanceof Damageable damage&&damage.getDamage()>0){damage.setDamage(0);item.setItemMeta(meta);p.getInventory().setItem(slot,item);count++;}}return count;}
|
||||
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){
|
||||
if(!(sender instanceof Player p))return true;if(!p.hasPermission("dune.admin")){p.sendMessage("This command is for staff.");return true;}if(args.length!=0){p.sendMessage("/"+command.getName());return true;}
|
||||
try{var core=Bukkit.getPluginManager().getPlugin("DuneCore");if(core==null||!core.isEnabled())throw new IllegalStateException("Shared inventory unavailable. Nothing changed.");int[] count={0};Consumer<Connection> action=connection->{try{count[0]=command.getName().equals("fix")?repair(p):condense(p);}catch(Exception e){throw new java.util.concurrent.CompletionException(e);}};core.getClass().getMethod("transactNetworkInventory",Player.class,Consumer.class).invoke(core,p,action);p.sendMessage(command.getName().equals("fix")?"Repaired "+count[0]+" items.":"Created "+count[0]+" condensed items.");}
|
||||
catch(Exception e){Throwable cause=e instanceof InvocationTargetException?e.getCause():e;plugin.getLogger().warning("Staff inventory operation failed: "+cause.getClass().getSimpleName());p.sendMessage("Inventory operation could not be confirmed. Reopen your inventory before retrying.");}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
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
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
name: DuneEss
|
||||
version: 1.0.12
|
||||
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:
|
||||
dune:
|
||||
description: DuneRealms commands
|
||||
usage: /dune help
|
||||
condense:
|
||||
description: Compress matching resources into storage blocks
|
||||
permission: dune.admin
|
||||
fix:
|
||||
description: Repair every damaged item in your inventory and equipment
|
||||
permission: dune.admin
|
||||
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
|
||||
rescue:
|
||||
description: Emergency teleport and heal for 1,000 DM
|
||||
usage: /rescue
|
||||
home:
|
||||
description: Teleport to a saved home on your current world
|
||||
usage: /home [world] [name]
|
||||
permission: duneess.basics
|
||||
sethome:
|
||||
description: Save a named home on your current world
|
||||
usage: /sethome [world] [name]
|
||||
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
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff