forked from unimatrix/web
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
577d975787 | ||
|
|
03b7332653 | ||
|
|
188f8fcd21 | ||
|
|
091720f9e4 | ||
|
|
4254a96b42 | ||
|
|
a61b9ec93f | ||
|
|
fe67c7820f | ||
|
|
96c3f601bc | ||
|
|
79cd02f99e | ||
|
|
afa1feb366 | ||
|
|
6d0f15082a | ||
|
|
1a011deb2b | ||
|
|
9641d1e855 | ||
|
|
93489c6119 | ||
|
|
633cb376e9 | ||
|
|
e5845b120c | ||
|
|
1fdf4dc720 | ||
|
|
d9f374defb | ||
|
|
0caf096fde | ||
|
|
9854418920 | ||
|
|
490a4c95b2 | ||
|
|
f2c72a6fd7 | ||
|
|
f8d8c9e206 | ||
|
|
6e27d69a09 | ||
|
|
8404c61329 | ||
|
|
8cb398e06f | ||
|
|
791a6408ca | ||
|
|
985e37e5eb | ||
|
|
8c25f491f4 | ||
|
|
44c82e767a | ||
|
|
33507e7be7 | ||
|
|
d88d96e87c | ||
|
|
4fd67cb42f | ||
|
|
d347f7a3d7 | ||
|
|
1e86aab3e5 | ||
|
|
a4e2fc64eb | ||
|
|
e99331a8e0 | ||
|
|
4e8d0bf49e | ||
|
|
507191ba3a | ||
|
|
279077a94d | ||
|
|
ea72de3eba | ||
|
|
4c51624723 | ||
|
|
51121e7b1d | ||
|
|
ff0161117e | ||
|
|
e94131d237 | ||
|
|
46d13ea03e | ||
|
|
9e833a4db9 | ||
|
|
ebb1ac3586 | ||
|
|
d9877dfd9c | ||
|
|
fb35577cfb | ||
|
|
699c66f064 | ||
|
|
491ad06e19 | ||
|
|
4af783012b | ||
|
|
aa986ad962 | ||
|
|
23b1879de2 | ||
|
|
525be204dd | ||
|
|
0097a856f7 | ||
| 484f121fcc | |||
|
|
47fc12d449 | ||
|
|
d142317b18 | ||
|
|
ca5acc79b2 | ||
|
|
b406b337db | ||
|
|
411324e4c0 | ||
|
|
c91a1a14f3 | ||
|
|
c3d2b9e2d0 | ||
|
|
d3a27db1ca | ||
|
|
8d93c32b19 | ||
|
|
73f3464e45 | ||
|
|
3de9c12f39 | ||
|
|
ae75883918 | ||
|
|
de31af7112 | ||
|
|
4f6b49918b | ||
|
|
a22648d579 | ||
|
|
6dc15b20b1 | ||
|
|
8b728d414e | ||
|
|
207002b48a | ||
| af8c0e463f | |||
|
|
c2018d6abe | ||
|
|
955424b42c | ||
|
|
5690ae3db6 | ||
|
|
94419ab22b | ||
|
|
3b69a7eb74 | ||
|
|
b204c2e978 | ||
|
|
eeee72a91e | ||
|
|
70098d57ff | ||
|
|
d4480cad6f | ||
|
|
16b91e5665 | ||
|
|
aca4e5e168 | ||
| cd2c30923a | |||
| c574d6f02e |
3059 changed files with 10567 additions and 70578 deletions
|
|
@ -9,7 +9,7 @@ const steps = new Map(
|
|||
return [chunk.slice(0, lineEnd).trim(), chunk.slice(lineEnd + 1)];
|
||||
})
|
||||
);
|
||||
const production = "github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main'";
|
||||
const production = "github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main'";
|
||||
|
||||
function step(name) {
|
||||
assert.ok(steps.has(name), 'Expected workflow step: ' + name);
|
||||
|
|
@ -20,7 +20,7 @@ test('development can dispatch a build and production still builds on main pushe
|
|||
assert.match(workflow, /^ workflow_dispatch:\s*$/m);
|
||||
assert.match(workflow, /^ push:\r?\n branches:\r?\n - main\r?$/m);
|
||||
assert.equal(workflow.match(/^ if: (.+)$/m)?.[1].trim(),
|
||||
"github.repository == 'unimatrix/MC' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch')");
|
||||
"github.repository == 'unimatrix/web' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch')");
|
||||
for (const name of ['Verify deployment policy', 'Build and test website']) {
|
||||
assert.doesNotMatch(step(name), /^ if:/m);
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ test('checkout fetches the exact event commit from the repository running the wo
|
|||
const checkout = step('Check out exact revision');
|
||||
assert.match(checkout, /fetch --depth=1 "https:\/\/www\.dunerealms\.com\/git\/\$\{GITHUB_REPOSITORY\}\.git" "\$GITHUB_SHA"/);
|
||||
assert.match(checkout, /git checkout --detach FETCH_HEAD\r?\n\s+test "\$\(git rev-parse HEAD\)" = "\$GITHUB_SHA"/);
|
||||
assert.doesNotMatch(checkout, /unimatrix\/MC/);
|
||||
assert.doesNotMatch(checkout, /unimatrix\/web/);
|
||||
});
|
||||
|
||||
test('publication comparison, artifact upload and deployment require canonical main', () => {
|
||||
|
|
@ -44,3 +44,11 @@ test('publication comparison, artifact upload and deployment require canonical m
|
|||
if (name !== 'Trigger deployment after successful CI') assert.doesNotMatch(body, /DUNEREALMS_DEPLOY_KEY|ssh .*dunedeploy@/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test('deployment uses the verified dedicated host and its pinned SSH key', () => {
|
||||
const deploy = step('Trigger deployment after successful CI');
|
||||
assert.ok(deploy.includes('95.216.100.187 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICdHgR/5lVFKbOpAYR2+/Bi5LSg+8nDCSm77mJOmJKRg'));
|
||||
assert.ok(deploy.includes('dunedeploy@95.216.100.187'));
|
||||
assert.ok(!deploy.includes('91.107.196.242'));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ jobs:
|
|||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/web.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- name: Install Node 22
|
||||
uses: actions/setup-node@v4
|
||||
|
|
|
|||
|
|
@ -1,23 +0,0 @@
|
|||
name: DuneRealms Kit Delivery CI
|
||||
on:
|
||||
push:
|
||||
branches: [main, dev/kit-atelier-v3]
|
||||
paths:
|
||||
- 'network/server-control/kit*'
|
||||
- 'network/server-control/player_kits.py'
|
||||
- '.forgejo/workflows/kit-delivery.yml'
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
kits:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Checkout
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- name: Verify kit delivery bridge
|
||||
run: python3 -m unittest discover -s network/server-control -p 'test_*.py' -v
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
name: DuneRealms Plugin CI
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.forgejo/workflows/plugins.yml'
|
||||
- 'Dune*/**'
|
||||
- 'JarvisConnector/**'
|
||||
- 'gui-common/**'
|
||||
- 'network/proxy/central-pack/**'
|
||||
|
||||
jobs:
|
||||
plugins:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '9.2.1'
|
||||
- name: Test and build first-party plugins
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
modules=(DuneEss DuneLobby DuneNPC DuneRealms-minecraft-only DuneTerrain JarvisConnector)
|
||||
if [[ -f network/proxy/central-pack/build.gradle.kts ]]; then
|
||||
modules+=(network/proxy/central-pack)
|
||||
fi
|
||||
mkdir -p plugin-artifacts
|
||||
for module in "${modules[@]}"; do
|
||||
gradle --no-daemon -p "$module" test jar
|
||||
for jar in "$module"/build/libs/*.jar; do
|
||||
test -f "$jar"
|
||||
artifact="plugin-artifacts/${jar##*/}"
|
||||
test ! -e "$artifact"
|
||||
cp "$jar" "$artifact"
|
||||
done
|
||||
done
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > plugin-artifacts/SOURCE_COMMIT
|
||||
(cd plugin-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Plugins
|
||||
path: plugin-artifacts/
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Test and build the replacement DuneMenus plugin
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneMenus test jar
|
||||
mkdir -p dunemenus-artifacts
|
||||
cp DuneMenus/build/libs/DuneMenus.jar dunemenus-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > dunemenus-artifacts/SOURCE_COMMIT
|
||||
(cd dunemenus-artifacts && sha256sum -- DuneMenus.jar SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ github.repository == 'dev/MC' && 'DuneMenus-Development' || 'DuneMenus' }}
|
||||
path: dunemenus-artifacts/
|
||||
if-no-files-found: error
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '25'
|
||||
- name: Build optional Paper 26.2 fullscreen provider
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneFullscreenPaper test jar
|
||||
mkdir -p fullscreen-artifacts
|
||||
cp DuneFullscreenPaper/build/libs/DuneFullscreenPaper.jar fullscreen-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > fullscreen-artifacts/SOURCE_COMMIT
|
||||
(cd fullscreen-artifacts && sha256sum -- DuneFullscreenPaper.jar SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Fullscreen-Paper-Development
|
||||
path: fullscreen-artifacts/
|
||||
if-no-files-found: error
|
||||
|
|
@ -1,113 +0,0 @@
|
|||
name: DuneRealms Resourcepack CI
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'DuneRealmsGUI/**'
|
||||
- 'tools/build-resourcepack-repair.py'
|
||||
- 'tools/test_resourcepack_repair.py'
|
||||
- 'tools/build-arrakis-fauna-pack.mjs'
|
||||
- 'tools/build-fauna-models.mjs'
|
||||
- 'tools/build-fauna-pack-update.py'
|
||||
- 'tools/test_fauna_pack_update.py'
|
||||
- 'DuneTerrain/**'
|
||||
- 'DuneRealms-minecraft-only/**'
|
||||
- 'JarvisConnector/**'
|
||||
- '.forgejo/workflows/resourcepack-ci.yml'
|
||||
jobs:
|
||||
resourcepack:
|
||||
if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Checkout exact reviewed revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- name: Build immutable repair archives and verify pinned inputs
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p resourcepack-baselines resourcepack-output
|
||||
curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v3.zip -o resourcepack-baselines/DuneRealms-Network-Artwork-v3.zip
|
||||
curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Materials-arrakis-v4.zip -o resourcepack-baselines/DuneRealms-Materials-arrakis-v4.zip
|
||||
DUNE_REPAIR_BASELINE_DIR="$PWD/resourcepack-baselines" python3 tools/test_resourcepack_repair.py -v
|
||||
python3 tools/build-resourcepack-repair.py resourcepack-baselines/DuneRealms-Network-Artwork-v3.zip resourcepack-baselines/DuneRealms-Materials-arrakis-v4.zip resourcepack-output
|
||||
DUNE_FAUNA_BASELINE_DIR="$PWD/resourcepack-output" python3 tools/test_fauna_pack_update.py -v
|
||||
python3 tools/build-fauna-pack-update.py resourcepack-output resourcepack-output/fauna-preview
|
||||
- name: Install Java 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- name: Install Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '9.2.1'
|
||||
- name: Build and test pack delivery plugin
|
||||
run: |
|
||||
gradle --no-daemon -p DuneTerrain test jar
|
||||
gradle --no-daemon -p DuneRealms-minecraft-only test jar
|
||||
gradle --no-daemon -p JarvisConnector test jar
|
||||
gradle --no-daemon -p DuneMenus test jar
|
||||
- name: Upload reviewed packs and GUI plugin
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Resourcepack-Repair
|
||||
path: |
|
||||
resourcepack-output/
|
||||
DuneMenus/build/libs/DuneMenus.jar
|
||||
DuneTerrain/build/libs/DuneRealms-Terrain.jar
|
||||
DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar
|
||||
JarvisConnector/build/libs/jarvistranslator.jar
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
central-pack-development:
|
||||
if: github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch'
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact development revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: Verify baseline and build a central pack candidate
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node --test tools/build-planet-texture-packs.test.mjs
|
||||
curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v6.zip -o central-pack-baseline.zip
|
||||
python3 - <<'PYTHON'
|
||||
import pathlib
|
||||
import runpy
|
||||
repair = runpy.run_path('tools/build-resourcepack-repair.py')
|
||||
entries = repair['read_pack'](
|
||||
pathlib.Path('central-pack-baseline.zip'),
|
||||
'ed2533646ee5e19a1dbfeec66e5791d1011a5107e6fcc4153372e431dfc5f56a',
|
||||
)
|
||||
for name, data in entries.items():
|
||||
target = pathlib.Path('central-pack-base') / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
PYTHON
|
||||
node tools/build-central-resource-pack.mjs central-pack-base central-pack-output 7 network/resource-pack/shared
|
||||
printf '%s\n' "$GITHUB_SHA" > central-pack-output/SOURCE_COMMIT
|
||||
(cd central-pack-output && sha256sum -- *.zip central-pack-manifest.json SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Central-Pack-Development
|
||||
path: central-pack-output/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
|
@ -1,85 +1,93 @@
|
|||
name: DuneRealms Web CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'website/**'
|
||||
- '.forgejo/workflows/web-deploy.yml'
|
||||
- '.forgejo/tests/web-deploy.test.mjs'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
web:
|
||||
if: github.repository == 'unimatrix/MC' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch')
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
|
||||
- name: Install Node 22
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
- name: Prepare publication comparison
|
||||
if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main'
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");')
|
||||
if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
|
||||
BEFORE=$(git rev-parse HEAD^)
|
||||
else
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE"
|
||||
fi
|
||||
node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA"
|
||||
|
||||
- name: Verify deployment policy
|
||||
run: |
|
||||
node --test .forgejo/tests/web-deploy.test.mjs
|
||||
python3 -m unittest discover -s website/ops -p 'test_*.py'
|
||||
|
||||
- name: Build and test website
|
||||
working-directory: website
|
||||
run: |
|
||||
corepack enable
|
||||
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/MC' && github.ref == 'refs/heads/main'
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Website
|
||||
path: website/dist/
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- name: Trigger deployment after successful CI
|
||||
if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main'
|
||||
shell: bash
|
||||
env:
|
||||
DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }}
|
||||
run: |
|
||||
install -m 700 -d ~/.ssh
|
||||
printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
trap 'rm -f ~/.ssh/deploy_key' EXIT
|
||||
printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts
|
||||
ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA"
|
||||
rm -f ~/.ssh/deploy_key
|
||||
|
||||
name: DuneRealms Web CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'website/**'
|
||||
- '.forgejo/workflows/web-deploy.yml'
|
||||
- '.forgejo/tests/web-deploy.test.mjs'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
web:
|
||||
if: github.repository == 'unimatrix/web' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch')
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
|
||||
- name: Install Node 22
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
- name: Prepare publication comparison
|
||||
if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main'
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");')
|
||||
if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/web.git "$GITHUB_SHA"
|
||||
BEFORE=$(git rev-parse HEAD^)
|
||||
else
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/web.git "$BEFORE"
|
||||
fi
|
||||
node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA"
|
||||
|
||||
- name: Verify deployment policy
|
||||
run: |
|
||||
node --test .forgejo/tests/web-deploy.test.mjs
|
||||
python3 -m unittest discover -s website/ops -p 'test_*.py'
|
||||
bash -n website/ops/dunerealms-ci-trigger website/ops/dunerealms-build-release
|
||||
|
||||
- name: Build and test website
|
||||
working-directory: website
|
||||
run: |
|
||||
corepack enable
|
||||
corepack pnpm install --frozen-lockfile
|
||||
corepack pnpm build
|
||||
corepack pnpm test
|
||||
|
||||
- name: Upload tested deployment scripts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Website-Operations
|
||||
path: website/dist/deployment/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload website build
|
||||
if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main'
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Website
|
||||
path: website/dist/
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- name: Trigger deployment after successful CI
|
||||
if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main'
|
||||
shell: bash
|
||||
env:
|
||||
DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }}
|
||||
run: |
|
||||
install -m 700 -d ~/.ssh
|
||||
printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
trap 'rm -f ~/.ssh/deploy_key' EXIT
|
||||
printf '%s\n' '95.216.100.187 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICdHgR/5lVFKbOpAYR2+/Bi5LSg+8nDCSm77mJOmJKRg' >> ~/.ssh/known_hosts
|
||||
ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@95.216.100.187 "$GITHUB_SHA"
|
||||
rm -f ~/.ssh/deploy_key
|
||||
|
||||
|
|
|
|||
4
.gitattributes
vendored
4
.gitattributes
vendored
|
|
@ -1,3 +1,7 @@
|
|||
*.pdf binary
|
||||
*.png binary
|
||||
*.zip binary
|
||||
.forgejo/workflows/web-deploy.yml text eol=lf
|
||||
website/ops/dunerealms-ci-trigger text eol=lf
|
||||
website/ops/dunerealms-build-release text eol=lf
|
||||
website/ops/README.md text eol=lf
|
||||
|
|
|
|||
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
|
||||
128
AGENTS.md
128
AGENTS.md
|
|
@ -1,105 +1,45 @@
|
|||
# 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.
|
||||
|
||||
- `unimatrix/MC:main` is the production source. Keep the website and the currently deployed Arrakis plugin source together. `dev/MC` is the development fork for edits, commits, builds and CI. 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.
|
||||
- Owner's mandatory release rule, 29 November 2026: EVERY plugin, page, asset and configuration alteration goes through the committed build pipeline. Do not publish independently created plugin JARs/pages, copy local edits live, or leave direct live patches outside the build. SSH may resolve a blocker, but its persistent correction must be committed and included in the next verified build.
|
||||
|
||||
- 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
|
||||
- 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.
|
||||
- Official CMS Exchange publications use the existing item-definition key and an immutable `cms.item` binding to the exact In-game Bank Treasury account. Player resales of custom items pay the player. Preserve the recovered HQ publisher, recipient-bound `/redeem` gift flow and atomic publication/payment/delivery receipts; do not replace them with placeholders or infer an official payee from an item's name or origin alone.
|
||||
- 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.
|
||||
- The owner requires one shared header and footer across portal, CP and other website surfaces. Use one canonical source and publication path; aligning labels on separate implementations is insufficient. Verify signed-in rendering as well as emitted HTML.
|
||||
|
||||
- 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.
|
||||
- Workspace menus (Staff, User CP and Bank) must display every menu item in the normal page flow. Never add a viewport height cap, sticky scrolling container or independent scrollbar to `#sidebar` or `#sidebar-right`. Scroll the main page; do not hide overflow to conceal unreachable links. Verify this after shared stylesheet publication.
|
||||
|
|
|
|||
|
|
@ -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.NativeMenus.inventory(this,player,"Dune Field Guide · "+(index+1),menu,actions);
|
||||
}
|
||||
|
||||
private ItemStack helpItem(Material material, String name, List<String> lore) {
|
||||
ItemStack item = new ItemStack(material);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(name);
|
||||
if (lore != null) meta.setLore(lore);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@EventHandler public void onHelpMenuClick(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().startsWith(HELP_TITLE)) return;
|
||||
event.setCancelled(true);
|
||||
ItemStack clicked = event.getCurrentItem();
|
||||
if (clicked == null || !clicked.hasItemMeta()) return;
|
||||
ItemMeta meta = clicked.getItemMeta();
|
||||
Integer page = meta.getPersistentDataContainer().get(helpPageKey, PersistentDataType.INTEGER);
|
||||
if (page != null) { openHelpMenu(player, page); return; }
|
||||
if (clicked.getType() == Material.BARRIER) { player.closeInventory(); return; }
|
||||
String action = meta.getPersistentDataContainer().get(helpActionKey, PersistentDataType.STRING);
|
||||
if (action != null) { player.closeInventory(); player.performCommand(action.substring(1)); }
|
||||
}
|
||||
|
||||
@EventHandler public void onHelpMenuDrag(org.bukkit.event.inventory.InventoryDragEvent event) {
|
||||
if (event.getView().getTitle().startsWith(HELP_TITLE)) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
economy.createPlayerAccount(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled=true)
|
||||
public void spiceSeller(org.bukkit.event.player.PlayerInteractEntityEvent event) {
|
||||
if(!event.getRightClicked().getPersistentDataContainer().has(new NamespacedKey("dunerealms","spice-seller"),PersistentDataType.BYTE))return;
|
||||
event.setCancelled(true);
|
||||
if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;
|
||||
Player player=event.getPlayer();
|
||||
Inventory menu=Bukkit.createInventory(null,9,"Spice Seller");
|
||||
int quantity=16;
|
||||
double price=java.math.BigDecimal.valueOf(Math.max(1,getConfig().getInt("currency.spice-price",15)))
|
||||
.multiply(new java.math.BigDecimal("1.35")).multiply(java.math.BigDecimal.valueOf(quantity)).doubleValue();
|
||||
ItemStack offer=new ItemStack(Material.ORANGE_DYE,quantity); ItemMeta meta=offer.getItemMeta();
|
||||
meta.setDisplayName("Buy 16 spice · "+economy.format(price));
|
||||
meta.setLore(List.of("35% above standard spice price", "Confirm purchase"));offer.setItemMeta(meta);menu.setItem(4,offer);
|
||||
Map<Integer,Runnable> actions=new HashMap<>();
|
||||
actions.put(4,()->{
|
||||
// Recheck proximity and capacity at confirmation; never charge for undeliverable goods.
|
||||
if(!event.getRightClicked().isValid() || !player.getWorld().equals(event.getRightClicked().getWorld())
|
||||
|| player.getLocation().distanceSquared(event.getRightClicked().getLocation())>64)return;
|
||||
ItemStack spice=new ItemStack(Material.ORANGE_DYE,quantity);ItemMeta sm=spice.getItemMeta();
|
||||
sm.setDisplayName(ChatColor.GOLD+"Melange Spice");sm.getPersistentDataContainer().set(spiceKey,PersistentDataType.STRING,"spice");spice.setItemMeta(sm);
|
||||
if(player.getInventory().firstEmpty()<0){player.sendMessage("Make an empty inventory slot first.");return;}
|
||||
if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Dunemarks, or economy unavailable.");return;}
|
||||
player.getInventory().addItem(spice);player.sendMessage(ChatColor.GOLD+"Bought 16 spice for "+economy.format(price)+".");
|
||||
});
|
||||
com.example.dunegui.NativeMenus.inventory(this,player,"Spice Seller · +35%",menu,actions);
|
||||
}
|
||||
|
||||
private void sellSpice(Player player) {
|
||||
int amount = 0;
|
||||
for (ItemStack item : player.getInventory().getStorageContents()) {
|
||||
if (isSpice(item)) { amount += item.getAmount(); item.setAmount(0); }
|
||||
}
|
||||
if (amount == 0) { player.sendMessage(ChatColor.RED + "You have no tagged spice to sell."); return; }
|
||||
int price = Math.max(1, getConfig().getInt("currency.spice-price", 15));
|
||||
int gross = Math.multiplyExact(amount, price);
|
||||
int net = callCoreSaleAdjustment(player, gross);
|
||||
economy.depositPlayer(player, net);
|
||||
player.sendMessage(ChatColor.GOLD + "Sold " + amount + " spice for " + economy.format(net) + ".");
|
||||
}
|
||||
|
||||
private boolean isSpice(ItemStack item) {
|
||||
return item != null && item.hasItemMeta()
|
||||
&& "spice".equals(item.getItemMeta().getPersistentDataContainer().get(spiceKey, PersistentDataType.STRING));
|
||||
}
|
||||
|
||||
private int callCoreSaleAdjustment(Player player, int gross) {
|
||||
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
|
||||
if (core == null || !core.isEnabled()) return gross;
|
||||
try {
|
||||
Method method = core.getClass().getMethod("processSpiceSale", Player.class, int.class);
|
||||
Object value = method.invoke(core, player, gross);
|
||||
if (value instanceof Number n) return Math.max(0, n.intValue());
|
||||
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not apply DuneCore spice trade rules: " + ex.getMessage()); }
|
||||
return gross;
|
||||
}
|
||||
|
||||
private void openTravelMenu(Player player) {
|
||||
Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Vaerkring Travel");
|
||||
for (int i = 0; i < PLANETS.size(); i++) {
|
||||
String planet = PLANETS.get(i);
|
||||
ItemStack item = new ItemStack(Material.ENDER_PEARL);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.GOLD + com.example.dunegui.PlanetSigils.label(planet) + " — " + getConfig().getInt("currency.travel-price", 100) + " Dunemarks");
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey(this, "planet"), PersistentDataType.STRING, planet);
|
||||
item.setItemMeta(meta);
|
||||
inventory.setItem(i, com.example.dunegui.PlanetSigils.apply(item,planet));
|
||||
}
|
||||
java.util.Map<Integer,Runnable> actions=new java.util.HashMap<>();
|
||||
for(int i=0;i<PLANETS.size();i++) { String planet=PLANETS.get(i); actions.put(i,()->travel(player,planet)); }
|
||||
com.example.dunegui.NativeMenus.inventory(this,player,"Vaerkring Travel",inventory,actions);
|
||||
}
|
||||
|
||||
@EventHandler public void onTravelMenuClick(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Vaerkring Travel")) return;
|
||||
event.setCancelled(true);
|
||||
ItemStack item = event.getCurrentItem();
|
||||
if (item == null || !item.hasItemMeta()) return;
|
||||
String planet = item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey(this, "planet"), PersistentDataType.STRING);
|
||||
if (planet == null) return;
|
||||
player.closeInventory();
|
||||
travel(player, planet);
|
||||
}
|
||||
|
||||
private void travel(Player player, String planet) {
|
||||
planet = planet.toLowerCase(Locale.ROOT);
|
||||
if (!PLANETS.contains(planet)) { player.sendMessage(ChatColor.RED + "Unknown planet."); return; }
|
||||
if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) { player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized."); return; }
|
||||
if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) {
|
||||
String server = getConfig().getString("network.servers." + planet, "");
|
||||
if (server.isBlank()) {
|
||||
YamlConfiguration core = YamlConfiguration.loadConfiguration(new File(getDataFolder().getParentFile(), "DuneCore/config.yml"));
|
||||
server = core.getString("network.servers." + planet, "");
|
||||
}
|
||||
if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; }
|
||||
int fare = travelFare(player, planet);
|
||||
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; }
|
||||
if (fare > 0) economy.withdrawPlayer(player, fare);
|
||||
if (!sendToServer(player, server, planet) && fare > 0) economy.depositPlayer(player, fare);
|
||||
return;
|
||||
}
|
||||
World world = Bukkit.getWorld(planet);
|
||||
if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; }
|
||||
int fare = travelFare(player, planet);
|
||||
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; }
|
||||
if (fare > 0) economy.withdrawPlayer(player, fare);
|
||||
if (!player.teleport(world.getSpawnLocation())) {
|
||||
if (fare > 0) economy.depositPlayer(player, fare);
|
||||
player.sendMessage(ChatColor.RED + "Vaerkring travel failed. Your fare was returned.");
|
||||
} else {
|
||||
player.sendMessage(ChatColor.AQUA + "Vaerkring arrival: " + planet);
|
||||
if (planet.equals("arrakis")) callCoreArrakisArrival(player);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean sendToServer(Player player, String server, String planet) {
|
||||
try {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
DataOutputStream data = new DataOutputStream(bytes);
|
||||
data.writeUTF("Connect"); data.writeUTF(server);
|
||||
player.sendPluginMessage(this, "BungeeCord", bytes.toByteArray());
|
||||
player.sendMessage(ChatColor.AQUA + "Vaerkring transfer requested: " + planet);
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
player.sendMessage(ChatColor.RED + "Guild transfer failed. Your fare was returned.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean callCoreArrakisAuthorization(Player player) {
|
||||
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
|
||||
if (core == null || !core.isEnabled()) return true;
|
||||
try {
|
||||
Method method = core.getClass().getMethod("authorizeArrakisTravel", Player.class);
|
||||
return Boolean.TRUE.equals(method.invoke(core, player));
|
||||
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not authorize Arrakis travel with DuneCore: " + ex.getMessage()); return false; }
|
||||
}
|
||||
|
||||
private void callCoreArrakisArrival(Player player) {
|
||||
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
|
||||
if (core == null || !core.isEnabled()) return;
|
||||
try { core.getClass().getMethod("enforceArrakisArrival", Player.class).invoke(core, player); }
|
||||
catch (ReflectiveOperationException ex) { getLogger().warning("Could not enforce Arrakis arrival rules: " + ex.getMessage()); }
|
||||
}
|
||||
|
||||
private int travelFare(Player player, String planet) {
|
||||
if (planet.equals("arrakis")) {
|
||||
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
|
||||
if (core != null && core.isEnabled()) try {
|
||||
Method method = core.getClass().getMethod("hasFreeArrakisTravel", Player.class);
|
||||
if (Boolean.TRUE.equals(method.invoke(core, player))) return 0;
|
||||
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not check Arrakis travel rights: " + ex.getMessage()); }
|
||||
}
|
||||
return Math.max(0, getConfig().getInt("currency.travel-price", 100));
|
||||
}
|
||||
|
||||
private boolean admin(CommandSender sender, String[] args) {
|
||||
if (!sender.hasPermission("dune.admin")) { sender.sendMessage(ChatColor.RED + "Admin only."); return true; }
|
||||
if (args.length < 2) { sender.sendMessage("Usage: /duneess admin <solari|teleport|spicebloom> ..."); return true; }
|
||||
if (args[1].equalsIgnoreCase("solari")) {
|
||||
if (args.length != 4) { sender.sendMessage("Usage: /duneess admin solari <player> <amount>"); return true; }
|
||||
Player target = Bukkit.getPlayerExact(args[2]);
|
||||
if (target == null) { sender.sendMessage(ChatColor.RED + "That player must be online."); return true; }
|
||||
try {
|
||||
double amount = Double.parseDouble(args[3]);
|
||||
if (amount <= 0 || !Double.isFinite(amount)) throw new NumberFormatException();
|
||||
economy.depositPlayer(target, amount);
|
||||
sender.sendMessage(ChatColor.GREEN + "Added " + economy.format(amount) + " to " + target.getName() + ".");
|
||||
target.sendMessage(ChatColor.GOLD + "An admin added " + economy.format(amount) + " to your balance.");
|
||||
} catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Dunemarks amount."); }
|
||||
return true;
|
||||
}
|
||||
if (args[1].equalsIgnoreCase("spicebloom")) {
|
||||
Player bloomTarget = args.length > 2 ? Bukkit.getPlayerExact(args[2]) : sender instanceof Player p ? p : null;
|
||||
if (bloomTarget == null) { sender.sendMessage("Usage: /duneess admin spicebloom [online player]"); return true; }
|
||||
World arrakisWorld = Bukkit.getWorld("arrakis");
|
||||
if (arrakisWorld == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; }
|
||||
spawnSpiceBloom(sender, bloomTarget, arrakisWorld);
|
||||
return true;
|
||||
}
|
||||
if (!args[1].equalsIgnoreCase("teleport")) { sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]"); return true; }
|
||||
if (args.length < 3) { sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]"); return true; }
|
||||
Player target = args.length > 3 ? Bukkit.getPlayerExact(args[3]) : sender instanceof Player p ? p : null;
|
||||
if (target == null) { sender.sendMessage(ChatColor.RED + "Specify an online player from console."); return true; }
|
||||
World arrakis = Bukkit.getWorld("arrakis");
|
||||
if (arrakis == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; }
|
||||
switch (args[2].toLowerCase(Locale.ROOT)) {
|
||||
case "arrakis" -> finishTeleport(sender, target, arrakis.getSpawnLocation(), "Arrakis spawn");
|
||||
case "sietch" -> teleportToSietch(sender, target, arrakis);
|
||||
case "spiceblow" -> teleportToSpiceBlow(sender, target, arrakis);
|
||||
default -> sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void finishTeleport(CommandSender sender, Player target, Location location, String label) {
|
||||
if (target.teleport(location)) { target.sendMessage(ChatColor.AQUA + "An admin sent you to " + label + "."); sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to " + label + "."); }
|
||||
else sender.sendMessage(ChatColor.RED + "Teleport failed.");
|
||||
}
|
||||
|
||||
private void teleportToSietch(CommandSender sender, Player target, World world) {
|
||||
Location origin = target.getWorld().equals(world) ? target.getLocation() : world.getSpawnLocation();
|
||||
for (long[] c : candidates(origin, 0x534945544348L)) {
|
||||
int x=(int)c[0], z=(int)c[1];
|
||||
world.getChunkAt(x >> 4, z >> 4).load(true);
|
||||
int chestX=x, chestZ=z-10, estimate=world.getHighestBlockYAt(x+12,z+12);
|
||||
for (int y=Math.max(world.getMinHeight()+1,estimate-80); y<=Math.min(world.getMaxHeight()-1,estimate+5); y++) {
|
||||
Block b=world.getBlockAt(chestX,y,chestZ);
|
||||
if (b.getType()==Material.CHEST && b.getState() instanceof org.bukkit.block.Chest chest && "Personal Sietch Cache".equals(chest.getCustomName())) {
|
||||
finishTeleport(sender,target,new Location(world,x+.5,y+14,z+.5),"a sietch"); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
sender.sendMessage(ChatColor.RED+"No generated sietch was found nearby. Explore new Arrakis terrain, then retry.");
|
||||
}
|
||||
|
||||
private void teleportToSpiceBlow(CommandSender sender, Player target, World world) {
|
||||
for (long[] c : candidates(target.getWorld().equals(world)?target.getLocation():world.getSpawnLocation(),0x5350494345424c4fL)) {
|
||||
int x=(int)c[0],z=(int)c[1]; world.getChunkAt(x>>4,z>>4).load(true);
|
||||
int top=world.getHighestBlockYAt(x,z); Material marker=world.getBlockAt(x,top,z).getType();
|
||||
if(marker==Material.MAGMA_BLOCK||marker==Material.GLOWSTONE) {
|
||||
int sx=x+4,sz=z+4; finishTeleport(sender,target,new Location(world,sx+.5,world.getHighestBlockYAt(sx,sz)+1,sz+.5),"a spice blow"); return;
|
||||
}
|
||||
}
|
||||
sender.sendMessage(ChatColor.RED+"No spice blow was found nearby. Explore new Arrakis terrain, then retry.");
|
||||
}
|
||||
|
||||
private List<long[]> candidates(Location origin,long salt) {
|
||||
int spacing=2000; long gx0=Math.floorDiv(origin.getBlockX(),spacing),gz0=Math.floorDiv(origin.getBlockZ(),spacing);
|
||||
List<long[]> points=new ArrayList<>();
|
||||
for(long gx=gx0-2;gx<=gx0+2;gx++)for(long gz=gz0-2;gz<=gz0+2;gz++){
|
||||
long h1=mix64(gx*0x9E3779B97F4A7C15L^gz*0xC2B2AE3D27D4EB4FL^salt);
|
||||
long h2=mix64(gz*0x165667B19E3779F9L^gx*0x85EBCA77C2B2AE63L^~salt);
|
||||
long x=gx*spacing+8+Math.floorMod(h1,spacing-16),z=gz*spacing+8+Math.floorMod(h2,spacing-16);
|
||||
long dx=x-origin.getBlockX(),dz=z-origin.getBlockZ();points.add(new long[]{x,z,dx*dx+dz*dz});
|
||||
}
|
||||
points.sort(Comparator.comparingLong(point->point[2]));return points;
|
||||
}
|
||||
private static long mix64(long value){value=(value^(value>>>30))*0xBF58476D1CE4E5B9L;value=(value^(value>>>27))*0x94D049BB133111EBL;return value^(value>>>31);}
|
||||
|
||||
private void spawnSpiceBloom(CommandSender sender, Player target, World world) {
|
||||
if(!target.getWorld().equals(world)){sender.sendMessage(ChatColor.RED+"The target must be on Arrakis.");return;}
|
||||
double base=Math.toRadians(90.0-target.getLocation().getYaw()); Block center=null;
|
||||
for(int offset=-12;offset<=12;offset++){
|
||||
double angle=base+Math.toRadians(offset*15.0);int x=target.getLocation().getBlockX()+(int)Math.round(Math.cos(angle)*50),z=target.getLocation().getBlockZ()+(int)Math.round(Math.sin(angle)*50),y=world.getHighestBlockYAt(x,z);boolean ok=true;
|
||||
for(int dx=-1;dx<=1&&ok;dx++)for(int dz=-1;dz<=1;dz++){Block b=world.getBlockAt(x+dx,y,z+dz);if((b.getType()!=Material.SAND&&b.getType()!=Material.RED_SAND)||!world.getBlockAt(x+dx,y+1,z+dz).isPassable()){ok=false;break;}}
|
||||
if(ok&&world.getBlockAt(x,y+2,z).isPassable()){center=world.getBlockAt(x,y,z);break;}
|
||||
}
|
||||
if(center==null){sender.sendMessage(ChatColor.RED+"No clear sand patch was found 50 blocks ahead.");return;}
|
||||
int x=center.getX(),y=center.getY(),z=center.getZ();for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++)world.getBlockAt(x+dx,y,z+dz).setType(Material.MAGMA_BLOCK,false);world.getBlockAt(x,y+1,z).setType(Material.MAGMA_BLOCK,false);
|
||||
org.bukkit.plugin.Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
|
||||
if (core != null && core.isEnabled()) try {
|
||||
Location bloom = new Location(world, x, y + 1, z);
|
||||
core.getClass().getMethod("announceArrakisEvent", String.class, Location.class, String.class)
|
||||
.invoke(core, "spicebloom", bloom, "bloom:" + world.getUID() + ":" + x + ":" + (y + 1) + ":" + z);
|
||||
} catch (ReflectiveOperationException ex) { getLogger().warning("Spice bloom announcement failed: " + ex.getMessage()); }
|
||||
sender.sendMessage(ChatColor.GREEN+"Placed a spice bloom near "+x+", "+z+".");target.sendMessage(ChatColor.GOLD+"A spice bloom appeared about 50 blocks ahead.");
|
||||
}
|
||||
|
||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
if(args.length==1)return complete(List.of("help","balance","sell","travel","admin"),args[0]);
|
||||
if(args[0].equalsIgnoreCase("help")&&args.length==2)return complete(List.of("1","2","3","4","next","previous","menu"),args[1]);
|
||||
if(args[0].equalsIgnoreCase("travel")&&args.length==2)return complete(PLANETS,args[1]);
|
||||
if(args[0].equalsIgnoreCase("admin")&&sender.hasPermission("dune.admin")){
|
||||
if(args.length==2)return complete(List.of("solari","teleport","spicebloom"),args[1]);
|
||||
if(args[1].equalsIgnoreCase("teleport")&&args.length==3)return complete(List.of("arrakis","sietch","spiceblow"),args[2]);
|
||||
if(args[1].equalsIgnoreCase("spicebloom")&&args.length==3)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[2]);
|
||||
if((args[1].equalsIgnoreCase("teleport")||args[1].equalsIgnoreCase("solari"))&&args.length==4)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[3]);
|
||||
}
|
||||
if(args[0].equalsIgnoreCase("balance")&&args.length==2&&sender.hasPermission("dune.admin"))return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[1]);
|
||||
return List.of();
|
||||
}
|
||||
private List<String> complete(Collection<String> options,String prefix){return options.stream().filter(s->s.toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT))).sorted(String.CASE_INSENSITIVE_ORDER).toList();}
|
||||
}
|
||||
|
|
@ -1,168 +0,0 @@
|
|||
package com.example.duneess;
|
||||
|
||||
import com.example.dunegui.NativeMenus;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Deliberately small essentials command surface; vanilla owns bed/anchor respawns. */
|
||||
final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener {
|
||||
private final DuneEss plugin;
|
||||
private final File file;
|
||||
private YamlConfiguration homes;
|
||||
private 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<NativeMenus.Choice> choices=new ArrayList<>();
|
||||
choices.add(new NativeMenus.Choice("Set home","Save your current position as home.",()->p.performCommand("sethome")));
|
||||
choices.add(new NativeMenus.Choice("Homes","Choose a saved home on this backend.",()->homeMenu(p)));
|
||||
choices.add(new NativeMenus.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn")));
|
||||
choices.add(new NativeMenus.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel")));
|
||||
choices.add(new NativeMenus.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance")));
|
||||
choices.add(new NativeMenus.Choice("Koopkring Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange")));
|
||||
choices.add(new NativeMenus.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu")));
|
||||
NativeMenus.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices);
|
||||
}
|
||||
private void homeMenu(Player p) {
|
||||
List<NativeMenus.Choice> choices=names(p).stream().sorted().map(name->new NativeMenus.Choice(name,"Teleport to this saved home.",()->p.performCommand("home "+name))).toList();
|
||||
if(choices.isEmpty()) p.sendMessage("You have no homes. Use /sethome [name].");
|
||||
else NativeMenus.show(plugin,p,"Your homes",choices);
|
||||
}
|
||||
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
|
||||
if(!(sender instanceof Player p)) { sender.sendMessage("Use this command in-game."); return true; }
|
||||
String action=command.getName();
|
||||
if(!p.hasPermission("duneess.basics")) { p.sendMessage("You do not have permission to use essentials."); return true; }
|
||||
try {
|
||||
switch(action) {
|
||||
case "essentials" -> menu(p);
|
||||
case "homes" -> homeMenu(p);
|
||||
case "sethome" -> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff