Compare commits
24
Commits
v1.2.0
...
94197e6bfa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94197e6bfa | ||
|
|
518c9c2f38 | ||
|
|
45cb8de544 | ||
|
|
c9bc102d9a | ||
|
|
ba730cf45f | ||
|
|
292b93e842 | ||
|
|
7816b75325 | ||
|
|
92ef7f6030 | ||
|
|
d9b1312e0c | ||
|
|
f8f731f927 | ||
|
|
66bf93b10d | ||
|
|
d6c8db6019 | ||
|
|
5d86f0e3eb | ||
|
|
061c3be2b1 | ||
|
|
113ae24afe | ||
|
|
c0289c55d3 | ||
|
|
0a45be832b | ||
|
|
376d63e906 | ||
|
|
00aa10a44e | ||
|
|
33ca8abd2a | ||
|
|
1863d04c65 | ||
|
|
22708cf75d | ||
|
|
505c59fb68 | ||
|
|
29c456d4bd |
@@ -0,0 +1,28 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: gradle
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
gradle-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
ignore:
|
||||
# 最低 Paper API 由版本兼容架构固定管理,不能自动升级为最新服务端版本。
|
||||
- dependency-name: "io.papermc.paper:paper-api"
|
||||
# 稳定发布不接受 paperweight 快照版本。
|
||||
- dependency-name: "io.papermc.paperweight.userdev"
|
||||
versions:
|
||||
- "*-SNAPSHOT"
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- "*"
|
||||
@@ -0,0 +1,79 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- 'dev/**'
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 设置 Java 25
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: temurin
|
||||
cache: gradle
|
||||
|
||||
- name: 验证 Gradle Wrapper
|
||||
uses: gradle/actions/wrapper-validation@v4
|
||||
|
||||
- name: 配置 Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
|
||||
- name: 授予执行权限
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: 构建插件
|
||||
run: ./gradlew clean build --no-daemon
|
||||
|
||||
- name: 上传测试产物
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: EssentialsC-test-build
|
||||
path: build/libs/EssentialsC-*.jar
|
||||
if-no-files-found: error
|
||||
|
||||
paper-smoke-test:
|
||||
name: Paper ${{ matrix.paper }} / Java ${{ matrix.java }}
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- paper: '1.21.11'
|
||||
java: '21'
|
||||
- paper: '26.1.2'
|
||||
java: '25'
|
||||
- paper: '26.2'
|
||||
java: '25'
|
||||
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 设置 Java ${{ matrix.java }}
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: ${{ matrix.java }}
|
||||
distribution: temurin
|
||||
|
||||
- name: 下载插件产物
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: EssentialsC-test-build
|
||||
path: build/libs
|
||||
|
||||
- name: 启动 Paper 并验证插件
|
||||
run: bash scripts/smoke-test-paper.sh '${{ matrix.paper }}'
|
||||
@@ -11,25 +11,38 @@ permissions:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 设置 Java
|
||||
|
||||
- name: 设置 Java 25
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '21'
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
|
||||
cache: gradle
|
||||
|
||||
- name: 授予执行权限
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: 配置 Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
|
||||
- name: 构建插件
|
||||
run: mvn clean package -B
|
||||
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
if [[ "$VERSION" == "$GITHUB_REF_NAME" || ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "无效的发布标签: $GITHUB_REF_NAME" >&2
|
||||
exit 1
|
||||
fi
|
||||
./gradlew clean build --no-daemon -PpluginVersion="$VERSION"
|
||||
|
||||
- name: 创建发行版
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: target/essentialsc-*.jar
|
||||
files: build/libs/EssentialsC*.jar
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
+5
-16
@@ -4,7 +4,7 @@
|
||||
# Log files
|
||||
*.log
|
||||
|
||||
# Package Files
|
||||
# Package files
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
@@ -13,20 +13,9 @@
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# Maven
|
||||
target/
|
||||
pom.xml.tag
|
||||
pom.xml.releaseBackup
|
||||
pom.xml.versionsBackup
|
||||
pom.xml.next
|
||||
release.properties
|
||||
dependency-reduced-pom.xml
|
||||
buildNumber.properties
|
||||
.mvn/timing.properties
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
# Gradle
|
||||
.gradle/
|
||||
.gradle-user-home/
|
||||
build/
|
||||
!gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
@@ -61,14 +50,14 @@ bin/
|
||||
# VS Code
|
||||
.vscode/
|
||||
|
||||
# macOS
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Test server (不要上传测试服务器文件)
|
||||
# 测试服务器目录
|
||||
test-server/
|
||||
|
||||
# Reference files (不要上传参考资料)
|
||||
# 参考资料目录
|
||||
references/
|
||||
|
||||
# Plugin build output
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# 更新日志
|
||||
|
||||
## 1.3.1 - 2026-08-16
|
||||
|
||||
### 移除
|
||||
|
||||
- 移除内置维护模式、相关命令、权限、配置和 LuckPerms 软依赖;维护功能建议使用独立的 Maintenance 插件。
|
||||
|
||||
### 调整
|
||||
|
||||
- GitHub 仓库迁移至 InfstarMC 组织,并同步更新项目文档与下载地址。
|
||||
|
||||
### 升级说明
|
||||
|
||||
- 升级时不再读取 `maintenance.yml`;为避免删除管理员数据,服务器目录中的旧文件会原样保留,可在确认迁移完成后手动删除。
|
||||
|
||||
## 1.3.0 - 2026-08-05
|
||||
|
||||
### 新增
|
||||
|
||||
- 按 HuskHomes 的单服逻辑完整实现 TPA 请求、接受、拒绝、忽略、预热、冷却、位置快照、音效与相关权限。
|
||||
- 新增维护模式,包括 MOTD、BossBar、登录拦截、白名单、管理员通知和 LuckPerms 异步权限检查。
|
||||
- 新增 SkinBridge,可识别 InfstarMC、LittleSkin 与自定义 Blessing Skin Provider,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
||||
- 新增管理模式独立状态存储与玩家功能状态管理。
|
||||
|
||||
### 优化
|
||||
|
||||
- 按便捷方块、管理、修复与皮肤功能重新整理运行时模块。
|
||||
- 完善潜影盒会话保护、TPA 请求队列、配置迁移、数据原子写入与持久化错误处理。
|
||||
- 验证兼容 Paper `1.21.11` 与 `26.2`,最终插件保持 Java 21 字节码兼容。
|
||||
- 移除实验性的 JEI 配方同步及其版本适配子项目,插件继续通过 Paper 公共 API 兼容支持的服务端版本。
|
||||
- 迁移 Paper 弃用 API,并将弃用警告设为构建错误。
|
||||
- 统一 HuskHomes 风格的中英文消息、颜色和配置注释。
|
||||
|
||||
### 注意事项
|
||||
|
||||
- 最低服务端版本为 Paper `1.21.11`,不支持 Folia 或 Fabric 服务端。
|
||||
- LuckPerms 为推荐软依赖;未安装时维护模式会在玩家加入后复核绕过权限。
|
||||
- SkinBridge 默认关闭,启用前必须配置有效的 MineSkin API Key。
|
||||
- 主配置版本为 `2`。
|
||||
@@ -1,192 +1,206 @@
|
||||
# EssentialsC
|
||||
|
||||
> 一个轻量级的 Paper 服务器插件,灵感来自 CMI,但更加精简、易用且现代化。
|
||||
轻量、现代、面向 Paper 服务端的基础功能插件,灵感来自 CMI,但更聚焦于常用能力与模块化构建。
|
||||
|
||||
[](https://github.com/Coldsmiles/EssentialsC/releases)
|
||||
[](LICENSE)
|
||||
[](https://papermc.io/)
|
||||
[](https://www.oracle.com/java/)
|
||||
[](https://github.com/InfstarMC/EssentialsC/releases)
|
||||
[](LICENSE)
|
||||
[](https://papermc.io/)
|
||||
[](https://adoptium.net/)
|
||||
|
||||
## ✨ 核心特性
|
||||
## 项目定位
|
||||
|
||||
### 🎯 随身功能方块
|
||||
随时随地打开各种功能性方块,无需放置实体方块:
|
||||
- **工作台** (`/workbench`, `/wb`)
|
||||
- **铁砧** (`/anvil`)
|
||||
- **制图台** (`/cartographytable`, `/ct`)
|
||||
- **砂轮** (`/grindstone`, `/gs`)
|
||||
- **织布机** (`/loom`)
|
||||
- **锻造台** (`/smithingtable`, `/st`)
|
||||
- **切石机** (`/stonecutter`, `/sc`)
|
||||
- 最低支持版本为 `Paper 1.21.11`
|
||||
- 已适配 `Paper 26.2`
|
||||
- 插件统一使用 Paper 公共 API 和 Java 21 字节码,无需按服务端版本拆分构建
|
||||
- 配置按职责拆分:主行为与 SkinBridge、模块开关、菜单布局和语言文本分别管理
|
||||
- 支持运行期模块开关,避免为不同功能组合构建多个插件版本
|
||||
|
||||
### 📦 智能容器管理
|
||||
- **末影箱** (`/enderchest`, `/ec`) - 参考 EssentialsX 实现,100% 数据安全
|
||||
- **潜影盒快捷打开** - 潜行+右键直接打开(类似 CMI)
|
||||
- ✅ 支持自定义标题(可配置)
|
||||
- ✅ 防刷物品机制(快照验证 + 数量检查)
|
||||
- ✅ 防止套娃(不能放入另一个潜影盒)
|
||||
- ✅ 异常恢复(物品丢失自动掉落)
|
||||
## 主要功能
|
||||
|
||||
### 🔧 实用工具
|
||||
- **帽子** (`/hat`) - 将手中物品戴在头上
|
||||
- **自杀** (`/suicide`, `/die`) - 快速自杀
|
||||
- **飞行** (`/fly`) - 切换飞行模式
|
||||
- **修复** (`/repair`, `/rep`) - 修复手中或所有物品
|
||||
- **饱食** (`/feed`) - 补满饱食度
|
||||
### 便捷方块
|
||||
|
||||
### 💚 生存辅助
|
||||
- **治疗** (`/heal`) - 恢复生命值和饱食度
|
||||
- **隐身** (`/vanish`, `/v`) - 管理员隐身模式
|
||||
- `/workbench` `(/wb)`
|
||||
- `/anvil`
|
||||
- `/cartographytable` `(/ct, /cartography)`
|
||||
- `/grindstone` `(/gs)`
|
||||
- `/loom`
|
||||
- `/smithingtable` `(/st, /smithing)`
|
||||
- `/stonecutter` `(/sc)`
|
||||
- `/enderchest` `(/ec)`
|
||||
- `/essc blocks` 打开便捷菜单
|
||||
|
||||
### 📊 管理功能
|
||||
- **玩家查询** (`/seen`, `/info`) - 查看玩家上线时间和信息
|
||||
- **功能方块菜单** (`/essc blocks`) - GUI 方块集合面板
|
||||
- **配置重载** (`/essc reload`) - 重新加载配置文件
|
||||
### 玩家功能
|
||||
|
||||
---
|
||||
- `/fly`
|
||||
- `/nightvision` `(/nv)`
|
||||
- `/glow`
|
||||
- `/heal`
|
||||
- `/feed`
|
||||
- `/repair` `(/rep)`
|
||||
- `/hat`
|
||||
- `/suicide` `(/die)`
|
||||
- `/vanish` `(/v)`
|
||||
- `/seen` `(/info)`
|
||||
- `/tpsbar`
|
||||
- `/essc admin` 管理模式切换
|
||||
|
||||
## 🌍 多语言支持
|
||||
### 控制台命令
|
||||
|
||||
- ✅ 完整的中文和英文配置
|
||||
- ✅ 方块标题自动跟随客户端语言
|
||||
- ✅ 可自定义所有消息文本
|
||||
- `/essc help`、`/essc version`、`/essc reload`
|
||||
- `/seen [玩家]`、`/heal [玩家]`、`/feed [玩家]`、`/tpsbar [玩家]`
|
||||
- `/essc skin [status|refresh] [玩家]`
|
||||
|
||||
## ⚡ 权限系统
|
||||
依赖发送者位置、背包或玩家交互状态的命令仅允许在游戏内执行。控制台执行玩家状态命令时必须明确提供目标玩家。
|
||||
|
||||
- ✅ 精细的权限管理
|
||||
- ✅ 帮助菜单智能显示(只显示有权限的命令)
|
||||
- ✅ 默认仅 OP 可用,可通过权限插件授权
|
||||
- ✅ CMI 风格的命令别名支持
|
||||
### 其它功能
|
||||
|
||||
## 📦 快速开始
|
||||
- Shift + 右键快捷打开潜影盒
|
||||
- 潜影盒交互保护,尽量避免刷物品、吞物品和嵌套放入问题
|
||||
- 管理模式独立背包、装备栏与状态切换
|
||||
- Enderman 掉落方块控制
|
||||
|
||||
### 系统要求
|
||||
- **服务器**: Paper 1.21+
|
||||
- **Java**: 21+
|
||||
## 模块配置
|
||||
|
||||
### 安装步骤
|
||||
1. 下载最新版本的 [`essentialsc-*.jar`](https://github.com/Coldsmiles/EssentialsC/releases)
|
||||
2. 将文件放入服务器的 `plugins` 文件夹
|
||||
3. 重启服务器
|
||||
4. 编辑 `plugins/EssentialsC/config.yml` 配置语言
|
||||
5. (可选)使用权限插件为玩家授予相应权限
|
||||
项目默认构建一个完整插件。玩家常用命令、Vanish 与 TPA 属于核心功能,始终加载并通过权限控制;其他可选功能由 `plugins/EssentialsC/modules.yml` 控制。
|
||||
|
||||
## 🎮 命令列表
|
||||
| 模块 | 默认状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `blocks` | 开启 | 便捷方块命令、`/essc blocks` 菜单、潜影盒快捷打开 |
|
||||
| `admin-mode` | 开启 | `/essc admin` 管理模式与独立状态保存 |
|
||||
| `tpsbar` | 开启 | 插件版 TPSBar,检测到服务端原生命令时自动避免冲突 |
|
||||
| `mob-drops` | 关闭 | 末影人掉落控制,默认关闭以保留过去标准版行为 |
|
||||
| `skin-bridge` | 关闭 | 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤 |
|
||||
|
||||
### 基础命令
|
||||
| 命令 | 说明 |
|
||||
|------|------|
|
||||
| `/essc help` | 显示帮助菜单(根据权限动态显示) |
|
||||
| `/essc reload` | 重载配置(管理员) |
|
||||
| `/essc blocks` | 打开功能方块菜单 |
|
||||
修改模块开关后使用 `/essc reload` 即可刷新运行期服务、监听器和命令门禁。可选模块命令始终注册,模块关闭时会返回统一的停用提示,因此无需为了启用命令重启服务器。
|
||||
|
||||
### 功能方块命令
|
||||
| 命令 | 别名 | 说明 |
|
||||
|------|------|------|
|
||||
| `/workbench` | `/wb` | 打开工作台 |
|
||||
| `/anvil` | - | 打开铁砧 |
|
||||
| `/cartographytable` | `/ct` | 打开制图台 |
|
||||
| `/grindstone` | `/gs` | 打开砂轮 |
|
||||
| `/loom` | - | 打开织布机 |
|
||||
| `/smithingtable` | `/st` | 打开锻造台 |
|
||||
| `/stonecutter` | `/sc` | 打开切石机 |
|
||||
| `/enderchest` | `/ec` | 打开末影箱 |
|
||||
## 安装说明
|
||||
|
||||
### 其他命令
|
||||
| 命令 | 别名 | 说明 |
|
||||
|------|------|------|
|
||||
| `/hat` | - | 将手中物品戴在头上 |
|
||||
| `/suicide` | `/die` | 自杀 |
|
||||
| `/fly` | - | 切换飞行模式 |
|
||||
| `/heal` | - | 恢复生命值和饱食度 |
|
||||
| `/vanish` | `/v` | 切换隐身模式(管理员) |
|
||||
| `/seen` | `/info` | 查看玩家信息(管理员) |
|
||||
| `/feed` | - | 补满饱食度 |
|
||||
| `/repair` | `/rep` | 修复手中或所有物品 |
|
||||
1. 从 [Releases](https://github.com/InfstarMC/EssentialsC/releases) 下载所需版本。
|
||||
2. 将插件放入服务端的 `plugins/` 目录。
|
||||
3. 启动一次服务端以生成配置文件。
|
||||
4. 按需修改 `plugins/EssentialsC/` 下的配置文件与 `lang/` 语言文件。
|
||||
5. 使用权限插件为玩家分配所需权限。
|
||||
|
||||
> 💡 **提示**: 使用 `/repair all` 可以修复背包中的所有物品
|
||||
维护功能建议独立安装 [Maintenance](https://github.com/kennytv/Maintenance)。EssentialsC 不再内置维护模式,也不要求安装该插件。
|
||||
|
||||
## ⚙️ 配置说明
|
||||
## 配置说明
|
||||
|
||||
### config.yml
|
||||
```yaml
|
||||
# 语言设置 (en_US, zh_CN)
|
||||
language: "zh_CN"
|
||||
当前配置按功能职责拆分,避免所有设置堆积在一个文件中:
|
||||
|
||||
# 通用设置
|
||||
settings:
|
||||
enable-feedback: true # 启用命令反馈消息
|
||||
SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-bridge.enabled`,填写 `config.yml` 中的 `skin-bridge.mineskin.api-key`,并至少启用一个 Provider。真实密钥只应填写在服务器运行目录的 `config.yml` 中,不要写入源码或提交到公开仓库。该模块不要求安装 SkinsRestorer。默认支持 InfstarMC 与 LittleSkin;Provider 的 `name` 可自由修改,并会显示在日志和 `/essc skin status <玩家>` 中。生成后的 MineSkin 纹理会按皮肤 URL 缓存到 `skin-cache.yml`,并遵守配置的 TTL。
|
||||
|
||||
# 潜影盒设置
|
||||
shulkerbox:
|
||||
default-title: "&e潜影盒" # 默认标题(支持颜色代码)
|
||||
- `config.yml`
|
||||
- 语言选择
|
||||
- 管理模式行为
|
||||
- 掉落控制
|
||||
- TPSBar 模式
|
||||
- TPA 请求、预热、冷却和音效
|
||||
- SkinBridge、MineSkin、Provider 与排除名单
|
||||
- `modules.yml`
|
||||
- 功能模块开关
|
||||
- `blocks-menu.yml`
|
||||
- 便捷菜单分区、槽位、材质和权限
|
||||
- `lang/zh_CN.yml`、`lang/en_US.yml`
|
||||
- 命令反馈
|
||||
- 帮助信息
|
||||
- 菜单文本
|
||||
- 管理模式文本
|
||||
- TPSBar 文本
|
||||
|
||||
主配置当前使用 `config-version: 2`。SkinBridge 直接配置在 `config.yml` 中,便捷菜单配置仍保存在独立文件中。
|
||||
|
||||
版本变化与升级说明见 [CHANGELOG.md](CHANGELOG.md)。
|
||||
|
||||
## 权限示例
|
||||
|
||||
常用权限节点:
|
||||
|
||||
```text
|
||||
essentialsc.command.blocks
|
||||
essentialsc.command.workbench
|
||||
essentialsc.command.enderchest
|
||||
essentialsc.command.fly
|
||||
essentialsc.command.nightvision
|
||||
essentialsc.command.glow
|
||||
essentialsc.command.heal
|
||||
essentialsc.command.feed
|
||||
essentialsc.command.repair
|
||||
essentialsc.command.vanish
|
||||
essentialsc.vanish.see
|
||||
essentialsc.command.seen
|
||||
essentialsc.command.tpa
|
||||
essentialsc.command.tpahere
|
||||
essentialsc.command.tpaall
|
||||
essentialsc.command.tpaccept
|
||||
essentialsc.command.tpdeny
|
||||
essentialsc.command.tpignore
|
||||
essentialsc.tpa.bypass-warmup
|
||||
essentialsc.tpa.bypass-cooldown
|
||||
# 使用数字覆盖玩家预热时间,例如 3 秒
|
||||
essentialsc.tpa.warmup.3
|
||||
essentialsc.command.admin
|
||||
essentialsc.command.tpsbar
|
||||
essentialsc.command.skin
|
||||
essentialsc.command.skin.status
|
||||
essentialsc.command.skin.refresh
|
||||
essentialsc.command.skin.others
|
||||
essentialsc.shulkerbox.open
|
||||
essentialsc.mobdrops.enderman
|
||||
essentialsc.*
|
||||
```
|
||||
|
||||
### 自定义语言
|
||||
编辑 `plugins/EssentialsC/lang/` 目录下的语言文件来自定义所有消息文本。
|
||||
具体默认值与完整节点以 `paper-plugin.yml` 为准。
|
||||
|
||||
## 🔐 权限节点
|
||||
|
||||
所有命令默认需要 OP 权限。使用权限插件授予权限:
|
||||
|
||||
### 基础权限
|
||||
```
|
||||
essentialsc.command.workbench # 工作台
|
||||
essentialsc.command.anvil # 铁砧
|
||||
essentialsc.command.cartographytable # 制图台
|
||||
essentialsc.command.grindstone # 砂轮
|
||||
essentialsc.command.loom # 织布机
|
||||
essentialsc.command.smithingtable # 锻造台
|
||||
essentialsc.command.stonecutter # 切石机
|
||||
essentialsc.command.enderchest # 末影箱
|
||||
essentialsc.command.hat # 帽子
|
||||
essentialsc.command.suicide # 自杀
|
||||
essentialsc.command.fly # 飞行
|
||||
essentialsc.command.heal # 治疗
|
||||
essentialsc.command.vanish # 隐身
|
||||
essentialsc.command.seen # 玩家查询
|
||||
essentialsc.command.feed # 饱食度
|
||||
essentialsc.command.repair # 修复
|
||||
essentialsc.shulkerbox.open # 潜行+右键潜影盒
|
||||
```
|
||||
|
||||
### 管理权限
|
||||
```
|
||||
essentialsc.command.blocks # 功能方块菜单
|
||||
essentialsc.command.reload # 重载配置
|
||||
essentialsc.command.help # 帮助(默认开放)
|
||||
```
|
||||
|
||||
### 通配符
|
||||
```
|
||||
essentialsc.* # 所有权限
|
||||
```
|
||||
|
||||
## 🔨 从源码构建
|
||||
## 从源码构建
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Coldsmiles/EssentialsC.git
|
||||
git clone https://github.com/InfstarMC/EssentialsC.git
|
||||
cd EssentialsC
|
||||
mvn clean package
|
||||
./gradlew build
|
||||
```
|
||||
|
||||
编译后的文件位于 `target/essentialsc-*.jar`
|
||||
Windows 可使用:
|
||||
|
||||
## 🤝 贡献
|
||||
```powershell
|
||||
.\gradlew.bat build
|
||||
```
|
||||
|
||||
欢迎提交 Issue 和 Pull Request!
|
||||
构建产物输出到 `build/libs/EssentialsC-<version>.jar`。
|
||||
|
||||
## 📄 许可证
|
||||
常用任务:
|
||||
|
||||
本项目采用 MIT 许可证 - 详见 [LICENSE](LICENSE) 文件
|
||||
```bash
|
||||
./gradlew shadowJar
|
||||
./gradlew build
|
||||
./gradlew deployToPaper12111
|
||||
./gradlew deployToPaper262
|
||||
./gradlew deployToLeaves262
|
||||
```
|
||||
|
||||
## 👨💻 作者
|
||||
## 本地测试服
|
||||
|
||||
**Coldsmiles_7**
|
||||
项目包含三个本地测试服目录:
|
||||
|
||||
- GitHub: [@Coldsmiles](https://github.com/Coldsmiles)
|
||||
- 网站: www.infstar.cn
|
||||
| 测试服 | 端口 | 部署任务 | 启动脚本 |
|
||||
| --- | --- | --- | --- |
|
||||
| Paper 1.21.11 | `25566` | `deployToPaper12111` | `test-server/paper-1.21.11/start.bat` |
|
||||
| Paper 26.2 | `25567` | `deployToPaper262` | `test-server/paper-26.2/start.bat` |
|
||||
| Leaves 26.2 | `25568` | `deployToLeaves262` | `test-server/leaves-26.2/start.bat` |
|
||||
|
||||
## ⭐ 支持
|
||||
IDEA 运行配置会先构建插件,再由启动脚本复制最新 JAR,并保留插件数据以便测试升级流程。手动执行部署任务会替换 `EssentialsC*.jar` 并删除 `plugins/EssentialsC` 数据目录,用于测试全新安装及默认配置生成。
|
||||
|
||||
如果觉得这个插件对你有帮助,请考虑在 GitHub 上给它一个 Star!
|
||||
## 开发说明
|
||||
|
||||
- 使用 `paperweight-userdev` 进行 Paper 开发
|
||||
- 使用 Paper Lifecycle Command API 注册命令,避免直接反射 Bukkit CommandMap
|
||||
- 运行时通过 `modules.yml` 控制模块加载,命令始终注册并按模块状态执行门禁
|
||||
- 普通 push/PR 会执行构建与测试,版本标签继续生成 GitHub Release
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目基于 [MIT License](LICENSE) 开源。
|
||||
|
||||
## 仓库
|
||||
|
||||
- GitHub: <https://github.com/InfstarMC/EssentialsC>
|
||||
- Gitea: <https://git.infstar.cn/InfStarMC/EssentialsC>
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
import org.gradle.language.jvm.tasks.ProcessResources
|
||||
import org.gradle.api.tasks.testing.Test
|
||||
import java.util.zip.ZipFile
|
||||
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'io.papermc.paperweight.userdev' version '2.0.0-beta.21'
|
||||
id 'com.gradleup.shadow' version '8.3.11'
|
||||
}
|
||||
|
||||
group = 'cn.infstar'
|
||||
def pluginVersion = providers.gradleProperty('pluginVersion').orElse('1.3.1').get()
|
||||
version = pluginVersion
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven {
|
||||
name = 'papermc'
|
||||
url = uri('https://repo.papermc.io/repository/maven-public/')
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
paperweight.paperDevBundle('1.21.11-R0.1-SNAPSHOT')
|
||||
implementation 'com.google.code.gson:gson:2.11.0'
|
||||
testImplementation platform('org.junit:junit-bom:5.13.4')
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(21))
|
||||
}
|
||||
|
||||
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||
|
||||
allprojects {
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8'
|
||||
options.compilerArgs.addAll(['-Xlint:deprecation', '-Werror'])
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(ProcessResources).configureEach {
|
||||
filteringCharset = 'UTF-8'
|
||||
}
|
||||
|
||||
tasks.withType(Test).configureEach {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.named('processResources', ProcessResources).configure {
|
||||
inputs.property('version', pluginVersion)
|
||||
filesMatching('paper-plugin.yml') {
|
||||
expand('version': pluginVersion)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named('jar').configure {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
tasks.named('shadowJar', ShadowJar).configure {
|
||||
group = 'build'
|
||||
description = '构建包含全部运行期可开关模块的 EssentialsC 插件。'
|
||||
archiveFileName.set("EssentialsC-${pluginVersion}.jar")
|
||||
configurations = [project.configurations.runtimeClasspath]
|
||||
relocate 'com.google.gson', 'cn.infstar.essentialsC.libs.gson'
|
||||
}
|
||||
|
||||
tasks.named('assemble').configure {
|
||||
dependsOn(tasks.named('shadowJar'))
|
||||
}
|
||||
|
||||
tasks.register('verifyJava21Bytecode') {
|
||||
group = 'verification'
|
||||
description = '验证最终插件中的全部 class 均可由 Java 21 加载。'
|
||||
dependsOn(tasks.named('shadowJar'))
|
||||
|
||||
doLast {
|
||||
def artifact = tasks.named('shadowJar', ShadowJar).get().archiveFile.get().asFile
|
||||
def unsupportedClasses = []
|
||||
new ZipFile(artifact).withCloseable { zip ->
|
||||
zip.entries().each { entry ->
|
||||
if (!entry.directory && entry.name.endsWith('.class')) {
|
||||
zip.getInputStream(entry).withCloseable { input ->
|
||||
byte[] header = input.readNBytes(8)
|
||||
if (header.length == 8) {
|
||||
int majorVersion = ((header[6] & 0xff) << 8) | (header[7] & 0xff)
|
||||
if (majorVersion > 65) {
|
||||
unsupportedClasses.add("${entry.name} (class ${majorVersion})")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!unsupportedClasses.isEmpty()) {
|
||||
throw new GradleException("检测到无法由 Java 21 加载的类:\n" + unsupportedClasses.join('\n'))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named('check').configure {
|
||||
dependsOn(tasks.named('verifyJava21Bytecode'))
|
||||
}
|
||||
|
||||
def registerTestServerDeployTask = { String taskName, String serverPath, String serverName ->
|
||||
tasks.register(taskName, Copy) {
|
||||
group = 'deployment'
|
||||
description = "构建并部署插件到本地 ${serverName} 测试服务器。"
|
||||
def artifact = tasks.named('shadowJar').flatMap { it.archiveFile }
|
||||
def pluginsDir = layout.projectDirectory.dir("${serverPath}/plugins")
|
||||
dependsOn(tasks.named('shadowJar'))
|
||||
from(artifact)
|
||||
into(pluginsDir)
|
||||
|
||||
doFirst {
|
||||
delete(fileTree(pluginsDir) {
|
||||
include 'EssentialsC*.jar'
|
||||
})
|
||||
delete(pluginsDir.file('EssentialsC').asFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerTestServerDeployTask('deployToPaper12111', 'test-server/paper-1.21.11', 'Paper 1.21.11')
|
||||
registerTestServerDeployTask('deployToPaper262', 'test-server/paper-26.2', 'Paper 26.2')
|
||||
registerTestServerDeployTask('deployToLeaves262', 'test-server/leaves-26.2', 'Leaves 26.2')
|
||||
Vendored
BIN
Binary file not shown.
+7
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://mirrors.aliyun.com/gradle/distributions/v9.1.0/gradle-9.1.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1,75 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>cn.infstar</groupId>
|
||||
<artifactId>essentialsc</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>essentialsc</name>
|
||||
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<test.server.path>${project.basedir}/test-server/plugins</test.server.path>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<defaultGoal>clean package</defaultGoal>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.5.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<!-- 阿里云 Maven 镜像 -->
|
||||
<repository>
|
||||
<id>aliyunmaven</id>
|
||||
<url>https://maven.aliyun.com/repository/public</url>
|
||||
</repository>
|
||||
<!-- PaperMC 仓库 -->
|
||||
<repository>
|
||||
<id>papermc-repo</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.21.11-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
paper_version="${1:?必须提供 Paper 版本}"
|
||||
workspace="$(mktemp -d)"
|
||||
server_pid=""
|
||||
plugin_jar="$(find build/libs -maxdepth 1 -type f -name 'EssentialsC-*.jar' -print -quit)"
|
||||
if [[ -z "$plugin_jar" ]]; then
|
||||
echo "未找到 EssentialsC 构建产物。" >&2
|
||||
exit 1
|
||||
fi
|
||||
plugin_filename="$(basename "$plugin_jar")"
|
||||
plugin_version="${plugin_filename#EssentialsC-}"
|
||||
plugin_version="${plugin_version%.jar}"
|
||||
|
||||
cleanup() {
|
||||
if [[ -n "$server_pid" ]] && kill -0 "$server_pid" 2>/dev/null; then
|
||||
kill -TERM "$server_pid" 2>/dev/null || true
|
||||
for _ in $(seq 1 10); do
|
||||
if ! kill -0 "$server_pid" 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if kill -0 "$server_pid" 2>/dev/null; then
|
||||
kill -KILL "$server_pid" 2>/dev/null || true
|
||||
fi
|
||||
wait "$server_pid" 2>/dev/null || true
|
||||
fi
|
||||
for _ in 1 2 3; do
|
||||
if rm -rf "$workspace"; then
|
||||
return
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "警告:无法完全清理临时测试目录 $workspace" >&2
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
metadata_url="https://fill.papermc.io/v3/projects/paper/versions/${paper_version}/builds/latest"
|
||||
download_url="$(curl --fail --silent --show-error --location "$metadata_url" \
|
||||
| python3 -c 'import json,sys; print(json.load(sys.stdin)["downloads"]["server:default"]["url"])')"
|
||||
|
||||
curl --fail --silent --show-error --location "$download_url" --output "$workspace/paper.jar"
|
||||
mkdir -p "$workspace/plugins"
|
||||
cp "$plugin_jar" "$workspace/plugins/EssentialsC.jar"
|
||||
printf 'eula=true\n' > "$workspace/eula.txt"
|
||||
printf 'online-mode=false\nserver-port=0\nenable-query=false\n' > "$workspace/server.properties"
|
||||
|
||||
(
|
||||
cd "$workspace"
|
||||
exec java -Xms512M -Xmx1G -jar paper.jar --nogui > server.log 2>&1
|
||||
) &
|
||||
server_pid=$!
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
if grep -Fq "EssentialsC v${plugin_version} 已启用" "$workspace/server.log"; then
|
||||
if grep -Eq 'UnsupportedClassVersionError|Error occurred while enabling EssentialsC|Could not load.*EssentialsC' "$workspace/server.log"; then
|
||||
cat "$workspace/server.log"
|
||||
exit 1
|
||||
fi
|
||||
echo "Paper ${paper_version} 启动验证通过。"
|
||||
exit 0
|
||||
fi
|
||||
if ! kill -0 "$server_pid" 2>/dev/null; then
|
||||
cat "$workspace/server.log"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
cat "$workspace/server.log"
|
||||
echo "Paper ${paper_version} 启动验证超时。" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,22 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
// 阿里云 Gradle 插件镜像,优先使用以提升国内拉取稳定性
|
||||
maven {
|
||||
name = 'aliyun-gradle-plugin'
|
||||
url = uri('https://maven.aliyun.com/repository/gradle-plugin')
|
||||
}
|
||||
// Gradle 官方插件仓库
|
||||
gradlePluginPortal()
|
||||
// PaperMC 官方仓库,用于解析 paperweight 插件
|
||||
maven {
|
||||
name = 'papermc'
|
||||
url = uri('https://repo.papermc.io/repository/maven-public/')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
|
||||
}
|
||||
|
||||
rootProject.name = 'EssentialsC'
|
||||
@@ -1,132 +1,387 @@
|
||||
package cn.infstar.essentialsC;
|
||||
|
||||
import cn.infstar.essentialsC.commands.*;
|
||||
import cn.infstar.essentialsC.admin.AdminModeManager;
|
||||
import cn.infstar.essentialsC.commands.BaseCommand;
|
||||
import cn.infstar.essentialsC.commands.BlocksMenuCommand;
|
||||
import cn.infstar.essentialsC.commands.CommandRegistry;
|
||||
import cn.infstar.essentialsC.commands.HelpCommand;
|
||||
import cn.infstar.essentialsC.commands.PaperCommand;
|
||||
import cn.infstar.essentialsC.commands.VanishCommand;
|
||||
import cn.infstar.essentialsC.listeners.MobDropListener;
|
||||
import cn.infstar.essentialsC.listeners.MobDropMenuListener;
|
||||
import cn.infstar.essentialsC.listeners.ShulkerBoxListener;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import cn.infstar.essentialsC.listeners.VanishListener;
|
||||
import cn.infstar.essentialsC.player.PlayerStateManager;
|
||||
import cn.infstar.essentialsC.skinbridge.SkinBridgeManager;
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import cn.infstar.essentialsC.tpsbar.TpsBarManager;
|
||||
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import io.papermc.paper.command.brigadier.BasicCommand;
|
||||
import io.papermc.paper.command.brigadier.CommandSourceStack;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class EssentialsC extends JavaPlugin {
|
||||
|
||||
private static LangManager langManager;
|
||||
private ModuleManager moduleManager;
|
||||
private FeatureConfigManager featureConfigManager;
|
||||
private AdminModeManager adminModeManager;
|
||||
private TeleportRequestManager teleportRequestManager;
|
||||
private PlayerStateManager playerStateManager;
|
||||
private TpsBarService tpsBarManager;
|
||||
private ShulkerBoxListener shulkerBoxListener;
|
||||
private BlocksMenuCommand blocksMenuCommandListener;
|
||||
private MobDropListener mobDropListener;
|
||||
private MobDropMenuListener mobDropMenuListener;
|
||||
private VanishListener vanishListener;
|
||||
private SkinBridgeManager skinBridgeManager;
|
||||
private boolean commandsRegistered;
|
||||
private final Map<String, String> moduleStatus = new LinkedHashMap<>();
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
// 初始化语言管理器
|
||||
featureConfigManager = new FeatureConfigManager(this);
|
||||
langManager = new LangManager(this);
|
||||
|
||||
// 注册监听器
|
||||
registerListeners();
|
||||
|
||||
// 注册命令
|
||||
moduleManager = new ModuleManager(this);
|
||||
|
||||
reloadRuntimeModules();
|
||||
registerCommands();
|
||||
|
||||
getLogger().info("EssentialsC 插件已启用!");
|
||||
getLogger().info("当前语言: " + langManager.getCurrentLanguage());
|
||||
|
||||
logStartupSummary();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
getLogger().info("EssentialsC 插件已禁用!");
|
||||
if (tpsBarManager != null) {
|
||||
tpsBarManager.shutdown();
|
||||
}
|
||||
if (adminModeManager != null) {
|
||||
adminModeManager.shutdown();
|
||||
}
|
||||
if (teleportRequestManager != null) {
|
||||
teleportRequestManager.shutdown();
|
||||
}
|
||||
if (playerStateManager != null) {
|
||||
playerStateManager.shutdown();
|
||||
}
|
||||
if (skinBridgeManager != null) {
|
||||
skinBridgeManager.shutdown();
|
||||
}
|
||||
if (shulkerBoxListener != null) {
|
||||
shulkerBoxListener.shutdown();
|
||||
}
|
||||
if (vanishListener != null) {
|
||||
vanishListener.shutdown();
|
||||
}
|
||||
VanishCommand.clearAll(this);
|
||||
unregisterRuntimeListeners();
|
||||
getLogger().info("EssentialsC 已禁用。");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取语言管理器实例
|
||||
*/
|
||||
|
||||
public static LangManager getLangManager() {
|
||||
return langManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册所有监听器
|
||||
*/
|
||||
private void registerListeners() {
|
||||
// 注册潜影盒右键打开监听器
|
||||
new ShulkerBoxListener(this);
|
||||
getLogger().info("成功注册监听器!");
|
||||
|
||||
public AdminModeManager getAdminModeManager() {
|
||||
return adminModeManager;
|
||||
}
|
||||
|
||||
private void registerCommands() {
|
||||
try {
|
||||
// 获取 CommandMap
|
||||
Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
|
||||
bukkitCommandMap.setAccessible(true);
|
||||
org.bukkit.command.CommandMap commandMap = (org.bukkit.command.CommandMap) bukkitCommandMap.get(Bukkit.getServer());
|
||||
|
||||
// 注册所有命令(使用 CMI 风格:独立命令 + 别名)
|
||||
registerCommandWithAliases(commandMap, "workbench", new WorkbenchCommand(), "wb");
|
||||
registerCommandWithAliases(commandMap, "anvil", new AnvilCommand());
|
||||
registerCommandWithAliases(commandMap, "cartographytable", new CartographyTableCommand(), "ct", "cartography");
|
||||
registerCommandWithAliases(commandMap, "grindstone", new GrindstoneCommand(), "gs");
|
||||
registerCommandWithAliases(commandMap, "loom", new LoomCommand());
|
||||
registerCommandWithAliases(commandMap, "smithingtable", new SmithingTableCommand(), "st", "smithing");
|
||||
registerCommandWithAliases(commandMap, "stonecutter", new StonecutterCommand(), "sc");
|
||||
registerCommandWithAliases(commandMap, "enderchest", new EnderChestCommand(), "ec");
|
||||
registerCommandWithAliases(commandMap, "hat", new HatCommand());
|
||||
registerCommandWithAliases(commandMap, "suicide", new SuicideCommand(), "die");
|
||||
registerCommandWithAliases(commandMap, "fly", new FlyCommand());
|
||||
registerCommandWithAliases(commandMap, "heal", new HealCommand());
|
||||
registerCommandWithAliases(commandMap, "vanish", new VanishCommand(), "v");
|
||||
registerCommandWithAliases(commandMap, "seen", new SeenCommand(), "info");
|
||||
registerCommandWithAliases(commandMap, "feed", new FeedCommand());
|
||||
registerCommandWithAliases(commandMap, "repair", new RepairCommand(), "rep");
|
||||
registerCommandWithAliases(commandMap, "essentialsc", new HelpCommand(), "essc");
|
||||
|
||||
getLogger().info("成功注册所有命令!");
|
||||
} catch (Exception e) {
|
||||
getLogger().severe("无法注册命令: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
|
||||
public ModuleManager getModuleManager() {
|
||||
return moduleManager;
|
||||
}
|
||||
|
||||
public FeatureConfigManager getFeatureConfigManager() {
|
||||
return featureConfigManager;
|
||||
}
|
||||
|
||||
public TeleportRequestManager getTeleportRequestManager() {
|
||||
return teleportRequestManager;
|
||||
}
|
||||
|
||||
public PlayerStateManager getPlayerStateManager() {
|
||||
return playerStateManager;
|
||||
}
|
||||
|
||||
public TpsBarService getTpsBarManager() {
|
||||
return tpsBarManager;
|
||||
}
|
||||
|
||||
public SkinBridgeManager getSkinBridgeManager() {
|
||||
return skinBridgeManager;
|
||||
}
|
||||
|
||||
public void reloadRuntimeModules() {
|
||||
moduleStatus.clear();
|
||||
refreshCorePlayerFeatures();
|
||||
refreshAdminMode();
|
||||
refreshTpsBar();
|
||||
refreshBlocks();
|
||||
refreshMobDrops();
|
||||
refreshSkinBridge();
|
||||
}
|
||||
|
||||
private void refreshCorePlayerFeatures() {
|
||||
if (playerStateManager == null) {
|
||||
playerStateManager = new PlayerStateManager(this);
|
||||
getServer().getPluginManager().registerEvents(playerStateManager, this);
|
||||
}
|
||||
if (vanishListener == null) {
|
||||
vanishListener = new VanishListener(this);
|
||||
getServer().getPluginManager().registerEvents(vanishListener, this);
|
||||
}
|
||||
if (teleportRequestManager == null) {
|
||||
teleportRequestManager = new TeleportRequestManager(this);
|
||||
getServer().getPluginManager().registerEvents(teleportRequestManager, this);
|
||||
} else {
|
||||
teleportRequestManager.reload();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册命令并支持别名
|
||||
* @param commandMap Bukkit CommandMap
|
||||
* @param name 主命令名
|
||||
* @param executor 命令执行器
|
||||
* @param aliases 别名列表(可选)
|
||||
*/
|
||||
private void registerCommandWithAliases(org.bukkit.command.CommandMap commandMap, String name, cn.infstar.essentialsC.commands.BaseCommand executor, String... aliases) {
|
||||
Command command = new Command(name) {
|
||||
@Override
|
||||
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
|
||||
return executor.onCommand(sender, this, commandLabel, args);
|
||||
|
||||
private void refreshAdminMode() {
|
||||
if (!moduleManager.isEnabled(ModuleManager.ADMIN_MODE)) {
|
||||
if (adminModeManager != null) {
|
||||
adminModeManager.shutdown();
|
||||
HandlerList.unregisterAll(adminModeManager);
|
||||
adminModeManager = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
|
||||
if (executor instanceof org.bukkit.command.TabCompleter) {
|
||||
return ((org.bukkit.command.TabCompleter) executor).onTabComplete(sender, this, alias, args);
|
||||
setModuleStatus("管理模式", false, "已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
if (adminModeManager == null) {
|
||||
adminModeManager = new AdminModeManager(this);
|
||||
getServer().getPluginManager().registerEvents(adminModeManager, this);
|
||||
} else {
|
||||
adminModeManager.reload();
|
||||
}
|
||||
setModuleStatus("管理模式", true, "监听器已注册");
|
||||
}
|
||||
|
||||
private void refreshTpsBar() {
|
||||
if (!moduleManager.isEnabled(ModuleManager.TPSBAR)) {
|
||||
if (tpsBarManager != null) {
|
||||
tpsBarManager.shutdown();
|
||||
if (tpsBarManager instanceof Listener listener) {
|
||||
HandlerList.unregisterAll(listener);
|
||||
}
|
||||
return super.tabComplete(sender, alias, args);
|
||||
tpsBarManager = null;
|
||||
}
|
||||
};
|
||||
|
||||
command.setPermission(executor.getPermission());
|
||||
// 注册到默认命名空间,使玩家可以直接使用 /workbench 而不是 /essentialsc:workbench
|
||||
commandMap.register("", command);
|
||||
|
||||
// 注册别名
|
||||
for (String alias : aliases) {
|
||||
Command aliasCmd = new Command(alias) {
|
||||
@Override
|
||||
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
|
||||
return executor.onCommand(sender, this, commandLabel, args);
|
||||
setModuleStatus("TPSBar", false, "模块已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
if (tpsBarManager == null) {
|
||||
tpsBarManager = new TpsBarManager(this);
|
||||
if (tpsBarManager instanceof Listener listener) {
|
||||
getServer().getPluginManager().registerEvents(listener, this);
|
||||
}
|
||||
} else {
|
||||
tpsBarManager.reloadSettings();
|
||||
}
|
||||
if (tpsBarManager == null) {
|
||||
setModuleStatus("TPSBar", false, "初始化失败");
|
||||
} else if (!tpsBarManager.isPluginCommandEnabled()) {
|
||||
setModuleStatus("TPSBar", false, tpsBarManager.isNativeCommandAvailable() ? "使用服务端原生命令" : "插件命令关闭");
|
||||
} else {
|
||||
setModuleStatus("TPSBar", true, "插件命令已启用");
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshBlocks() {
|
||||
if (!moduleManager.isEnabled(ModuleManager.BLOCKS)) {
|
||||
if (blocksMenuCommandListener != null) {
|
||||
HandlerList.unregisterAll(blocksMenuCommandListener);
|
||||
blocksMenuCommandListener = null;
|
||||
}
|
||||
if (shulkerBoxListener != null) {
|
||||
shulkerBoxListener.shutdown();
|
||||
HandlerList.unregisterAll(shulkerBoxListener);
|
||||
shulkerBoxListener = null;
|
||||
}
|
||||
setModuleStatus("便捷方块", false, "已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
if (shulkerBoxListener == null) {
|
||||
shulkerBoxListener = new ShulkerBoxListener(this);
|
||||
getServer().getPluginManager().registerEvents(shulkerBoxListener, this);
|
||||
}
|
||||
if (blocksMenuCommandListener == null) {
|
||||
BaseCommand command = CommandRegistry.getCommand("blocks");
|
||||
if (command instanceof BlocksMenuCommand blocksMenuCommand) {
|
||||
blocksMenuCommandListener = blocksMenuCommand;
|
||||
getServer().getPluginManager().registerEvents(blocksMenuCommandListener, this);
|
||||
}
|
||||
}
|
||||
setModuleStatus("便捷方块", true, "命令和潜影盒监听器已启用");
|
||||
}
|
||||
|
||||
private void refreshMobDrops() {
|
||||
if (!moduleManager.isEnabled(ModuleManager.MOB_DROPS)) {
|
||||
if (mobDropListener != null) {
|
||||
HandlerList.unregisterAll(mobDropListener);
|
||||
mobDropListener = null;
|
||||
}
|
||||
if (mobDropMenuListener != null) {
|
||||
HandlerList.unregisterAll(mobDropMenuListener);
|
||||
mobDropMenuListener = null;
|
||||
}
|
||||
setModuleStatus("生物掉落", false, "已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
if (mobDropListener == null) {
|
||||
mobDropListener = new MobDropListener(this);
|
||||
getServer().getPluginManager().registerEvents(mobDropListener, this);
|
||||
} else {
|
||||
mobDropListener.reload();
|
||||
}
|
||||
if (mobDropMenuListener == null) {
|
||||
mobDropMenuListener = new MobDropMenuListener(this);
|
||||
getServer().getPluginManager().registerEvents(mobDropMenuListener, this);
|
||||
}
|
||||
setModuleStatus("生物掉落", true, "末影人掉落控制已启用");
|
||||
}
|
||||
|
||||
private void refreshSkinBridge() {
|
||||
if (!moduleManager.isEnabled(ModuleManager.SKIN_BRIDGE)) {
|
||||
if (skinBridgeManager != null) {
|
||||
skinBridgeManager.shutdown();
|
||||
HandlerList.unregisterAll(skinBridgeManager);
|
||||
skinBridgeManager = null;
|
||||
}
|
||||
setModuleStatus("皮肤桥接", false, "已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
if (skinBridgeManager == null) {
|
||||
skinBridgeManager = new SkinBridgeManager(this);
|
||||
getServer().getPluginManager().registerEvents(skinBridgeManager, this);
|
||||
} else {
|
||||
skinBridgeManager.reload();
|
||||
}
|
||||
setModuleStatus("皮肤桥接", true, skinBridgeManager.getModuleDetail());
|
||||
}
|
||||
|
||||
private void unregisterRuntimeListeners() {
|
||||
unregisterListener(adminModeManager);
|
||||
unregisterListener(shulkerBoxListener);
|
||||
unregisterListener(blocksMenuCommandListener);
|
||||
unregisterListener(mobDropListener);
|
||||
unregisterListener(mobDropMenuListener);
|
||||
unregisterListener(vanishListener);
|
||||
unregisterListener(teleportRequestManager);
|
||||
unregisterListener(playerStateManager);
|
||||
unregisterListener(skinBridgeManager);
|
||||
if (tpsBarManager instanceof Listener listener) {
|
||||
unregisterListener(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private void unregisterListener(Listener listener) {
|
||||
if (listener != null) {
|
||||
HandlerList.unregisterAll(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private void setModuleStatus(String moduleName, boolean enabled, String detail) {
|
||||
moduleStatus.put(moduleName, (enabled ? "启用" : "关闭") + " - " + detail);
|
||||
}
|
||||
|
||||
private void logStartupSummary() {
|
||||
long enabledCount = moduleStatus.values().stream()
|
||||
.filter(status -> status.startsWith("启用"))
|
||||
.count();
|
||||
long disabledCount = moduleStatus.size() - enabledCount;
|
||||
|
||||
getLogger().info("EssentialsC v" + getPluginMeta().getVersion()
|
||||
+ " 已启用 | 模块: " + enabledCount + " 启用, " + disabledCount + " 关闭");
|
||||
|
||||
if (!getConfig().getBoolean("debug", false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
getLogger().info("模块明细:");
|
||||
for (Map.Entry<String, String> entry : moduleStatus.entrySet()) {
|
||||
getLogger().info(" " + entry.getKey() + ": " + entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private void registerCommands() {
|
||||
if (commandsRegistered) {
|
||||
return;
|
||||
}
|
||||
commandsRegistered = true;
|
||||
getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event -> {
|
||||
for (CommandRegistry.CommandSpec spec : CommandRegistry.getCommandSpecs()) {
|
||||
if (!spec.standalone()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
|
||||
if (executor instanceof org.bukkit.command.TabCompleter) {
|
||||
return ((org.bukkit.command.TabCompleter) executor).onTabComplete(sender, this, alias, args);
|
||||
}
|
||||
return super.tabComplete(sender, alias, args);
|
||||
BaseCommand executor = CommandRegistry.getRegisteredCommand(spec.name());
|
||||
if (executor == null) {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
aliasCmd.setPermission(executor.getPermission());
|
||||
commandMap.register("", aliasCmd);
|
||||
event.registrar().register(
|
||||
spec.name(),
|
||||
spec.name(),
|
||||
spec.aliases(),
|
||||
new EssentialsBasicCommand(spec.name(), executor)
|
||||
);
|
||||
}
|
||||
|
||||
event.registrar().register(
|
||||
"essentialsc",
|
||||
"essentialsc",
|
||||
List.of("essc"),
|
||||
new EssentialsBasicCommand("essentialsc", new HelpCommand())
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private static final class EssentialsBasicCommand implements BasicCommand {
|
||||
|
||||
private final String name;
|
||||
private final BaseCommand executor;
|
||||
private final PaperCommand commandAdapter;
|
||||
|
||||
private EssentialsBasicCommand(String name, BaseCommand executor) {
|
||||
this.name = name;
|
||||
this.executor = executor;
|
||||
this.commandAdapter = new PaperCommand(name, executor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSourceStack commandSourceStack, String[] args) {
|
||||
CommandSender sender = commandSourceStack.getSender();
|
||||
if (CommandRegistry.resolveCommandName(name) != null && !CommandRegistry.isAvailable(name)) {
|
||||
sender.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.module-disabled"));
|
||||
return;
|
||||
}
|
||||
executor.onCommand(sender, commandAdapter, name, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> suggest(CommandSourceStack commandSourceStack, String[] args) {
|
||||
if (executor instanceof TabCompleter completer) {
|
||||
String[] completionArgs = args.length == 0 ? new String[]{""} : args;
|
||||
return completer.onTabComplete(commandSourceStack.getSender(), commandAdapter, name, completionArgs);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String permission() {
|
||||
return "essentialsc".equals(name) ? null : executor.getPermission();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package cn.infstar.essentialsC;
|
||||
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
/**
|
||||
* 管理主配置与独立功能配置,并负责按顺序执行配置迁移。
|
||||
*/
|
||||
public final class FeatureConfigManager {
|
||||
|
||||
private static final int MAIN_CONFIG_VERSION = 2;
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final File mainConfigFile;
|
||||
private final File blocksMenuFile;
|
||||
private FileConfiguration blocksMenuConfig;
|
||||
|
||||
public FeatureConfigManager(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
this.mainConfigFile = new File(plugin.getDataFolder(), "config.yml");
|
||||
this.blocksMenuFile = new File(plugin.getDataFolder(), "blocks-menu.yml");
|
||||
reload();
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
ensureResource(mainConfigFile, "config.yml");
|
||||
ensureResource(blocksMenuFile, "blocks-menu.yml");
|
||||
|
||||
blocksMenuConfig = loadWithDefaults(blocksMenuFile, "blocks-menu.yml");
|
||||
YamlConfiguration loadedMainConfig = loadWithDefaults(mainConfigFile, "config.yml");
|
||||
YamlConfiguration mainConfig = migrateMainConfigVersion(loadedMainConfig);
|
||||
|
||||
boolean mainChanged = mainConfig != loadedMainConfig;
|
||||
mainChanged |= migrateLegacyMainConfig(mainConfig);
|
||||
mainChanged |= migrateLegacyDebugSettings(mainConfig);
|
||||
mainChanged |= removeRetiredJeiSettings(mainConfig);
|
||||
if (mainConfig.getInt("config-version", 0) != MAIN_CONFIG_VERSION) {
|
||||
mainConfig.set("config-version", MAIN_CONFIG_VERSION);
|
||||
mainChanged = true;
|
||||
}
|
||||
|
||||
if (mainChanged) {
|
||||
save(mainConfig, mainConfigFile);
|
||||
}
|
||||
plugin.reloadConfig();
|
||||
}
|
||||
|
||||
public FileConfiguration getBlocksMenuConfig() {
|
||||
return blocksMenuConfig;
|
||||
}
|
||||
|
||||
public void saveBlocksMenuConfig() {
|
||||
save(blocksMenuConfig, blocksMenuFile);
|
||||
}
|
||||
|
||||
public boolean updateMainConfigValue(String path, Object value) {
|
||||
YamlConfiguration mainConfig = loadWithDefaults(mainConfigFile, "config.yml");
|
||||
mainConfig.set(path, value);
|
||||
if (!save(mainConfig, mainConfigFile)) {
|
||||
return false;
|
||||
}
|
||||
plugin.getConfig().set(path, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
private YamlConfiguration migrateMainConfigVersion(YamlConfiguration existingConfig) {
|
||||
int existingVersion = existingConfig.getInt("config-version", 0);
|
||||
if (existingVersion >= MAIN_CONFIG_VERSION) {
|
||||
return existingConfig;
|
||||
}
|
||||
|
||||
File backupFile = new File(plugin.getDataFolder(),
|
||||
"config.v" + existingVersion + ".bak-" + System.currentTimeMillis() + ".yml");
|
||||
try {
|
||||
Files.copy(mainConfigFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
YamlConfiguration migratedConfig = loadResource("config.yml");
|
||||
if (migratedConfig == null) {
|
||||
existingConfig.set("config-version", MAIN_CONFIG_VERSION);
|
||||
return existingConfig;
|
||||
}
|
||||
|
||||
for (String path : existingConfig.getKeys(true)) {
|
||||
boolean legacyFeaturePath = path.startsWith("skin-bridge.") || path.startsWith("blocks-menu.");
|
||||
if (!existingConfig.isConfigurationSection(path)
|
||||
&& (migratedConfig.contains(path) || legacyFeaturePath)) {
|
||||
migratedConfig.set(path, existingConfig.get(path));
|
||||
}
|
||||
}
|
||||
migratedConfig.set("config-version", MAIN_CONFIG_VERSION);
|
||||
plugin.getLogger().info("已将 config.yml 从版本 " + existingVersion
|
||||
+ " 迁移到 " + MAIN_CONFIG_VERSION + ",备份文件: " + backupFile.getName());
|
||||
return migratedConfig;
|
||||
} catch (IOException exception) {
|
||||
plugin.getLogger().severe("迁移 config.yml 失败: " + exception.getMessage());
|
||||
return existingConfig;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean migrateLegacyMainConfig(FileConfiguration mainConfig) {
|
||||
if (!mainConfig.contains("blocks-menu", true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
copySection(mainConfig.getConfigurationSection("blocks-menu"), blocksMenuConfig);
|
||||
mainConfig.set("blocks-menu", null);
|
||||
saveBlocksMenuConfig();
|
||||
plugin.getLogger().info("已将便捷菜单配置迁移到 blocks-menu.yml。");
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean migrateLegacyDebugSettings(FileConfiguration mainConfig) {
|
||||
boolean hasJeiDebug = mainConfig.contains("jei-sync.debug", true);
|
||||
boolean hasSkinBridgeDebug = mainConfig.contains("skin-bridge.debug", true);
|
||||
if (!hasJeiDebug && !hasSkinBridgeDebug) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean debugEnabled = mainConfig.getBoolean("debug", false)
|
||||
|| mainConfig.getBoolean("jei-sync.debug", false)
|
||||
|| mainConfig.getBoolean("skin-bridge.debug", false);
|
||||
mainConfig.set("debug", debugEnabled);
|
||||
mainConfig.set("jei-sync.debug", null);
|
||||
mainConfig.set("skin-bridge.debug", null);
|
||||
plugin.getLogger().info("已将独立功能调试开关合并到 config.yml 的全局 debug。");
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean removeRetiredJeiSettings(FileConfiguration mainConfig) {
|
||||
if (!mainConfig.contains("jei-sync", true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mainConfig.set("jei-sync", null);
|
||||
plugin.getLogger().info("已从 config.yml 移除停用的 JEI 配方同步配置。");
|
||||
return true;
|
||||
}
|
||||
|
||||
private void copySection(ConfigurationSection source, FileConfiguration target) {
|
||||
if (source == null) {
|
||||
return;
|
||||
}
|
||||
for (String path : source.getKeys(true)) {
|
||||
if (!source.isConfigurationSection(path)) {
|
||||
target.set(path, source.get(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private YamlConfiguration loadWithDefaults(File file, String resourcePath) {
|
||||
YamlConfiguration config = loadFile(file);
|
||||
YamlConfiguration defaults = loadResource(resourcePath);
|
||||
if (defaults != null) {
|
||||
config.setDefaults(defaults);
|
||||
config.options().copyDefaults(true);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private YamlConfiguration loadFile(File file) {
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
config.options().parseComments(true);
|
||||
try {
|
||||
config.load(file);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
plugin.getLogger().severe("加载 " + file.getName() + " 失败: " + exception.getMessage());
|
||||
throw new IllegalStateException("无法加载 " + file.getName() + ",请修复配置格式后重试。", exception);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private YamlConfiguration loadResource(String resourcePath) {
|
||||
InputStream resource = plugin.getResource(resourcePath);
|
||||
if (resource == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
config.options().parseComments(true);
|
||||
try (InputStream input = resource;
|
||||
InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) {
|
||||
config.load(reader);
|
||||
return config;
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
plugin.getLogger().severe("加载内置资源 " + resourcePath + " 失败: " + exception.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureResource(File file, String resourcePath) {
|
||||
if (!file.exists()) {
|
||||
plugin.saveResource(resourcePath, false);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean save(FileConfiguration config, File file) {
|
||||
try {
|
||||
AtomicYamlWriter.save(config, file);
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
plugin.getLogger().warning("保存 " + file.getName() + " 失败: " + exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,152 +1,250 @@
|
||||
package cn.infstar.essentialsC;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class LangManager {
|
||||
|
||||
|
||||
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("(?i)&#([0-9a-f]{6})");
|
||||
private static final Pattern MINI_MESSAGE_TAG_PATTERN = Pattern.compile(
|
||||
"(?<!\\\\)(</?)([A-Za-z][A-Za-z0-9_-]*)(?=[:>])"
|
||||
);
|
||||
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
|
||||
private static final LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.legacyAmpersand();
|
||||
private static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection();
|
||||
private static final Map<String, String> THEME_COLORS = Map.of(
|
||||
"&a", "�fb9a",
|
||||
"&b", "ᒦff",
|
||||
"&c", "&#ff7e5e",
|
||||
"&d", "&#c160ff",
|
||||
"&e", "&#ffc43b",
|
||||
"&6", "&#f5c962"
|
||||
);
|
||||
|
||||
private final JavaPlugin plugin;
|
||||
private FileConfiguration config;
|
||||
private FileConfiguration langFile;
|
||||
private String currentLanguage;
|
||||
|
||||
|
||||
public LangManager(JavaPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
loadConfig();
|
||||
loadLanguage();
|
||||
}
|
||||
|
||||
private void loadConfig() {
|
||||
File configFile = new File(plugin.getDataFolder(), "config.yml");
|
||||
|
||||
if (!configFile.exists()) {
|
||||
plugin.saveResource("config.yml", false);
|
||||
}
|
||||
|
||||
config = YamlConfiguration.loadConfiguration(configFile);
|
||||
|
||||
// 设置默认值
|
||||
config.addDefault("language", "zh_CN");
|
||||
config.addDefault("settings.enable-feedback", true);
|
||||
config.addDefault("settings.message-prefix", "&6[EssentialsC] &r");
|
||||
config.options().copyDefaults(true);
|
||||
|
||||
try {
|
||||
config.save(configFile);
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().severe("无法保存配置文件: " + e.getMessage());
|
||||
}
|
||||
|
||||
public String getPrefix() {
|
||||
return renderToLegacy(langFile.getString("prefix", "&6[EssentialsC] &r"));
|
||||
}
|
||||
|
||||
private void loadLanguage() {
|
||||
currentLanguage = config.getString("language", "zh_CN");
|
||||
|
||||
File langFolder = new File(plugin.getDataFolder(), "lang");
|
||||
if (!langFolder.exists()) {
|
||||
langFolder.mkdirs();
|
||||
|
||||
public String getString(String path) {
|
||||
String value = langFile.getString(path);
|
||||
if (value == null) {
|
||||
return translateColorCodes("&c缺少语言文本: " + path);
|
||||
}
|
||||
|
||||
return renderToLegacy(value);
|
||||
}
|
||||
|
||||
public String getString(String path, Map<String, String> placeholders) {
|
||||
String value = langFile.getString(path);
|
||||
if (value == null) {
|
||||
return translateColorCodes("&c缺少语言文本: " + path);
|
||||
}
|
||||
return renderToLegacy(applyPlaceholders(value, placeholders));
|
||||
}
|
||||
|
||||
public Component getComponent(String path) {
|
||||
return getComponent(path, Map.of());
|
||||
}
|
||||
|
||||
public Component getComponent(String path, Map<String, String> placeholders) {
|
||||
String value = langFile.getString(path);
|
||||
if (value == null) {
|
||||
return LEGACY_SECTION.deserialize(translateColorCodes("&c缺少语言文本: " + path));
|
||||
}
|
||||
|
||||
return renderToComponent(applyPlaceholders(value, placeholders));
|
||||
}
|
||||
|
||||
public Component getPrefixedComponent(String path) {
|
||||
return getPrefixedComponent(path, Map.of());
|
||||
}
|
||||
|
||||
public Component getPrefixedComponent(String path, Map<String, String> placeholders) {
|
||||
String value = langFile.getString(path);
|
||||
if (value == null) {
|
||||
return LEGACY_SECTION.deserialize(getPrefix() + translateColorCodes("&c缺少语言文本: " + path));
|
||||
}
|
||||
return renderToComponent(langFile.getString("prefix", "") + applyPlaceholders(value, placeholders));
|
||||
}
|
||||
|
||||
public String getPrefixedString(String path) {
|
||||
return getPrefix() + getString(path);
|
||||
}
|
||||
|
||||
public String getPrefixedString(String path, Map<String, String> placeholders) {
|
||||
return getPrefix() + getString(path, placeholders);
|
||||
}
|
||||
|
||||
public List<String> getStringList(String path) {
|
||||
List<String> values = langFile.getStringList(path);
|
||||
if (values.isEmpty()) {
|
||||
values = List.of("&c缺少语言文本: " + path);
|
||||
}
|
||||
|
||||
List<String> translated = new ArrayList<>();
|
||||
for (String value : values) {
|
||||
translated.add(renderToLegacy(value));
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
loadLanguage();
|
||||
}
|
||||
|
||||
public String getCurrentLanguage() {
|
||||
return currentLanguage;
|
||||
}
|
||||
|
||||
private void loadLanguage() {
|
||||
currentLanguage = plugin.getConfig().getString("language", "zh_CN");
|
||||
|
||||
File langFolder = new File(plugin.getDataFolder(), "lang");
|
||||
if (!langFolder.exists() && !langFolder.mkdirs()) {
|
||||
plugin.getLogger().warning("创建语言文件夹失败: " + langFolder.getAbsolutePath());
|
||||
}
|
||||
|
||||
File langFileObj = new File(langFolder, currentLanguage + ".yml");
|
||||
|
||||
// 如果语言文件不存在,从资源中复制
|
||||
if (!langFileObj.exists()) {
|
||||
InputStream inputStream = plugin.getResource("lang/" + currentLanguage + ".yml");
|
||||
if (inputStream != null) {
|
||||
if (plugin.getResource("lang/" + currentLanguage + ".yml") != null) {
|
||||
plugin.saveResource("lang/" + currentLanguage + ".yml", false);
|
||||
} else {
|
||||
plugin.getLogger().warning("未找到语言文件: " + currentLanguage + ".yml,使用默认语言 en_US");
|
||||
plugin.getLogger().warning("未找到语言文件: " + currentLanguage + ".yml,已回退到 en_US");
|
||||
currentLanguage = "en_US";
|
||||
plugin.saveResource("lang/en_US.yml", false);
|
||||
langFileObj = new File(langFolder, "en_US.yml");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
langFile = YamlConfiguration.loadConfiguration(langFileObj);
|
||||
|
||||
// 尝试加载默认语言作为后备
|
||||
if (!currentLanguage.equals("en_US")) {
|
||||
InputStream defaultLangStream = plugin.getResource("lang/en_US.yml");
|
||||
if (defaultLangStream != null) {
|
||||
YamlConfiguration defaultLang = YamlConfiguration.loadConfiguration(
|
||||
new InputStreamReader(defaultLangStream, StandardCharsets.UTF_8)
|
||||
loadDefaultLanguageFallback();
|
||||
}
|
||||
|
||||
private void loadDefaultLanguageFallback() {
|
||||
InputStream selectedLangStream = plugin.getResource("lang/" + currentLanguage + ".yml");
|
||||
if (selectedLangStream == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
YamlConfiguration selectedDefaults = YamlConfiguration.loadConfiguration(
|
||||
new InputStreamReader(selectedLangStream, StandardCharsets.UTF_8)
|
||||
);
|
||||
if (!"en_US".equalsIgnoreCase(currentLanguage)) {
|
||||
InputStream englishLangStream = plugin.getResource("lang/en_US.yml");
|
||||
if (englishLangStream != null) {
|
||||
YamlConfiguration englishDefaults = YamlConfiguration.loadConfiguration(
|
||||
new InputStreamReader(englishLangStream, StandardCharsets.UTF_8)
|
||||
);
|
||||
langFile.setDefaults(defaultLang);
|
||||
selectedDefaults.setDefaults(englishDefaults);
|
||||
}
|
||||
}
|
||||
langFile.setDefaults(selectedDefaults);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件前缀
|
||||
*/
|
||||
public String getPrefix() {
|
||||
return translateColorCodes(langFile.getString("prefix", "&6[EssentialsC] &r"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取翻译文本
|
||||
*/
|
||||
public String getString(String path) {
|
||||
String value = langFile.getString(path);
|
||||
if (value == null) {
|
||||
return "&cMissing translation: " + path;
|
||||
}
|
||||
return translateColorCodes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取翻译文本并替换占位符
|
||||
*/
|
||||
public String getString(String path, Map<String, String> placeholders) {
|
||||
String value = getString(path);
|
||||
|
||||
static String applyPlaceholders(String value, Map<String, String> placeholders) {
|
||||
String result = value;
|
||||
boolean miniMessage = looksLikeMiniMessage(value);
|
||||
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
|
||||
value = value.replace("{" + entry.getKey() + "}", entry.getValue());
|
||||
String replacement = miniMessage
|
||||
? escapeMiniMessageReplacement(entry.getValue())
|
||||
: entry.getValue();
|
||||
result = result.replace("{" + entry.getKey() + "}", replacement == null ? "" : replacement);
|
||||
}
|
||||
return value;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字符串列表(用于 Lore 等多行文本)
|
||||
*/
|
||||
public java.util.List<String> getStringList(String path) {
|
||||
java.util.List<String> values = langFile.getStringList(path);
|
||||
if (values.isEmpty()) {
|
||||
// 如果找不到,返回包含错误信息的列表
|
||||
return java.util.Arrays.asList("&cMissing translation: " + path);
|
||||
|
||||
static String escapeMiniMessageReplacement(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
// 翻译颜色代码
|
||||
java.util.List<String> translated = new java.util.ArrayList<>();
|
||||
for (String value : values) {
|
||||
translated.add(translateColorCodes(value));
|
||||
if (value.indexOf('§') >= 0) {
|
||||
return MINI_MESSAGE.serialize(LEGACY_SECTION.deserialize(value));
|
||||
}
|
||||
return translated;
|
||||
return value.replace("\\", "\\\\").replace("<", "\\<");
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新加载配置和语言
|
||||
*/
|
||||
public void reload() {
|
||||
loadConfig();
|
||||
loadLanguage();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前语言
|
||||
*/
|
||||
public String getCurrentLanguage() {
|
||||
return currentLanguage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 翻译颜色代码
|
||||
*/
|
||||
|
||||
private String translateColorCodes(String text) {
|
||||
return text.replace("&", "§");
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String themedText = text;
|
||||
for (Map.Entry<String, String> color : THEME_COLORS.entrySet()) {
|
||||
themedText = themedText.replace(color.getKey(), color.getValue());
|
||||
}
|
||||
return LEGACY_SECTION.serialize(LEGACY_AMPERSAND.deserialize(expandHexColors(themedText)));
|
||||
}
|
||||
|
||||
private String expandHexColors(String text) {
|
||||
Matcher matcher = HEX_COLOR_PATTERN.matcher(text);
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
String hex = matcher.group(1);
|
||||
StringBuilder legacyHex = new StringBuilder("&x");
|
||||
for (char digit : hex.toCharArray()) {
|
||||
legacyHex.append('&').append(digit);
|
||||
}
|
||||
matcher.appendReplacement(result, Matcher.quoteReplacement(legacyHex.toString()));
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String renderToLegacy(String text) {
|
||||
return LEGACY_SECTION.serialize(renderToComponent(text));
|
||||
}
|
||||
|
||||
private Component renderToComponent(String text) {
|
||||
if (text == null) {
|
||||
return Component.empty();
|
||||
}
|
||||
if (looksLikeMiniMessage(text)) {
|
||||
try {
|
||||
return MINI_MESSAGE.deserialize(normalizeMiniMessageTags(text));
|
||||
} catch (RuntimeException ignored) {
|
||||
// 配置中 MiniMessage 语法错误时回退到旧颜色码解析,避免消息完全不可用。
|
||||
}
|
||||
}
|
||||
return LEGACY_SECTION.deserialize(translateColorCodes(text));
|
||||
}
|
||||
|
||||
private static boolean looksLikeMiniMessage(String text) {
|
||||
int open = text.indexOf('<');
|
||||
return open >= 0 && text.indexOf('>', open) > open;
|
||||
}
|
||||
|
||||
static String normalizeMiniMessageTags(String text) {
|
||||
Matcher matcher = MINI_MESSAGE_TAG_PATTERN.matcher(text);
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
matcher.appendReplacement(result, Matcher.quoteReplacement(
|
||||
matcher.group(1) + matcher.group(2).toLowerCase(java.util.Locale.ROOT)
|
||||
));
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package cn.infstar.essentialsC;
|
||||
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class ModuleManager {
|
||||
|
||||
private static final int CURRENT_CONFIG_VERSION = 1;
|
||||
|
||||
public static final String BLOCKS = "blocks";
|
||||
public static final String ADMIN_MODE = "admin-mode";
|
||||
public static final String TPSBAR = "tpsbar";
|
||||
public static final String MOB_DROPS = "mob-drops";
|
||||
public static final String SKIN_BRIDGE = "skin-bridge";
|
||||
|
||||
private static final Map<String, Boolean> DEFAULT_MODULES = new LinkedHashMap<>();
|
||||
|
||||
static {
|
||||
DEFAULT_MODULES.put(BLOCKS, true);
|
||||
DEFAULT_MODULES.put(ADMIN_MODE, true);
|
||||
DEFAULT_MODULES.put(TPSBAR, true);
|
||||
DEFAULT_MODULES.put(MOB_DROPS, false);
|
||||
DEFAULT_MODULES.put(SKIN_BRIDGE, false);
|
||||
}
|
||||
|
||||
private final JavaPlugin plugin;
|
||||
private final File modulesFile;
|
||||
private FileConfiguration modulesConfig;
|
||||
|
||||
public ModuleManager(JavaPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.modulesFile = new File(plugin.getDataFolder(), "modules.yml");
|
||||
reload();
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
if (!modulesFile.exists()) {
|
||||
plugin.saveResource("modules.yml", false);
|
||||
}
|
||||
|
||||
YamlConfiguration loaded = new YamlConfiguration();
|
||||
loaded.options().parseComments(true);
|
||||
try {
|
||||
loaded.load(modulesFile);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
plugin.getLogger().severe("加载 modules.yml 失败: " + exception.getMessage());
|
||||
throw new IllegalStateException("无法加载 modules.yml,请修复配置格式后重试。", exception);
|
||||
}
|
||||
modulesConfig = loaded;
|
||||
boolean removedRetiredModules = false;
|
||||
for (String retiredModule : new String[]{"jei-sync", "maintenance"}) {
|
||||
String retiredPath = "modules." + retiredModule;
|
||||
if (modulesConfig.contains(retiredPath, true)) {
|
||||
modulesConfig.set(retiredPath, null);
|
||||
removedRetiredModules = true;
|
||||
}
|
||||
}
|
||||
modulesConfig.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
||||
for (Map.Entry<String, Boolean> module : DEFAULT_MODULES.entrySet()) {
|
||||
modulesConfig.addDefault(path(module.getKey()), module.getValue());
|
||||
}
|
||||
modulesConfig.options().copyDefaults(true);
|
||||
if (removedRetiredModules) {
|
||||
try {
|
||||
AtomicYamlWriter.save(modulesConfig, modulesFile);
|
||||
plugin.getLogger().info("已从 modules.yml 移除退役功能的配置项。");
|
||||
} catch (IOException exception) {
|
||||
plugin.getLogger().warning("清理 modules.yml 中的退役配置失败: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled(String moduleKey) {
|
||||
if (moduleKey == null || moduleKey.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
return modulesConfig.getBoolean(path(moduleKey), true);
|
||||
}
|
||||
|
||||
private String path(String moduleKey) {
|
||||
return "modules." + moduleKey + ".enabled";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
package cn.infstar.essentialsC.admin;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class AdminModeManager implements Listener {
|
||||
|
||||
private static final float VANILLA_FLY_SPEED = 0.1F;
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final AdminModeStore store;
|
||||
private final Set<UUID> activePlayers = new HashSet<>();
|
||||
|
||||
private BukkitTask actionBarTask;
|
||||
|
||||
public AdminModeManager(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
addConfigDefaults();
|
||||
this.store = new AdminModeStore(plugin);
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
if (actionBarTask != null) {
|
||||
actionBarTask.cancel();
|
||||
actionBarTask = null;
|
||||
}
|
||||
float flySpeed = getAdminFlySpeed();
|
||||
for (UUID uuid : new ArrayList<>(activePlayers)) {
|
||||
Player player = plugin.getServer().getPlayer(uuid);
|
||||
if (player != null && player.isOnline()) {
|
||||
player.setFlySpeed(flySpeed);
|
||||
}
|
||||
}
|
||||
if (!activePlayers.isEmpty()) {
|
||||
startActionBarTask();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAdminMode(Player player) {
|
||||
return activePlayers.contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
public void toggle(Player player) {
|
||||
if (isAdminMode(player)) {
|
||||
disable(player, true);
|
||||
} else {
|
||||
enable(player);
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
for (UUID uuid : new ArrayList<>(activePlayers)) {
|
||||
Player player = plugin.getServer().getPlayer(uuid);
|
||||
if (player != null) {
|
||||
disable(player, false);
|
||||
}
|
||||
}
|
||||
|
||||
if (actionBarTask != null) {
|
||||
actionBarTask.cancel();
|
||||
actionBarTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
YamlConfiguration data = store.load(player.getUniqueId());
|
||||
if (data == null) {
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
return;
|
||||
}
|
||||
if (!data.getBoolean("active", false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
saveProfile(player, data, "admin");
|
||||
if (!saveData(player, data)) {
|
||||
activePlayers.add(player.getUniqueId());
|
||||
startActionBarTask();
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
return;
|
||||
}
|
||||
restoreNormalProfile(player, data);
|
||||
data.set("active", false);
|
||||
if (!saveData(player, data)) {
|
||||
data.set("active", true);
|
||||
loadProfile(player, data, "admin");
|
||||
activePlayers.add(player.getUniqueId());
|
||||
startActionBarTask();
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
return;
|
||||
}
|
||||
sendLangMessage(player, "admin-mode.messages.crash-restored");
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if (isAdminMode(player)) {
|
||||
disable(player, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void enable(Player player) {
|
||||
YamlConfiguration data = store.load(player.getUniqueId());
|
||||
if (data == null) {
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
return;
|
||||
}
|
||||
player.closeInventory();
|
||||
saveProfile(player, data, "normal");
|
||||
data.set("active", true);
|
||||
if (!saveData(player, data)) {
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
data.set("active", false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!loadProfile(player, data, "admin")) {
|
||||
clearInventory(player);
|
||||
}
|
||||
|
||||
activePlayers.add(player.getUniqueId());
|
||||
|
||||
player.setGameMode(GameMode.CREATIVE);
|
||||
player.setAllowFlight(true);
|
||||
player.setFlying(true);
|
||||
player.setFlySpeed(getAdminFlySpeed());
|
||||
|
||||
sendLangMessage(player, "admin-mode.messages.enabled");
|
||||
sendActionBar(player);
|
||||
startActionBarTask();
|
||||
}
|
||||
|
||||
private boolean disable(Player player, boolean notify) {
|
||||
YamlConfiguration data = store.load(player.getUniqueId());
|
||||
if (data == null) {
|
||||
if (notify) {
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
player.closeInventory();
|
||||
saveProfile(player, data, "admin");
|
||||
data.set("active", true);
|
||||
if (!saveData(player, data)) {
|
||||
if (notify) {
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
restoreNormalProfile(player, data);
|
||||
|
||||
data.set("active", false);
|
||||
if (!saveData(player, data)) {
|
||||
data.set("active", true);
|
||||
loadProfile(player, data, "admin");
|
||||
activePlayers.add(player.getUniqueId());
|
||||
if (notify) {
|
||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
activePlayers.remove(player.getUniqueId());
|
||||
|
||||
if (notify) {
|
||||
sendLangMessage(player, "admin-mode.messages.disabled");
|
||||
}
|
||||
stopActionBarTaskIfIdle();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void restoreNormalProfile(Player player, YamlConfiguration data) {
|
||||
if (!loadProfile(player, data, "normal")) {
|
||||
clearInventory(player);
|
||||
player.setGameMode(GameMode.SURVIVAL);
|
||||
player.setAllowFlight(false);
|
||||
player.setFlying(false);
|
||||
player.setFlySpeed(VANILLA_FLY_SPEED);
|
||||
}
|
||||
}
|
||||
|
||||
private void saveProfile(Player player, YamlConfiguration data, String path) {
|
||||
PlayerInventory inventory = player.getInventory();
|
||||
data.set(path + ".storage", Arrays.asList(inventory.getStorageContents()));
|
||||
data.set(path + ".armor", Arrays.asList(inventory.getArmorContents()));
|
||||
data.set(path + ".extra", Arrays.asList(inventory.getExtraContents()));
|
||||
data.set(path + ".cursor", player.getItemOnCursor());
|
||||
data.set(path + ".held-slot", inventory.getHeldItemSlot());
|
||||
data.set(path + ".game-mode", player.getGameMode().name());
|
||||
data.set(path + ".allow-flight", player.getAllowFlight());
|
||||
data.set(path + ".flying", player.isFlying());
|
||||
data.set(path + ".fly-speed", player.getFlySpeed());
|
||||
data.set(path + ".health", player.getHealth());
|
||||
data.set(path + ".food-level", player.getFoodLevel());
|
||||
data.set(path + ".saturation", player.getSaturation());
|
||||
data.set(path + ".exhaustion", player.getExhaustion());
|
||||
data.set(path + ".exp", player.getExp());
|
||||
data.set(path + ".level", player.getLevel());
|
||||
data.set(path + ".total-experience", player.getTotalExperience());
|
||||
data.set(path + ".fire-ticks", player.getFireTicks());
|
||||
}
|
||||
|
||||
private boolean loadProfile(Player player, YamlConfiguration data, String path) {
|
||||
if (!data.contains(path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
PlayerInventory inventory = player.getInventory();
|
||||
clearInventory(player);
|
||||
inventory.setStorageContents(readItemArray(data, path + ".storage", inventory.getStorageContents().length));
|
||||
inventory.setArmorContents(readItemArray(data, path + ".armor", inventory.getArmorContents().length));
|
||||
inventory.setExtraContents(readItemArray(data, path + ".extra", inventory.getExtraContents().length));
|
||||
inventory.setHeldItemSlot(clampHeldSlot(data.getInt(path + ".held-slot", inventory.getHeldItemSlot())));
|
||||
player.setItemOnCursor(readItem(data, path + ".cursor"));
|
||||
|
||||
player.setGameMode(readGameMode(data, path + ".game-mode", player.getGameMode()));
|
||||
player.setAllowFlight(data.getBoolean(path + ".allow-flight", player.getAllowFlight()));
|
||||
player.setFlying(data.getBoolean(path + ".flying", false) && player.getAllowFlight());
|
||||
player.setFlySpeed(clampFlySpeed(data.getDouble(path + ".fly-speed", VANILLA_FLY_SPEED)));
|
||||
player.setHealth(readHealth(player, data, path + ".health"));
|
||||
player.setFoodLevel(clampFoodLevel(data.getInt(path + ".food-level", player.getFoodLevel())));
|
||||
player.setSaturation(clampSaturation(data.getDouble(path + ".saturation", player.getSaturation())));
|
||||
player.setExhaustion(clampExhaustion(data.getDouble(path + ".exhaustion", player.getExhaustion())));
|
||||
player.setExp(clampExp(data.getDouble(path + ".exp", player.getExp())));
|
||||
player.setLevel(Math.max(0, data.getInt(path + ".level", player.getLevel())));
|
||||
player.setTotalExperience(Math.max(0, data.getInt(path + ".total-experience", player.getTotalExperience())));
|
||||
player.setFireTicks(Math.max(0, data.getInt(path + ".fire-ticks", player.getFireTicks())));
|
||||
return true;
|
||||
}
|
||||
|
||||
private ItemStack[] readItemArray(YamlConfiguration data, String path, int size) {
|
||||
ItemStack[] items = new ItemStack[size];
|
||||
List<?> list = data.getList(path);
|
||||
if (list == null) {
|
||||
return items;
|
||||
}
|
||||
|
||||
for (int index = 0; index < Math.min(size, list.size()); index++) {
|
||||
Object value = list.get(index);
|
||||
if (value instanceof ItemStack itemStack) {
|
||||
items[index] = itemStack;
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private GameMode readGameMode(YamlConfiguration data, String path, GameMode fallback) {
|
||||
try {
|
||||
return GameMode.valueOf(data.getString(path, fallback.name()));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private double readHealth(Player player, YamlConfiguration data, String path) {
|
||||
double maxHealth = player.getAttribute(Attribute.MAX_HEALTH) != null
|
||||
? player.getAttribute(Attribute.MAX_HEALTH).getValue()
|
||||
: player.getHealth();
|
||||
double health = data.getDouble(path, player.getHealth());
|
||||
if (!Double.isFinite(health)) {
|
||||
return Math.min(Math.max(1.0D, player.getHealth()), maxHealth);
|
||||
}
|
||||
return Math.min(Math.max(1.0D, health), maxHealth);
|
||||
}
|
||||
|
||||
private ItemStack readItem(YamlConfiguration data, String path) {
|
||||
Object value = data.get(path);
|
||||
if (value instanceof ItemStack itemStack) {
|
||||
return itemStack;
|
||||
}
|
||||
return new ItemStack(Material.AIR);
|
||||
}
|
||||
|
||||
private void clearInventory(Player player) {
|
||||
PlayerInventory inventory = player.getInventory();
|
||||
inventory.clear();
|
||||
inventory.setArmorContents(new ItemStack[inventory.getArmorContents().length]);
|
||||
inventory.setExtraContents(new ItemStack[inventory.getExtraContents().length]);
|
||||
player.setItemOnCursor(new ItemStack(Material.AIR));
|
||||
}
|
||||
|
||||
private void startActionBarTask() {
|
||||
if (actionBarTask != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
int interval = Math.max(10, plugin.getConfig().getInt("admin-mode.actionbar.interval-ticks", 40));
|
||||
actionBarTask = plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
|
||||
for (UUID uuid : new ArrayList<>(activePlayers)) {
|
||||
Player player = plugin.getServer().getPlayer(uuid);
|
||||
if (player != null && player.isOnline()) {
|
||||
sendActionBar(player);
|
||||
}
|
||||
}
|
||||
stopActionBarTaskIfIdle();
|
||||
}, 0L, interval);
|
||||
}
|
||||
|
||||
private void stopActionBarTaskIfIdle() {
|
||||
if (!activePlayers.isEmpty() || actionBarTask == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
actionBarTask.cancel();
|
||||
actionBarTask = null;
|
||||
}
|
||||
|
||||
private void sendActionBar(Player player) {
|
||||
player.sendActionBar(EssentialsC.getLangManager().getComponent("admin-mode.actionbar"));
|
||||
}
|
||||
|
||||
private float getAdminFlySpeed() {
|
||||
double speed = plugin.getConfig().getDouble("admin-mode.fly-speed", 0.2D);
|
||||
return clampFlySpeed(speed);
|
||||
}
|
||||
|
||||
private float clampFlySpeed(double speed) {
|
||||
if (!Double.isFinite(speed)) {
|
||||
return VANILLA_FLY_SPEED;
|
||||
}
|
||||
return (float) Math.max(-1.0D, Math.min(1.0D, speed));
|
||||
}
|
||||
|
||||
private int clampHeldSlot(int slot) {
|
||||
return Math.max(0, Math.min(8, slot));
|
||||
}
|
||||
|
||||
private int clampFoodLevel(int foodLevel) {
|
||||
return Math.max(0, Math.min(20, foodLevel));
|
||||
}
|
||||
|
||||
private float clampSaturation(double saturation) {
|
||||
if (!Double.isFinite(saturation)) {
|
||||
return 0.0F;
|
||||
}
|
||||
return (float) Math.max(0.0D, Math.min(20.0D, saturation));
|
||||
}
|
||||
|
||||
private float clampExhaustion(double exhaustion) {
|
||||
if (!Double.isFinite(exhaustion)) {
|
||||
return 0.0F;
|
||||
}
|
||||
return (float) Math.max(0.0D, exhaustion);
|
||||
}
|
||||
|
||||
private float clampExp(double exp) {
|
||||
if (!Double.isFinite(exp)) {
|
||||
return 0.0F;
|
||||
}
|
||||
return (float) Math.max(0.0D, Math.min(1.0D, exp));
|
||||
}
|
||||
|
||||
private void sendLangMessage(Player player, String path) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(path));
|
||||
}
|
||||
|
||||
private boolean saveData(Player player, YamlConfiguration data) {
|
||||
return store.save(player.getUniqueId(), data);
|
||||
}
|
||||
|
||||
private void addConfigDefaults() {
|
||||
plugin.getConfig().addDefault("admin-mode.fly-speed", 0.2D);
|
||||
plugin.getConfig().addDefault("admin-mode.actionbar.interval-ticks", 40);
|
||||
plugin.getConfig().options().copyDefaults(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package cn.infstar.essentialsC.admin;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
final class AdminModeStore {
|
||||
|
||||
private final File directory;
|
||||
private final File legacyFile;
|
||||
private final Logger logger;
|
||||
|
||||
AdminModeStore(EssentialsC plugin) {
|
||||
this(new File(plugin.getDataFolder(), "admin-mode"),
|
||||
new File(plugin.getDataFolder(), "admin-mode.yml"), plugin.getLogger());
|
||||
}
|
||||
|
||||
AdminModeStore(File directory, File legacyFile, Logger logger) {
|
||||
this.directory = directory;
|
||||
this.legacyFile = legacyFile;
|
||||
this.logger = logger;
|
||||
migrateLegacyFile();
|
||||
}
|
||||
|
||||
YamlConfiguration load(UUID playerId) {
|
||||
File playerFile = getPlayerFile(playerId);
|
||||
YamlConfiguration data = new YamlConfiguration();
|
||||
if (!playerFile.exists()) {
|
||||
return data;
|
||||
}
|
||||
try {
|
||||
data.load(playerFile);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
logger.warning("加载管理模式玩家存档失败 (" + playerId + "): " + exception.getMessage());
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
boolean save(UUID playerId, YamlConfiguration data) {
|
||||
try {
|
||||
AtomicYamlWriter.save(data, getPlayerFile(playerId));
|
||||
return true;
|
||||
} catch (IOException exception) {
|
||||
logger.warning("保存管理模式玩家存档失败 (" + playerId + "): " + exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void migrateLegacyFile() {
|
||||
if (!legacyFile.exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
YamlConfiguration legacy = new YamlConfiguration();
|
||||
try {
|
||||
legacy.load(legacyFile);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
logger.warning("加载旧 admin-mode.yml 失败,已保留原文件: " + exception.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
ConfigurationSection players = legacy.getConfigurationSection("players");
|
||||
if (players != null) {
|
||||
for (String playerIdText : players.getKeys(false)) {
|
||||
UUID playerId;
|
||||
try {
|
||||
playerId = UUID.fromString(playerIdText);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
logger.warning("忽略 admin-mode.yml 中无效的玩家 UUID: " + playerIdText);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (getPlayerFile(playerId).exists()) {
|
||||
continue;
|
||||
}
|
||||
YamlConfiguration migrated = new YamlConfiguration();
|
||||
copySection(players.getConfigurationSection(playerIdText), migrated);
|
||||
if (!save(playerId, migrated)) {
|
||||
logger.warning("admin-mode.yml 迁移未完成,已保留原文件供下次重试。");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File backup = new File(legacyFile.getParentFile(),
|
||||
"admin-mode.legacy-" + System.currentTimeMillis() + ".yml");
|
||||
try {
|
||||
Files.move(legacyFile.toPath(), backup.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
logger.info("已将 admin-mode.yml 拆分为每玩家存档,旧文件已备份为 " + backup.getName());
|
||||
} catch (IOException exception) {
|
||||
logger.warning("备份旧 admin-mode.yml 失败: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void copySection(ConfigurationSection source, YamlConfiguration target) {
|
||||
if (source == null) {
|
||||
return;
|
||||
}
|
||||
for (String path : source.getKeys(true)) {
|
||||
if (!source.isConfigurationSection(path)) {
|
||||
target.set(path, source.get(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private File getPlayerFile(UUID playerId) {
|
||||
return new File(directory, playerId + ".yml");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.infstar.essentialsC.api.event;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
public final class TeleportEvent extends Event implements Cancellable {
|
||||
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player player;
|
||||
private final TeleportRequest request;
|
||||
private Location destination;
|
||||
private boolean cancelled;
|
||||
|
||||
public TeleportEvent(Player player, TeleportRequest request, Location destination) {
|
||||
this.player = player;
|
||||
this.request = request;
|
||||
this.destination = destination.clone();
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public TeleportRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public Location getDestination() {
|
||||
return destination.clone();
|
||||
}
|
||||
|
||||
public void setDestination(Location destination) {
|
||||
this.destination = destination.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cn.infstar.essentialsC.api.event;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
public final class TeleportRequestReceiveEvent extends Event implements Cancellable {
|
||||
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player recipient;
|
||||
private final TeleportRequest request;
|
||||
private boolean cancelled;
|
||||
|
||||
public TeleportRequestReceiveEvent(Player recipient, TeleportRequest request) {
|
||||
this.recipient = recipient;
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public Player getRecipient() {
|
||||
return recipient;
|
||||
}
|
||||
|
||||
public TeleportRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cn.infstar.essentialsC.api.event;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
public final class TeleportRequestReplyEvent extends Event implements Cancellable {
|
||||
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player recipient;
|
||||
private final TeleportRequest request;
|
||||
private boolean cancelled;
|
||||
|
||||
public TeleportRequestReplyEvent(Player recipient, TeleportRequest request) {
|
||||
this.recipient = recipient;
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public Player getRecipient() {
|
||||
return recipient;
|
||||
}
|
||||
|
||||
public TeleportRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public boolean isAccepted() {
|
||||
return request.status() == TeleportRequest.Status.ACCEPTED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cn.infstar.essentialsC.api.event;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
public final class TeleportRequestSendEvent extends Event implements Cancellable {
|
||||
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player sender;
|
||||
private final TeleportRequest request;
|
||||
private boolean cancelled;
|
||||
|
||||
public TeleportRequestSendEvent(Player sender, TeleportRequest request) {
|
||||
this.sender = sender;
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public Player getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public TeleportRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.infstar.essentialsC.api.event;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
public final class TeleportWarmupCancelledEvent extends Event {
|
||||
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player player;
|
||||
private final TeleportRequest request;
|
||||
private final int durationSeconds;
|
||||
private final int elapsedSeconds;
|
||||
private final Reason reason;
|
||||
|
||||
public TeleportWarmupCancelledEvent(Player player, TeleportRequest request, int durationSeconds,
|
||||
int elapsedSeconds, Reason reason) {
|
||||
this.player = player;
|
||||
this.request = request;
|
||||
this.durationSeconds = durationSeconds;
|
||||
this.elapsedSeconds = elapsedSeconds;
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public TeleportRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public int getDurationSeconds() {
|
||||
return durationSeconds;
|
||||
}
|
||||
|
||||
public int getElapsedSeconds() {
|
||||
return elapsedSeconds;
|
||||
}
|
||||
|
||||
public Reason getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public enum Reason {
|
||||
PLAYER_MOVE,
|
||||
PLAYER_DAMAGE,
|
||||
PLAYER_QUIT,
|
||||
PLUGIN_SHUTDOWN
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cn.infstar.essentialsC.api.event;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
public final class TeleportWarmupEvent extends Event implements Cancellable {
|
||||
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player player;
|
||||
private final TeleportRequest request;
|
||||
private final int durationSeconds;
|
||||
private boolean cancelled;
|
||||
|
||||
public TeleportWarmupEvent(Player player, TeleportRequest request, int durationSeconds) {
|
||||
this.player = player;
|
||||
this.request = request;
|
||||
this.durationSeconds = durationSeconds;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public TeleportRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public int getDurationSeconds() {
|
||||
return durationSeconds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class AdminCommand extends BaseCommand {
|
||||
|
||||
public AdminCommand() {
|
||||
super("essentialsc.command.admin");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (plugin.getAdminModeManager() == null) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
plugin.getAdminModeManager().toggle(player);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class AnvilCommand extends BaseCommand {
|
||||
|
||||
|
||||
public AnvilCommand() {
|
||||
super("essentialsc.command.anvil");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 使用 Paper API 打开铁砧(标题跟随客户端语言)
|
||||
player.openAnvil(null, true);
|
||||
player.openInventory(MenuType.ANVIL.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.ANVIL, Sound.BLOCK_ANVIL_USE);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,51 +2,87 @@ package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.LangManager;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.SoundGroup;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class BaseCommand implements CommandExecutor {
|
||||
|
||||
|
||||
protected String permission;
|
||||
protected static cn.infstar.essentialsC.EssentialsC plugin;
|
||||
|
||||
protected static EssentialsC plugin;
|
||||
|
||||
public BaseCommand(String permission) {
|
||||
this.permission = permission;
|
||||
if (plugin == null) {
|
||||
plugin = cn.infstar.essentialsC.EssentialsC.getPlugin(cn.infstar.essentialsC.EssentialsC.class);
|
||||
plugin = EssentialsC.getPlugin(EssentialsC.class);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public String getPermission() {
|
||||
return permission;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取语言管理器
|
||||
*/
|
||||
|
||||
protected LangManager getLang() {
|
||||
return EssentialsC.getLangManager();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
||||
if (!(sender instanceof Player player)) {
|
||||
sender.sendMessage(getLang().getString("messages.player-only"));
|
||||
return true;
|
||||
|
||||
protected void playBlockShortcutSound(Player player, Material material, Sound fallbackSound) {
|
||||
Sound sound = fallbackSound;
|
||||
if (sound == null) {
|
||||
sound = resolvePlaceSound(material);
|
||||
}
|
||||
|
||||
if (!player.hasPermission(permission)) {
|
||||
String message = getLang().getString("messages.no-permission",
|
||||
java.util.Map.of("permission", permission));
|
||||
player.sendMessage(message);
|
||||
return true;
|
||||
}
|
||||
|
||||
return execute(player, args);
|
||||
|
||||
playShortcutSound(player, sound);
|
||||
}
|
||||
|
||||
|
||||
protected void playShortcutSound(Player player, Sound sound) {
|
||||
if (sound != null) {
|
||||
player.playSound(player.getLocation(), sound, 0.65F, 1.0F);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
return dispatch(sender, args);
|
||||
}
|
||||
|
||||
final boolean dispatch(CommandSender sender, String[] args) {
|
||||
if (!sender.hasPermission(permission)) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
||||
Map.of("permission", permission)));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sender instanceof Player player) {
|
||||
return execute(player, args);
|
||||
}
|
||||
|
||||
return executeConsole(sender, args);
|
||||
}
|
||||
|
||||
protected abstract boolean execute(Player player, String[] args);
|
||||
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.player-only"));
|
||||
return true;
|
||||
}
|
||||
|
||||
private Sound resolvePlaceSound(Material material) {
|
||||
if (material == null || !material.isBlock()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
SoundGroup soundGroup = material.createBlockData().getSoundGroup();
|
||||
return soundGroup.getPlaceSound();
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,126 +3,320 @@ package cn.infstar.essentialsC.commands;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
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.inventory.InventoryDragEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BlocksMenuCommand extends BaseCommand implements Listener {
|
||||
|
||||
|
||||
private static final int MENU_SIZE = 36;
|
||||
private static final int[] DIVIDER_SLOTS = {4, 13, 22, 31};
|
||||
private final NamespacedKey blockKey;
|
||||
|
||||
|
||||
private static final class BlocksMenuHolder implements InventoryHolder {
|
||||
private final Inventory inventory;
|
||||
|
||||
private BlocksMenuHolder(Component title) {
|
||||
this.inventory = Bukkit.createInventory(this, MENU_SIZE, title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return inventory;
|
||||
}
|
||||
}
|
||||
|
||||
public BlocksMenuCommand() {
|
||||
super("essentialsc.command.blocks");
|
||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||
blockKey = new NamespacedKey(plugin, "block_key");
|
||||
addConfigDefaults();
|
||||
this.blockKey = new NamespacedKey(plugin, "block_key");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
openMenu(player);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
private void openMenu(Player player) {
|
||||
String title = plugin.getConfig().getString("blocks-menu.title", "&6&lEssentialsC &8- &e&l功能方块菜单");
|
||||
Inventory menu = Bukkit.createInventory(null, MENU_SIZE, translateColor(title));
|
||||
|
||||
// 从配置中读取所有物品
|
||||
var itemsConfig = plugin.getConfig().getConfigurationSection("blocks-menu.items");
|
||||
if (itemsConfig == null) return;
|
||||
|
||||
for (String key : itemsConfig.getKeys(false)) {
|
||||
var section = itemsConfig.getConfigurationSection(key);
|
||||
if (section == null) continue;
|
||||
|
||||
// 检查权限
|
||||
String permission = section.getString("permission");
|
||||
if (permission != null && !player.hasPermission(permission)) {
|
||||
Inventory menu = new BlocksMenuHolder(getLang().getComponent("blocks-menu.title")).getInventory();
|
||||
|
||||
FileConfiguration menuConfig = plugin.getFeatureConfigManager().getBlocksMenuConfig();
|
||||
var sectionsConfig = menuConfig.getConfigurationSection("sections");
|
||||
if (sectionsConfig != null) {
|
||||
int visibleSections = renderSections(menu, player, sectionsConfig);
|
||||
if (visibleSections > 1) {
|
||||
renderDivider(menu);
|
||||
}
|
||||
if (menu.isEmpty()) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.blocks-menu-empty"));
|
||||
return;
|
||||
}
|
||||
player.openInventory(menu);
|
||||
playShortcutSound(player, Sound.UI_BUTTON_CLICK);
|
||||
return;
|
||||
}
|
||||
|
||||
var itemsConfig = menuConfig.getConfigurationSection("items");
|
||||
if (itemsConfig == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
renderItems(menu, player, itemsConfig);
|
||||
if (menu.isEmpty()) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.blocks-menu-empty"));
|
||||
return;
|
||||
}
|
||||
|
||||
player.openInventory(menu);
|
||||
playShortcutSound(player, Sound.UI_BUTTON_CLICK);
|
||||
}
|
||||
|
||||
private int renderSections(Inventory menu, Player player, org.bukkit.configuration.ConfigurationSection sectionsConfig) {
|
||||
int visibleSections = 0;
|
||||
for (String sectionKey : sectionsConfig.getKeys(false)) {
|
||||
var section = sectionsConfig.getConfigurationSection(sectionKey);
|
||||
if (section == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int slot = section.getInt("slot");
|
||||
Material material = Material.matchMaterial(section.getString("material", "STONE"));
|
||||
if (material == null) material = Material.STONE;
|
||||
|
||||
String name = translateColor(section.getString("name", "&fItem"));
|
||||
java.util.List<String> lore = section.getStringList("lore").stream()
|
||||
.map(this::translateColor)
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
|
||||
addItem(menu, slot, material, name, lore, key);
|
||||
|
||||
var itemsConfig = section.getConfigurationSection("items");
|
||||
if (itemsConfig == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
List<MenuItem> visibleItems = collectVisibleItems(player, itemsConfig);
|
||||
if (visibleItems.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
visibleSections++;
|
||||
for (MenuItem item : visibleItems) {
|
||||
addItem(menu, item);
|
||||
}
|
||||
}
|
||||
|
||||
player.openInventory(menu);
|
||||
return visibleSections;
|
||||
}
|
||||
|
||||
private void addItem(Inventory inv, int slot, Material material, String name, java.util.List<String> lore, String key) {
|
||||
ItemStack item = new ItemStack(material);
|
||||
|
||||
private void renderItems(Inventory menu, Player player, org.bukkit.configuration.ConfigurationSection itemsConfig) {
|
||||
for (MenuItem item : collectVisibleItems(player, itemsConfig)) {
|
||||
addItem(menu, item);
|
||||
}
|
||||
}
|
||||
|
||||
private List<MenuItem> collectVisibleItems(Player player, org.bukkit.configuration.ConfigurationSection itemsConfig) {
|
||||
List<MenuItem> items = new ArrayList<>();
|
||||
for (String key : itemsConfig.getKeys(false)) {
|
||||
var section = itemsConfig.getConfigurationSection(key);
|
||||
if (section == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String permission = section.getString("permission");
|
||||
if (permission != null && !permission.isBlank() && !player.hasPermission(permission)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String commandKey = section.getString("command", key);
|
||||
if (!CommandRegistry.isAvailable(commandKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
MenuItem item = createMenuItem(section, commandKey);
|
||||
if (item != null) {
|
||||
items.add(item);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private MenuItem createMenuItem(org.bukkit.configuration.ConfigurationSection section, String commandKey) {
|
||||
int slot = section.getInt("slot", -1);
|
||||
if (slot < 0 || slot >= MENU_SIZE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Material material = Material.matchMaterial(section.getString("material", "STONE"));
|
||||
if (material == null) {
|
||||
material = Material.STONE;
|
||||
}
|
||||
|
||||
String name = getLang().getString("blocks-menu.items." + commandKey + ".name");
|
||||
List<String> lore = getLang().getStringList("blocks-menu.items." + commandKey + ".lore");
|
||||
return new MenuItem(slot, material, name, lore, commandKey);
|
||||
}
|
||||
|
||||
private void addItem(Inventory inventory, MenuItem menuItem) {
|
||||
ItemStack item = new ItemStack(menuItem.material());
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setDisplayName(name);
|
||||
meta.setLore(lore);
|
||||
meta.getPersistentDataContainer().set(this.blockKey, PersistentDataType.STRING, key);
|
||||
meta.displayName(legacyComponent(menuItem.name()));
|
||||
meta.lore(menuItem.lore().isEmpty() ? null : menuItem.lore().stream()
|
||||
.map(this::legacyComponent)
|
||||
.toList());
|
||||
if (menuItem.commandKey() != null && !menuItem.commandKey().isBlank()) {
|
||||
meta.getPersistentDataContainer().set(blockKey, PersistentDataType.STRING, menuItem.commandKey());
|
||||
}
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
inv.setItem(slot, item);
|
||||
inventory.setItem(menuItem.slot(), item);
|
||||
}
|
||||
|
||||
|
||||
private void renderDivider(Inventory inventory) {
|
||||
ItemStack divider = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
|
||||
ItemMeta meta = divider.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.displayName(Component.text(" "));
|
||||
divider.setItemMeta(meta);
|
||||
}
|
||||
|
||||
for (int slot : DIVIDER_SLOTS) {
|
||||
if (inventory.getItem(slot) == null) {
|
||||
inventory.setItem(slot, divider);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onMenuClick(InventoryClickEvent event) {
|
||||
// 动态获取配置的标题
|
||||
String configTitle = plugin.getConfig().getString("blocks-menu.title", "&6&lEssentialsC &8- &e&l功能方块菜单");
|
||||
String actualTitle = translateColor(configTitle);
|
||||
|
||||
if (!event.getView().getTitle().equals(actualTitle)) return;
|
||||
if (!(event.getWhoClicked() instanceof Player player)) return;
|
||||
|
||||
if (!(event.getView().getTopInventory().getHolder(false) instanceof BlocksMenuHolder)) {
|
||||
return;
|
||||
}
|
||||
event.setCancelled(true);
|
||||
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
if (event.getClickedInventory() != event.getView().getTopInventory()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemStack clicked = event.getCurrentItem();
|
||||
if (clicked == null || !clicked.hasItemMeta()) return;
|
||||
|
||||
if (clicked == null || !clicked.hasItemMeta()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemMeta meta = clicked.getItemMeta();
|
||||
String key = meta.getPersistentDataContainer().get(this.blockKey, PersistentDataType.STRING);
|
||||
|
||||
// 点击后执行对应命令并播放音效(如果有)
|
||||
if (key != null && HelpCommand.COMMAND_CACHE.containsKey(key)) {
|
||||
playBlockOpenSound(player, key);
|
||||
HelpCommand.COMMAND_CACHE.get(key).execute(player, new String[]{});
|
||||
String key = meta.getPersistentDataContainer().get(blockKey, PersistentDataType.STRING);
|
||||
if (key == null || key.isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
BaseCommand blockCommand = CommandRegistry.getCommand(key);
|
||||
if (blockCommand == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String permission = blockCommand.getPermission();
|
||||
if (permission != null && !permission.isBlank() && !player.hasPermission(permission)) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
||||
Map.of("permission", permission)));
|
||||
return;
|
||||
}
|
||||
|
||||
blockCommand.execute(player, new String[0]);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onMenuDrag(InventoryDragEvent event) {
|
||||
if (!(event.getView().getTopInventory().getHolder(false) instanceof BlocksMenuHolder)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int topSize = event.getView().getTopInventory().getSize();
|
||||
for (int rawSlot : event.getRawSlots()) {
|
||||
if (rawSlot >= 0 && rawSlot < topSize) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放对应方块的打开音效(优先使用交互音效)
|
||||
*/
|
||||
private void playBlockOpenSound(Player player, String key) {
|
||||
org.bukkit.Sound sound = switch (key) {
|
||||
case "workbench" -> org.bukkit.Sound.BLOCK_WOOD_HIT;
|
||||
case "anvil" -> org.bukkit.Sound.BLOCK_ANVIL_USE;
|
||||
case "cartographytable" -> org.bukkit.Sound.UI_CARTOGRAPHY_TABLE_TAKE_RESULT;
|
||||
case "grindstone" -> org.bukkit.Sound.BLOCK_GRINDSTONE_USE;
|
||||
case "loom" -> org.bukkit.Sound.UI_LOOM_TAKE_RESULT;
|
||||
case "smithingtable" -> org.bukkit.Sound.BLOCK_SMITHING_TABLE_USE;
|
||||
case "stonecutter" -> org.bukkit.Sound.BLOCK_STONE_HIT;
|
||||
case "enderchest" -> org.bukkit.Sound.BLOCK_ENDER_CHEST_OPEN;
|
||||
default -> null;
|
||||
};
|
||||
|
||||
if (sound != null) {
|
||||
player.playSound(player.getLocation(), sound, 1.0f, 1.0f);
|
||||
}
|
||||
|
||||
private Component legacyComponent(String text) {
|
||||
return LegacyComponentSerializer.legacySection().deserialize(text == null ? "" : text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换颜色代码 & -> §
|
||||
*/
|
||||
private String translateColor(String text) {
|
||||
return text.replace("&", "§");
|
||||
|
||||
private void addConfigDefaults() {
|
||||
FileConfiguration config = plugin.getFeatureConfigManager().getBlocksMenuConfig();
|
||||
config.addDefault("config-version", 1);
|
||||
config.addDefault("layout-version", 2);
|
||||
|
||||
addMenuItemDefaults(config, "sections.blocks.items.workbench", 10, "CRAFTING_TABLE",
|
||||
"essentialsc.command.workbench", "workbench");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.enderchest", 11, "ENDER_CHEST",
|
||||
"essentialsc.command.enderchest", "enderchest");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.anvil", 12, "ANVIL",
|
||||
"essentialsc.command.anvil", "anvil");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.grindstone", 19, "GRINDSTONE",
|
||||
"essentialsc.command.grindstone", "grindstone");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.smithingtable", 20, "SMITHING_TABLE",
|
||||
"essentialsc.command.smithingtable", "smithingtable");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.stonecutter", 21, "STONECUTTER",
|
||||
"essentialsc.command.stonecutter", "stonecutter");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.loom", 28, "LOOM",
|
||||
"essentialsc.command.loom", "loom");
|
||||
addMenuItemDefaults(config, "sections.blocks.items.cartographytable", 29, "CARTOGRAPHY_TABLE",
|
||||
"essentialsc.command.cartographytable", "cartographytable");
|
||||
|
||||
addMenuItemDefaults(config, "sections.shortcuts.items.nightvision", 14, "TINTED_GLASS",
|
||||
"essentialsc.command.nightvision", "nightvision");
|
||||
addMenuItemDefaults(config, "sections.shortcuts.items.glow", 15, "GLOWSTONE",
|
||||
"essentialsc.command.glow", "glow");
|
||||
|
||||
config.options().copyDefaults(true);
|
||||
migrateLayoutIfNeeded(config);
|
||||
plugin.getFeatureConfigManager().saveBlocksMenuConfig();
|
||||
}
|
||||
|
||||
private void migrateLayoutIfNeeded(FileConfiguration config) {
|
||||
boolean hasStoredLayoutVersion = config.contains("layout-version", true);
|
||||
if (hasStoredLayoutVersion && config.getInt("layout-version", 0) >= 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
applySlot(config, "blocks", "workbench", 10);
|
||||
applySlot(config, "blocks", "enderchest", 11);
|
||||
applySlot(config, "blocks", "anvil", 12);
|
||||
applySlot(config, "blocks", "grindstone", 19);
|
||||
applySlot(config, "blocks", "smithingtable", 20);
|
||||
applySlot(config, "blocks", "stonecutter", 21);
|
||||
applySlot(config, "blocks", "loom", 28);
|
||||
applySlot(config, "blocks", "cartographytable", 29);
|
||||
applySlot(config, "shortcuts", "nightvision", 14);
|
||||
applySlot(config, "shortcuts", "glow", 15);
|
||||
|
||||
config.set("sections.blocks.title-item", null);
|
||||
config.set("sections.shortcuts.title-item", null);
|
||||
config.set("layout-version", 2);
|
||||
}
|
||||
|
||||
private void applySlot(FileConfiguration config, String section, String key, int slot) {
|
||||
config.set("sections." + section + ".items." + key + ".slot", slot);
|
||||
}
|
||||
|
||||
private void addMenuItemDefaults(FileConfiguration config, String path, int slot, String material,
|
||||
String permission, String command) {
|
||||
config.addDefault(path + ".slot", slot);
|
||||
config.addDefault(path + ".material", material);
|
||||
config.addDefault(path + ".permission", permission);
|
||||
config.addDefault(path + ".command", command);
|
||||
}
|
||||
|
||||
private record MenuItem(int slot, Material material, String name, List<String> lore, String commandKey) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class CartographyTableCommand extends BaseCommand {
|
||||
|
||||
|
||||
public CartographyTableCommand() {
|
||||
super("essentialsc.command.cartographytable");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 使用 Paper API 打开制图台(标题跟随客户端语言)
|
||||
player.openCartographyTable(null, true);
|
||||
player.openInventory(MenuType.CARTOGRAPHY_TABLE.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.CARTOGRAPHY_TABLE, Sound.ENTITY_VILLAGER_WORK_CARTOGRAPHER);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.ModuleManager;
|
||||
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public final class CommandRegistry {
|
||||
|
||||
private static final Map<String, CommandSpec> COMMANDS = new LinkedHashMap<>();
|
||||
private static final Map<String, String> ALIAS_TO_COMMAND = new HashMap<>();
|
||||
private static final Map<String, BaseCommand> COMMAND_CACHE = new HashMap<>();
|
||||
private static final Set<String> UNAVAILABLE_COMMANDS = new java.util.HashSet<>();
|
||||
|
||||
static {
|
||||
register("workbench", "essentialsc.command.workbench", ModuleManager.BLOCKS, WorkbenchCommand::new, "wb");
|
||||
register("anvil", "essentialsc.command.anvil", ModuleManager.BLOCKS, AnvilCommand::new);
|
||||
register("cartographytable", "essentialsc.command.cartographytable", ModuleManager.BLOCKS, CartographyTableCommand::new, "ct", "cartography");
|
||||
register("grindstone", "essentialsc.command.grindstone", ModuleManager.BLOCKS, GrindstoneCommand::new, "gs");
|
||||
register("loom", "essentialsc.command.loom", ModuleManager.BLOCKS, LoomCommand::new);
|
||||
register("smithingtable", "essentialsc.command.smithingtable", ModuleManager.BLOCKS, SmithingTableCommand::new, "st", "smithing");
|
||||
register("stonecutter", "essentialsc.command.stonecutter", ModuleManager.BLOCKS, StonecutterCommand::new, "sc");
|
||||
register("enderchest", "essentialsc.command.enderchest", ModuleManager.BLOCKS, EnderChestCommand::new, "ec");
|
||||
register("blocks", "essentialsc.command.blocks", ModuleManager.BLOCKS, BlocksMenuCommand::new);
|
||||
registerCore("hat", "essentialsc.command.hat", HatCommand::new);
|
||||
registerCore("suicide", "essentialsc.command.suicide", SuicideCommand::new, "die");
|
||||
registerCore("fly", "essentialsc.command.fly", FlyCommand::new);
|
||||
registerCore("nightvision", "essentialsc.command.nightvision", NightVisionCommand::new, "nv");
|
||||
registerCore("glow", "essentialsc.command.glow", GlowCommand::new);
|
||||
registerCore("heal", "essentialsc.command.heal", HealCommand::new);
|
||||
registerCore("vanish", "essentialsc.command.vanish", VanishCommand::new, "v");
|
||||
registerCore("seen", "essentialsc.command.seen", SeenCommand::new, "info");
|
||||
registerCore("feed", "essentialsc.command.feed", FeedCommand::new);
|
||||
registerCore("repair", "essentialsc.command.repair", RepairCommand::new, "rep");
|
||||
registerCore("tpa", "essentialsc.command.tpa", TpaCommand::new);
|
||||
registerCore("tpahere", "essentialsc.command.tpahere", TpaHereCommand::new);
|
||||
registerCore("tpaall", "essentialsc.command.tpaall", TpaAllCommand::new);
|
||||
registerCore("tpaccept", "essentialsc.command.tpaccept", TpAcceptCommand::new, "tpyes");
|
||||
registerCore("tpdeny", "essentialsc.command.tpdeny", TpDenyCommand::new, "tpdecline", "tpno");
|
||||
registerCore("tpignore", "essentialsc.command.tpignore", TpIgnoreCommand::new);
|
||||
register("tpsbar", "essentialsc.command.tpsbar", ModuleManager.TPSBAR, TpsBarCommand::new);
|
||||
register("mobdrops", "essentialsc.mobdrops.enderman", ModuleManager.MOB_DROPS, MobDropCommand::new);
|
||||
registerSubCommand("admin", "essentialsc.command.admin", ModuleManager.ADMIN_MODE, AdminCommand::new);
|
||||
registerSubCommand("skin", "essentialsc.command.skin", ModuleManager.SKIN_BRIDGE, SkinBridgeCommand::new);
|
||||
}
|
||||
|
||||
private CommandRegistry() {
|
||||
}
|
||||
|
||||
private static void registerCore(String name, String permission, Supplier<BaseCommand> factory, String... aliases) {
|
||||
register(name, permission, null, factory, aliases);
|
||||
}
|
||||
|
||||
private static void register(String name, String permission, String moduleKey, Supplier<BaseCommand> factory, String... aliases) {
|
||||
register(name, permission, moduleKey, factory, true, aliases);
|
||||
}
|
||||
|
||||
private static void registerSubCommand(String name, String permission, String moduleKey, Supplier<BaseCommand> factory, String... aliases) {
|
||||
register(name, permission, moduleKey, factory, false, aliases);
|
||||
}
|
||||
|
||||
private static void register(String name, String permission, String moduleKey, Supplier<BaseCommand> factory,
|
||||
boolean standalone, String... aliases) {
|
||||
List<String> aliasList = List.of(aliases);
|
||||
CommandSpec spec = new CommandSpec(name, permission, moduleKey, factory, aliasList, standalone);
|
||||
COMMANDS.put(name, spec);
|
||||
ALIAS_TO_COMMAND.put(name, name);
|
||||
for (String alias : aliasList) {
|
||||
ALIAS_TO_COMMAND.put(alias, name);
|
||||
}
|
||||
}
|
||||
|
||||
public static Collection<CommandSpec> getCommandSpecs() {
|
||||
return Collections.unmodifiableCollection(COMMANDS.values());
|
||||
}
|
||||
|
||||
public static String resolveCommandName(String input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
return ALIAS_TO_COMMAND.get(input.toLowerCase());
|
||||
}
|
||||
|
||||
public static boolean isAvailable(String name) {
|
||||
String resolvedName = resolveCommandName(name);
|
||||
return resolvedName != null && !isRuntimeDisabled(resolvedName) && getRegisteredCommand(resolvedName) != null;
|
||||
}
|
||||
|
||||
public static String getPermission(String name) {
|
||||
CommandSpec spec = COMMANDS.get(name);
|
||||
return spec == null ? null : spec.permission();
|
||||
}
|
||||
|
||||
public static BaseCommand getCommand(String name) {
|
||||
String resolvedName = resolveCommandName(name);
|
||||
if (resolvedName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isRuntimeDisabled(resolvedName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return getRegisteredCommand(resolvedName);
|
||||
}
|
||||
|
||||
public static BaseCommand getRegisteredCommand(String name) {
|
||||
String resolvedName = resolveCommandName(name);
|
||||
if (resolvedName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
BaseCommand cached = COMMAND_CACHE.get(resolvedName);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
if (UNAVAILABLE_COMMANDS.contains(resolvedName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
CommandSpec spec = COMMANDS.get(resolvedName);
|
||||
if (spec == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
BaseCommand command = spec.factory().get();
|
||||
COMMAND_CACHE.put(resolvedName, command);
|
||||
return command;
|
||||
} catch (RuntimeException | LinkageError exception) {
|
||||
UNAVAILABLE_COMMANDS.add(resolvedName);
|
||||
try {
|
||||
EssentialsC.getPlugin(EssentialsC.class).getLogger()
|
||||
.warning("初始化命令 /" + resolvedName + " 失败: " + exception.getMessage());
|
||||
} catch (IllegalStateException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isRuntimeDisabled(String resolvedName) {
|
||||
CommandSpec spec = COMMANDS.get(resolvedName);
|
||||
if (spec == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
EssentialsC plugin = EssentialsC.getPlugin(EssentialsC.class);
|
||||
ModuleManager moduleManager = plugin.getModuleManager();
|
||||
if (moduleManager != null && !moduleManager.isEnabled(spec.moduleKey())) {
|
||||
return true;
|
||||
}
|
||||
} catch (IllegalStateException ignored) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!"tpsbar".equals(resolvedName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
EssentialsC plugin = EssentialsC.getPlugin(EssentialsC.class);
|
||||
TpsBarService tpsBarService = plugin.getTpsBarManager();
|
||||
return tpsBarService == null || !tpsBarService.isPluginCommandEnabled();
|
||||
} catch (IllegalStateException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void clearInitializationFailures() {
|
||||
UNAVAILABLE_COMMANDS.clear();
|
||||
}
|
||||
|
||||
public record CommandSpec(String name, String permission, String moduleKey, Supplier<BaseCommand> factory,
|
||||
List<String> aliases, boolean standalone) {
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,19 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* 末影箱命令 - 参考 EssentialsX 实现
|
||||
* 直接打开玩家的末影箱,确保数据安全
|
||||
*/
|
||||
public class EnderChestCommand extends BaseCommand {
|
||||
|
||||
|
||||
public EnderChestCommand() {
|
||||
super("essentialsc.command.enderchest");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 直接打开玩家的末影箱(EssentialsX 方式)
|
||||
// 优点:100% 安全,不会吞物品或刷物品
|
||||
// 缺点:标题显示为 "Ender Chest"(由客户端语言决定)
|
||||
player.openInventory(player.getEnderChest());
|
||||
playBlockShortcutSound(player, Material.ENDER_CHEST, Sound.BLOCK_ENDER_CHEST_OPEN);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,43 +1,66 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class FeedCommand extends BaseCommand {
|
||||
|
||||
|
||||
public FeedCommand() {
|
||||
super("essentialsc.command.feed");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (args.length == 0) {
|
||||
// 喂饱自己
|
||||
feedPlayer(player);
|
||||
player.sendMessage(getLang().getString("messages.feed-self"));
|
||||
} else {
|
||||
// 检查是否有喂饱他人的权限
|
||||
if (!player.hasPermission("essentialsc.command.feed.others")) {
|
||||
player.sendMessage(getLang().getString("messages.no-permission-others"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayer(args[0]);
|
||||
if (target == null) {
|
||||
player.sendMessage(getLang().getString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
feedPlayer(target);
|
||||
player.sendMessage(getLang().getString("messages.feed-other", Map.of("player", target.getName())));
|
||||
target.sendMessage(getLang().getString("messages.feed-by-other", Map.of("admin", player.getName())));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.feed-self"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!player.hasPermission("essentialsc.command.feed.others")) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.no-permission-others"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayerExact(args[0]);
|
||||
if (target == null) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
feedPlayer(target);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.feed-other", Map.of("player", target.getName())));
|
||||
target.sendMessage(getLang().getPrefixedString("messages.feed-by-other", Map.of("admin", player.getName())));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
if (args.length != 1) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.feed-usage-console"));
|
||||
return true;
|
||||
}
|
||||
if (!sender.hasPermission("essentialsc.command.feed.others")) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission-others"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayerExact(args[0]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
feedPlayer(target);
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.feed-other", Map.of("player", target.getName())));
|
||||
target.sendMessage(getLang().getPrefixedString("messages.feed-by-other",
|
||||
Map.of("admin", getLang().getString("messages.console-name"))));
|
||||
return true;
|
||||
}
|
||||
|
||||
private void feedPlayer(Player player) {
|
||||
player.setFoodLevel(20);
|
||||
player.setSaturation(20f);
|
||||
|
||||
@@ -10,16 +10,14 @@ public class FlyCommand extends BaseCommand {
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
boolean currentFlyState = player.getAllowFlight();
|
||||
boolean currentFlyState = plugin.getPlayerStateManager().isFlyEnabled(player);
|
||||
|
||||
if (currentFlyState) {
|
||||
player.setAllowFlight(false);
|
||||
player.setFlying(false);
|
||||
player.sendMessage(getLang().getString("messages.fly-disabled"));
|
||||
plugin.getPlayerStateManager().disableFly(player);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.fly-disabled"));
|
||||
} else {
|
||||
player.setAllowFlight(true);
|
||||
player.setFlying(true);
|
||||
player.sendMessage(getLang().getString("messages.fly-enabled"));
|
||||
plugin.getPlayerStateManager().enableFly(player);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.fly-enabled"));
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class GlowCommand extends BaseCommand {
|
||||
|
||||
public GlowCommand() {
|
||||
super("essentialsc.command.glow");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
boolean currentState = isPluginGlowEnabled(player);
|
||||
Boolean targetState = resolveTargetState(currentState, args);
|
||||
if (targetState == null) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.glow-usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (targetState) {
|
||||
plugin.getPlayerStateManager().enableGlow(player);
|
||||
playShortcutSound(player, Sound.BLOCK_AMETHYST_BLOCK_CHIME);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.glow-enabled"));
|
||||
} else {
|
||||
plugin.getPlayerStateManager().disableGlow(player);
|
||||
playShortcutSound(player, Sound.BLOCK_AMETHYST_CLUSTER_FALL);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.glow-disabled"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Boolean resolveTargetState(boolean currentState, String[] args) {
|
||||
if (args.length == 0) {
|
||||
return !currentState;
|
||||
}
|
||||
|
||||
return switch (args[0].toLowerCase()) {
|
||||
case "on", "true", "enable", "enabled" -> true;
|
||||
case "off", "false", "disable", "disabled" -> false;
|
||||
case "toggle" -> !currentState;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isPluginGlowEnabled(Player player) {
|
||||
return plugin.getPlayerStateManager().isGlowEnabled(player);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class GrindstoneCommand extends BaseCommand {
|
||||
|
||||
|
||||
public GrindstoneCommand() {
|
||||
super("essentialsc.command.grindstone");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 使用 Paper API 打开砂轮(标题跟随客户端语言)
|
||||
player.openGrindstone(null, true);
|
||||
player.openInventory(MenuType.GRINDSTONE.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.GRINDSTONE, Sound.BLOCK_GRINDSTONE_USE);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,37 +6,27 @@ import org.bukkit.inventory.ItemStack;
|
||||
import java.util.Map;
|
||||
|
||||
public class HatCommand extends BaseCommand {
|
||||
|
||||
|
||||
public HatCommand() {
|
||||
super("essentialsc.command.hat");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
ItemStack handItem = player.getInventory().getItemInMainHand();
|
||||
|
||||
|
||||
if (handItem == null || handItem.isEmpty()) {
|
||||
player.sendMessage(getLang().getString("messages.hat-no-item"));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.hat-no-item"));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
ItemStack helmet = player.getInventory().getHelmet();
|
||||
|
||||
// 如果头盔栏有物品,先放回背包
|
||||
if (helmet != null && !helmet.isEmpty()) {
|
||||
player.getInventory().setHelmet(handItem);
|
||||
player.getInventory().setItemInMainHand(helmet);
|
||||
} else {
|
||||
player.getInventory().setHelmet(handItem);
|
||||
player.getInventory().setItemInMainHand(null);
|
||||
}
|
||||
|
||||
player.getInventory().setHelmet(handItem);
|
||||
player.getInventory().setItemInMainHand(helmet == null || helmet.isEmpty() ? null : helmet);
|
||||
player.updateInventory();
|
||||
|
||||
String itemName = handItem.getType().toString();
|
||||
String message = getLang().getString("messages.hat-success",
|
||||
Map.of("item", itemName));
|
||||
player.sendMessage(message);
|
||||
|
||||
player.sendMessage(getLang().getPrefixedString("messages.hat-success",
|
||||
Map.of("item", handItem.getType().toString())));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +1,71 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeInstance;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class HealCommand extends BaseCommand {
|
||||
|
||||
|
||||
public HealCommand() {
|
||||
super("essentialsc.command.heal");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (args.length == 0) {
|
||||
// 治疗自己
|
||||
healPlayer(player);
|
||||
player.sendMessage(getLang().getString("messages.heal-self"));
|
||||
} else {
|
||||
// 检查是否有治疗他人的权限
|
||||
if (!player.hasPermission("essentialsc.command.heal.others")) {
|
||||
player.sendMessage(getLang().getString("messages.no-permission-others"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayer(args[0]);
|
||||
if (target == null) {
|
||||
player.sendMessage(getLang().getString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
healPlayer(target);
|
||||
player.sendMessage(getLang().getString("messages.heal-other", Map.of("player", target.getName())));
|
||||
target.sendMessage(getLang().getString("messages.heal-by-other", Map.of("admin", player.getName())));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.heal-self"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!player.hasPermission("essentialsc.command.heal.others")) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.no-permission-others"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayerExact(args[0]);
|
||||
if (target == null) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
healPlayer(target);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.heal-other", Map.of("player", target.getName())));
|
||||
target.sendMessage(getLang().getPrefixedString("messages.heal-by-other", Map.of("admin", player.getName())));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
if (args.length != 1) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.heal-usage-console"));
|
||||
return true;
|
||||
}
|
||||
if (!sender.hasPermission("essentialsc.command.heal.others")) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission-others"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayerExact(args[0]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
healPlayer(target);
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.heal-other", Map.of("player", target.getName())));
|
||||
target.sendMessage(getLang().getPrefixedString("messages.heal-by-other",
|
||||
Map.of("admin", getLang().getString("messages.console-name"))));
|
||||
return true;
|
||||
}
|
||||
|
||||
private void healPlayer(Player player) {
|
||||
player.setHealth(player.getMaxHealth());
|
||||
AttributeInstance maxHealth = player.getAttribute(Attribute.MAX_HEALTH);
|
||||
player.setHealth(maxHealth == null ? player.getHealth() : maxHealth.getValue());
|
||||
player.setFoodLevel(20);
|
||||
player.setSaturation(20f);
|
||||
player.clearActivePotionEffects();
|
||||
|
||||
@@ -2,217 +2,318 @@ package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.LangManager;
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HelpCommand extends BaseCommand implements TabCompleter {
|
||||
|
||||
// 缓存命令实例,避免重复创建
|
||||
static final java.util.Map<String, BaseCommand> COMMAND_CACHE = new java.util.HashMap<>();
|
||||
|
||||
static {
|
||||
COMMAND_CACHE.put("workbench", new WorkbenchCommand());
|
||||
COMMAND_CACHE.put("anvil", new AnvilCommand());
|
||||
COMMAND_CACHE.put("cartographytable", new CartographyTableCommand());
|
||||
COMMAND_CACHE.put("grindstone", new GrindstoneCommand());
|
||||
COMMAND_CACHE.put("loom", new LoomCommand());
|
||||
COMMAND_CACHE.put("smithingtable", new SmithingTableCommand());
|
||||
COMMAND_CACHE.put("stonecutter", new StonecutterCommand());
|
||||
COMMAND_CACHE.put("enderchest", new EnderChestCommand());
|
||||
COMMAND_CACHE.put("hat", new HatCommand());
|
||||
COMMAND_CACHE.put("suicide", new SuicideCommand());
|
||||
COMMAND_CACHE.put("fly", new FlyCommand());
|
||||
COMMAND_CACHE.put("heal", new HealCommand());
|
||||
COMMAND_CACHE.put("vanish", new VanishCommand());
|
||||
COMMAND_CACHE.put("seen", new SeenCommand());
|
||||
COMMAND_CACHE.put("feed", new FeedCommand());
|
||||
COMMAND_CACHE.put("repair", new RepairCommand());
|
||||
COMMAND_CACHE.put("blocks", new BlocksMenuCommand());
|
||||
}
|
||||
|
||||
|
||||
public HelpCommand() {
|
||||
super("essentialsc.command.help");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length > 0) {
|
||||
if (sender instanceof Player player) {
|
||||
return handleCommand(sender, player, args);
|
||||
}
|
||||
return executeConsole(sender, args);
|
||||
}
|
||||
return super.onCommand(sender, command, label, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
return handleCommand(player, player, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
|
||||
sendConsoleHelp(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase("reload")) {
|
||||
if (!sender.hasPermission("essentialsc.command.reload")) {
|
||||
sendNoPermission(sender, "essentialsc.command.reload");
|
||||
return true;
|
||||
}
|
||||
plugin.getFeatureConfigManager().reload();
|
||||
EssentialsC.getLangManager().reload();
|
||||
plugin.getModuleManager().reload();
|
||||
CommandRegistry.clearInitializationFailures();
|
||||
plugin.reloadRuntimeModules();
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.config-reloaded"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase("version") || args[0].equalsIgnoreCase("v")) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.version",
|
||||
Map.of("version", plugin.getPluginMeta().getVersion())));
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.paper-version",
|
||||
Map.of("version", Bukkit.getVersion())));
|
||||
return true;
|
||||
}
|
||||
|
||||
String actualCommand = getActualCommand(args[0]);
|
||||
BaseCommand targetCommand = CommandRegistry.getCommand(actualCommand);
|
||||
if (actualCommand != null && targetCommand != null) {
|
||||
return targetCommand.dispatch(sender, Arrays.copyOfRange(args, 1, args.length));
|
||||
}
|
||||
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.unknown-subcommand",
|
||||
Map.of("command", args[0])));
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.help-usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
private void sendConsoleHelp(CommandSender sender) {
|
||||
LangManager lang = getLang();
|
||||
sendPrefixed(sender, lang.getString("help.title"));
|
||||
sendPrefixed(sender, lang.getString("help.version",
|
||||
Map.of("version", plugin.getPluginMeta().getVersion())));
|
||||
sender.sendMessage("");
|
||||
|
||||
sendPrefixed(sender, lang.getString("help.section-other"));
|
||||
if (sender.hasPermission("essentialsc.command.reload")) {
|
||||
sendPrefixed(sender, lang.getString("help.commands.reload"));
|
||||
}
|
||||
sendPrefixed(sender, lang.getString("help.commands.version"));
|
||||
if (CommandRegistry.isAvailable("seen") && sender.hasPermission("essentialsc.command.seen")) {
|
||||
sendPrefixed(sender, lang.getString("help.commands.seen"));
|
||||
}
|
||||
if (CommandRegistry.isAvailable("heal") && sender.hasPermission("essentialsc.command.heal")) {
|
||||
sendPrefixed(sender, lang.getString("help.commands.heal"));
|
||||
}
|
||||
if (CommandRegistry.isAvailable("feed") && sender.hasPermission("essentialsc.command.feed")) {
|
||||
sendPrefixed(sender, lang.getString("help.commands.feed"));
|
||||
}
|
||||
if (CommandRegistry.isAvailable("skin") && sender.hasPermission("essentialsc.command.skin")) {
|
||||
sendPrefixed(sender, lang.getString("help.commands.skin"));
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpsbar") && sender.hasPermission("essentialsc.command.tpsbar")) {
|
||||
sendPrefixed(sender, lang.getString("help.commands.tpsbar"));
|
||||
}
|
||||
sender.sendMessage("");
|
||||
sendPrefixed(sender, lang.getString("help.footer"));
|
||||
}
|
||||
|
||||
private boolean handleCommand(CommandSender sender, Player player, String[] args) {
|
||||
if (args.length > 0) {
|
||||
String subCommand = args[0].toLowerCase();
|
||||
|
||||
// 管理相关
|
||||
|
||||
if (subCommand.equals("reload")) {
|
||||
if (!player.hasPermission("essentialsc.command.reload")) {
|
||||
player.sendMessage(getLang().getString("messages.no-permission"));
|
||||
if (!sender.hasPermission("essentialsc.command.reload")) {
|
||||
sendNoPermission(sender, "essentialsc.command.reload");
|
||||
return true;
|
||||
}
|
||||
plugin.reloadConfig();
|
||||
plugin.getFeatureConfigManager().reload();
|
||||
EssentialsC.getLangManager().reload();
|
||||
player.sendMessage("§a配置已重载!");
|
||||
plugin.getModuleManager().reload();
|
||||
CommandRegistry.clearInitializationFailures();
|
||||
plugin.reloadRuntimeModules();
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.config-reloaded"));
|
||||
return true;
|
||||
}
|
||||
// 功能方块和其他命令 - 使用别名映射
|
||||
|
||||
String actualCommand = getActualCommand(subCommand);
|
||||
if (actualCommand != null && COMMAND_CACHE.containsKey(actualCommand)) {
|
||||
String permission = getPermissionForCommand(actualCommand);
|
||||
if (!player.hasPermission(permission)) {
|
||||
player.sendMessage(getLang().getString("messages.no-permission"));
|
||||
BaseCommand targetCommand = CommandRegistry.getCommand(actualCommand);
|
||||
if (actualCommand != null && targetCommand != null) {
|
||||
String permission = CommandRegistry.getPermission(actualCommand);
|
||||
if (permission != null && !player.hasPermission(permission)) {
|
||||
sendNoPermission(player, permission);
|
||||
return true;
|
||||
}
|
||||
|
||||
// seen 需要特殊处理参数
|
||||
if (actualCommand.equals("seen")) {
|
||||
if (args.length < 2) {
|
||||
player.sendMessage("§c用法: /essc seen <玩家名>");
|
||||
|
||||
String[] forwardedArgs = Arrays.copyOfRange(args, 1, args.length);
|
||||
if (actualCommand.equals("seen") && forwardedArgs.length == 0) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.seen-usage-console"));
|
||||
return true;
|
||||
}
|
||||
COMMAND_CACHE.get("seen").execute(player, new String[]{args[1]});
|
||||
} else {
|
||||
COMMAND_CACHE.get(actualCommand).execute(player, new String[]{});
|
||||
}
|
||||
return true;
|
||||
} else if (subCommand.equals("version") || subCommand.equals("v")) {
|
||||
player.sendMessage("§6EssentialsC §fv" + plugin.getDescription().getVersion());
|
||||
player.sendMessage("§7运行在 Paper " + Bukkit.getVersion());
|
||||
return true;
|
||||
} else {
|
||||
// 未知子命令
|
||||
player.sendMessage("§c未知子命令: " + subCommand);
|
||||
player.sendMessage("§7使用 §f/essc help §7查看所有可用命令");
|
||||
targetCommand.execute(player, forwardedArgs);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (subCommand.equals("version") || subCommand.equals("v")) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.version",
|
||||
Map.of("version", plugin.getPluginMeta().getVersion())));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.paper-version",
|
||||
Map.of("version", Bukkit.getVersion())));
|
||||
return true;
|
||||
}
|
||||
|
||||
player.sendMessage(getLang().getPrefixedString("messages.unknown-subcommand",
|
||||
Map.of("command", subCommand)));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.help-usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// 显示帮助
|
||||
|
||||
LangManager lang = getLang();
|
||||
String version = plugin.getDescription().getVersion();
|
||||
|
||||
player.sendMessage(lang.getString("help.title"));
|
||||
player.sendMessage(lang.getString("help.version",
|
||||
java.util.Map.of("version", version)));
|
||||
String version = plugin.getPluginMeta().getVersion();
|
||||
|
||||
sendPrefixed(player, lang.getString("help.title"));
|
||||
sendPrefixed(player, lang.getString("help.version", Map.of("version", version)));
|
||||
player.sendMessage("");
|
||||
|
||||
// 功能方块命令(检查权限后显示)
|
||||
|
||||
boolean hasBlockCommands = false;
|
||||
StringBuilder blockCommands = new StringBuilder();
|
||||
|
||||
if (player.hasPermission("essentialsc.command.workbench")) {
|
||||
|
||||
if (CommandRegistry.isAvailable("workbench") && player.hasPermission("essentialsc.command.workbench")) {
|
||||
blockCommands.append(lang.getString("help.commands.workbench")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.anvil")) {
|
||||
if (CommandRegistry.isAvailable("anvil") && player.hasPermission("essentialsc.command.anvil")) {
|
||||
blockCommands.append(lang.getString("help.commands.anvil")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.cartographytable")) {
|
||||
if (CommandRegistry.isAvailable("cartographytable") && player.hasPermission("essentialsc.command.cartographytable")) {
|
||||
blockCommands.append(lang.getString("help.commands.cartographytable")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.grindstone")) {
|
||||
if (CommandRegistry.isAvailable("grindstone") && player.hasPermission("essentialsc.command.grindstone")) {
|
||||
blockCommands.append(lang.getString("help.commands.grindstone")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.loom")) {
|
||||
if (CommandRegistry.isAvailable("loom") && player.hasPermission("essentialsc.command.loom")) {
|
||||
blockCommands.append(lang.getString("help.commands.loom")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.smithingtable")) {
|
||||
if (CommandRegistry.isAvailable("smithingtable") && player.hasPermission("essentialsc.command.smithingtable")) {
|
||||
blockCommands.append(lang.getString("help.commands.smithingtable")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.stonecutter")) {
|
||||
if (CommandRegistry.isAvailable("stonecutter") && player.hasPermission("essentialsc.command.stonecutter")) {
|
||||
blockCommands.append(lang.getString("help.commands.stonecutter")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.enderchest")) {
|
||||
if (CommandRegistry.isAvailable("enderchest") && player.hasPermission("essentialsc.command.enderchest")) {
|
||||
blockCommands.append(lang.getString("help.commands.enderchest")).append("\n");
|
||||
hasBlockCommands = true;
|
||||
}
|
||||
|
||||
|
||||
if (hasBlockCommands) {
|
||||
player.sendMessage(lang.getString("help.section-blocks"));
|
||||
player.sendMessage(blockCommands.toString().trim());
|
||||
sendPrefixed(player, lang.getString("help.section-blocks"));
|
||||
sendPrefixedLines(player, blockCommands.toString().trim());
|
||||
player.sendMessage("");
|
||||
}
|
||||
|
||||
// 其他命令(检查权限后显示)
|
||||
|
||||
boolean hasOtherCommands = false;
|
||||
StringBuilder otherCommands = new StringBuilder();
|
||||
|
||||
if (player.hasPermission("essentialsc.command.hat")) {
|
||||
|
||||
if (CommandRegistry.isAvailable("hat") && player.hasPermission("essentialsc.command.hat")) {
|
||||
otherCommands.append(lang.getString("help.commands.hat")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.suicide")) {
|
||||
if (CommandRegistry.isAvailable("suicide") && player.hasPermission("essentialsc.command.suicide")) {
|
||||
otherCommands.append(lang.getString("help.commands.suicide")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.fly")) {
|
||||
if (CommandRegistry.isAvailable("fly") && player.hasPermission("essentialsc.command.fly")) {
|
||||
otherCommands.append(lang.getString("help.commands.fly")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.heal")) {
|
||||
if (CommandRegistry.isAvailable("nightvision") && player.hasPermission("essentialsc.command.nightvision")) {
|
||||
otherCommands.append(lang.getString("help.commands.nightvision")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("glow") && player.hasPermission("essentialsc.command.glow")) {
|
||||
otherCommands.append(lang.getString("help.commands.glow")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("heal") && player.hasPermission("essentialsc.command.heal")) {
|
||||
otherCommands.append(lang.getString("help.commands.heal")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.vanish")) {
|
||||
if (CommandRegistry.isAvailable("vanish") && player.hasPermission("essentialsc.command.vanish")) {
|
||||
otherCommands.append(lang.getString("help.commands.vanish")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (player.hasPermission("essentialsc.command.seen")) {
|
||||
if (CommandRegistry.isAvailable("seen") && player.hasPermission("essentialsc.command.seen")) {
|
||||
otherCommands.append(lang.getString("help.commands.seen")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
|
||||
if (CommandRegistry.isAvailable("tpa") && player.hasPermission("essentialsc.command.tpa")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpa")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpahere") && player.hasPermission("essentialsc.command.tpahere")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpahere")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpaall") && player.hasPermission("essentialsc.command.tpaall")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpaall")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpaccept") && player.hasPermission("essentialsc.command.tpaccept")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpaccept")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpdeny") && player.hasPermission("essentialsc.command.tpdeny")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpdeny")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpignore") && player.hasPermission("essentialsc.command.tpignore")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpignore")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("skin") && player.hasPermission("essentialsc.command.skin")) {
|
||||
otherCommands.append(lang.getString("help.commands.skin")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("admin") && player.hasPermission("essentialsc.command.admin")) {
|
||||
otherCommands.append(lang.getString("help.commands.admin")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
if (CommandRegistry.isAvailable("tpsbar") && player.hasPermission("essentialsc.command.tpsbar")) {
|
||||
otherCommands.append(lang.getString("help.commands.tpsbar")).append("\n");
|
||||
hasOtherCommands = true;
|
||||
}
|
||||
|
||||
if (hasOtherCommands) {
|
||||
player.sendMessage(lang.getString("help.section-other"));
|
||||
player.sendMessage(otherCommands.toString().trim());
|
||||
sendPrefixed(player, lang.getString("help.section-other"));
|
||||
sendPrefixedLines(player, otherCommands.toString().trim());
|
||||
player.sendMessage("");
|
||||
}
|
||||
|
||||
player.sendMessage(lang.getString("help.footer"));
|
||||
|
||||
sendPrefixed(player, lang.getString("help.footer"));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将别名映射到实际命令名
|
||||
*/
|
||||
|
||||
private void sendNoPermission(CommandSender sender, String permission) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
||||
Map.of("permission", permission)));
|
||||
}
|
||||
|
||||
private void sendPrefixed(CommandSender sender, String message) {
|
||||
sender.sendMessage(getLang().getPrefix() + message);
|
||||
}
|
||||
|
||||
private void sendPrefixedLines(CommandSender sender, String message) {
|
||||
for (String line : message.split("\\R")) {
|
||||
sendPrefixed(sender, line);
|
||||
}
|
||||
}
|
||||
|
||||
private String getActualCommand(String alias) {
|
||||
return switch (alias) {
|
||||
case "wb" -> "workbench";
|
||||
case "cartography", "ct" -> "cartographytable";
|
||||
case "gs" -> "grindstone";
|
||||
case "smithing", "st" -> "smithingtable";
|
||||
case "sc" -> "stonecutter";
|
||||
case "ec" -> "enderchest";
|
||||
case "die" -> "suicide";
|
||||
case "info" -> "seen";
|
||||
case "rep" -> "repair";
|
||||
default -> alias;
|
||||
};
|
||||
return CommandRegistry.resolveCommandName(alias);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取命令对应的权限节点
|
||||
*/
|
||||
private String getPermissionForCommand(String command) {
|
||||
return "essentialsc.command." + command;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 1) {
|
||||
List<String> completions = new ArrayList<>();
|
||||
String partial = args[0].toLowerCase();
|
||||
|
||||
// 所有可能的子命令及其权限(包括别名)
|
||||
|
||||
String[][] subCommands = {
|
||||
{"reload", "essentialsc.command.reload"},
|
||||
{"blocks", "essentialsc.command.blocks"},
|
||||
@@ -236,6 +337,9 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
||||
{"suicide", "essentialsc.command.suicide"},
|
||||
{"die", "essentialsc.command.suicide"},
|
||||
{"fly", "essentialsc.command.fly"},
|
||||
{"nightvision", "essentialsc.command.nightvision"},
|
||||
{"nv", "essentialsc.command.nightvision"},
|
||||
{"glow", "essentialsc.command.glow"},
|
||||
{"heal", "essentialsc.command.heal"},
|
||||
{"vanish", "essentialsc.command.vanish"},
|
||||
{"v", "essentialsc.command.vanish"},
|
||||
@@ -244,20 +348,39 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
||||
{"feed", "essentialsc.command.feed"},
|
||||
{"repair", "essentialsc.command.repair"},
|
||||
{"rep", "essentialsc.command.repair"},
|
||||
{"tpa", "essentialsc.command.tpa"},
|
||||
{"tpahere", "essentialsc.command.tpahere"},
|
||||
{"tpaall", "essentialsc.command.tpaall"},
|
||||
{"tpaccept", "essentialsc.command.tpaccept"},
|
||||
{"tpyes", "essentialsc.command.tpaccept"},
|
||||
{"tpdeny", "essentialsc.command.tpdeny"},
|
||||
{"tpdecline", "essentialsc.command.tpdeny"},
|
||||
{"tpno", "essentialsc.command.tpdeny"},
|
||||
{"tpignore", "essentialsc.command.tpignore"},
|
||||
{"skin", "essentialsc.command.skin"},
|
||||
{"tpsbar", "essentialsc.command.tpsbar"},
|
||||
{"mobdrops", "essentialsc.mobdrops.enderman"},
|
||||
{"admin", "essentialsc.command.admin"},
|
||||
{"version", null},
|
||||
{"help", null}
|
||||
};
|
||||
|
||||
|
||||
for (String[] subCmd : subCommands) {
|
||||
if (subCmd[0].startsWith(partial)) {
|
||||
if (subCmd[1] == null || sender.hasPermission(subCmd[1])) {
|
||||
completions.add(subCmd[0]);
|
||||
}
|
||||
if (!subCmd[0].startsWith(partial)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String actualCommand = getActualCommand(subCmd[0]);
|
||||
boolean available = actualCommand == null || CommandRegistry.isAvailable(actualCommand);
|
||||
if (available && (subCmd[1] == null || sender.hasPermission(subCmd[1]))) {
|
||||
completions.add(subCmd[0]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return completions;
|
||||
} else if (args.length == 2) {
|
||||
}
|
||||
|
||||
if (args.length == 2) {
|
||||
String subCmd = args[0].toLowerCase();
|
||||
if ((subCmd.equals("seen") || subCmd.equals("info")) && sender.hasPermission("essentialsc.command.seen")) {
|
||||
List<String> players = new ArrayList<>();
|
||||
@@ -269,8 +392,97 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
||||
}
|
||||
return players;
|
||||
}
|
||||
|
||||
Player completionPlayer = sender instanceof Player senderPlayer ? senderPlayer : null;
|
||||
if ((subCmd.equals("tpa") || subCmd.equals("tpahere"))
|
||||
&& completionPlayer != null
|
||||
&& sender.hasPermission("essentialsc.command." + subCmd)) {
|
||||
return completeOnlinePlayers(completionPlayer, args[1], false);
|
||||
}
|
||||
|
||||
if ((subCmd.equals("tpaccept") || subCmd.equals("tpyes") || subCmd.equals("tpdeny")
|
||||
|| subCmd.equals("tpdecline") || subCmd.equals("tpno"))
|
||||
&& completionPlayer != null
|
||||
&& (sender.hasPermission("essentialsc.command.tpaccept") || sender.hasPermission("essentialsc.command.tpdeny"))) {
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
return manager == null ? List.of() : manager.getIncomingRequesterNames(completionPlayer, args[1]);
|
||||
}
|
||||
|
||||
if (subCmd.equals("skin") && sender.hasPermission("essentialsc.command.skin")) {
|
||||
String partial = args[1].toLowerCase();
|
||||
List<String> actions = new ArrayList<>();
|
||||
if (sender.hasPermission("essentialsc.command.skin.status")) {
|
||||
actions.add("status");
|
||||
}
|
||||
if (sender.hasPermission("essentialsc.command.skin.refresh")) {
|
||||
actions.add("refresh");
|
||||
}
|
||||
return actions.stream()
|
||||
.filter(option -> option.startsWith(partial))
|
||||
.toList();
|
||||
}
|
||||
|
||||
if ((subCmd.equals("nightvision") || subCmd.equals("nv")) && sender.hasPermission("essentialsc.command.nightvision")) {
|
||||
return completeToggleArgs(args[1]);
|
||||
}
|
||||
|
||||
if (subCmd.equals("glow") && sender.hasPermission("essentialsc.command.glow")) {
|
||||
return completeToggleArgs(args[1]);
|
||||
}
|
||||
|
||||
if (subCmd.equals("tpsbar") && sender.hasPermission("essentialsc.command.tpsbar.others")) {
|
||||
List<String> players = new ArrayList<>();
|
||||
String partial = args[1].toLowerCase();
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (p.getName().toLowerCase().startsWith(partial)) {
|
||||
players.add(p.getName());
|
||||
}
|
||||
}
|
||||
return players;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (args.length == 3 && args[0].equalsIgnoreCase("skin")
|
||||
&& (args[1].equalsIgnoreCase("status") || args[1].equalsIgnoreCase("refresh"))
|
||||
&& sender.hasPermission("essentialsc.command.skin.others")
|
||||
&& sender.hasPermission(args[1].equalsIgnoreCase("status")
|
||||
? "essentialsc.command.skin.status"
|
||||
: "essentialsc.command.skin.refresh")) {
|
||||
List<String> players = new ArrayList<>();
|
||||
String partial = args[2].toLowerCase();
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
if (player.getName().toLowerCase().startsWith(partial)) {
|
||||
players.add(player.getName());
|
||||
}
|
||||
}
|
||||
return players;
|
||||
}
|
||||
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
private List<String> completeToggleArgs(String partialInput) {
|
||||
List<String> completions = new ArrayList<>();
|
||||
String partial = partialInput.toLowerCase();
|
||||
for (String option : List.of("on", "off", "toggle")) {
|
||||
if (option.startsWith(partial)) {
|
||||
completions.add(option);
|
||||
}
|
||||
}
|
||||
return completions;
|
||||
}
|
||||
|
||||
private List<String> completeOnlinePlayers(Player sender, String partialInput, boolean includeSelf) {
|
||||
List<String> completions = new ArrayList<>();
|
||||
String partial = partialInput.toLowerCase();
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
if ((includeSelf || !player.getUniqueId().equals(sender.getUniqueId()))
|
||||
&& player.getName().toLowerCase().startsWith(partial)) {
|
||||
completions.add(player.getName());
|
||||
}
|
||||
}
|
||||
return completions;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class LoomCommand extends BaseCommand {
|
||||
|
||||
|
||||
public LoomCommand() {
|
||||
super("essentialsc.command.loom");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 使用 Paper API 打开织布机(标题跟随客户端语言)
|
||||
player.openLoom(null, true);
|
||||
player.openInventory(MenuType.LOOM.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.LOOM, Sound.UI_LOOM_SELECT_PATTERN);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class MobDropCommand extends BaseCommand {
|
||||
|
||||
private static final int MENU_SIZE = 27;
|
||||
private static final int ENDERMAN_SLOT = 13;
|
||||
|
||||
public static final class MobDropMenuHolder implements InventoryHolder {
|
||||
private final Inventory inventory;
|
||||
|
||||
public MobDropMenuHolder(Component title) {
|
||||
this.inventory = Bukkit.createInventory(this, MENU_SIZE, title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return inventory;
|
||||
}
|
||||
}
|
||||
|
||||
public MobDropCommand() {
|
||||
super("essentialsc.mobdrops.enderman");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
openMobDropMenu(player);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void openMobDropMenu(EssentialsC plugin, Player player) {
|
||||
var lang = EssentialsC.getLangManager();
|
||||
boolean endermanDropsAllowed = plugin.getConfig().getBoolean("mob-drops.enderman.allow-drops", true);
|
||||
String status = lang.getString(endermanDropsAllowed
|
||||
? "mobdrops-menu.status.enabled"
|
||||
: "mobdrops-menu.status.disabled");
|
||||
|
||||
Inventory menu = new MobDropMenuHolder(lang.getComponent("mobdrops-menu.title")).getInventory();
|
||||
|
||||
ItemStack endermanItem = new ItemStack(Material.ENDER_PEARL);
|
||||
ItemMeta endermanMeta = endermanItem.getItemMeta();
|
||||
if (endermanMeta != null) {
|
||||
endermanMeta.displayName(legacyComponent(lang.getString("mobdrops-menu.enderman.name")));
|
||||
endermanMeta.lore(List.of(
|
||||
lang.getString("mobdrops-menu.enderman.status", Map.of("status", status)),
|
||||
"",
|
||||
lang.getString("mobdrops-menu.enderman.toggle")
|
||||
).stream().map(MobDropCommand::legacyComponent).toList());
|
||||
endermanItem.setItemMeta(endermanMeta);
|
||||
}
|
||||
menu.setItem(ENDERMAN_SLOT, endermanItem);
|
||||
|
||||
ItemStack glass = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
|
||||
ItemMeta glassMeta = glass.getItemMeta();
|
||||
if (glassMeta != null) {
|
||||
glassMeta.displayName(Component.text(" "));
|
||||
glass.setItemMeta(glassMeta);
|
||||
}
|
||||
|
||||
for (int slot = 0; slot < MENU_SIZE; slot++) {
|
||||
if (menu.getItem(slot) == null) {
|
||||
menu.setItem(slot, glass);
|
||||
}
|
||||
}
|
||||
|
||||
player.openInventory(menu);
|
||||
}
|
||||
|
||||
public static int getEndermanSlot() {
|
||||
return ENDERMAN_SLOT;
|
||||
}
|
||||
|
||||
private static Component legacyComponent(String text) {
|
||||
return LegacyComponentSerializer.legacySection().deserialize(text == null ? "" : text);
|
||||
}
|
||||
|
||||
private void openMobDropMenu(Player player) {
|
||||
openMobDropMenu(plugin, player);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class NightVisionCommand extends BaseCommand {
|
||||
|
||||
public NightVisionCommand() {
|
||||
super("essentialsc.command.nightvision");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
boolean currentState = isPluginNightVisionEnabled(player);
|
||||
Boolean targetState = resolveTargetState(currentState, args);
|
||||
if (targetState == null) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.nightvision-usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (targetState) {
|
||||
plugin.getPlayerStateManager().enableNightVision(player);
|
||||
playShortcutSound(player, Sound.BLOCK_BEACON_POWER_SELECT);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.nightvision-enabled"));
|
||||
} else {
|
||||
plugin.getPlayerStateManager().disableNightVision(player);
|
||||
playShortcutSound(player, Sound.BLOCK_BEACON_DEACTIVATE);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.nightvision-disabled"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Boolean resolveTargetState(boolean currentState, String[] args) {
|
||||
if (args.length == 0) {
|
||||
return !currentState;
|
||||
}
|
||||
|
||||
return switch (args[0].toLowerCase()) {
|
||||
case "on", "true", "enable", "enabled" -> true;
|
||||
case "off", "false", "disable", "disabled" -> false;
|
||||
case "toggle" -> !currentState;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isPluginNightVisionEnabled(Player player) {
|
||||
return plugin.getPlayerStateManager().isNightVisionEnabled(player);
|
||||
}
|
||||
}
|
||||
@@ -3,80 +3,71 @@ package cn.infstar.essentialsC.commands;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class RepairCommand extends BaseCommand {
|
||||
|
||||
|
||||
public RepairCommand() {
|
||||
super("essentialsc.command.repair");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (args.length > 0 && args[0].equalsIgnoreCase("all")) {
|
||||
// 检查是否有修复全部的权限
|
||||
if (!player.hasPermission("essentialsc.command.repair.all")) {
|
||||
player.sendMessage(getLang().getString("messages.no-permission-repair-all"));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.no-permission-repair-all"));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
int repairedCount = repairAll(player);
|
||||
if (repairedCount > 0) {
|
||||
player.sendMessage(getLang().getString("messages.repair-all-success", java.util.Map.of("count", String.valueOf(repairedCount))));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.repair-all-success",
|
||||
Map.of("count", String.valueOf(repairedCount))));
|
||||
} else {
|
||||
player.sendMessage(getLang().getString("messages.repair-no-items"));
|
||||
player.sendMessage(getLang().getPrefixedString("messages.repair-no-items"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ItemStack item = player.getInventory().getItemInMainHand();
|
||||
if (item == null || item.getType().isAir()) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.repair-no-item-in-hand"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (repairItem(item)) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.repair-hand-success"));
|
||||
} else {
|
||||
// 修复手中物品
|
||||
ItemStack item = player.getInventory().getItemInMainHand();
|
||||
if (item == null || item.getType().isAir()) {
|
||||
player.sendMessage(getLang().getString("messages.repair-no-item-in-hand"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (repairItem(item)) {
|
||||
player.sendMessage(getLang().getString("messages.repair-hand-success"));
|
||||
} else {
|
||||
player.sendMessage(getLang().getString("messages.repair-not-damaged"));
|
||||
}
|
||||
player.sendMessage(getLang().getPrefixedString("messages.repair-not-damaged"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
private boolean repairItem(ItemStack item) {
|
||||
if (item.getItemMeta() instanceof Damageable damageable) {
|
||||
if (damageable.hasDamage()) {
|
||||
Damageable newMeta = (Damageable) damageable.clone();
|
||||
newMeta.setDamage(0);
|
||||
item.setItemMeta((org.bukkit.inventory.meta.ItemMeta) newMeta);
|
||||
return true;
|
||||
}
|
||||
if (item.getItemMeta() instanceof Damageable damageable && damageable.hasDamage()) {
|
||||
Damageable newMeta = (Damageable) damageable.clone();
|
||||
newMeta.setDamage(0);
|
||||
item.setItemMeta((org.bukkit.inventory.meta.ItemMeta) newMeta);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
private int repairAll(Player player) {
|
||||
int count = 0;
|
||||
ItemStack[] contents = player.getInventory().getContents();
|
||||
|
||||
for (ItemStack item : contents) {
|
||||
if (item != null && !item.getType().isAir()) {
|
||||
if (repairItem(item)) {
|
||||
count++;
|
||||
}
|
||||
for (ItemStack item : player.getInventory().getContents()) {
|
||||
if (item != null && !item.getType().isAir() && repairItem(item)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
// 也修复盔甲栏
|
||||
ItemStack[] armor = player.getInventory().getArmorContents();
|
||||
for (ItemStack item : armor) {
|
||||
if (item != null && !item.getType().isAir()) {
|
||||
if (repairItem(item)) {
|
||||
count++;
|
||||
}
|
||||
|
||||
for (ItemStack item : player.getInventory().getArmorContents()) {
|
||||
if (item != null && !item.getType().isAir() && repairItem(item)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
player.updateInventory();
|
||||
return count;
|
||||
}
|
||||
|
||||
@@ -2,55 +2,72 @@ package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
public class SeenCommand extends BaseCommand {
|
||||
|
||||
|
||||
public SeenCommand() {
|
||||
super("essentialsc.command.seen");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
return executeCommand(player, player, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
return executeCommand(sender, null, args);
|
||||
}
|
||||
|
||||
private boolean executeCommand(CommandSender sender, Player viewer, String[] args) {
|
||||
if (args.length == 0) {
|
||||
player.sendMessage(getLang().getString("messages.seen-usage"));
|
||||
sender.sendMessage(getLang().getPrefixedString(viewer == null
|
||||
? "messages.seen-usage-console"
|
||||
: "messages.seen-usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
Player onlineTarget = Bukkit.getPlayerExact(args[0]);
|
||||
if (onlineTarget != null && VanishCommand.isVanished(onlineTarget)
|
||||
&& viewer != null && !viewer.hasPermission(VanishCommand.SEE_PERMISSION)) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
OfflinePlayer target = Bukkit.getOfflinePlayer(args[0]);
|
||||
if (!target.hasPlayedBefore() && !target.isOnline()) {
|
||||
player.sendMessage(getLang().getString("messages.player-not-found", Map.of("player", args[0])));
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
StringBuilder info = new StringBuilder();
|
||||
info.append("§6========== §e玩家信息 §6==========\n");
|
||||
info.append("§7玩家名称: §f").append(target.getName()).append("\n");
|
||||
|
||||
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
sender.sendMessage(getLang().getPrefixedComponent("messages.seen-header",
|
||||
Map.of("player", String.valueOf(target.getName()))));
|
||||
|
||||
if (target.isOnline()) {
|
||||
info.append("§7状态: §a在线\n");
|
||||
sender.sendMessage(getLang().getComponent("messages.seen-status-online"));
|
||||
Player onlinePlayer = target.getPlayer();
|
||||
if (onlinePlayer != null) {
|
||||
info.append("§7所在世界: §f").append(onlinePlayer.getWorld().getName()).append("\n");
|
||||
sender.sendMessage(getLang().getComponent("messages.seen-world",
|
||||
Map.of("world", onlinePlayer.getWorld().getName())));
|
||||
}
|
||||
} else {
|
||||
info.append("§7状态: §c离线\n");
|
||||
sender.sendMessage(getLang().getComponent("messages.seen-status-offline"));
|
||||
long lastSeen = target.getLastSeen();
|
||||
if (lastSeen > 0) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
info.append("§7最后上线: §f").append(sdf.format(new Date(lastSeen))).append("\n");
|
||||
sender.sendMessage(getLang().getComponent("messages.seen-last-online",
|
||||
Map.of("time", format.format(new Date(lastSeen)))));
|
||||
}
|
||||
}
|
||||
|
||||
info.append("§7首次加入: §f").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(target.getFirstPlayed()))).append("\n");
|
||||
info.append("§6=============================");
|
||||
|
||||
player.sendMessage(info.toString());
|
||||
|
||||
sender.sendMessage(getLang().getComponent("messages.seen-first-joined",
|
||||
Map.of("time", format.format(new Date(target.getFirstPlayed())))));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.skinbridge.SkinBridgeManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
public final class SkinBridgeCommand extends BaseCommand implements TabCompleter {
|
||||
|
||||
private static final String STATUS_PERMISSION = "essentialsc.command.skin.status";
|
||||
private static final String REFRESH_PERMISSION = "essentialsc.command.skin.refresh";
|
||||
private static final String OTHERS_PERMISSION = "essentialsc.command.skin.others";
|
||||
|
||||
public SkinBridgeCommand() {
|
||||
super("essentialsc.command.skin");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
return executeCommand(player, args, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
return executeCommand(sender, args, true);
|
||||
}
|
||||
|
||||
private boolean executeCommand(CommandSender sender, String[] args, boolean console) {
|
||||
if (args.length < 1 || args.length > 2) {
|
||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
SkinBridgeManager manager = plugin.getSkinBridgeManager();
|
||||
if (manager == null) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = console ? null : (Player) sender;
|
||||
if (args.length == 2) {
|
||||
target = Bukkit.getPlayerExact(args[1]);
|
||||
if (target == null || !target.isOnline()) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[1])));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (target == null) {
|
||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
String action = args[0].toLowerCase(Locale.ROOT);
|
||||
boolean targetsOther = sender instanceof Player playerSender
|
||||
&& !playerSender.getUniqueId().equals(target.getUniqueId());
|
||||
if (action.equals("status")) {
|
||||
if (!hasPermission(sender, STATUS_PERMISSION)) {
|
||||
sendNoPermission(sender, STATUS_PERMISSION);
|
||||
return true;
|
||||
}
|
||||
if (targetsOther && !hasPermission(sender, OTHERS_PERMISSION)) {
|
||||
sendNoPermission(sender, OTHERS_PERMISSION);
|
||||
return true;
|
||||
}
|
||||
sendStatus(sender, target, manager);
|
||||
return true;
|
||||
}
|
||||
if (action.equals("refresh")) {
|
||||
if (!hasPermission(sender, REFRESH_PERMISSION)) {
|
||||
sendNoPermission(sender, REFRESH_PERMISSION);
|
||||
return true;
|
||||
}
|
||||
if (targetsOther && !hasPermission(sender, OTHERS_PERMISSION)) {
|
||||
sendNoPermission(sender, OTHERS_PERMISSION);
|
||||
return true;
|
||||
}
|
||||
sendRefreshResult(sender, target, manager.queueSync(target, true));
|
||||
return true;
|
||||
}
|
||||
|
||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.usage"));
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean hasPermission(CommandSender sender, String permission) {
|
||||
return !(sender instanceof Player) || sender.hasPermission(permission);
|
||||
}
|
||||
|
||||
private void sendNoPermission(CommandSender sender, String permission) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission", Map.of("permission", permission)));
|
||||
}
|
||||
|
||||
private void sendStatus(CommandSender sender, Player target, SkinBridgeManager manager) {
|
||||
if (!manager.isSkinGatewayAvailable()) {
|
||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.dependency-missing"));
|
||||
return;
|
||||
}
|
||||
if (manager.getProviderCount() == 0) {
|
||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.no-providers"));
|
||||
return;
|
||||
}
|
||||
|
||||
SkinBridgeManager.Status status = manager.getStatus(target);
|
||||
Map<String, String> placeholders = Map.of("player", target.getName(), "provider", String.valueOf(status.providerId()));
|
||||
switch (status.state()) {
|
||||
case EXTERNAL -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-external", placeholders));
|
||||
case EXCLUDED -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-excluded", placeholders));
|
||||
case NOT_EXTERNAL -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-not-external", placeholders));
|
||||
case PENDING -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-pending", placeholders));
|
||||
case UNKNOWN -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-unknown", placeholders));
|
||||
}
|
||||
}
|
||||
|
||||
private void sendRefreshResult(CommandSender sender, Player target, SkinBridgeManager.SyncResult result) {
|
||||
Map<String, String> placeholders = Map.of("player", target.getName());
|
||||
String messagePath = switch (result) {
|
||||
case QUEUED -> "skin-bridge.messages.refresh-queued";
|
||||
case CACHED -> "skin-bridge.messages.refresh-cached";
|
||||
case ALREADY_RUNNING -> "skin-bridge.messages.refresh-running";
|
||||
case EXCLUDED -> "skin-bridge.messages.refresh-excluded";
|
||||
case QUEUE_FULL -> "skin-bridge.messages.queue-full";
|
||||
case DEPENDENCY_MISSING -> "skin-bridge.messages.dependency-missing";
|
||||
case NO_PROVIDERS -> "skin-bridge.messages.no-providers";
|
||||
case REFRESH_COOLDOWN -> "skin-bridge.messages.refresh-cooldown";
|
||||
};
|
||||
if (result == SkinBridgeManager.SyncResult.REFRESH_COOLDOWN) {
|
||||
placeholders = Map.of(
|
||||
"player", target.getName(),
|
||||
"seconds", String.valueOf(plugin.getSkinBridgeManager().getRemainingForceRefreshCooldownSeconds(target))
|
||||
);
|
||||
}
|
||||
sender.sendMessage(getLang().getPrefixedString(messagePath, placeholders));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 1) {
|
||||
String partial = args[0].toLowerCase(Locale.ROOT);
|
||||
List<String> actions = new ArrayList<>();
|
||||
if (hasPermission(sender, STATUS_PERMISSION)) {
|
||||
actions.add("status");
|
||||
}
|
||||
if (hasPermission(sender, REFRESH_PERMISSION)) {
|
||||
actions.add("refresh");
|
||||
}
|
||||
return actions.stream()
|
||||
.filter(option -> option.startsWith(partial))
|
||||
.toList();
|
||||
}
|
||||
if (args.length == 2 && hasPermission(sender, OTHERS_PERMISSION)
|
||||
&& ((args[0].equalsIgnoreCase("status") && hasPermission(sender, STATUS_PERMISSION))
|
||||
|| (args[0].equalsIgnoreCase("refresh") && hasPermission(sender, REFRESH_PERMISSION)))) {
|
||||
String partial = args[1].toLowerCase(Locale.ROOT);
|
||||
List<String> players = new ArrayList<>();
|
||||
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
||||
if (onlinePlayer.getName().toLowerCase(Locale.ROOT).startsWith(partial)) {
|
||||
players.add(onlinePlayer.getName());
|
||||
}
|
||||
}
|
||||
return players;
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class SmithingTableCommand extends BaseCommand {
|
||||
|
||||
|
||||
public SmithingTableCommand() {
|
||||
super("essentialsc.command.smithingtable");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 使用 Paper API 打开锻造台(标题跟随客户端语言)
|
||||
player.openSmithingTable(null, true);
|
||||
player.openInventory(MenuType.SMITHING.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.SMITHING_TABLE, Sound.BLOCK_SMITHING_TABLE_USE);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class StonecutterCommand extends BaseCommand {
|
||||
|
||||
|
||||
public StonecutterCommand() {
|
||||
super("essentialsc.command.stonecutter");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 使用 Paper API 打开切石机(标题跟随客户端语言)
|
||||
player.openStonecutter(null, true);
|
||||
player.openInventory(MenuType.STONECUTTER.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.STONECUTTER, Sound.UI_STONECUTTER_SELECT_RECIPE);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,20 +2,15 @@ package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class SuicideCommand extends BaseCommand {
|
||||
|
||||
|
||||
public SuicideCommand() {
|
||||
super("essentialsc.command.suicide");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
String message = getLang().getString("messages.suicide-message",
|
||||
Map.of("player", player.getName()));
|
||||
player.setHealth(0);
|
||||
// 消息会在玩家死亡后显示,所以这里不发送
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class TpAcceptCommand extends BaseCommand implements TabCompleter {
|
||||
|
||||
public TpAcceptCommand() {
|
||||
super("essentialsc.command.tpaccept");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (args.length > 1) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.usage-tpaccept"));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
if (manager.isIgnoringRequests(player)) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Optional<TeleportRequestManager.TeleportRequest> request = manager.findIncoming(
|
||||
player,
|
||||
args.length == 0 ? null : args[0]
|
||||
);
|
||||
if (request.isEmpty()) {
|
||||
player.sendMessage(args.length == 0
|
||||
? getLang().getPrefixedComponent("tpa.messages.no-request")
|
||||
: getLang().getPrefixedComponent("tpa.messages.invalid-request", Map.of("requester", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager.TeleportRequest accepted = request.get();
|
||||
Map<String, String> placeholders = manager.placeholders(accepted);
|
||||
TeleportRequestManager.TeleportResult result = manager.accept(player, accepted);
|
||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.EXPIRED) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.expired", placeholders));
|
||||
return true;
|
||||
}
|
||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.PLAYER_OFFLINE) {
|
||||
return true;
|
||||
}
|
||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.ON_COOLDOWN) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.accept-cooldown",
|
||||
Map.of("seconds", String.valueOf(result.cooldownSeconds()))));
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length != 1 || !(sender instanceof Player player)) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
return List.of();
|
||||
}
|
||||
return manager.getIncomingRequesterNames(player, args[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class TpDenyCommand extends BaseCommand implements TabCompleter {
|
||||
|
||||
public TpDenyCommand() {
|
||||
super("essentialsc.command.tpdeny");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (args.length > 1) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.usage-tpdeny"));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
if (manager.isIgnoringRequests(player)) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
||||
return true;
|
||||
}
|
||||
|
||||
Optional<TeleportRequestManager.TeleportRequest> request = manager.findIncoming(
|
||||
player,
|
||||
args.length == 0 ? null : args[0]
|
||||
);
|
||||
if (request.isEmpty()) {
|
||||
player.sendMessage(args.length == 0
|
||||
? getLang().getPrefixedComponent("tpa.messages.no-request")
|
||||
: getLang().getPrefixedComponent("tpa.messages.invalid-request", Map.of("requester", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager.TeleportRequest denied = request.get();
|
||||
TeleportRequestManager.TeleportResult result = manager.deny(player, denied);
|
||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.EXPIRED) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.expired", manager.placeholders(denied)));
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length != 1 || !(sender instanceof Player player)) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
return List.of();
|
||||
}
|
||||
return manager.getIncomingRequesterNames(player, args[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class TpIgnoreCommand extends BaseCommand {
|
||||
|
||||
public TpIgnoreCommand() {
|
||||
super("essentialsc.command.tpignore");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager.ToggleIgnoreResult result = manager.toggleIgnoringRequests(player);
|
||||
String messagePath = switch (result) {
|
||||
case ENABLED -> "tpa.messages.ignore-enabled";
|
||||
case DISABLED -> "tpa.messages.ignore-disabled";
|
||||
case SAVE_FAILED -> "tpa.messages.ignore-save-failed";
|
||||
};
|
||||
player.sendMessage(getLang().getPrefixedComponent(messagePath));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class TpaAllCommand extends BaseCommand {
|
||||
|
||||
public TpaAllCommand() {
|
||||
super("essentialsc.command.tpaall");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
if (args.length != 0) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.usage-tpaall"));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
if (manager.isIgnoringRequests(player)) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
||||
return true;
|
||||
}
|
||||
|
||||
int sent = manager.sendTeleportAllRequest(player);
|
||||
if (sent <= 0) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.tpaall-no-targets"));
|
||||
return true;
|
||||
}
|
||||
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.tpaall-sent"));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class TpaCommand extends BaseCommand implements TabCompleter {
|
||||
|
||||
public TpaCommand() {
|
||||
super("essentialsc.command.tpa");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
return sendRequest(player, args, TeleportRequestManager.TeleportRequest.Type.TPA);
|
||||
}
|
||||
|
||||
protected boolean sendRequest(Player player, String[] args, TeleportRequestManager.TeleportRequest.Type type) {
|
||||
if (args.length != 1) {
|
||||
player.sendMessage(getLang().getPrefixedComponent(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
||||
? "tpa.messages.usage-tpa"
|
||||
: "tpa.messages.usage-tpahere"));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
if (manager.isIgnoringRequests(player)) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase(player.getName())) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.self"));
|
||||
return true;
|
||||
}
|
||||
|
||||
int remainingCooldown = manager.getRemainingSendCooldownSeconds(player);
|
||||
if (remainingCooldown > 0) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.send-cooldown",
|
||||
Map.of("seconds", String.valueOf(remainingCooldown))));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = manager.findOnlinePlayer(args[0], onlinePlayer ->
|
||||
!onlinePlayer.getUniqueId().equals(player.getUniqueId()) && !manager.isVanished(onlinePlayer)
|
||||
).orElse(null);
|
||||
if (target == null || !target.isOnline()) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("messages.player-not-found", Map.of("player", args[0])));
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager.CreateRequestResult createdRequest = manager.createRequest(player, target, type);
|
||||
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.ON_COOLDOWN) {
|
||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.send-cooldown",
|
||||
Map.of("seconds", String.valueOf(createdRequest.cooldownSeconds()))));
|
||||
return true;
|
||||
}
|
||||
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.CANCELLED) {
|
||||
return true;
|
||||
}
|
||||
|
||||
TeleportRequestManager.TeleportRequest request = createdRequest.request();
|
||||
Map<String, String> placeholders = manager.placeholders(request);
|
||||
player.sendMessage(getLang().getPrefixedComponent(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
||||
? "tpa.messages.sent-tpa"
|
||||
: "tpa.messages.sent-tpahere", placeholders));
|
||||
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.IGNORED
|
||||
|| createdRequest.status() == TeleportRequestManager.CreateRequestStatus.DUPLICATE) {
|
||||
return true;
|
||||
}
|
||||
target.sendMessage(getLang().getPrefixedComponent(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
||||
? "tpa.messages.received-tpa"
|
||||
: "tpa.messages.received-tpahere", placeholders));
|
||||
manager.playRequestReceivedSound(target);
|
||||
manager.sendResponseHint(target, placeholders);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length != 1 || !(sender instanceof Player player)) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||
if (manager == null) {
|
||||
return List.of();
|
||||
}
|
||||
String partial = args[0].toLowerCase();
|
||||
List<String> completions = new ArrayList<>();
|
||||
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
||||
if (!onlinePlayer.getUniqueId().equals(player.getUniqueId())
|
||||
&& !manager.isVanished(onlinePlayer)
|
||||
&& onlinePlayer.getName().toLowerCase().startsWith(partial)) {
|
||||
completions.add(onlinePlayer.getName());
|
||||
}
|
||||
}
|
||||
return completions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class TpaHereCommand extends TpaCommand {
|
||||
|
||||
public TpaHereCommand() {
|
||||
super();
|
||||
this.permission = "essentialsc.command.tpahere";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
return sendRequest(player, args, TeleportRequestManager.TeleportRequest.Type.TPAHERE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class TpsBarCommand extends BaseCommand implements TabCompleter {
|
||||
|
||||
public TpsBarCommand() {
|
||||
super("essentialsc.command.tpsbar");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
TpsBarService tpsBarService = plugin.getTpsBarManager();
|
||||
if (tpsBarService == null) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length == 0) {
|
||||
boolean enabled = tpsBarService.toggle(player);
|
||||
tpsBarService.sendToggleMessage(player, player, enabled);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length != 1) {
|
||||
player.sendMessage(tpsBarService.getUsageMessage());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!player.hasPermission("essentialsc.command.tpsbar.others")) {
|
||||
player.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
||||
Map.of("permission", "essentialsc.command.tpsbar.others")));
|
||||
return true;
|
||||
}
|
||||
|
||||
Collection<Player> targets = tpsBarService.resolveTargets(player, args[0]);
|
||||
if (targets.isEmpty()) {
|
||||
Player exactPlayer = Bukkit.getPlayerExact(args[0]);
|
||||
if (exactPlayer == null) {
|
||||
player.sendMessage(tpsBarService.getPlayerNotFoundMessage(args[0]));
|
||||
} else {
|
||||
player.sendMessage(tpsBarService.getNoTargetsMessage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
for (Player target : targets) {
|
||||
boolean enabled = tpsBarService.toggle(target);
|
||||
tpsBarService.sendToggleMessage(player, target, enabled);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||
TpsBarService tpsBarService = plugin.getTpsBarManager();
|
||||
if (tpsBarService == null) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||
return true;
|
||||
}
|
||||
if (args.length != 1) {
|
||||
sender.sendMessage(tpsBarService.getUsageMessage());
|
||||
return true;
|
||||
}
|
||||
if (!sender.hasPermission("essentialsc.command.tpsbar.others")) {
|
||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
||||
Map.of("permission", "essentialsc.command.tpsbar.others")));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayerExact(args[0]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(tpsBarService.getPlayerNotFoundMessage(args[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean enabled = tpsBarService.toggle(target);
|
||||
sender.sendMessage(getLang().getPrefixedString(enabled
|
||||
? "tpsbar.messages.enabled-other"
|
||||
: "tpsbar.messages.disabled-other", Map.of("player", target.getName())));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length != 1 || !sender.hasPermission("essentialsc.command.tpsbar.others")) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String partial = args[0].toLowerCase();
|
||||
List<String> completions = new ArrayList<>();
|
||||
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
||||
if (onlinePlayer.getName().toLowerCase().startsWith(partial)) {
|
||||
completions.add(onlinePlayer.getName());
|
||||
}
|
||||
}
|
||||
return completions;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,152 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class VanishCommand extends BaseCommand {
|
||||
|
||||
|
||||
private static final Set<UUID> vanishedPlayers = new HashSet<>();
|
||||
|
||||
public static final String SEE_PERMISSION = "essentialsc.vanish.see";
|
||||
private static File stateFile;
|
||||
|
||||
public VanishCommand() {
|
||||
super("essentialsc.command.vanish");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(@NotNull Player player, String[] args) {
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
|
||||
|
||||
if (vanishedPlayers.contains(uuid)) {
|
||||
// 取消隐身
|
||||
vanishedPlayers.remove(uuid);
|
||||
showPlayerToAll(player);
|
||||
player.sendMessage(getLang().getString("messages.vanish-disabled"));
|
||||
if (!saveState(plugin)) {
|
||||
vanishedPlayers.add(uuid);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-save-failed"));
|
||||
return true;
|
||||
}
|
||||
showPlayerToAll(plugin, player);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-disabled"));
|
||||
} else {
|
||||
// 开启隐身
|
||||
vanishedPlayers.add(uuid);
|
||||
hidePlayerFromAll(player);
|
||||
player.sendMessage(getLang().getString("messages.vanish-enabled"));
|
||||
if (!saveState(plugin)) {
|
||||
vanishedPlayers.remove(uuid);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-save-failed"));
|
||||
return true;
|
||||
}
|
||||
hidePlayerFromAll(plugin, player);
|
||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-enabled"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void hidePlayerFromAll(Player player) {
|
||||
|
||||
public static void loadState(EssentialsC plugin) {
|
||||
stateFile = new File(plugin.getDataFolder(), "vanished-players.yml");
|
||||
vanishedPlayers.clear();
|
||||
if (!stateFile.exists()) {
|
||||
return;
|
||||
}
|
||||
YamlConfiguration state = new YamlConfiguration();
|
||||
try {
|
||||
state.load(stateFile);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
plugin.getLogger().severe("加载 vanished-players.yml 失败: " + exception.getMessage());
|
||||
throw new IllegalStateException("无法加载 vanished-players.yml,请修复文件格式后重试。", exception);
|
||||
}
|
||||
for (String value : state.getStringList("players")) {
|
||||
try {
|
||||
vanishedPlayers.add(UUID.fromString(value));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
plugin.getLogger().warning("忽略无效的隐身玩家 UUID: " + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void hideVanishedPlayersFrom(EssentialsC plugin, Player observer) {
|
||||
if (observer.hasPermission(SEE_PERMISSION)) {
|
||||
return;
|
||||
}
|
||||
for (Player vanished : plugin.getServer().getOnlinePlayers()) {
|
||||
if (!observer.equals(vanished) && isVanished(vanished)) {
|
||||
observer.hidePlayer(plugin, vanished);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean restoreVisibility(EssentialsC plugin, Player player, boolean notify) {
|
||||
if (!vanishedPlayers.remove(player.getUniqueId())) {
|
||||
return true;
|
||||
}
|
||||
if (!saveState(plugin)) {
|
||||
vanishedPlayers.add(player.getUniqueId());
|
||||
if (notify) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-save-failed"));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
showPlayerToAll(plugin, player);
|
||||
if (notify) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-permission-removed"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void applyHiddenState(EssentialsC plugin, Player player) {
|
||||
if (isVanished(player)) {
|
||||
hidePlayerFromAll(plugin, player);
|
||||
}
|
||||
}
|
||||
|
||||
public static void clearAll(EssentialsC plugin) {
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
if (isVanished(player)) {
|
||||
showPlayerToAll(plugin, player);
|
||||
}
|
||||
}
|
||||
vanishedPlayers.clear();
|
||||
}
|
||||
|
||||
private static void hidePlayerFromAll(EssentialsC plugin, Player player) {
|
||||
for (Player online : player.getServer().getOnlinePlayers()) {
|
||||
if (online != player) {
|
||||
if (online != player && !online.hasPermission(SEE_PERMISSION)) {
|
||||
online.hidePlayer(plugin, player);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void showPlayerToAll(Player player) {
|
||||
|
||||
private static void showPlayerToAll(EssentialsC plugin, Player player) {
|
||||
for (Player online : player.getServer().getOnlinePlayers()) {
|
||||
if (online != player) {
|
||||
online.showPlayer(plugin, player);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static boolean isVanished(Player player) {
|
||||
return vanishedPlayers.contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
private static boolean saveState(EssentialsC plugin) {
|
||||
if (stateFile == null) {
|
||||
stateFile = new File(plugin.getDataFolder(), "vanished-players.yml");
|
||||
}
|
||||
FileConfiguration state = new YamlConfiguration();
|
||||
state.set("players", vanishedPlayers.stream().map(UUID::toString).sorted().toList());
|
||||
try {
|
||||
AtomicYamlWriter.save(state, stateFile);
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
plugin.getLogger().warning("保存 vanished-players.yml 失败: " + exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package cn.infstar.essentialsC.commands;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.MenuType;
|
||||
|
||||
public class WorkbenchCommand extends BaseCommand {
|
||||
|
||||
|
||||
public WorkbenchCommand() {
|
||||
super("essentialsc.command.workbench");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean execute(Player player, String[] args) {
|
||||
// 打开工作台(标题由客户端语言决定)
|
||||
player.openWorkbench(null, true);
|
||||
player.openInventory(MenuType.CRAFTING.builder().checkReachable(false).build(player));
|
||||
playBlockShortcutSound(player, Material.CRAFTING_TABLE, Sound.UI_BUTTON_CLICK);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package cn.infstar.essentialsC.listeners;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDeathEvent;
|
||||
|
||||
public class MobDropListener implements Listener {
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private boolean endermanDropsAllowed;
|
||||
|
||||
public MobDropListener(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
loadConfig();
|
||||
}
|
||||
|
||||
private void loadConfig() {
|
||||
FileConfiguration config = plugin.getConfig();
|
||||
config.addDefault("mob-drops.enderman.allow-drops", true);
|
||||
config.options().copyDefaults(true);
|
||||
|
||||
this.endermanDropsAllowed = config.getBoolean("mob-drops.enderman.allow-drops", true);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEntityDeath(EntityDeathEvent event) {
|
||||
if (event.getEntityType() != EntityType.ENDERMAN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!plugin.getConfig().getBoolean("mob-drops.enderman.allow-drops", true)) {
|
||||
event.getDrops().clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
loadConfig();
|
||||
plugin.getLogger().info("生物掉落配置已重载(末影人掉落: " + (endermanDropsAllowed ? "允许" : "禁止") + ")");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package cn.infstar.essentialsC.listeners;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.commands.MobDropCommand;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class MobDropMenuListener implements Listener {
|
||||
|
||||
private final EssentialsC plugin;
|
||||
|
||||
public MobDropMenuListener(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!(event.getView().getTopInventory().getHolder(false) instanceof MobDropCommand.MobDropMenuHolder)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.setCancelled(true);
|
||||
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemStack clickedItem = event.getCurrentItem();
|
||||
if (clickedItem == null || clickedItem.getType().isAir()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getRawSlot() == MobDropCommand.getEndermanSlot()) {
|
||||
if (!player.hasPermission("essentialsc.mobdrops.enderman")) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.no-permission",
|
||||
Map.of("permission", "essentialsc.mobdrops.enderman")));
|
||||
player.closeInventory();
|
||||
return;
|
||||
}
|
||||
toggleEndermanDrops(player);
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> MobDropCommand.openMobDropMenu(plugin, player), 2L);
|
||||
}
|
||||
}
|
||||
|
||||
private void toggleEndermanDrops(Player player) {
|
||||
FileConfiguration config = plugin.getConfig();
|
||||
boolean newValue = !config.getBoolean("mob-drops.enderman.allow-drops", true);
|
||||
if (!plugin.getFeatureConfigManager().updateMainConfigValue(
|
||||
"mob-drops.enderman.allow-drops", newValue)) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.mobdrop-save-failed",
|
||||
Map.of("error", "无法写入 config.yml")));
|
||||
return;
|
||||
}
|
||||
|
||||
String status = EssentialsC.getLangManager().getString(newValue
|
||||
? "mobdrops-menu.status.enabled"
|
||||
: "mobdrops-menu.status.disabled");
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.mobdrop-toggled",
|
||||
Map.of("status", status)));
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,53 @@
|
||||
package cn.infstar.essentialsC.listeners;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.event.inventory.InventoryType;
|
||||
import org.bukkit.event.player.PlayerDropItemEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerKickEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
|
||||
import org.bukkit.event.server.PluginDisableEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.bukkit.inventory.meta.BlockStateMeta;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class ShulkerBoxListener implements Listener {
|
||||
|
||||
private final EssentialsC plugin;
|
||||
// 存储玩家打开的潜影盒:玩家UUID -> (原始物品快照, 当前物品引用)
|
||||
private final Map<UUID, ShulkerBoxData> openShulkerBoxes = new HashMap<>();
|
||||
|
||||
// 预定义所有潜影盒材质(性能优化)
|
||||
|
||||
private static final int SHULKER_SIZE = 27;
|
||||
private static final int OFF_HAND_SLOT = 40;
|
||||
|
||||
private static final Set<Material> SHULKER_BOX_MATERIALS = Set.of(
|
||||
Material.SHULKER_BOX,
|
||||
Material.WHITE_SHULKER_BOX,
|
||||
@@ -46,189 +67,659 @@ public class ShulkerBoxListener implements Listener {
|
||||
Material.RED_SHULKER_BOX,
|
||||
Material.BLACK_SHULKER_BOX
|
||||
);
|
||||
|
||||
/**
|
||||
* 潜影盒数据记录
|
||||
*/
|
||||
private static class ShulkerBoxData {
|
||||
ItemStack originalSnapshot; // 打开时的物品快照(用于验证)
|
||||
ItemStack currentItem; // 当前物品引用(用于更新)
|
||||
int totalItems; // 打开时的物品总数(用于防刷)
|
||||
|
||||
ShulkerBoxData(ItemStack snapshot, ItemStack current, int items) {
|
||||
this.originalSnapshot = snapshot;
|
||||
this.currentItem = current;
|
||||
this.totalItems = items;
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final NamespacedKey sessionKey;
|
||||
private final Map<UUID, OpenShulkerSession> openShulkerBoxes = new HashMap<>();
|
||||
|
||||
private static final class ShulkerBoxHolder implements InventoryHolder {
|
||||
private final Inventory inventory;
|
||||
|
||||
private ShulkerBoxHolder(Component title) {
|
||||
this.inventory = Bukkit.createInventory(this, InventoryType.SHULKER_BOX, title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return inventory;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static final class OpenShulkerSession {
|
||||
private final String token;
|
||||
private final Inventory inventory;
|
||||
private final int preferredSlot;
|
||||
private boolean syncScheduled;
|
||||
|
||||
private OpenShulkerSession(String token, Inventory inventory, int preferredSlot) {
|
||||
this.token = token;
|
||||
this.inventory = inventory;
|
||||
this.preferredSlot = preferredSlot;
|
||||
}
|
||||
}
|
||||
|
||||
private record LocatedSource(ItemStack item, Consumer<ItemStack> save) {
|
||||
}
|
||||
|
||||
public ShulkerBoxListener(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||
this.sessionKey = new NamespacedKey(plugin, "open_shulker_session");
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
clearStaleSessionTokens(player);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onPlayerInteract(PlayerInteractEvent event) {
|
||||
// 只处理右键点击空气或方块的事件
|
||||
if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Player player = event.getPlayer();
|
||||
|
||||
// 检查权限
|
||||
if (!player.hasPermission("essentialsc.shulkerbox.open")) {
|
||||
if (!player.isSneaking() || !player.hasPermission("essentialsc.shulkerbox.open")) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemStack item = event.getItem();
|
||||
if (item == null || !isShulkerBox(item)) {
|
||||
|
||||
if (event.useItemInHand() == org.bukkit.event.Event.Result.DENY) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 只有潜行+右键才打开潜影盒
|
||||
if (!player.isSneaking()) {
|
||||
|
||||
if (openShulkerBoxes.containsKey(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 取消默认行为(防止放置潜影盒)
|
||||
event.setCancelled(true);
|
||||
|
||||
// 打开潜影盒
|
||||
openShulkerBox(player, item);
|
||||
|
||||
EquipmentSlot hand = event.getHand() == EquipmentSlot.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND;
|
||||
ItemStack sourceItem = getItemFromHand(player, hand);
|
||||
if (!isShulkerBox(sourceItem)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
|
||||
event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
|
||||
|
||||
if (sourceItem.getAmount() != 1) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-unstack-first"));
|
||||
return;
|
||||
}
|
||||
|
||||
ItemStack sourceSnapshot = sourceItem.clone();
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
||||
if (!player.isOnline() || openShulkerBoxes.containsKey(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemStack currentItem = getItemFromHand(player, hand);
|
||||
if (!isSameShulkerItem(currentItem, sourceSnapshot)) {
|
||||
return;
|
||||
}
|
||||
|
||||
openShulkerBox(player, hand, currentItem);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
||||
if (session == null || event.getView().getTopInventory() != session.inventory) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasSessionToken(event.getCurrentItem(), session.token)
|
||||
|| hasSessionToken(event.getCursor(), session.token)) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getClick() == ClickType.NUMBER_KEY) {
|
||||
ItemStack hotbarItem = player.getInventory().getItem(event.getHotbarButton());
|
||||
if (hasSessionToken(hotbarItem, session.token)) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (event.getClick() == ClickType.SWAP_OFFHAND
|
||||
&& hasSessionToken(player.getInventory().getItemInOffHand(), session.token)) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
int topSize = session.inventory.getSize();
|
||||
boolean clickTopInventory = ShulkerBoxSessionPolicy.isTopSlot(event.getRawSlot(), topSize);
|
||||
|
||||
if (clickTopInventory && isShulkerBox(event.getCursor())) {
|
||||
event.setCancelled(true);
|
||||
sendNestedMessage(player);
|
||||
return;
|
||||
}
|
||||
|
||||
if (clickTopInventory && event.getClick() == ClickType.NUMBER_KEY) {
|
||||
ItemStack hotbarItem = player.getInventory().getItem(event.getHotbarButton());
|
||||
if (isShulkerBox(hotbarItem)) {
|
||||
event.setCancelled(true);
|
||||
sendNestedMessage(player);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (clickTopInventory && event.getClick() == ClickType.SWAP_OFFHAND
|
||||
&& isShulkerBox(player.getInventory().getItemInOffHand())) {
|
||||
event.setCancelled(true);
|
||||
sendNestedMessage(player);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.isShiftClick() && isShulkerBox(event.getCurrentItem())) {
|
||||
event.setCancelled(true);
|
||||
sendNestedMessage(player);
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleSynchronization(player, session);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryDrag(InventoryDragEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
||||
if (session == null || event.getView().getTopInventory() != session.inventory) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasSessionToken(event.getOldCursor(), session.token)) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isShulkerBox(event.getOldCursor())
|
||||
&& ShulkerBoxSessionPolicy.touchesTopInventory(event.getRawSlots(), session.inventory.getSize())) {
|
||||
event.setCancelled(true);
|
||||
sendNestedMessage(player);
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleSynchronization(player, session);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClose(InventoryCloseEvent event) {
|
||||
if (!(event.getPlayer() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
UUID playerId = player.getUniqueId();
|
||||
ShulkerBoxData data = openShulkerBoxes.remove(playerId);
|
||||
|
||||
if (data == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Inventory closedInventory = event.getInventory();
|
||||
ItemStack currentItem = data.currentItem;
|
||||
|
||||
// 验证物品是否还存在
|
||||
if (currentItem == null || currentItem.getType().isAir()) {
|
||||
// 物品已不存在,丢弃 inventory 中的所有物品
|
||||
for (ItemStack item : closedInventory.getContents()) {
|
||||
if (item != null && !item.getType().isAir()) {
|
||||
player.getWorld().dropItemNaturally(player.getLocation(), item);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新潜影盒物品中的内容
|
||||
if (currentItem.getItemMeta() instanceof BlockStateMeta blockStateMeta) {
|
||||
if (blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox) {
|
||||
// 将 inventory 的内容复制回潜影盒
|
||||
ItemStack[] contents = closedInventory.getContents();
|
||||
for (int i = 0; i < 27 && i < contents.length; i++) {
|
||||
shulkerBox.getInventory().setItem(i, contents[i]);
|
||||
}
|
||||
|
||||
// 更新物品元数据
|
||||
blockStateMeta.setBlockState(shulkerBox);
|
||||
currentItem.setItemMeta(blockStateMeta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否是玩家打开的潜影盒(使用 get 避免两次查找)
|
||||
if (openShulkerBoxes.get(player.getUniqueId()) == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取点击的物品
|
||||
ItemStack clickedItem = event.getCurrentItem();
|
||||
if (clickedItem == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否是潜影盒,如果是则阻止放置
|
||||
if (isShulkerBox(clickedItem)) {
|
||||
event.setCancelled(true);
|
||||
player.sendMessage("§c不能在潜影盒中放入另一个潜影盒!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 检查物品是否为潜影盒(O(1) 时间复杂度)
|
||||
*/
|
||||
private boolean isShulkerBox(ItemStack item) {
|
||||
return SHULKER_BOX_MATERIALS.contains(item.getType());
|
||||
if (commitOpenShulker(player, event.getInventory())) {
|
||||
player.playSound(player.getLocation(), Sound.BLOCK_SHULKER_BOX_CLOSE, 0.8F, 1.0F);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开潜影盒
|
||||
*/
|
||||
private void openShulkerBox(Player player, ItemStack shulkerBox) {
|
||||
// 获取潜影盒的 BlockStateMeta
|
||||
if (!(shulkerBox.getItemMeta() instanceof BlockStateMeta blockStateMeta)) {
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onPlayerDropItem(PlayerDropItemEvent event) {
|
||||
OpenShulkerSession session = openShulkerBoxes.get(event.getPlayer().getUniqueId());
|
||||
if (session != null && hasSessionToken(event.getItemDrop().getItemStack(), session.token)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) {
|
||||
OpenShulkerSession session = openShulkerBoxes.get(event.getPlayer().getUniqueId());
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取潜影盒的方块状态
|
||||
if (!(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBoxBlock)) {
|
||||
|
||||
if (hasSessionToken(event.getMainHandItem(), session.token)
|
||||
|| hasSessionToken(event.getOffHandItem(), session.token)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onPlayerDeath(PlayerDeathEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
OpenShulkerSession session = openShulkerBoxes.remove(player.getUniqueId());
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建物品快照(用于后续验证)
|
||||
ItemStack snapshot = shulkerBox.clone();
|
||||
|
||||
// 计算当前物品总数(用于防刷检查)
|
||||
int totalItems = 0;
|
||||
for (ItemStack item : shulkerBoxBlock.getInventory().getContents()) {
|
||||
if (item != null && !item.getType().isAir()) {
|
||||
totalItems += item.getAmount();
|
||||
}
|
||||
}
|
||||
|
||||
// 获取潜影盒的自定义名称,如果没有则使用配置中的默认标题
|
||||
String title;
|
||||
if (shulkerBox.hasItemMeta() && shulkerBox.getItemMeta().hasDisplayName()) {
|
||||
// 使用潜影盒的自定义名称
|
||||
title = shulkerBox.getItemMeta().getDisplayName();
|
||||
|
||||
boolean saved;
|
||||
if (event.getKeepInventory()) {
|
||||
saved = writeSessionToPlayer(player, session, true);
|
||||
} else {
|
||||
// 使用配置文件中的默认标题
|
||||
String defaultTitle = plugin.getConfig().getString("shulkerbox.default-title", "");
|
||||
if (defaultTitle != null && !defaultTitle.isEmpty()) {
|
||||
// 转换颜色代码 & -> §
|
||||
title = defaultTitle.replace('&', '§');
|
||||
} else {
|
||||
// 如果配置为空,使用 "Shulker Box"(客户端会自动翻译)
|
||||
title = "Shulker Box";
|
||||
saved = writeSessionToDrops(event.getDrops(), session);
|
||||
if (!saved) {
|
||||
saved = writeSessionToPlayer(player, session, true);
|
||||
}
|
||||
}
|
||||
|
||||
// 创建一个新的 inventory(基于潜影盒的内容)
|
||||
Inventory inventory = Bukkit.createInventory(null, 27, title);
|
||||
|
||||
// 复制潜影盒的内容到新 inventory
|
||||
ItemStack[] contents = shulkerBoxBlock.getInventory().getContents();
|
||||
for (int i = 0; i < 27 && i < contents.length; i++) {
|
||||
inventory.setItem(i, contents[i]);
|
||||
|
||||
if (!saved) {
|
||||
handleLostSource(player, session, "玩家死亡时未找到唯一的源物品");
|
||||
}
|
||||
|
||||
// 记录玩家打开的潜影盒(包含快照和当前引用)
|
||||
openShulkerBoxes.put(player.getUniqueId(), new ShulkerBoxData(snapshot, shulkerBox, totalItems));
|
||||
|
||||
// 打开 inventory
|
||||
player.openInventory(inventory);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
commitCurrentSession(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerKick(PlayerKickEvent event) {
|
||||
commitCurrentSession(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
if (!openShulkerBoxes.containsKey(event.getPlayer().getUniqueId())) {
|
||||
clearStaleSessionTokens(event.getPlayer());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPluginDisable(PluginDisableEvent event) {
|
||||
if (event.getPlugin() == plugin) {
|
||||
shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
for (UUID playerId : List.copyOf(openShulkerBoxes.keySet())) {
|
||||
Player player = Bukkit.getPlayer(playerId);
|
||||
if (player == null) {
|
||||
openShulkerBoxes.remove(playerId);
|
||||
plugin.getLogger().warning("潜影盒会话关闭失败: 玩家 " + playerId + " 已离线。");
|
||||
continue;
|
||||
}
|
||||
|
||||
OpenShulkerSession session = openShulkerBoxes.get(playerId);
|
||||
boolean viewingSession = session != null && player.getOpenInventory().getTopInventory() == session.inventory;
|
||||
commitCurrentSession(player);
|
||||
if (viewingSession) {
|
||||
player.closeInventory();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void openShulkerBox(Player player, EquipmentSlot hand, ItemStack sourceItem) {
|
||||
if (!(sourceItem.getItemMeta() instanceof BlockStateMeta blockStateMeta)
|
||||
|| !(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox)) {
|
||||
sendOpenFailedMessage(player);
|
||||
return;
|
||||
}
|
||||
|
||||
String token = UUID.randomUUID().toString();
|
||||
ItemStack taggedSource = sourceItem.clone();
|
||||
setSessionToken(taggedSource, token);
|
||||
setItemInHand(player, hand, taggedSource);
|
||||
|
||||
ShulkerBoxHolder holder;
|
||||
try {
|
||||
holder = new ShulkerBoxHolder(resolveTitle(sourceItem));
|
||||
holder.getInventory().setContents(cloneContents(shulkerBox.getInventory().getContents()));
|
||||
} catch (RuntimeException exception) {
|
||||
clearTokenFromPlayer(player, token);
|
||||
plugin.getLogger().warning("打开潜影盒失败: " + exception.getMessage());
|
||||
sendOpenFailedMessage(player);
|
||||
return;
|
||||
}
|
||||
|
||||
int preferredSlot = hand == EquipmentSlot.HAND ? player.getInventory().getHeldItemSlot() : OFF_HAND_SLOT;
|
||||
OpenShulkerSession session = new OpenShulkerSession(token, holder.getInventory(), preferredSlot);
|
||||
openShulkerBoxes.put(player.getUniqueId(), session);
|
||||
|
||||
try {
|
||||
InventoryView openedView = player.openInventory(session.inventory);
|
||||
if (openedView == null
|
||||
|| openedView.getTopInventory() != session.inventory
|
||||
|| player.getOpenInventory().getTopInventory() != session.inventory) {
|
||||
rollbackFailedOpen(player, session);
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
plugin.getLogger().warning("打开潜影盒失败: " + exception.getMessage());
|
||||
rollbackFailedOpen(player, session);
|
||||
return;
|
||||
}
|
||||
|
||||
player.playSound(player.getLocation(), Sound.BLOCK_SHULKER_BOX_OPEN, 0.8F, 1.0F);
|
||||
}
|
||||
|
||||
private void rollbackFailedOpen(Player player, OpenShulkerSession session) {
|
||||
openShulkerBoxes.remove(player.getUniqueId(), session);
|
||||
clearTokenFromPlayer(player, session.token);
|
||||
sendOpenFailedMessage(player);
|
||||
}
|
||||
|
||||
private void scheduleSynchronization(Player player, OpenShulkerSession session) {
|
||||
if (session.syncScheduled) {
|
||||
return;
|
||||
}
|
||||
|
||||
session.syncScheduled = true;
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
||||
session.syncScheduled = false;
|
||||
if (openShulkerBoxes.get(player.getUniqueId()) != session) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!writeSessionToPlayer(player, session, false)) {
|
||||
openShulkerBoxes.remove(player.getUniqueId(), session);
|
||||
handleLostSource(player, session, "同步期间未找到唯一的源物品");
|
||||
if (player.getOpenInventory().getTopInventory() == session.inventory) {
|
||||
player.closeInventory();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void commitCurrentSession(Player player) {
|
||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
||||
if (session != null) {
|
||||
commitOpenShulker(player, session.inventory);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean commitOpenShulker(Player player, Inventory inventory) {
|
||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
||||
if (session == null || session.inventory != inventory) {
|
||||
return false;
|
||||
}
|
||||
|
||||
openShulkerBoxes.remove(player.getUniqueId(), session);
|
||||
boolean saved = writeSessionToPlayer(player, session, true);
|
||||
if (!saved) {
|
||||
handleLostSource(player, session, "关闭期间未找到唯一的源物品");
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
private boolean writeSessionToPlayer(Player player, OpenShulkerSession session, boolean clearToken) {
|
||||
List<LocatedSource> sources = findSources(player, session);
|
||||
if (sources.size() != 1) {
|
||||
clearSessionTokens(sources);
|
||||
return false;
|
||||
}
|
||||
|
||||
LocatedSource source = sources.getFirst();
|
||||
if (source.item().getAmount() != 1) {
|
||||
clearSessionTokens(sources);
|
||||
return false;
|
||||
}
|
||||
|
||||
ItemStack updatedItem = source.item().clone();
|
||||
if (!writeInventoryBack(updatedItem, session.inventory.getContents(), clearToken)) {
|
||||
clearSessionTokens(sources);
|
||||
return false;
|
||||
}
|
||||
|
||||
source.save().accept(updatedItem);
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean writeSessionToDrops(List<ItemStack> drops, OpenShulkerSession session) {
|
||||
List<Integer> matchingIndexes = new ArrayList<>();
|
||||
for (int index = 0; index < drops.size(); index++) {
|
||||
if (hasSessionToken(drops.get(index), session.token)) {
|
||||
matchingIndexes.add(index);
|
||||
}
|
||||
}
|
||||
|
||||
if (matchingIndexes.size() != 1) {
|
||||
clearTokensFromDrops(drops, matchingIndexes);
|
||||
return false;
|
||||
}
|
||||
|
||||
int sourceIndex = matchingIndexes.getFirst();
|
||||
ItemStack sourceItem = drops.get(sourceIndex);
|
||||
if (sourceItem.getAmount() != 1) {
|
||||
clearTokensFromDrops(drops, matchingIndexes);
|
||||
return false;
|
||||
}
|
||||
|
||||
ItemStack updatedItem = sourceItem.clone();
|
||||
if (!writeInventoryBack(updatedItem, session.inventory.getContents(), true)) {
|
||||
clearTokensFromDrops(drops, matchingIndexes);
|
||||
return false;
|
||||
}
|
||||
|
||||
drops.set(sourceIndex, updatedItem);
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean writeInventoryBack(ItemStack shulkerItem, ItemStack[] contents, boolean clearToken) {
|
||||
if (containsShulkerBox(contents)) {
|
||||
plugin.getLogger().warning("保存潜影盒内容失败: 虚拟容器中检测到嵌套潜影盒。");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(shulkerItem.getItemMeta() instanceof BlockStateMeta blockStateMeta)) {
|
||||
plugin.getLogger().warning("保存潜影盒内容失败: 缺少 BlockStateMeta。");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox)) {
|
||||
plugin.getLogger().warning("保存潜影盒内容失败: 方块状态不是 ShulkerBox。");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
shulkerBox.getInventory().setContents(cloneContents(contents));
|
||||
blockStateMeta.setBlockState(shulkerBox);
|
||||
if (clearToken) {
|
||||
blockStateMeta.getPersistentDataContainer().remove(sessionKey);
|
||||
}
|
||||
shulkerItem.setItemMeta(blockStateMeta);
|
||||
return true;
|
||||
} catch (RuntimeException exception) {
|
||||
plugin.getLogger().warning("保存潜影盒内容失败: " + exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private List<LocatedSource> findSources(Player player, OpenShulkerSession session) {
|
||||
List<LocatedSource> sources = new ArrayList<>();
|
||||
PlayerInventory inventory = player.getInventory();
|
||||
|
||||
if (session.preferredSlot >= 0 && session.preferredSlot < inventory.getSize()) {
|
||||
addSourceIfMatching(
|
||||
sources,
|
||||
inventory.getItem(session.preferredSlot),
|
||||
item -> inventory.setItem(session.preferredSlot, item),
|
||||
session.token
|
||||
);
|
||||
}
|
||||
|
||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
||||
if (slot == session.preferredSlot) {
|
||||
continue;
|
||||
}
|
||||
int inventorySlot = slot;
|
||||
addSourceIfMatching(
|
||||
sources,
|
||||
inventory.getItem(inventorySlot),
|
||||
item -> inventory.setItem(inventorySlot, item),
|
||||
session.token
|
||||
);
|
||||
}
|
||||
|
||||
addSourceIfMatching(sources, player.getItemOnCursor(), player::setItemOnCursor, session.token);
|
||||
return sources;
|
||||
}
|
||||
|
||||
private void addSourceIfMatching(
|
||||
List<LocatedSource> sources,
|
||||
ItemStack item,
|
||||
Consumer<ItemStack> save,
|
||||
String token
|
||||
) {
|
||||
if (hasSessionToken(item, token)) {
|
||||
sources.add(new LocatedSource(item, save));
|
||||
}
|
||||
}
|
||||
|
||||
private void clearSessionTokens(List<LocatedSource> sources) {
|
||||
for (LocatedSource source : sources) {
|
||||
ItemStack cleanedItem = source.item().clone();
|
||||
clearSessionToken(cleanedItem);
|
||||
source.save().accept(cleanedItem);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearTokensFromDrops(List<ItemStack> drops, List<Integer> indexes) {
|
||||
for (int index : indexes) {
|
||||
ItemStack cleanedItem = drops.get(index).clone();
|
||||
clearSessionToken(cleanedItem);
|
||||
drops.set(index, cleanedItem);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearTokenFromPlayer(Player player, String token) {
|
||||
PlayerInventory inventory = player.getInventory();
|
||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
||||
ItemStack item = inventory.getItem(slot);
|
||||
if (!hasSessionToken(item, token)) {
|
||||
continue;
|
||||
}
|
||||
ItemStack cleanedItem = item.clone();
|
||||
clearSessionToken(cleanedItem);
|
||||
inventory.setItem(slot, cleanedItem);
|
||||
}
|
||||
|
||||
ItemStack cursor = player.getItemOnCursor();
|
||||
if (hasSessionToken(cursor, token)) {
|
||||
ItemStack cleanedCursor = cursor.clone();
|
||||
clearSessionToken(cleanedCursor);
|
||||
player.setItemOnCursor(cleanedCursor);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearStaleSessionTokens(Player player) {
|
||||
PlayerInventory inventory = player.getInventory();
|
||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
||||
ItemStack item = inventory.getItem(slot);
|
||||
if (!hasAnySessionToken(item)) {
|
||||
continue;
|
||||
}
|
||||
ItemStack cleanedItem = item.clone();
|
||||
clearSessionToken(cleanedItem);
|
||||
inventory.setItem(slot, cleanedItem);
|
||||
}
|
||||
|
||||
ItemStack cursor = player.getItemOnCursor();
|
||||
if (hasAnySessionToken(cursor)) {
|
||||
ItemStack cleanedCursor = cursor.clone();
|
||||
clearSessionToken(cleanedCursor);
|
||||
player.setItemOnCursor(cleanedCursor);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleLostSource(Player player, OpenShulkerSession session, String reason) {
|
||||
clearTokenFromPlayer(player, session.token);
|
||||
plugin.getLogger().warning("潜影盒会话已终止: " + player.getName() + " (" + player.getUniqueId() + ")," + reason + "。");
|
||||
if (player.isOnline()) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-session-invalid"));
|
||||
}
|
||||
}
|
||||
|
||||
private void setSessionToken(ItemStack item, String token) {
|
||||
ItemMeta itemMeta = item.getItemMeta();
|
||||
itemMeta.getPersistentDataContainer().set(sessionKey, PersistentDataType.STRING, token);
|
||||
item.setItemMeta(itemMeta);
|
||||
}
|
||||
|
||||
private void clearSessionToken(ItemStack item) {
|
||||
ItemMeta itemMeta = item.getItemMeta();
|
||||
if (itemMeta == null) {
|
||||
return;
|
||||
}
|
||||
itemMeta.getPersistentDataContainer().remove(sessionKey);
|
||||
item.setItemMeta(itemMeta);
|
||||
}
|
||||
|
||||
private boolean hasSessionToken(ItemStack item, String token) {
|
||||
if (!isShulkerBox(item)) {
|
||||
return false;
|
||||
}
|
||||
ItemMeta itemMeta = item.getItemMeta();
|
||||
if (itemMeta == null) {
|
||||
return false;
|
||||
}
|
||||
String storedToken = itemMeta.getPersistentDataContainer().get(sessionKey, PersistentDataType.STRING);
|
||||
return token.equals(storedToken);
|
||||
}
|
||||
|
||||
private boolean hasAnySessionToken(ItemStack item) {
|
||||
if (!isShulkerBox(item)) {
|
||||
return false;
|
||||
}
|
||||
ItemMeta itemMeta = item.getItemMeta();
|
||||
return itemMeta != null && itemMeta.getPersistentDataContainer().has(sessionKey, PersistentDataType.STRING);
|
||||
}
|
||||
|
||||
private ItemStack[] cloneContents(ItemStack[] contents) {
|
||||
ItemStack[] copied = new ItemStack[SHULKER_SIZE];
|
||||
for (int index = 0; index < SHULKER_SIZE && index < contents.length; index++) {
|
||||
copied[index] = contents[index] == null ? null : contents[index].clone();
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
|
||||
private boolean containsShulkerBox(ItemStack[] contents) {
|
||||
for (ItemStack item : contents) {
|
||||
if (isShulkerBox(item)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private ItemStack getItemFromHand(Player player, EquipmentSlot hand) {
|
||||
return hand == EquipmentSlot.OFF_HAND
|
||||
? player.getInventory().getItemInOffHand()
|
||||
: player.getInventory().getItemInMainHand();
|
||||
}
|
||||
|
||||
private void setItemInHand(Player player, EquipmentSlot hand, ItemStack item) {
|
||||
if (hand == EquipmentSlot.OFF_HAND) {
|
||||
player.getInventory().setItemInOffHand(item);
|
||||
} else {
|
||||
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), item);
|
||||
}
|
||||
}
|
||||
|
||||
private Component resolveTitle(ItemStack shulkerBox) {
|
||||
ItemMeta itemMeta = shulkerBox.getItemMeta();
|
||||
if (itemMeta != null && itemMeta.hasDisplayName()) {
|
||||
Component displayName = itemMeta.displayName();
|
||||
if (displayName != null) {
|
||||
return displayName;
|
||||
}
|
||||
}
|
||||
|
||||
return Component.translatable(shulkerBox.getType().getItemTranslationKey());
|
||||
}
|
||||
|
||||
private void sendNestedMessage(Player player) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-nested"));
|
||||
}
|
||||
|
||||
private void sendOpenFailedMessage(Player player) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-open-failed"));
|
||||
}
|
||||
|
||||
private boolean isShulkerBox(ItemStack item) {
|
||||
return item != null && !item.getType().isAir() && SHULKER_BOX_MATERIALS.contains(item.getType());
|
||||
}
|
||||
|
||||
private boolean isSameShulkerItem(ItemStack currentItem, ItemStack sourceSnapshot) {
|
||||
if (!isShulkerBox(currentItem) || sourceSnapshot == null) {
|
||||
return false;
|
||||
}
|
||||
return currentItem.getAmount() == sourceSnapshot.getAmount() && currentItem.isSimilar(sourceSnapshot);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package cn.infstar.essentialsC.listeners;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
final class ShulkerBoxSessionPolicy {
|
||||
|
||||
private ShulkerBoxSessionPolicy() {
|
||||
}
|
||||
|
||||
static boolean isTopSlot(int rawSlot, int topInventorySize) {
|
||||
return rawSlot >= 0 && rawSlot < topInventorySize;
|
||||
}
|
||||
|
||||
static boolean touchesTopInventory(Set<Integer> rawSlots, int topInventorySize) {
|
||||
return rawSlots.stream().anyMatch(rawSlot -> isTopSlot(rawSlot, topInventorySize));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package cn.infstar.essentialsC.listeners;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.commands.VanishCommand;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class VanishListener implements Listener {
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final BukkitTask permissionTask;
|
||||
private final Map<UUID, Boolean> observerSeePermissions = new HashMap<>();
|
||||
|
||||
public VanishListener(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
VanishCommand.loadState(plugin);
|
||||
this.permissionTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this::checkPermissions, 40L, 40L);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
observerSeePermissions.put(player.getUniqueId(), player.hasPermission(VanishCommand.SEE_PERMISSION));
|
||||
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
||||
VanishCommand.restoreVisibility(plugin, player, false);
|
||||
}
|
||||
if (VanishCommand.isVanished(player)) {
|
||||
event.joinMessage(null);
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> VanishCommand.applyHiddenState(plugin, player));
|
||||
}
|
||||
VanishCommand.hideVanishedPlayersFrom(plugin, event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
observerSeePermissions.remove(event.getPlayer().getUniqueId());
|
||||
Player player = event.getPlayer();
|
||||
if (VanishCommand.isVanished(player)) {
|
||||
event.quitMessage(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
permissionTask.cancel();
|
||||
}
|
||||
|
||||
private void checkPermissions() {
|
||||
Set<UUID> onlinePlayers = new HashSet<>();
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
onlinePlayers.add(player.getUniqueId());
|
||||
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
||||
VanishCommand.restoreVisibility(plugin, player, true);
|
||||
}
|
||||
}
|
||||
observerSeePermissions.keySet().removeIf(uuid -> !onlinePlayers.contains(uuid));
|
||||
|
||||
for (Player observer : plugin.getServer().getOnlinePlayers()) {
|
||||
boolean canSeeVanished = observer.hasPermission(VanishCommand.SEE_PERMISSION);
|
||||
Boolean previous = observerSeePermissions.put(observer.getUniqueId(), canSeeVanished);
|
||||
if (previous == null || previous != canSeeVanished) {
|
||||
refreshObserverVisibility(observer, canSeeVanished);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshObserverVisibility(Player observer, boolean canSeeVanished) {
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
if (observer.equals(player) || !VanishCommand.isVanished(player)) {
|
||||
continue;
|
||||
}
|
||||
if (canSeeVanished) {
|
||||
observer.showPlayer(plugin, player);
|
||||
} else {
|
||||
observer.hidePlayer(plugin, player);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package cn.infstar.essentialsC.player;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
public final class PlayerStateManager implements Listener {
|
||||
|
||||
public static final String FLY_PERMISSION = "essentialsc.command.fly";
|
||||
public static final String NIGHT_VISION_PERMISSION = "essentialsc.command.nightvision";
|
||||
public static final String GLOW_PERMISSION = "essentialsc.command.glow";
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final NamespacedKey flyEnabledKey;
|
||||
private final NamespacedKey flyPreviousAllowKey;
|
||||
private final NamespacedKey flyPreviousFlyingKey;
|
||||
private final NamespacedKey nightVisionEnabledKey;
|
||||
private final NamespacedKey glowEnabledKey;
|
||||
private final BukkitTask permissionTask;
|
||||
|
||||
public PlayerStateManager(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
this.flyEnabledKey = new NamespacedKey(plugin, "fly_enabled");
|
||||
this.flyPreviousAllowKey = new NamespacedKey(plugin, "fly_previous_allow");
|
||||
this.flyPreviousFlyingKey = new NamespacedKey(plugin, "fly_previous_flying");
|
||||
this.nightVisionEnabledKey = new NamespacedKey(plugin, "nightvision_enabled");
|
||||
this.glowEnabledKey = new NamespacedKey(plugin, "glow_enabled");
|
||||
this.permissionTask = plugin.getServer().getScheduler()
|
||||
.runTaskTimer(plugin, this::reconcileOnlinePlayers, 40L, 40L);
|
||||
}
|
||||
|
||||
public boolean isFlyEnabled(Player player) {
|
||||
return isMarked(player, flyEnabledKey);
|
||||
}
|
||||
|
||||
public void enableFly(Player player) {
|
||||
if (isFlyEnabled(player)) {
|
||||
player.setAllowFlight(true);
|
||||
player.setFlying(true);
|
||||
return;
|
||||
}
|
||||
|
||||
PersistentDataContainer data = player.getPersistentDataContainer();
|
||||
setBoolean(data, flyPreviousAllowKey, player.getAllowFlight());
|
||||
setBoolean(data, flyPreviousFlyingKey, player.isFlying());
|
||||
setBoolean(data, flyEnabledKey, true);
|
||||
player.setAllowFlight(true);
|
||||
player.setFlying(true);
|
||||
}
|
||||
|
||||
public void disableFly(Player player) {
|
||||
PersistentDataContainer data = player.getPersistentDataContainer();
|
||||
if (!isMarked(data, flyEnabledKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean previousAllow = getBoolean(data, flyPreviousAllowKey);
|
||||
boolean previousFlying = getBoolean(data, flyPreviousFlyingKey);
|
||||
clearFlyMarkers(data);
|
||||
|
||||
boolean allowFlight = previousAllow || hasGameModeFlight(player);
|
||||
player.setFlying(previousFlying && allowFlight);
|
||||
player.setAllowFlight(allowFlight);
|
||||
}
|
||||
|
||||
public boolean isNightVisionEnabled(Player player) {
|
||||
return isMarked(player, nightVisionEnabledKey);
|
||||
}
|
||||
|
||||
public void enableNightVision(Player player) {
|
||||
if (!player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
|
||||
player.addPotionEffect(new PotionEffect(
|
||||
PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false, false));
|
||||
setBoolean(player.getPersistentDataContainer(), nightVisionEnabledKey, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void disableNightVision(Player player) {
|
||||
if (!isNightVisionEnabled(player)) {
|
||||
return;
|
||||
}
|
||||
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
|
||||
player.getPersistentDataContainer().remove(nightVisionEnabledKey);
|
||||
}
|
||||
|
||||
public boolean isGlowEnabled(Player player) {
|
||||
return isMarked(player, glowEnabledKey);
|
||||
}
|
||||
|
||||
public void enableGlow(Player player) {
|
||||
if (!player.isGlowing()) {
|
||||
player.setGlowing(true);
|
||||
setBoolean(player.getPersistentDataContainer(), glowEnabledKey, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void disableGlow(Player player) {
|
||||
if (!isGlowEnabled(player)) {
|
||||
return;
|
||||
}
|
||||
player.setGlowing(false);
|
||||
player.getPersistentDataContainer().remove(glowEnabledKey);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> reconcilePlayer(event.getPlayer(), false));
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
permissionTask.cancel();
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
releaseOwnedStates(player, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileOnlinePlayers() {
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
reconcilePlayer(player, true);
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcilePlayer(Player player, boolean notify) {
|
||||
if (isFlyEnabled(player)) {
|
||||
if (!player.hasPermission(FLY_PERMISSION)) {
|
||||
disableFly(player);
|
||||
notifyPermissionRemoval(player, "messages.fly-permission-removed", notify);
|
||||
} else if (!player.getAllowFlight()) {
|
||||
player.setAllowFlight(true);
|
||||
}
|
||||
}
|
||||
|
||||
if (isNightVisionEnabled(player)) {
|
||||
if (!player.hasPermission(NIGHT_VISION_PERMISSION)) {
|
||||
disableNightVision(player);
|
||||
notifyPermissionRemoval(player, "messages.nightvision-permission-removed", notify);
|
||||
} else if (!player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
|
||||
player.addPotionEffect(new PotionEffect(
|
||||
PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false, false));
|
||||
}
|
||||
}
|
||||
|
||||
if (isGlowEnabled(player)) {
|
||||
if (!player.hasPermission(GLOW_PERMISSION)) {
|
||||
disableGlow(player);
|
||||
notifyPermissionRemoval(player, "messages.glow-permission-removed", notify);
|
||||
} else if (!player.isGlowing()) {
|
||||
player.setGlowing(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseOwnedStates(Player player, boolean notify) {
|
||||
if (isFlyEnabled(player)) {
|
||||
disableFly(player);
|
||||
notifyPermissionRemoval(player, "messages.fly-permission-removed", notify);
|
||||
}
|
||||
if (isNightVisionEnabled(player)) {
|
||||
disableNightVision(player);
|
||||
notifyPermissionRemoval(player, "messages.nightvision-permission-removed", notify);
|
||||
}
|
||||
if (isGlowEnabled(player)) {
|
||||
disableGlow(player);
|
||||
notifyPermissionRemoval(player, "messages.glow-permission-removed", notify);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyPermissionRemoval(Player player, String path, boolean notify) {
|
||||
if (notify) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(path));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isMarked(Player player, NamespacedKey key) {
|
||||
return isMarked(player.getPersistentDataContainer(), key);
|
||||
}
|
||||
|
||||
private boolean isMarked(PersistentDataContainer data, NamespacedKey key) {
|
||||
Byte value = data.get(key, PersistentDataType.BYTE);
|
||||
return value != null && value == (byte) 1;
|
||||
}
|
||||
|
||||
private boolean getBoolean(PersistentDataContainer data, NamespacedKey key) {
|
||||
return isMarked(data, key);
|
||||
}
|
||||
|
||||
private void setBoolean(PersistentDataContainer data, NamespacedKey key, boolean value) {
|
||||
data.set(key, PersistentDataType.BYTE, value ? (byte) 1 : (byte) 0);
|
||||
}
|
||||
|
||||
private void clearFlyMarkers(PersistentDataContainer data) {
|
||||
data.remove(flyEnabledKey);
|
||||
data.remove(flyPreviousAllowKey);
|
||||
data.remove(flyPreviousFlyingKey);
|
||||
}
|
||||
|
||||
private boolean hasGameModeFlight(Player player) {
|
||||
return player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package cn.infstar.essentialsC.skinbridge;
|
||||
|
||||
import com.destroystokyo.paper.profile.PlayerProfile;
|
||||
import com.destroystokyo.paper.profile.ProfileProperty;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
|
||||
public final class MineSkinGateway implements SkinBridgeGateway {
|
||||
|
||||
private static final String TEXTURES_PROPERTY = "textures";
|
||||
private static final String QUEUE_PATH = "/v2/queue";
|
||||
private static final long POLL_INTERVAL_MILLIS = 1000L;
|
||||
private static final int MAX_RATE_LIMIT_RETRIES = 3;
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final URI queueUri;
|
||||
private final String apiKey;
|
||||
private final String visibility;
|
||||
private final int timeoutSeconds;
|
||||
private final long minimumSubmitIntervalMillis;
|
||||
private final String userAgent;
|
||||
private final Object submissionLock = new Object();
|
||||
private long lastSubmissionMillis;
|
||||
|
||||
public MineSkinGateway(HttpClient httpClient, String endpoint, String apiKey, String visibility, int timeoutSeconds,
|
||||
long minimumSubmitIntervalMillis, String userAgent) {
|
||||
this.httpClient = httpClient;
|
||||
this.queueUri = URI.create(normalizeEndpoint(endpoint) + QUEUE_PATH);
|
||||
this.apiKey = apiKey;
|
||||
this.visibility = normalizeVisibility(visibility);
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
this.minimumSubmitIntervalMillis = minimumSubmitIntervalMillis;
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GeneratedSkin generateSkin(String skinUrl, SkinModel model) throws Exception {
|
||||
JsonObject requestBody = new JsonObject();
|
||||
requestBody.addProperty("url", skinUrl);
|
||||
requestBody.addProperty("variant", model == SkinModel.SLIM ? "slim" : "classic");
|
||||
requestBody.addProperty("visibility", visibility);
|
||||
|
||||
HttpResponse<String> response;
|
||||
synchronized (submissionLock) {
|
||||
waitForSubmissionInterval();
|
||||
try {
|
||||
response = submitWithRateLimitRetry(requestBody.toString());
|
||||
} finally {
|
||||
lastSubmissionMillis = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
JsonObject body = parseResponse(response);
|
||||
if (response.statusCode() == 200) {
|
||||
return parseGeneratedSkin(body);
|
||||
}
|
||||
if (response.statusCode() != 202) {
|
||||
throw apiError("提交 MineSkin 生成请求", response, body);
|
||||
}
|
||||
|
||||
JsonObject job = object(body, "job");
|
||||
String jobId = string(job, "id");
|
||||
return pollJob(jobId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applySkin(Player player, GeneratedSkin skin) {
|
||||
PlayerProfile profile = player.getPlayerProfile();
|
||||
profile.removeProperty(TEXTURES_PROPERTY);
|
||||
profile.setProperty(new ProfileProperty(TEXTURES_PROPERTY, skin.value(), skin.signature()));
|
||||
player.setPlayerProfile(profile);
|
||||
}
|
||||
|
||||
private GeneratedSkin pollJob(String jobId) throws Exception {
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(timeoutSeconds).toNanos();
|
||||
URI jobUri = URI.create(queueUri + "/" + jobId);
|
||||
while (System.nanoTime() < deadline) {
|
||||
HttpResponse<String> response = send(HttpRequest.newBuilder(jobUri).GET());
|
||||
if (response.statusCode() == 429) {
|
||||
Thread.sleep(readRetryDelayMillis(response, 0));
|
||||
continue;
|
||||
}
|
||||
JsonObject body = parseResponse(response);
|
||||
if (response.statusCode() != 200) {
|
||||
throw apiError("查询 MineSkin 生成任务", response, body);
|
||||
}
|
||||
|
||||
JsonObject job = object(body, "job");
|
||||
String status = string(job, "status");
|
||||
if ("completed".equalsIgnoreCase(status)) {
|
||||
return parseGeneratedSkin(body);
|
||||
}
|
||||
if ("failed".equalsIgnoreCase(status)) {
|
||||
throw new IllegalStateException("MineSkin 生成任务失败: " + errorMessage(body));
|
||||
}
|
||||
if (!"waiting".equalsIgnoreCase(status) && !"active".equalsIgnoreCase(status)) {
|
||||
throw new IllegalStateException("MineSkin 返回未知任务状态: " + status);
|
||||
}
|
||||
Thread.sleep(POLL_INTERVAL_MILLIS);
|
||||
}
|
||||
throw new IllegalStateException("MineSkin 生成任务超时,请增大 config.yml 中的 skin-bridge.mineskin.request-timeout-seconds。");
|
||||
}
|
||||
|
||||
private void waitForSubmissionInterval() throws InterruptedException {
|
||||
long waitMillis = minimumSubmitIntervalMillis - (System.currentTimeMillis() - lastSubmissionMillis);
|
||||
if (waitMillis > 0L) {
|
||||
Thread.sleep(waitMillis);
|
||||
}
|
||||
}
|
||||
|
||||
private HttpResponse<String> submitWithRateLimitRetry(String requestBody) throws Exception {
|
||||
HttpResponse<String> response = null;
|
||||
for (int attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
|
||||
response = send(HttpRequest.newBuilder(queueUri)
|
||||
.POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
|
||||
.header("Content-Type", "application/json"));
|
||||
if (response.statusCode() != 429 || attempt == MAX_RATE_LIMIT_RETRIES) {
|
||||
return response;
|
||||
}
|
||||
Thread.sleep(readRetryDelayMillis(response, attempt));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private long readRetryDelayMillis(HttpResponse<?> response, int attempt) {
|
||||
long fallback = Math.min(30_000L, 1000L << Math.min(attempt, 5));
|
||||
return response.headers().firstValue("Retry-After")
|
||||
.map(String::trim)
|
||||
.filter(value -> value.matches("\\d+"))
|
||||
.map(value -> {
|
||||
try {
|
||||
return Math.min(60_000L, Long.parseLong(value) * 1000L);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
})
|
||||
.orElse(fallback);
|
||||
}
|
||||
|
||||
private HttpResponse<String> send(HttpRequest.Builder builder) throws Exception {
|
||||
HttpRequest request = builder
|
||||
.timeout(Duration.ofSeconds(timeoutSeconds))
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", "Bearer " + apiKey)
|
||||
.header("User-Agent", userAgent)
|
||||
.build();
|
||||
return httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private JsonObject parseResponse(HttpResponse<String> response) {
|
||||
if (response.body() == null || response.body().isBlank()) {
|
||||
throw new IllegalStateException("MineSkin 返回空响应,HTTP " + response.statusCode());
|
||||
}
|
||||
if (response.body().length() > 1_048_576) {
|
||||
throw new IllegalStateException("MineSkin 响应超过 1 MiB 限制。");
|
||||
}
|
||||
try {
|
||||
return JsonParser.parseString(response.body()).getAsJsonObject();
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IllegalStateException("MineSkin 返回了无效 JSON,HTTP " + response.statusCode(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private GeneratedSkin parseGeneratedSkin(JsonObject body) {
|
||||
JsonObject skin = object(body, "skin");
|
||||
JsonObject texture = object(skin, "texture");
|
||||
JsonObject data = object(texture, "data");
|
||||
return new GeneratedSkin(string(data, "value"), string(data, "signature"));
|
||||
}
|
||||
|
||||
private IllegalStateException apiError(String action, HttpResponse<String> response, JsonObject body) {
|
||||
return new IllegalStateException(action + "失败,HTTP " + response.statusCode() + ": " + errorMessage(body));
|
||||
}
|
||||
|
||||
private String errorMessage(JsonObject body) {
|
||||
for (String key : new String[]{"message", "error", "code"}) {
|
||||
if (body.has(key) && body.get(key).isJsonPrimitive()) {
|
||||
return body.get(key).getAsString();
|
||||
}
|
||||
}
|
||||
return "未提供错误信息";
|
||||
}
|
||||
|
||||
private static JsonObject object(JsonObject parent, String key) {
|
||||
if (!parent.has(key) || !parent.get(key).isJsonObject()) {
|
||||
throw new IllegalStateException("MineSkin 响应缺少对象字段: " + key);
|
||||
}
|
||||
return parent.getAsJsonObject(key);
|
||||
}
|
||||
|
||||
private static String string(JsonObject parent, String key) {
|
||||
if (!parent.has(key) || !parent.get(key).isJsonPrimitive()) {
|
||||
throw new IllegalStateException("MineSkin 响应缺少字符串字段: " + key);
|
||||
}
|
||||
String value = parent.get(key).getAsString();
|
||||
if (value.isBlank()) {
|
||||
throw new IllegalStateException("MineSkin 响应字符串字段为空: " + key);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String normalizeEndpoint(String endpoint) {
|
||||
String normalized = endpoint == null ? "" : endpoint.trim();
|
||||
while (normalized.endsWith("/")) {
|
||||
normalized = normalized.substring(0, normalized.length() - 1);
|
||||
}
|
||||
if (normalized.isBlank()) {
|
||||
throw new IllegalArgumentException("MineSkin API 地址不能为空。");
|
||||
}
|
||||
URI uri = URI.create(normalized);
|
||||
if (!"https".equalsIgnoreCase(uri.getScheme())) {
|
||||
throw new IllegalArgumentException("MineSkin API 必须使用 HTTPS。");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String normalizeVisibility(String visibility) {
|
||||
String normalized = visibility == null ? "" : visibility.trim().toLowerCase(java.util.Locale.ROOT);
|
||||
if (!normalized.equals("public") && !normalized.equals("unlisted") && !normalized.equals("private")) {
|
||||
throw new IllegalArgumentException("MineSkin visibility 必须是 public、unlisted 或 private。");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package cn.infstar.essentialsC.skinbridge;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
interface SkinBridgeGateway {
|
||||
|
||||
GeneratedSkin generateSkin(String skinUrl, SkinModel model) throws Exception;
|
||||
|
||||
void applySkin(Player player, GeneratedSkin skin) throws Exception;
|
||||
}
|
||||
|
||||
enum SkinModel {
|
||||
CLASSIC,
|
||||
SLIM
|
||||
}
|
||||
|
||||
record GeneratedSkin(String value, String signature) {
|
||||
}
|
||||
@@ -0,0 +1,818 @@
|
||||
package cn.infstar.essentialsC.skinbridge;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import com.destroystokyo.paper.profile.ProfileProperty;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public final class SkinBridgeManager implements Listener {
|
||||
|
||||
private static final int WORKER_THREADS = 2;
|
||||
private static final int MAX_PENDING_LOOKUPS = 100;
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final HttpClient httpClient;
|
||||
private final ThreadPoolExecutor executor;
|
||||
private final SkinCacheStore cacheStore;
|
||||
private final ConcurrentMap<UUID, CachedLookup> cache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<SkinCacheStore.Key, SkinCacheStore.Entry> generatedSkinCache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<UUID, Long> pendingLookups = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<UUID, BukkitRunnable> scheduledLookups = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<LookupKey, Future<?>> runningLookups = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<UUID, Long> forceRefreshCooldowns = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<UUID, String> loginSkinUrls = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<SkinCacheStore.Key, CompletableFuture<GeneratedSkin>> pendingGenerations = new ConcurrentHashMap<>();
|
||||
private final AtomicLong configurationGeneration = new AtomicLong();
|
||||
private BukkitTask generatedCacheSaveTask;
|
||||
private boolean generatedCacheDirty;
|
||||
private volatile boolean shuttingDown;
|
||||
|
||||
private volatile List<SkinProvider> providers = List.of();
|
||||
private volatile SkinBridgeGateway gateway;
|
||||
private volatile boolean debug;
|
||||
private volatile boolean sendPlayerMessage;
|
||||
private volatile boolean logDetectionResults;
|
||||
private volatile int requestTimeoutSeconds;
|
||||
private volatile int cacheMinutes;
|
||||
private volatile int maxGeneratedCacheEntries;
|
||||
private volatile int forceRefreshCooldownSeconds;
|
||||
private volatile boolean requireCurrentTextureMatch;
|
||||
private volatile long joinDelayTicks;
|
||||
private volatile Set<String> excludedUuids = Set.of();
|
||||
private volatile Set<String> excludedNames = Set.of();
|
||||
|
||||
public SkinBridgeManager(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
this.cacheStore = new SkinCacheStore(plugin);
|
||||
this.httpClient = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
this.executor = new ThreadPoolExecutor(
|
||||
WORKER_THREADS,
|
||||
WORKER_THREADS,
|
||||
0L,
|
||||
TimeUnit.MILLISECONDS,
|
||||
new ArrayBlockingQueue<>(MAX_PENDING_LOOKUPS),
|
||||
new SkinBridgeThreadFactory(),
|
||||
new ThreadPoolExecutor.AbortPolicy()
|
||||
);
|
||||
reload();
|
||||
loadGeneratedSkinCache();
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
configurationGeneration.incrementAndGet();
|
||||
cancelScheduledLookups();
|
||||
cancelRunningLookups();
|
||||
pendingLookups.clear();
|
||||
pendingGenerations.clear();
|
||||
FileConfiguration config = plugin.getConfig();
|
||||
|
||||
debug = plugin.getConfig().getBoolean("debug", false);
|
||||
sendPlayerMessage = config.getBoolean("skin-bridge.send-player-message", true);
|
||||
logDetectionResults = config.getBoolean("skin-bridge.log-detection-results", true);
|
||||
requestTimeoutSeconds = clamp(config.getInt("skin-bridge.profile-request-timeout-seconds", 5), 1, 30);
|
||||
String mineSkinEndpoint = config.getString("skin-bridge.mineskin.endpoint", "https://api.mineskin.org");
|
||||
String mineSkinApiKey = config.getString("skin-bridge.mineskin.api-key", "").trim();
|
||||
String mineSkinVisibility = config.getString("skin-bridge.mineskin.visibility", "unlisted");
|
||||
int mineSkinTimeoutSeconds = clamp(config.getInt("skin-bridge.mineskin.request-timeout-seconds", 30), 10, 180);
|
||||
long minimumSubmitIntervalMillis = clamp(
|
||||
config.getLong("skin-bridge.mineskin.minimum-submit-interval-millis", 1000L), 0L, 10000L);
|
||||
cacheMinutes = clamp(config.getInt("skin-bridge.cache-minutes", 120), 5, 10080);
|
||||
maxGeneratedCacheEntries = clamp(config.getInt("skin-bridge.max-generated-cache-entries", 500), 10, 10_000);
|
||||
forceRefreshCooldownSeconds = clamp(config.getInt("skin-bridge.force-refresh-cooldown-seconds", 30), 0, 3600);
|
||||
requireCurrentTextureMatch = config.getBoolean("skin-bridge.require-current-texture-match", true);
|
||||
joinDelayTicks = clamp(config.getLong("skin-bridge.join-delay-ticks", 20L), 0, 200);
|
||||
excludedUuids = loadNormalizedValues(config, "skin-bridge.exclusions.uuids");
|
||||
excludedNames = loadNormalizedValues(config, "skin-bridge.exclusions.names");
|
||||
providers = loadProviders(config);
|
||||
cache.clear();
|
||||
gateway = loadGateway(mineSkinEndpoint, mineSkinApiKey, mineSkinVisibility,
|
||||
mineSkinTimeoutSeconds, minimumSubmitIntervalMillis);
|
||||
|
||||
if (gateway == null) {
|
||||
plugin.getLogger().warning("SkinBridge 已启用,但未配置有效的 MineSkin API Key,皮肤同步不会执行。");
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
shuttingDown = true;
|
||||
configurationGeneration.incrementAndGet();
|
||||
cancelScheduledLookups();
|
||||
cancelRunningLookups();
|
||||
executor.shutdownNow();
|
||||
cancelGeneratedCacheSave();
|
||||
saveGeneratedSkinCache();
|
||||
cache.clear();
|
||||
generatedSkinCache.clear();
|
||||
pendingLookups.clear();
|
||||
pendingGenerations.clear();
|
||||
forceRefreshCooldowns.clear();
|
||||
loginSkinUrls.clear();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
UUID playerId = event.getPlayer().getUniqueId();
|
||||
getCurrentSkinUrl(event.getPlayer()).ifPresentOrElse(
|
||||
skinUrl -> loginSkinUrls.put(playerId, skinUrl),
|
||||
() -> loginSkinUrls.remove(playerId)
|
||||
);
|
||||
queueSync(event.getPlayer(), false);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
UUID playerId = event.getPlayer().getUniqueId();
|
||||
loginSkinUrls.remove(playerId);
|
||||
pendingLookups.remove(playerId);
|
||||
cancelScheduledLookup(playerId);
|
||||
cancelRunningLookup(playerId);
|
||||
}
|
||||
|
||||
public SyncResult queueSync(Player player, boolean force) {
|
||||
UUID playerId = player.getUniqueId();
|
||||
if (isExcluded(player)) {
|
||||
cache.put(playerId, cached(null, null, State.EXCLUDED));
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.excluded", Map.of());
|
||||
if (logDetectionResults) {
|
||||
plugin.getLogger().info("SkinBridge 已根据排除名单跳过玩家: " + player.getName());
|
||||
}
|
||||
return SyncResult.EXCLUDED;
|
||||
}
|
||||
if (gateway == null) {
|
||||
return SyncResult.DEPENDENCY_MISSING;
|
||||
}
|
||||
if (providers.isEmpty()) {
|
||||
return SyncResult.NO_PROVIDERS;
|
||||
}
|
||||
|
||||
if (force) {
|
||||
long now = System.currentTimeMillis();
|
||||
long expiresAt = forceRefreshCooldowns.getOrDefault(playerId, 0L);
|
||||
if (expiresAt > now) {
|
||||
return SyncResult.REFRESH_COOLDOWN;
|
||||
}
|
||||
cache.remove(playerId);
|
||||
}
|
||||
|
||||
CachedLookup cached = cache.get(playerId);
|
||||
if (!force && cached != null && !cached.hasExpired()) {
|
||||
if (cached.skin() != null) {
|
||||
applySkin(playerId, cached, configurationGeneration.get());
|
||||
}
|
||||
return SyncResult.CACHED;
|
||||
}
|
||||
|
||||
long lookupGeneration = configurationGeneration.get();
|
||||
if (!pendingLookups.containsKey(playerId) && pendingLookups.size() >= MAX_PENDING_LOOKUPS) {
|
||||
plugin.getLogger().warning("SkinBridge 查询队列已满,已跳过玩家: " + player.getName());
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.queue-full", Map.of());
|
||||
return SyncResult.QUEUE_FULL;
|
||||
}
|
||||
if (!registerPendingLookup(playerId, lookupGeneration)) {
|
||||
return SyncResult.ALREADY_RUNNING;
|
||||
}
|
||||
if (force && forceRefreshCooldownSeconds > 0) {
|
||||
forceRefreshCooldowns.put(playerId,
|
||||
System.currentTimeMillis() + forceRefreshCooldownSeconds * 1000L);
|
||||
}
|
||||
|
||||
String playerName = player.getName();
|
||||
String loginSkinUrl = loginSkinUrls.computeIfAbsent(playerId,
|
||||
ignored -> getCurrentSkinUrl(player).orElse(""));
|
||||
String currentSkinUrl = loginSkinUrl.isEmpty() ? null : loginSkinUrl;
|
||||
BukkitRunnable scheduledLookup = new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
scheduledLookups.remove(playerId, this);
|
||||
startLookup(playerId, playerName, currentSkinUrl, lookupGeneration);
|
||||
}
|
||||
};
|
||||
BukkitRunnable previousLookup = scheduledLookups.put(playerId, scheduledLookup);
|
||||
if (previousLookup != null) {
|
||||
previousLookup.cancel();
|
||||
}
|
||||
scheduledLookup.runTaskLater(plugin, joinDelayTicks);
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.detecting", Map.of());
|
||||
return SyncResult.QUEUED;
|
||||
}
|
||||
|
||||
public Status getStatus(Player player) {
|
||||
CachedLookup cached = cache.get(player.getUniqueId());
|
||||
if (cached != null && !cached.hasExpired()) {
|
||||
return new Status(cached.state(), cached.providerId());
|
||||
}
|
||||
if (pendingLookups.containsKey(player.getUniqueId())) {
|
||||
return new Status(State.PENDING, null);
|
||||
}
|
||||
return new Status(State.UNKNOWN, null);
|
||||
}
|
||||
|
||||
public int getRemainingForceRefreshCooldownSeconds(Player player) {
|
||||
long remaining = forceRefreshCooldowns.getOrDefault(player.getUniqueId(), 0L) - System.currentTimeMillis();
|
||||
return remaining <= 0L ? 0 : (int) Math.ceil(remaining / 1000.0D);
|
||||
}
|
||||
|
||||
public boolean isSkinGatewayAvailable() {
|
||||
return gateway != null;
|
||||
}
|
||||
|
||||
public int getProviderCount() {
|
||||
return providers.size();
|
||||
}
|
||||
|
||||
public String getModuleDetail() {
|
||||
if (gateway == null) {
|
||||
return "缺少 MineSkin API Key 或配置无效";
|
||||
}
|
||||
if (providers.isEmpty()) {
|
||||
return "未配置有效 Provider";
|
||||
}
|
||||
return providers.size() + " 个 Provider 已就绪";
|
||||
}
|
||||
|
||||
private void startLookup(UUID playerId, String playerName, String currentSkinUrl, long lookupGeneration) {
|
||||
Player player = Bukkit.getPlayer(playerId);
|
||||
if (executor.isShutdown() || lookupGeneration != configurationGeneration.get()
|
||||
|| !isLookupActive(playerId, lookupGeneration) || player == null || !player.isOnline()) {
|
||||
pendingLookups.remove(playerId, lookupGeneration);
|
||||
return;
|
||||
}
|
||||
LookupKey lookupKey = new LookupKey(playerId, lookupGeneration);
|
||||
try {
|
||||
Future<?> lookupTask = executor.submit(() -> {
|
||||
try {
|
||||
CachedLookup resolved = resolve(playerId, playerName, currentSkinUrl);
|
||||
if (lookupGeneration != configurationGeneration.get() || !isLookupActive(playerId, lookupGeneration)) {
|
||||
return;
|
||||
}
|
||||
cache.put(playerId, resolved);
|
||||
if (resolved.skin() != null) {
|
||||
applySkin(playerId, resolved, lookupGeneration);
|
||||
} else {
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.not-external", Map.of());
|
||||
if (logDetectionResults) {
|
||||
plugin.getLogger().info("SkinBridge 未匹配到外置皮肤站,已保留玩家皮肤: " + playerName);
|
||||
}
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
if (!isLookupActive(playerId, lookupGeneration) || exception instanceof InterruptedException) {
|
||||
return;
|
||||
}
|
||||
plugin.getLogger().warning("SkinBridge 查询 " + playerName + " 的皮肤资料失败: " + exception.getMessage());
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.failed", Map.of());
|
||||
if (debug) {
|
||||
plugin.getLogger().warning("SkinBridge 异常类型: " + exception.getClass().getName());
|
||||
}
|
||||
} finally {
|
||||
pendingLookups.remove(playerId, lookupGeneration);
|
||||
runningLookups.remove(lookupKey);
|
||||
}
|
||||
});
|
||||
runningLookups.put(lookupKey, lookupTask);
|
||||
if (!isLookupActive(playerId, lookupGeneration)) {
|
||||
runningLookups.remove(lookupKey, lookupTask);
|
||||
lookupTask.cancel(true);
|
||||
executor.purge();
|
||||
}
|
||||
} catch (RejectedExecutionException exception) {
|
||||
pendingLookups.remove(playerId, lookupGeneration);
|
||||
plugin.getLogger().warning("SkinBridge 查询队列拒绝了玩家任务: " + playerName);
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.queue-full", Map.of());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean registerPendingLookup(UUID playerId, long lookupGeneration) {
|
||||
while (true) {
|
||||
Long runningGeneration = pendingLookups.putIfAbsent(playerId, lookupGeneration);
|
||||
if (runningGeneration == null) {
|
||||
return true;
|
||||
}
|
||||
if (runningGeneration == lookupGeneration) {
|
||||
return false;
|
||||
}
|
||||
if (pendingLookups.replace(playerId, runningGeneration, lookupGeneration)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private CachedLookup resolve(UUID playerId, String playerName, String currentSkinUrl) throws Exception {
|
||||
Exception lastFailure = null;
|
||||
for (SkinProvider provider : providers) {
|
||||
Optional<ProviderProfile> profile;
|
||||
try {
|
||||
profile = queryProfile(provider, playerId, playerName);
|
||||
} catch (Exception exception) {
|
||||
lastFailure = exception;
|
||||
plugin.getLogger().warning("SkinBridge Provider " + provider.id() + " 查询失败: " + exception.getMessage());
|
||||
continue;
|
||||
}
|
||||
if (profile.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
SkinBridgeGateway currentGateway = gateway;
|
||||
if (currentGateway == null) {
|
||||
throw new IllegalStateException("MineSkin 网关在查询期间不可用。");
|
||||
}
|
||||
|
||||
ProviderProfile matchedProfile = profile.get();
|
||||
if (requireCurrentTextureMatch
|
||||
&& (currentSkinUrl == null || !currentSkinUrl.equals(matchedProfile.skinUrl()))) {
|
||||
if (debug) {
|
||||
plugin.getLogger().info("SkinBridge 已忽略与当前登录纹理不一致的 Provider: " + provider.name());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (logDetectionResults) {
|
||||
plugin.getLogger().info("SkinBridge 已识别玩家 " + playerName + " 的皮肤来源: " + provider.name());
|
||||
}
|
||||
SkinCacheStore.Key cacheKey = new SkinCacheStore.Key(matchedProfile.skinUrl(), matchedProfile.model());
|
||||
GeneratedSkin generatedSkin = getOrGenerateSkin(cacheKey, currentGateway);
|
||||
return cached(provider.name(), generatedSkin, State.EXTERNAL);
|
||||
}
|
||||
|
||||
if (lastFailure != null) {
|
||||
throw new IllegalStateException("所有可用 Provider 均未能完成确认。", lastFailure);
|
||||
}
|
||||
return cached(null, null, State.NOT_EXTERNAL);
|
||||
}
|
||||
|
||||
private Optional<ProviderProfile> queryProfile(SkinProvider provider, UUID playerId, String playerName) throws Exception {
|
||||
URI requestUri = URI.create(provider.resolveProfileUrl(playerId));
|
||||
HttpRequest request = HttpRequest.newBuilder(requestUri)
|
||||
.timeout(Duration.ofSeconds(requestTimeoutSeconds))
|
||||
.header("Accept", "application/json")
|
||||
.header("User-Agent", "EssentialsC/" + plugin.getPluginMeta().getVersion() + " SkinBridge")
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
|
||||
if (response.statusCode() == 204 || response.statusCode() == 404) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException(provider.id() + " 返回 HTTP " + response.statusCode());
|
||||
}
|
||||
if (response.body().length() > 1_048_576) {
|
||||
throw new IllegalStateException(provider.id() + " 返回的 profile 超过 1 MiB 限制。");
|
||||
}
|
||||
|
||||
JsonObject profile = JsonParser.parseString(response.body()).getAsJsonObject();
|
||||
String profileId = requireString(profile, "id");
|
||||
String profileName = requireString(profile, "name");
|
||||
if (!normalizeUuid(profileId).equals(normalizeUuid(playerId.toString())) || !profileName.equalsIgnoreCase(playerName)) {
|
||||
if (debug) {
|
||||
plugin.getLogger().warning("SkinBridge 忽略 " + provider.id() + " 的不匹配 profile: " + profileName + " / " + profileId);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
JsonObject textureData = findTextureData(profile);
|
||||
JsonObject skin = textureData.getAsJsonObject("textures").getAsJsonObject("SKIN");
|
||||
String skinUrl = requireString(skin, "url");
|
||||
URI skinUri = URI.create(skinUrl);
|
||||
if (!"https".equalsIgnoreCase(skinUri.getScheme())) {
|
||||
throw new IllegalStateException(provider.id() + " 返回了非 HTTPS 皮肤 URL。");
|
||||
}
|
||||
|
||||
SkinModel model = SkinModel.CLASSIC;
|
||||
JsonObject metadata = skin.has("metadata") && skin.get("metadata").isJsonObject()
|
||||
? skin.getAsJsonObject("metadata")
|
||||
: null;
|
||||
if (metadata != null && "slim".equalsIgnoreCase(metadata.has("model") ? metadata.get("model").getAsString() : "")) {
|
||||
model = SkinModel.SLIM;
|
||||
}
|
||||
return Optional.of(new ProviderProfile(skinUrl, model));
|
||||
}
|
||||
|
||||
private JsonObject findTextureData(JsonObject profile) {
|
||||
JsonArray properties = profile.has("properties") && profile.get("properties").isJsonArray()
|
||||
? profile.getAsJsonArray("properties")
|
||||
: new JsonArray();
|
||||
for (JsonElement element : properties) {
|
||||
if (!element.isJsonObject()) {
|
||||
continue;
|
||||
}
|
||||
JsonObject property = element.getAsJsonObject();
|
||||
if (!"textures".equals(property.has("name") ? property.get("name").getAsString() : "")) {
|
||||
continue;
|
||||
}
|
||||
String encodedValue = requireString(property, "value");
|
||||
String decodedValue = new String(Base64.getDecoder().decode(encodedValue), StandardCharsets.UTF_8);
|
||||
JsonObject textureData = JsonParser.parseString(decodedValue).getAsJsonObject();
|
||||
if (textureData.has("textures")
|
||||
&& textureData.get("textures").isJsonObject()
|
||||
&& textureData.getAsJsonObject("textures").has("SKIN")
|
||||
&& textureData.getAsJsonObject("textures").get("SKIN").isJsonObject()) {
|
||||
return textureData;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("profile 不包含有效的皮肤 textures 属性。");
|
||||
}
|
||||
|
||||
private Optional<String> getCurrentSkinUrl(Player player) {
|
||||
try {
|
||||
for (ProfileProperty property : player.getPlayerProfile().getProperties()) {
|
||||
if (!"textures".equals(property.getName())) {
|
||||
continue;
|
||||
}
|
||||
String decoded = new String(Base64.getDecoder().decode(property.getValue()), StandardCharsets.UTF_8);
|
||||
JsonObject textureData = JsonParser.parseString(decoded).getAsJsonObject();
|
||||
if (!textureData.has("textures") || !textureData.get("textures").isJsonObject()) {
|
||||
continue;
|
||||
}
|
||||
JsonObject textures = textureData.getAsJsonObject("textures");
|
||||
if (!textures.has("SKIN") || !textures.get("SKIN").isJsonObject()) {
|
||||
continue;
|
||||
}
|
||||
String skinUrl = requireString(textures.getAsJsonObject("SKIN"), "url");
|
||||
if ("https".equalsIgnoreCase(URI.create(skinUrl).getScheme())) {
|
||||
return Optional.of(skinUrl);
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
if (debug) {
|
||||
plugin.getLogger().warning("SkinBridge 无法解析玩家当前纹理: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private void loadGeneratedSkinCache() {
|
||||
generatedSkinCache.putAll(cacheStore.load());
|
||||
trimGeneratedSkinCache();
|
||||
}
|
||||
|
||||
private synchronized void saveGeneratedSkinCache() {
|
||||
if (!generatedCacheDirty) {
|
||||
return;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
generatedSkinCache.entrySet().removeIf(entry -> entry.getValue().expiresAtMillis() <= now);
|
||||
trimGeneratedSkinCache();
|
||||
if (cacheStore.save(generatedSkinCache)) {
|
||||
generatedCacheDirty = false;
|
||||
} else if (!shuttingDown) {
|
||||
scheduleGeneratedCacheSave();
|
||||
}
|
||||
}
|
||||
|
||||
private GeneratedSkin getOrGenerateSkin(SkinCacheStore.Key cacheKey, SkinBridgeGateway currentGateway) throws Exception {
|
||||
SkinCacheStore.Entry cachedEntry = generatedSkinCache.get(cacheKey);
|
||||
if (cachedEntry != null && !cachedEntry.hasExpired()) {
|
||||
return cachedEntry.skin();
|
||||
}
|
||||
if (cachedEntry != null) {
|
||||
generatedSkinCache.remove(cacheKey, cachedEntry);
|
||||
}
|
||||
|
||||
CompletableFuture<GeneratedSkin> created = new CompletableFuture<>();
|
||||
CompletableFuture<GeneratedSkin> running = pendingGenerations.putIfAbsent(cacheKey, created);
|
||||
if (running != null) {
|
||||
return awaitGeneratedSkin(running);
|
||||
}
|
||||
|
||||
try {
|
||||
GeneratedSkin generated = currentGateway.generateSkin(cacheKey.skinUrl(), cacheKey.model());
|
||||
cacheGeneratedSkin(cacheKey, generated);
|
||||
created.complete(generated);
|
||||
return generated;
|
||||
} catch (Exception exception) {
|
||||
created.completeExceptionally(exception);
|
||||
throw exception;
|
||||
} catch (Error error) {
|
||||
created.completeExceptionally(error);
|
||||
throw error;
|
||||
} finally {
|
||||
pendingGenerations.remove(cacheKey, created);
|
||||
}
|
||||
}
|
||||
|
||||
private GeneratedSkin awaitGeneratedSkin(CompletableFuture<GeneratedSkin> running) throws Exception {
|
||||
try {
|
||||
return running.get();
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw exception;
|
||||
} catch (ExecutionException exception) {
|
||||
Throwable cause = exception.getCause();
|
||||
if (cause instanceof Exception nested) {
|
||||
throw nested;
|
||||
}
|
||||
if (cause instanceof Error error) {
|
||||
throw error;
|
||||
}
|
||||
throw new IllegalStateException("MineSkin 生成任务失败。", cause);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void cacheGeneratedSkin(SkinCacheStore.Key cacheKey, GeneratedSkin generatedSkin) {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
generatedSkinCache.put(cacheKey, new SkinCacheStore.Entry(generatedSkin,
|
||||
System.currentTimeMillis() + Duration.ofMinutes(cacheMinutes).toMillis()));
|
||||
trimGeneratedSkinCache();
|
||||
generatedCacheDirty = true;
|
||||
scheduleGeneratedCacheSave();
|
||||
}
|
||||
|
||||
private synchronized void scheduleGeneratedCacheSave() {
|
||||
if (shuttingDown || generatedCacheSaveTask != null) {
|
||||
return;
|
||||
}
|
||||
generatedCacheSaveTask = Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> {
|
||||
synchronized (this) {
|
||||
generatedCacheSaveTask = null;
|
||||
}
|
||||
saveGeneratedSkinCache();
|
||||
}, 100L);
|
||||
}
|
||||
|
||||
private synchronized void cancelGeneratedCacheSave() {
|
||||
if (generatedCacheSaveTask != null) {
|
||||
generatedCacheSaveTask.cancel();
|
||||
generatedCacheSaveTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void trimGeneratedSkinCache() {
|
||||
long now = System.currentTimeMillis();
|
||||
generatedSkinCache.entrySet().removeIf(entry -> entry.getValue().expiresAtMillis() <= now);
|
||||
int excessEntries = generatedSkinCache.size() - maxGeneratedCacheEntries;
|
||||
if (excessEntries <= 0) {
|
||||
return;
|
||||
}
|
||||
generatedSkinCache.entrySet().stream()
|
||||
.sorted(Comparator.comparingLong(entry -> entry.getValue().expiresAtMillis()))
|
||||
.limit(excessEntries)
|
||||
.map(Map.Entry::getKey)
|
||||
.forEach(generatedSkinCache::remove);
|
||||
}
|
||||
|
||||
private boolean isLookupActive(UUID playerId, long lookupGeneration) {
|
||||
return Long.valueOf(lookupGeneration).equals(pendingLookups.get(playerId));
|
||||
}
|
||||
|
||||
private void cancelScheduledLookup(UUID playerId) {
|
||||
BukkitRunnable scheduledLookup = scheduledLookups.remove(playerId);
|
||||
if (scheduledLookup != null) {
|
||||
scheduledLookup.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelScheduledLookups() {
|
||||
for (UUID playerId : List.copyOf(scheduledLookups.keySet())) {
|
||||
cancelScheduledLookup(playerId);
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelRunningLookup(UUID playerId) {
|
||||
runningLookups.forEach((lookupKey, lookupTask) -> {
|
||||
if (lookupKey.playerId().equals(playerId) && runningLookups.remove(lookupKey, lookupTask)) {
|
||||
lookupTask.cancel(true);
|
||||
}
|
||||
});
|
||||
executor.purge();
|
||||
}
|
||||
|
||||
private void cancelRunningLookups() {
|
||||
runningLookups.forEach((lookupKey, lookupTask) -> {
|
||||
if (runningLookups.remove(lookupKey, lookupTask)) {
|
||||
lookupTask.cancel(true);
|
||||
}
|
||||
});
|
||||
executor.purge();
|
||||
}
|
||||
|
||||
private List<SkinProvider> loadProviders(FileConfiguration config) {
|
||||
ConfigurationSection providersSection = config.getConfigurationSection("skin-bridge.providers");
|
||||
if (providersSection == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<SkinProvider> loadedProviders = new ArrayList<>();
|
||||
for (String key : providersSection.getKeys(false)) {
|
||||
ConfigurationSection providerSection = providersSection.getConfigurationSection(key);
|
||||
if (providerSection == null || !providerSection.getBoolean("enabled", false)) {
|
||||
continue;
|
||||
}
|
||||
String profileUrl = providerSection.getString("profile-url", "").trim();
|
||||
if (!profileUrl.contains("{uuid}") && !profileUrl.contains("{uuid-dashed}")) {
|
||||
plugin.getLogger().warning("SkinBridge Provider " + key + " 缺少 {uuid} 或 {uuid-dashed} 占位符,已跳过。");
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
URI profileUri = URI.create(profileUrl.replace("{uuid}", "00000000000000000000000000000000")
|
||||
.replace("{uuid-dashed}", "00000000-0000-0000-0000-000000000000"));
|
||||
if (!"https".equalsIgnoreCase(profileUri.getScheme())) {
|
||||
plugin.getLogger().warning("SkinBridge Provider " + key + " 必须使用 HTTPS,已跳过。");
|
||||
continue;
|
||||
}
|
||||
String configuredName = providerSection.getString("name", key);
|
||||
String providerName = configuredName == null ? key : configuredName.trim();
|
||||
if (providerName.isEmpty()) {
|
||||
providerName = key;
|
||||
}
|
||||
loadedProviders.add(new SkinProvider(key, providerName, profileUrl,
|
||||
providerSection.getInt("priority", 100)));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
plugin.getLogger().warning("SkinBridge Provider " + key + " 的 profile-url 无效,已跳过。");
|
||||
}
|
||||
}
|
||||
loadedProviders.sort(Comparator.comparingInt(SkinProvider::priority).thenComparing(SkinProvider::id));
|
||||
return List.copyOf(loadedProviders);
|
||||
}
|
||||
|
||||
private SkinBridgeGateway loadGateway(String endpoint, String apiKey, String visibility, int timeoutSeconds,
|
||||
long minimumSubmitIntervalMillis) {
|
||||
if (apiKey.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new MineSkinGateway(httpClient, endpoint, apiKey, visibility, timeoutSeconds,
|
||||
minimumSubmitIntervalMillis,
|
||||
"EssentialsC/" + plugin.getPluginMeta().getVersion() + " SkinBridge");
|
||||
} catch (Exception | LinkageError exception) {
|
||||
plugin.getLogger().warning("加载 MineSkin SkinBridge 适配器失败: " + exception.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> loadNormalizedValues(FileConfiguration config, String path) {
|
||||
Set<String> values = ConcurrentHashMap.newKeySet();
|
||||
for (String value : config.getStringList(path)) {
|
||||
String normalized = value == null ? "" : value.trim().toLowerCase(java.util.Locale.ROOT);
|
||||
if (!normalized.isEmpty()) {
|
||||
values.add(normalized);
|
||||
}
|
||||
}
|
||||
return Set.copyOf(values);
|
||||
}
|
||||
|
||||
private boolean isExcluded(Player player) {
|
||||
return excludedUuids.contains(player.getUniqueId().toString().toLowerCase(java.util.Locale.ROOT))
|
||||
|| excludedNames.contains(player.getName().toLowerCase(java.util.Locale.ROOT));
|
||||
}
|
||||
|
||||
private void applySkin(UUID playerId, CachedLookup resolved, long lookupGeneration) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
if (lookupGeneration != configurationGeneration.get()) {
|
||||
return;
|
||||
}
|
||||
Player player = Bukkit.getPlayer(playerId);
|
||||
SkinBridgeGateway currentGateway = gateway;
|
||||
if (player == null || !player.isOnline() || currentGateway == null || resolved.skin() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
currentGateway.applySkin(player, resolved.skin());
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.synced",
|
||||
Map.of("provider", resolved.providerId()));
|
||||
if (debug) {
|
||||
plugin.getLogger().info("SkinBridge 已应用 " + player.getName() + " 的 " + resolved.providerId() + " 皮肤。");
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
plugin.getLogger().warning("SkinBridge 应用 " + player.getName() + " 的皮肤失败: " + exception.getMessage());
|
||||
sendPlayerNotification(playerId, "skin-bridge.notifications.failed", Map.of());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void sendPlayerNotification(UUID playerId, String messagePath, Map<String, String> placeholders) {
|
||||
if (!sendPlayerMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
Runnable notification = () -> {
|
||||
Player player = Bukkit.getPlayer(playerId);
|
||||
if (player != null && player.isOnline()) {
|
||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(messagePath, placeholders));
|
||||
}
|
||||
};
|
||||
if (Bukkit.isPrimaryThread()) {
|
||||
notification.run();
|
||||
} else {
|
||||
Bukkit.getScheduler().runTask(plugin, notification);
|
||||
}
|
||||
}
|
||||
|
||||
private CachedLookup cached(String providerId, GeneratedSkin skin, State state) {
|
||||
return new CachedLookup(providerId, skin, state, System.currentTimeMillis() + Duration.ofMinutes(cacheMinutes).toMillis());
|
||||
}
|
||||
|
||||
private static String requireString(JsonObject object, String key) {
|
||||
if (!object.has(key) || !object.get(key).isJsonPrimitive()) {
|
||||
throw new IllegalStateException("缺少字符串字段: " + key);
|
||||
}
|
||||
String value = object.get(key).getAsString();
|
||||
if (value.isBlank()) {
|
||||
throw new IllegalStateException("字符串字段为空: " + key);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String normalizeUuid(String value) {
|
||||
return value.replace("-", "").toLowerCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
private static int clamp(int value, int min, int max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
private static long clamp(long value, long min, long max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
private record SkinProvider(String id, String name, String profileUrl, int priority) {
|
||||
private String resolveProfileUrl(UUID playerId) {
|
||||
return profileUrl.replace("{uuid}", playerId.toString().replace("-", ""))
|
||||
.replace("{uuid-dashed}", playerId.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private record ProviderProfile(String skinUrl, SkinModel model) {
|
||||
}
|
||||
|
||||
private record LookupKey(UUID playerId, long generation) {
|
||||
}
|
||||
|
||||
private record CachedLookup(String providerId, GeneratedSkin skin, State state, long expiresAtMillis) {
|
||||
private boolean hasExpired() {
|
||||
return System.currentTimeMillis() >= expiresAtMillis;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class SkinBridgeThreadFactory implements ThreadFactory {
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, "EssentialsC-SkinBridge");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
}
|
||||
|
||||
public enum SyncResult {
|
||||
QUEUED,
|
||||
CACHED,
|
||||
ALREADY_RUNNING,
|
||||
EXCLUDED,
|
||||
QUEUE_FULL,
|
||||
DEPENDENCY_MISSING,
|
||||
NO_PROVIDERS,
|
||||
REFRESH_COOLDOWN
|
||||
}
|
||||
|
||||
public record Status(State state, String providerId) {
|
||||
}
|
||||
|
||||
public enum State {
|
||||
EXTERNAL,
|
||||
EXCLUDED,
|
||||
NOT_EXTERNAL,
|
||||
PENDING,
|
||||
UNKNOWN
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package cn.infstar.essentialsC.skinbridge;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
final class SkinCacheStore {
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final File cacheFile;
|
||||
|
||||
SkinCacheStore(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
this.cacheFile = new File(plugin.getDataFolder(), "skin-cache.yml");
|
||||
}
|
||||
|
||||
Map<Key, Entry> load() {
|
||||
Map<Key, Entry> loaded = new HashMap<>();
|
||||
if (!cacheFile.exists()) {
|
||||
return loaded;
|
||||
}
|
||||
|
||||
YamlConfiguration config = YamlConfiguration.loadConfiguration(cacheFile);
|
||||
ConfigurationSection entries = config.getConfigurationSection("entries");
|
||||
if (entries == null) {
|
||||
return loaded;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
for (String id : entries.getKeys(false)) {
|
||||
String path = "entries." + id;
|
||||
try {
|
||||
String skinUrl = config.getString(path + ".skin-url", "");
|
||||
SkinModel model = SkinModel.valueOf(config.getString(path + ".model", "CLASSIC"));
|
||||
long expiresAt = config.getLong(path + ".expires-at", 0L);
|
||||
String value = config.getString(path + ".value", "");
|
||||
String signature = config.getString(path + ".signature", "");
|
||||
if (expiresAt > now && !skinUrl.isBlank() && !value.isBlank() && !signature.isBlank()) {
|
||||
loaded.put(new Key(skinUrl, model),
|
||||
new Entry(new GeneratedSkin(value, signature), expiresAt));
|
||||
}
|
||||
} catch (IllegalArgumentException exception) {
|
||||
plugin.getLogger().warning("忽略无效的 SkinBridge 缓存记录: " + id);
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
boolean save(Map<Key, Entry> entries) {
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
entries.forEach((key, entry) -> {
|
||||
String path = "entries." + cacheId(key);
|
||||
config.set(path + ".skin-url", key.skinUrl());
|
||||
config.set(path + ".model", key.model().name());
|
||||
config.set(path + ".expires-at", entry.expiresAtMillis());
|
||||
config.set(path + ".value", entry.skin().value());
|
||||
config.set(path + ".signature", entry.skin().signature());
|
||||
});
|
||||
try {
|
||||
AtomicYamlWriter.save(config, cacheFile);
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
plugin.getLogger().warning("保存 skin-cache.yml 失败: " + exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String cacheId(Key key) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash = digest.digest((key.skinUrl() + "\n" + key.model().name())
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
|
||||
} catch (NoSuchAlgorithmException exception) {
|
||||
throw new IllegalStateException("当前 Java 环境不支持 SHA-256。", exception);
|
||||
}
|
||||
}
|
||||
|
||||
record Key(String skinUrl, SkinModel model) {
|
||||
}
|
||||
|
||||
record Entry(GeneratedSkin skin, long expiresAtMillis) {
|
||||
boolean hasExpired() {
|
||||
return System.currentTimeMillis() >= expiresAtMillis;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
package cn.infstar.essentialsC.teleport;
|
||||
|
||||
import java.util.Deque;
|
||||
|
||||
final class TeleportRequestQueuePolicy {
|
||||
|
||||
private TeleportRequestQueuePolicy() {
|
||||
}
|
||||
|
||||
static <T> void addFirstBounded(Deque<T> queue, T value, int maximumSize) {
|
||||
while (queue.size() >= maximumSize) {
|
||||
queue.removeLast();
|
||||
}
|
||||
queue.addFirst(value);
|
||||
}
|
||||
|
||||
static boolean shouldPrune(long expiresAtMillis, long nowMillis, long retentionMillis) {
|
||||
return expiresAtMillis <= nowMillis - retentionMillis;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package cn.infstar.essentialsC.teleport;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
final class TeleportStateStore {
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final File cooldownFile;
|
||||
private final File ignoreFile;
|
||||
private boolean cooldownWritable = true;
|
||||
private boolean ignoreWritable = true;
|
||||
|
||||
TeleportStateStore(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
this.cooldownFile = new File(plugin.getDataFolder(), "teleport-cooldowns.yml");
|
||||
this.ignoreFile = new File(plugin.getDataFolder(), "teleport-ignore.yml");
|
||||
}
|
||||
|
||||
CooldownState loadCooldowns() {
|
||||
Map<UUID, Long> send = new HashMap<>();
|
||||
Map<UUID, Long> accept = new HashMap<>();
|
||||
if (!cooldownFile.exists()) {
|
||||
return new CooldownState(send, accept);
|
||||
}
|
||||
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
try {
|
||||
config.load(cooldownFile);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
cooldownWritable = false;
|
||||
plugin.getLogger().severe("加载 teleport-cooldowns.yml 失败,已禁止覆盖原文件: "
|
||||
+ exception.getMessage());
|
||||
return new CooldownState(send, accept);
|
||||
}
|
||||
loadCooldownMap(config, "send", send);
|
||||
loadCooldownMap(config, "accept", accept);
|
||||
return new CooldownState(send, accept);
|
||||
}
|
||||
|
||||
void saveCooldowns(Map<UUID, Long> send, Map<UUID, Long> accept) {
|
||||
if (!cooldownWritable) {
|
||||
return;
|
||||
}
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
long now = System.currentTimeMillis();
|
||||
saveCooldownMap(config, "send", send, now);
|
||||
saveCooldownMap(config, "accept", accept, now);
|
||||
try {
|
||||
AtomicYamlWriter.save(config, cooldownFile);
|
||||
} catch (Exception exception) {
|
||||
plugin.getLogger().warning("保存 teleport-cooldowns.yml 失败: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
Set<UUID> loadIgnoringRequests() {
|
||||
Set<UUID> ignoredPlayers = new HashSet<>();
|
||||
if (!ignoreFile.exists()) {
|
||||
return ignoredPlayers;
|
||||
}
|
||||
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
try {
|
||||
config.load(ignoreFile);
|
||||
} catch (IOException | InvalidConfigurationException exception) {
|
||||
ignoreWritable = false;
|
||||
plugin.getLogger().severe("加载 teleport-ignore.yml 失败,已禁止覆盖原文件: "
|
||||
+ exception.getMessage());
|
||||
return ignoredPlayers;
|
||||
}
|
||||
ConfigurationSection ignored = config.getConfigurationSection("ignored");
|
||||
if (ignored == null) {
|
||||
return ignoredPlayers;
|
||||
}
|
||||
for (String key : ignored.getKeys(false)) {
|
||||
if (!ignored.getBoolean(key, false)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ignoredPlayers.add(UUID.fromString(key));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
plugin.getLogger().warning("忽略无效的 TPA 忽略记录 UUID: " + key);
|
||||
}
|
||||
}
|
||||
return ignoredPlayers;
|
||||
}
|
||||
|
||||
boolean saveIgnoringRequests(Set<UUID> ignoredPlayers) {
|
||||
if (!ignoreWritable) {
|
||||
return false;
|
||||
}
|
||||
YamlConfiguration config = new YamlConfiguration();
|
||||
for (UUID playerId : ignoredPlayers) {
|
||||
config.set("ignored." + playerId, true);
|
||||
}
|
||||
try {
|
||||
AtomicYamlWriter.save(config, ignoreFile);
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
plugin.getLogger().warning("保存 teleport-ignore.yml 失败: " + exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void loadCooldownMap(YamlConfiguration config, String path, Map<UUID, Long> destination) {
|
||||
ConfigurationSection section = config.getConfigurationSection(path);
|
||||
if (section == null) {
|
||||
return;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
for (String key : section.getKeys(false)) {
|
||||
try {
|
||||
UUID playerId = UUID.fromString(key);
|
||||
long expiresAt = section.getLong(key, 0L);
|
||||
if (expiresAt > now) {
|
||||
destination.put(playerId, expiresAt);
|
||||
}
|
||||
} catch (IllegalArgumentException exception) {
|
||||
plugin.getLogger().warning("忽略无效的 TPA 冷却记录 UUID: " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void saveCooldownMap(YamlConfiguration config, String path, Map<UUID, Long> source, long now) {
|
||||
source.forEach((playerId, expiresAt) -> {
|
||||
if (expiresAt > now) {
|
||||
config.set(path + "." + playerId, expiresAt);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
record CooldownState(Map<UUID, Long> send, Map<UUID, Long> accept) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
package cn.infstar.essentialsC.tpsbar;
|
||||
|
||||
import cn.infstar.essentialsC.EssentialsC;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.boss.BarColor;
|
||||
import org.bukkit.boss.BarStyle;
|
||||
import org.bukkit.boss.BossBar;
|
||||
import org.bukkit.command.CommandMap;
|
||||
import org.bukkit.command.PluginIdentifiableCommand;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class TpsBarManager implements Listener, TpsBarService {
|
||||
|
||||
private static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection();
|
||||
private static final PlainTextComponentSerializer PLAIN_TEXT = PlainTextComponentSerializer.plainText();
|
||||
private static final double MAX_TPS = 20.0D;
|
||||
private static final int UPDATE_INTERVAL_TICKS = 20;
|
||||
private static final BarStyle BAR_STYLE = BarStyle.SEGMENTED_20;
|
||||
private static final double TPS_WARN_THRESHOLD = 18.0D;
|
||||
private static final double TPS_CRITICAL_THRESHOLD = 15.0D;
|
||||
private static final double MSPT_WARN_THRESHOLD = 40.0D;
|
||||
private static final double MSPT_CRITICAL_THRESHOLD = 50.0D;
|
||||
private static final double PING_WARN_THRESHOLD = 100.0D;
|
||||
private static final double PING_CRITICAL_THRESHOLD = 200.0D;
|
||||
|
||||
private final EssentialsC plugin;
|
||||
private final Set<UUID> enabledPlayers = new LinkedHashSet<>();
|
||||
private final Map<UUID, BossBar> activeBars = new java.util.HashMap<>();
|
||||
|
||||
private BukkitTask updateTask;
|
||||
private boolean pluginCommandEnabled;
|
||||
private boolean nativeCommandAvailable;
|
||||
private boolean nativeDetectionInitialized;
|
||||
private String titleFormat;
|
||||
private String enabledSelfMessage;
|
||||
private String disabledSelfMessage;
|
||||
private String enabledOtherMessage;
|
||||
private String disabledOtherMessage;
|
||||
private String usageMessage;
|
||||
private String playerNotFoundMessage;
|
||||
private String noTargetsMessage;
|
||||
private String nativeDetectedMessage;
|
||||
private String pluginEnabledMessage;
|
||||
|
||||
public TpsBarManager(EssentialsC plugin) {
|
||||
this.plugin = plugin;
|
||||
reloadSettings();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPluginCommandEnabled() {
|
||||
return pluginCommandEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNativeCommandAvailable() {
|
||||
return nativeCommandAvailable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadSettings() {
|
||||
var lang = EssentialsC.getLangManager();
|
||||
|
||||
this.titleFormat = lang.getString("tpsbar.title-format");
|
||||
this.enabledSelfMessage = lang.getString("tpsbar.messages.enabled-self");
|
||||
this.disabledSelfMessage = lang.getString("tpsbar.messages.disabled-self");
|
||||
this.enabledOtherMessage = lang.getString("tpsbar.messages.enabled-other");
|
||||
this.disabledOtherMessage = lang.getString("tpsbar.messages.disabled-other");
|
||||
this.usageMessage = lang.getString("tpsbar.messages.usage");
|
||||
this.playerNotFoundMessage = lang.getString("tpsbar.messages.player-not-found");
|
||||
this.noTargetsMessage = lang.getString("tpsbar.messages.no-targets");
|
||||
this.nativeDetectedMessage = lang.getString("tpsbar.messages.native-detected");
|
||||
this.pluginEnabledMessage = lang.getString("tpsbar.messages.plugin-enabled");
|
||||
|
||||
if (!nativeDetectionInitialized) {
|
||||
this.nativeCommandAvailable = detectNativeTpsBar();
|
||||
this.nativeDetectionInitialized = true;
|
||||
}
|
||||
this.pluginCommandEnabled = !nativeCommandAvailable;
|
||||
|
||||
if (nativeCommandAvailable) {
|
||||
plugin.getLogger().info(stripColor(nativeDetectedMessage));
|
||||
} else if (pluginCommandEnabled) {
|
||||
plugin.getLogger().info(stripColor(pluginEnabledMessage));
|
||||
}
|
||||
|
||||
if (!pluginCommandEnabled) {
|
||||
clearActiveBars();
|
||||
return;
|
||||
}
|
||||
|
||||
restartTaskIfNeeded();
|
||||
refreshBars();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
clearActiveBars();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean toggle(Player target) {
|
||||
if (enabledPlayers.contains(target.getUniqueId())) {
|
||||
disable(target);
|
||||
return false;
|
||||
}
|
||||
|
||||
enable(target);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToggleMessage(Player actor, Player target, boolean enabled) {
|
||||
if (actor.getUniqueId().equals(target.getUniqueId())) {
|
||||
actor.sendMessage(prefixed(enabled ? enabledSelfMessage : disabledSelfMessage));
|
||||
return;
|
||||
}
|
||||
|
||||
actor.sendMessage(prefixed(applyPlaceholders(
|
||||
enabled ? enabledOtherMessage : disabledOtherMessage,
|
||||
Map.of("player", target.getName())
|
||||
)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsageMessage() {
|
||||
return prefixed(usageMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerNotFoundMessage(String input) {
|
||||
return prefixed(applyPlaceholders(playerNotFoundMessage, Map.of("player", input)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNoTargetsMessage() {
|
||||
return prefixed(noTargetsMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Player> resolveTargets(Player sender, String input) {
|
||||
Set<Player> targets = new LinkedHashSet<>();
|
||||
try {
|
||||
for (Entity entity : Bukkit.selectEntities(sender, input)) {
|
||||
if (entity instanceof Player target) {
|
||||
targets.add(target);
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
|
||||
if (!targets.isEmpty()) {
|
||||
return targets;
|
||||
}
|
||||
|
||||
Player target = Bukkit.getPlayerExact(input);
|
||||
if (target != null) {
|
||||
targets.add(target);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
disable(event.getPlayer());
|
||||
}
|
||||
|
||||
private void clearActiveBars() {
|
||||
if (updateTask != null) {
|
||||
updateTask.cancel();
|
||||
updateTask = null;
|
||||
}
|
||||
|
||||
for (BossBar bossBar : activeBars.values()) {
|
||||
bossBar.removeAll();
|
||||
}
|
||||
activeBars.clear();
|
||||
enabledPlayers.clear();
|
||||
}
|
||||
|
||||
private void enable(Player player) {
|
||||
enabledPlayers.add(player.getUniqueId());
|
||||
|
||||
BossBar bossBar = activeBars.computeIfAbsent(player.getUniqueId(), uuid ->
|
||||
Bukkit.createBossBar("", BarColor.GREEN, BAR_STYLE)
|
||||
);
|
||||
bossBar.setVisible(true);
|
||||
bossBar.addPlayer(player);
|
||||
|
||||
updateBar(player, bossBar);
|
||||
startTaskIfNeeded();
|
||||
}
|
||||
|
||||
private void disable(Player player) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
enabledPlayers.remove(uuid);
|
||||
|
||||
BossBar bossBar = activeBars.remove(uuid);
|
||||
if (bossBar != null) {
|
||||
bossBar.removeAll();
|
||||
}
|
||||
|
||||
stopTaskIfIdle();
|
||||
}
|
||||
|
||||
private void startTaskIfNeeded() {
|
||||
if (updateTask != null || enabledPlayers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateTask = Bukkit.getScheduler().runTaskTimer(plugin, this::refreshBars, 0L, UPDATE_INTERVAL_TICKS);
|
||||
}
|
||||
|
||||
private void restartTaskIfNeeded() {
|
||||
if (updateTask != null) {
|
||||
updateTask.cancel();
|
||||
updateTask = null;
|
||||
}
|
||||
startTaskIfNeeded();
|
||||
}
|
||||
|
||||
private void stopTaskIfIdle() {
|
||||
if (!enabledPlayers.isEmpty() || updateTask == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateTask.cancel();
|
||||
updateTask = null;
|
||||
}
|
||||
|
||||
private void refreshBars() {
|
||||
List<UUID> stalePlayers = new ArrayList<>();
|
||||
for (UUID uuid : enabledPlayers) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
if (player == null || !player.isOnline()) {
|
||||
stalePlayers.add(uuid);
|
||||
continue;
|
||||
}
|
||||
|
||||
BossBar bossBar = activeBars.computeIfAbsent(uuid, ignored ->
|
||||
Bukkit.createBossBar("", BarColor.GREEN, BAR_STYLE)
|
||||
);
|
||||
if (!bossBar.getPlayers().contains(player)) {
|
||||
bossBar.addPlayer(player);
|
||||
}
|
||||
updateBar(player, bossBar);
|
||||
}
|
||||
|
||||
for (UUID uuid : stalePlayers) {
|
||||
enabledPlayers.remove(uuid);
|
||||
BossBar bossBar = activeBars.remove(uuid);
|
||||
if (bossBar != null) {
|
||||
bossBar.removeAll();
|
||||
}
|
||||
}
|
||||
|
||||
stopTaskIfIdle();
|
||||
}
|
||||
|
||||
private void updateBar(Player player, BossBar bossBar) {
|
||||
double tps = clampTps(plugin.getServer().getTPS()[0]);
|
||||
double mspt = clampMspt(plugin.getServer().getAverageTickTime());
|
||||
int ping = Math.max(0, player.getPing());
|
||||
|
||||
bossBar.setTitle(buildTitle(tps, mspt, ping));
|
||||
bossBar.setColor(resolveBarColor(tps, mspt, ping));
|
||||
bossBar.setStyle(BAR_STYLE);
|
||||
bossBar.setProgress(clamp(tps / MAX_TPS, 0.0D, 1.0D));
|
||||
}
|
||||
|
||||
private String buildTitle(double tps, double mspt, int ping) {
|
||||
return applyPlaceholders(titleFormat, Map.of(
|
||||
"tps_1m", formatDouble(tps),
|
||||
"mspt", formatDouble(mspt),
|
||||
"ping", Integer.toString(ping)
|
||||
));
|
||||
}
|
||||
|
||||
private BarColor resolveBarColor(double tps, double mspt, int ping) {
|
||||
if (tps <= TPS_CRITICAL_THRESHOLD || mspt >= MSPT_CRITICAL_THRESHOLD || ping >= PING_CRITICAL_THRESHOLD) {
|
||||
return BarColor.RED;
|
||||
}
|
||||
if (tps <= TPS_WARN_THRESHOLD || mspt >= MSPT_WARN_THRESHOLD || ping >= PING_WARN_THRESHOLD) {
|
||||
return BarColor.YELLOW;
|
||||
}
|
||||
return BarColor.GREEN;
|
||||
}
|
||||
|
||||
private boolean detectNativeTpsBar() {
|
||||
try {
|
||||
CommandMap commandMap = Bukkit.getCommandMap();
|
||||
org.bukkit.command.Command command = commandMap.getCommand("tpsbar");
|
||||
if (command == null) {
|
||||
return false;
|
||||
}
|
||||
if (command instanceof PluginIdentifiableCommand pluginCommand
|
||||
&& pluginCommand.getPlugin().equals(plugin)) {
|
||||
return false;
|
||||
}
|
||||
return !command.getClass().getName().startsWith("cn.infstar.essentialsC.");
|
||||
} catch (Exception ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String prefixed(String message) {
|
||||
return EssentialsC.getLangManager().getPrefix() + message;
|
||||
}
|
||||
|
||||
private String applyPlaceholders(String text, Map<String, String> placeholders) {
|
||||
String result = text == null ? "" : text;
|
||||
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
|
||||
result = result.replace("{" + entry.getKey() + "}", entry.getValue());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String stripColor(String message) {
|
||||
return PLAIN_TEXT.serialize(LEGACY_SECTION.deserialize(message == null ? "" : message));
|
||||
}
|
||||
|
||||
private String formatDouble(double value) {
|
||||
return String.format(Locale.US, "%.2f", value);
|
||||
}
|
||||
|
||||
private double clampTps(double value) {
|
||||
if (!Double.isFinite(value)) {
|
||||
return 0.0D;
|
||||
}
|
||||
return clamp(value, 0.0D, MAX_TPS);
|
||||
}
|
||||
|
||||
private double clampMspt(double value) {
|
||||
if (!Double.isFinite(value)) {
|
||||
return 0.0D;
|
||||
}
|
||||
return Math.max(0.0D, value);
|
||||
}
|
||||
|
||||
private double clamp(double value, double min, double max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.infstar.essentialsC.tpsbar;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public interface TpsBarService {
|
||||
|
||||
boolean isPluginCommandEnabled();
|
||||
|
||||
boolean isNativeCommandAvailable();
|
||||
|
||||
void reloadSettings();
|
||||
|
||||
void shutdown();
|
||||
|
||||
boolean toggle(Player target);
|
||||
|
||||
void sendToggleMessage(Player actor, Player target, boolean enabled);
|
||||
|
||||
String getUsageMessage();
|
||||
|
||||
String getPlayerNotFoundMessage(String input);
|
||||
|
||||
String getNoTargetsMessage();
|
||||
|
||||
Collection<Player> resolveTargets(Player sender, String input);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package cn.infstar.essentialsC.util;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
public final class AtomicYamlWriter {
|
||||
|
||||
private AtomicYamlWriter() {
|
||||
}
|
||||
|
||||
public static void save(FileConfiguration configuration, File targetFile) throws IOException {
|
||||
Path target = targetFile.toPath().toAbsolutePath();
|
||||
Path parent = target.toAbsolutePath().getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
String temporaryPrefix = targetFile.getName();
|
||||
if (temporaryPrefix.length() < 3) {
|
||||
temporaryPrefix = (temporaryPrefix + "___").substring(0, 3);
|
||||
}
|
||||
Path temporary = Files.createTempFile(parent, temporaryPrefix, ".tmp");
|
||||
try {
|
||||
Files.writeString(temporary, configuration.saveToString(), StandardCharsets.UTF_8);
|
||||
try {
|
||||
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException ignored) {
|
||||
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
# ============================================================================
|
||||
# EssentialsC - 便捷菜单布局
|
||||
# ============================================================================
|
||||
# 模块总开关位于 modules.yml:modules.blocks.enabled
|
||||
# 菜单名称与物品文本位于 lang/<语言>.yml 的 blocks-menu 节点。
|
||||
|
||||
config-version: 1
|
||||
layout-version: 2
|
||||
|
||||
# 每个菜单项包含:
|
||||
# slot 槽位编号,范围为 0 - 35
|
||||
# material Bukkit Material 名称
|
||||
# permission 显示并使用该项目所需的权限
|
||||
# command 点击后执行的 EssentialsC 命令键
|
||||
|
||||
sections:
|
||||
# 功能方块命令
|
||||
blocks:
|
||||
items:
|
||||
workbench:
|
||||
slot: 10
|
||||
material: CRAFTING_TABLE
|
||||
permission: essentialsc.command.workbench
|
||||
command: workbench
|
||||
enderchest:
|
||||
slot: 11
|
||||
material: ENDER_CHEST
|
||||
permission: essentialsc.command.enderchest
|
||||
command: enderchest
|
||||
anvil:
|
||||
slot: 12
|
||||
material: ANVIL
|
||||
permission: essentialsc.command.anvil
|
||||
command: anvil
|
||||
grindstone:
|
||||
slot: 19
|
||||
material: GRINDSTONE
|
||||
permission: essentialsc.command.grindstone
|
||||
command: grindstone
|
||||
smithingtable:
|
||||
slot: 20
|
||||
material: SMITHING_TABLE
|
||||
permission: essentialsc.command.smithingtable
|
||||
command: smithingtable
|
||||
stonecutter:
|
||||
slot: 21
|
||||
material: STONECUTTER
|
||||
permission: essentialsc.command.stonecutter
|
||||
command: stonecutter
|
||||
loom:
|
||||
slot: 28
|
||||
material: LOOM
|
||||
permission: essentialsc.command.loom
|
||||
command: loom
|
||||
cartographytable:
|
||||
slot: 29
|
||||
material: CARTOGRAPHY_TABLE
|
||||
permission: essentialsc.command.cartographytable
|
||||
command: cartographytable
|
||||
|
||||
# 玩家快捷功能
|
||||
shortcuts:
|
||||
items:
|
||||
nightvision:
|
||||
slot: 14
|
||||
material: TINTED_GLASS
|
||||
permission: essentialsc.command.nightvision
|
||||
command: nightvision
|
||||
glow:
|
||||
slot: 15
|
||||
material: GLOWSTONE
|
||||
permission: essentialsc.command.glow
|
||||
command: glow
|
||||
+113
-82
@@ -1,87 +1,118 @@
|
||||
# EssentialsC 配置文件
|
||||
# 你可以编辑此文件来自定义插件行为
|
||||
# EssentialsC 主配置
|
||||
# 其他配置:modules.yml、blocks-menu.yml
|
||||
# 消息与颜色:lang/<语言>.yml
|
||||
# 修改后使用 /essc reload 重载;命令注册状态发生变化时建议重启服务器。
|
||||
|
||||
# 语言设置
|
||||
# 可用语言: en_US, zh_CN (你可以添加更多)
|
||||
config-version: 2
|
||||
language: "zh_CN"
|
||||
|
||||
# 通用设置
|
||||
settings:
|
||||
# 启用或禁用命令反馈消息
|
||||
enable-feedback: true
|
||||
# 输出 EssentialsC 及所有功能模块的详细调试日志。
|
||||
debug: false
|
||||
|
||||
# 功能方块菜单配置
|
||||
blocks-menu:
|
||||
title: "&6&lEssentialsC &8- &e&l功能方块菜单"
|
||||
items:
|
||||
workbench:
|
||||
slot: 10
|
||||
material: CRAFTING_TABLE
|
||||
name: "&e工作台"
|
||||
lore:
|
||||
- "&7/workbench"
|
||||
- "&7打开工作台"
|
||||
permission: essentialsc.command.workbench
|
||||
anvil:
|
||||
slot: 11
|
||||
material: ANVIL
|
||||
name: "&e铁砧"
|
||||
lore:
|
||||
- "&7/anvil"
|
||||
- "&7打开铁砧"
|
||||
permission: essentialsc.command.anvil
|
||||
cartographytable:
|
||||
slot: 19
|
||||
material: CARTOGRAPHY_TABLE
|
||||
name: "&e制图台"
|
||||
lore:
|
||||
- "&7/cartographytable"
|
||||
- "&7打开制图台"
|
||||
permission: essentialsc.command.cartographytable
|
||||
grindstone:
|
||||
slot: 20
|
||||
material: GRINDSTONE
|
||||
name: "&e砂轮"
|
||||
lore:
|
||||
- "&7/grindstone"
|
||||
- "&7打开砂轮"
|
||||
permission: essentialsc.command.grindstone
|
||||
loom:
|
||||
slot: 21
|
||||
material: LOOM
|
||||
name: "&e织布机"
|
||||
lore:
|
||||
- "&7/loom"
|
||||
- "&7打开织布机"
|
||||
permission: essentialsc.command.loom
|
||||
smithingtable:
|
||||
slot: 22
|
||||
material: SMITHING_TABLE
|
||||
name: "&e锻造台"
|
||||
lore:
|
||||
- "&7/smithingtable"
|
||||
- "&7打开锻造台"
|
||||
permission: essentialsc.command.smithingtable
|
||||
stonecutter:
|
||||
slot: 23
|
||||
material: STONECUTTER
|
||||
name: "&e切石机"
|
||||
lore:
|
||||
- "&7/stonecutter"
|
||||
- "&7打开切石机"
|
||||
permission: essentialsc.command.stonecutter
|
||||
enderchest:
|
||||
slot: 31
|
||||
material: ENDER_CHEST
|
||||
name: "&e末影箱"
|
||||
lore:
|
||||
- "&7/enderchest"
|
||||
- "&7打开末影箱"
|
||||
permission: essentialsc.command.enderchest
|
||||
# 管理模式
|
||||
admin-mode:
|
||||
# 原版飞行速度为 0.1;0.2 表示两倍速度。
|
||||
fly-speed: 0.2
|
||||
# 状态提示刷新间隔,单位为 tick。
|
||||
actionbar:
|
||||
interval-ticks: 40
|
||||
|
||||
# 潜影盒设置
|
||||
shulkerbox:
|
||||
# 潜影盒默认标题(当潜影盒没有自定义名称时使用)
|
||||
# 支持颜色代码(使用 & 符号)
|
||||
# 留空则使用 "Shulker Box"(客户端语言)
|
||||
default-title: "&e潜影盒"
|
||||
# 生物掉落
|
||||
mob-drops:
|
||||
enderman:
|
||||
# 控制该生物死亡时是否掉落物品(经验值正常掉落);当前仅支持末影人。
|
||||
allow-drops: true
|
||||
|
||||
# TPA 传送请求
|
||||
tpa:
|
||||
# 请求有效时间,单位为秒。
|
||||
timeout-seconds: 60
|
||||
# 每名接收者最多保留的待处理请求数;超出时移除最早请求。
|
||||
max-pending-requests: 5
|
||||
|
||||
# 位置规则
|
||||
# /tpa:使用目标接受请求时的位置快照。
|
||||
strict-tpa-requests: false
|
||||
# /tpahere:使用请求者发起请求时的位置快照。
|
||||
strict-tpahere-requests: true
|
||||
|
||||
# 传送预热
|
||||
warmup-seconds: 5
|
||||
cancel-warmup-on-move: true
|
||||
cancel-warmup-on-damage: true
|
||||
# chat / actionbar / title / subtitle / none
|
||||
warmup-display: actionbar
|
||||
# 异步传送会先加载目标区块,推荐 Paper / Leaves 服务器保持开启。
|
||||
teleport-async: true
|
||||
# 传送完成后的无敌时间,单位为秒;0 表示关闭。
|
||||
teleport-invulnerability-seconds: 0
|
||||
|
||||
# 冷却时间;单位为秒,0 表示关闭对应冷却。
|
||||
cooldowns:
|
||||
enabled: true
|
||||
cooldown-times:
|
||||
SEND_TELEPORT_REQUEST: 0
|
||||
ACCEPT_TELEPORT_REQUEST: 0
|
||||
|
||||
# 音效
|
||||
sounds:
|
||||
enabled: true
|
||||
request-received: "entity.experience_orb.pickup"
|
||||
warmup: "block.note_block.banjo"
|
||||
cancelled: "entity.item.break"
|
||||
complete: "entity.enderman.teleport"
|
||||
|
||||
# SkinBridge 外置皮肤站检测与同步;同时受 modules.yml 中的模块开关控制。
|
||||
skin-bridge:
|
||||
# 是否加载由 modules.yml 控制;加载前必须填写 MineSkin API Key。
|
||||
# 是否向玩家发送检测与同步结果。
|
||||
send-player-message: true
|
||||
# 是否在控制台记录每次来源检测结果。
|
||||
log-detection-results: true
|
||||
# 玩家加入后延迟多少 tick 开始检测。
|
||||
join-delay-ticks: 20
|
||||
# 检测结果与生成皮肤的内存缓存时间,单位为分钟。
|
||||
cache-minutes: 120
|
||||
# 持久化 MineSkin 纹理缓存的最大条目数,超出时优先清理最早过期的记录。
|
||||
max-generated-cache-entries: 500
|
||||
# 强制刷新同一玩家皮肤的冷却时间,单位为秒。
|
||||
force-refresh-cooldown-seconds: 30
|
||||
# 仅当 Provider 纹理与玩家登录时携带的纹理一致时,才确认其来自该皮肤站。
|
||||
require-current-texture-match: true
|
||||
# 查询皮肤站 Profile 的超时时间,单位为秒。
|
||||
profile-request-timeout-seconds: 5
|
||||
|
||||
# 排除名单中的玩家不会查询皮肤站,也不会修改当前皮肤。
|
||||
exclusions:
|
||||
uuids: []
|
||||
names: []
|
||||
|
||||
mineskin:
|
||||
endpoint: "https://api.mineskin.org"
|
||||
# 只应填写在服务器运行目录中,禁止提交真实密钥。
|
||||
api-key: ""
|
||||
# 可选值:public / unlisted / private
|
||||
visibility: "unlisted"
|
||||
# 等待 MineSkin 队列完成的最长时间,单位为秒。
|
||||
request-timeout-seconds: 30
|
||||
# 两次 MineSkin 生成任务之间的最小间隔,单位为毫秒。
|
||||
minimum-submit-interval-millis: 1000
|
||||
|
||||
# 数值越小,Provider 查询优先级越高;name 会显示在日志和状态命令中。
|
||||
providers:
|
||||
infstar-mc:
|
||||
enabled: true
|
||||
name: "InfstarMC"
|
||||
priority: 10
|
||||
profile-url: "https://skin.infstar.cn/api/yggdrasil/sessionserver/session/minecraft/profile/{uuid}?unsigned=false"
|
||||
littleskin:
|
||||
enabled: true
|
||||
name: "LittleSkin"
|
||||
priority: 20
|
||||
profile-url: "https://littleskin.cn/api/yggdrasil/sessionserver/session/minecraft/profile/{uuid}?unsigned=false"
|
||||
custom-blessing-skin:
|
||||
# 自建 Blessing Skin 示例。启用前请修改 name 和 profile-url。
|
||||
enabled: false
|
||||
name: "Blessing Skin"
|
||||
priority: 30
|
||||
profile-url: "https://skin.example.com/api/yggdrasil/sessionserver/session/minecraft/profile/{uuid}?unsigned=false"
|
||||
|
||||
@@ -1,62 +1,260 @@
|
||||
# English Language File (en_US)
|
||||
# You can customize all messages here
|
||||
# English language file
|
||||
# MiniMessage format with green success, red errors, and gray details.
|
||||
|
||||
# Plugin prefix
|
||||
prefix: "&6[EssentialsC] &r"
|
||||
prefix: '<#00FB9A><bold>[EssentialsC]</bold></#00FB9A><gray>: </gray>'
|
||||
|
||||
# Command messages
|
||||
messages:
|
||||
no-permission: "&cYou don't have permission to use this command!\n&7Required permission: {permission}"
|
||||
player-only: "&cThis command can only be executed by players!"
|
||||
hat-success: "&aYou are now wearing {item} on your head!"
|
||||
hat-failed: "&cFailed to wear item on head!"
|
||||
hat-no-item: "&cYou need to hold an item in your hand!"
|
||||
suicide-message: "&e{player} has committed suicide!"
|
||||
fly-enabled: "&aFlight mode enabled!"
|
||||
fly-disabled: "&cFlight mode disabled!"
|
||||
vanish-enabled: "&aYou are now vanished!"
|
||||
vanish-disabled: "&cYou are no longer vanished!"
|
||||
seen-usage: "&cUsage: /seen <player>"
|
||||
anvil-opened: "&aAnvil opened!"
|
||||
enchantingtable-opened: "&aEnchanting table opened!"
|
||||
heal-self: "&aYour health and hunger have been restored!"
|
||||
heal-other: "&aYou have healed player {player}!"
|
||||
heal-by-other: "&aYou have been healed by admin {admin}!"
|
||||
feed-self: "&aYour hunger has been restored!"
|
||||
feed-other: "&aYou have fed player {player}!"
|
||||
feed-by-other: "&aYou have been fed by admin {admin}!"
|
||||
repair-hand-success: "&aItem in hand repaired!"
|
||||
repair-all-success: "&aRepaired {count} items!"
|
||||
repair-not-damaged: "&cThis item is not damaged!"
|
||||
repair-no-item-in-hand: "&cYou don't have an item in your hand!"
|
||||
repair-no-items: "&cNo repairable items in inventory!"
|
||||
no-permission-repair-all: "&cYou don't have permission to repair all items!"
|
||||
player-not-found: "&cPlayer not found: {player}"
|
||||
no-permission-others: "&cYou don't have permission to heal others!"
|
||||
|
||||
# Help command
|
||||
no-permission: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to use this command.</#FF7E5E> <gray>Required: {permission}</gray>'
|
||||
player-only: '<#FF3300>Error:</#FF3300> <#FF7E5E>This command can only be run by players.</#FF7E5E>'
|
||||
console-name: 'Console'
|
||||
config-reloaded: '<#00FB9A>Configuration reloaded.</#00FB9A>'
|
||||
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
||||
paper-version: '<gray>Running on Paper {version}</gray>'
|
||||
unknown-subcommand: '<#FF3300>Error:</#FF3300> <#FF7E5E>Unknown subcommand: {command}</#FF7E5E>'
|
||||
help-usage: '<gray>Use <white>/essc help</white> to view available commands.</gray>'
|
||||
module-disabled: '<#FF3300>Error:</#FF3300> <#FF7E5E>This feature module is currently disabled.</#FF7E5E>'
|
||||
blocks-menu-empty: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have any available shortcut menu entries.</#FF7E5E>'
|
||||
|
||||
hat-success: '<#00FB9A>You are now wearing <bold>{item}</bold> on your head.</#00FB9A>'
|
||||
hat-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not wear that item on your head.</#FF7E5E>'
|
||||
hat-no-item: '<#FF3300>Error:</#FF3300> <#FF7E5E>You need to hold an item.</#FF7E5E>'
|
||||
suicide-message: '<#FF7E5E>{player} died by suicide.</#FF7E5E>'
|
||||
fly-enabled: '<#00FB9A>Flight mode enabled.</#00FB9A>'
|
||||
fly-disabled: '<#FF7E5E>Flight mode disabled.</#FF7E5E>'
|
||||
fly-permission-removed: '<#FF7E5E>Your flight permission was removed, so flight mode was disabled.</#FF7E5E>'
|
||||
nightvision-enabled: '<#00FB9A>Night vision enabled.</#00FB9A>'
|
||||
nightvision-disabled: '<#FF7E5E>Night vision disabled.</#FF7E5E>'
|
||||
nightvision-permission-removed: '<#FF7E5E>Your night vision permission was removed, so night vision was disabled.</#FF7E5E>'
|
||||
nightvision-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /nightvision [on|off|toggle]</#FF7E5E>'
|
||||
glow-enabled: '<#00FB9A>Glowing enabled.</#00FB9A>'
|
||||
glow-disabled: '<#FF7E5E>Glowing disabled.</#FF7E5E>'
|
||||
glow-permission-removed: '<#FF7E5E>Your glowing permission was removed, so glowing was disabled.</#FF7E5E>'
|
||||
glow-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /glow [on|off|toggle]</#FF7E5E>'
|
||||
vanish-enabled: '<#00FB9A>You are now vanished.</#00FB9A>'
|
||||
vanish-disabled: '<#FF7E5E>You are no longer vanished.</#FF7E5E>'
|
||||
vanish-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save vanish state; no changes were applied.</#FF7E5E>'
|
||||
vanish-permission-removed: '<#FFC43B>Your vanish permission was removed, so vanish mode was disabled.</#FFC43B>'
|
||||
seen-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
||||
seen-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
||||
seen-header: '<#00FB9A>Player information:</#00FB9A> <white>{player}</white>'
|
||||
seen-status-online: '<gray>Status: <#00FB9A>Online</#00FB9A></gray>'
|
||||
seen-status-offline: '<gray>Status: <#FF7E5E>Offline</#FF7E5E></gray>'
|
||||
seen-world: '<gray>World: <white>{world}</white></gray>'
|
||||
seen-last-online: '<gray>Last online: <white>{time}</white></gray>'
|
||||
seen-first-joined: '<gray>First joined: <white>{time}</white></gray>'
|
||||
player-not-found: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not find the player {player}.</#FF7E5E>'
|
||||
no-permission-others: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to affect other players.</#FF7E5E>'
|
||||
|
||||
anvil-opened: '<#00FB9A>Opened an anvil.</#00FB9A>'
|
||||
enchantingtable-opened: '<#00FB9A>Opened an enchanting table.</#00FB9A>'
|
||||
heal-self: '<#00FB9A>Your health and hunger have been restored.</#00FB9A>'
|
||||
heal-other: '<#00FB9A>You healed <bold>{player}</bold>.</#00FB9A>'
|
||||
heal-by-other: '<#00FB9A>You were healed by <bold>{admin}</bold>.</#00FB9A>'
|
||||
heal-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /heal [player]</#FF7E5E>'
|
||||
feed-self: '<#00FB9A>Your hunger has been restored.</#00FB9A>'
|
||||
feed-other: '<#00FB9A>You fed <bold>{player}</bold>.</#00FB9A>'
|
||||
feed-by-other: '<#00FB9A>You were fed by <bold>{admin}</bold>.</#00FB9A>'
|
||||
feed-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /feed [player]</#FF7E5E>'
|
||||
repair-hand-success: '<#00FB9A>Repaired the item in your hand.</#00FB9A>'
|
||||
repair-all-success: '<#00FB9A>Repaired <bold>{count}</bold> item(s).</#00FB9A>'
|
||||
repair-not-damaged: '<#FF3300>Error:</#FF3300> <#FF7E5E>This item is not damaged.</#FF7E5E>'
|
||||
repair-no-item-in-hand: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have an item in your hand.</#FF7E5E>'
|
||||
repair-no-items: '<#FF3300>Error:</#FF3300> <#FF7E5E>There are no repairable items in your inventory.</#FF7E5E>'
|
||||
no-permission-repair-all: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to repair all items.</#FF7E5E>'
|
||||
|
||||
mobdrop-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save config: {error}</#FF7E5E>'
|
||||
mobdrop-toggled: '<#00FB9A>Enderman drops are now {status}.</#00FB9A>'
|
||||
shulkerbox-nested: '<#FF3300>Error:</#FF3300> <#FF7E5E>You cannot put a shulker box inside another shulker box.</#FF7E5E>'
|
||||
shulkerbox-unstack-first: '<#FF3300>Error:</#FF3300> <#FF7E5E>Please unstack the shulker box before quick opening it.</#FF7E5E>'
|
||||
shulkerbox-open-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to open the shulker box. Please try again.</#FF7E5E>'
|
||||
shulkerbox-session-invalid: '<#FF3300>Error:</#FF3300> <#FF7E5E>The shulker box session became invalid. Saving was stopped to prevent item duplication.</#FF7E5E>'
|
||||
help:
|
||||
title: "&6========== &eEssentialsC Help &6=========="
|
||||
version: "&7Plugin Version: &f{version}"
|
||||
section-blocks: "&6Functional Block Commands:"
|
||||
section-other: "&6Other Commands:"
|
||||
footer: "&7Permissions required for each command"
|
||||
|
||||
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>Command Help</gray>'
|
||||
version: '<gray>Plugin version: <white>{version}</white></gray>'
|
||||
section-blocks: '<#00FB9A>Functional Block Commands</#00FB9A>'
|
||||
section-other: '<#00FB9A>Other Commands</#00FB9A>'
|
||||
footer: '<gray>Each command requires the corresponding permission.</gray>'
|
||||
|
||||
commands:
|
||||
workbench: " &f/workbench &7- Open a workbench"
|
||||
anvil: " &f/anvil &7- Open an anvil"
|
||||
enchantingtable: " &f/enchantingtable &7- Open an enchanting table"
|
||||
cartographytable: " &f/cartographytable &7- Open a cartography table"
|
||||
grindstone: " &f/grindstone &7- Open a grindstone"
|
||||
loom: " &f/loom &7- Open a loom"
|
||||
smithingtable: " &f/smithingtable &7- Open a smithing table"
|
||||
stonecutter: " &f/stonecutter &7- Open a stonecutter"
|
||||
enderchest: " &f/enderchest &7- Open your ender chest"
|
||||
hat: " &f/hat &7- Wear held item as a hat"
|
||||
suicide: " &f/suicide &7- Commit suicide"
|
||||
fly: " &f/fly &7- Toggle flight mode"
|
||||
heal: " &f/heal &7- Restore health and hunger"
|
||||
vanish: " &f/vanish &7- Toggle vanish mode"
|
||||
seen: " &f/seen &7- View player information"
|
||||
feed: " &f/feed &7- Restore hunger"
|
||||
repair: " &f/repair &7- Repair hand or all items"
|
||||
reload: '<white>/essc reload</white> <gray>- Reload plugin configuration</gray>'
|
||||
version: '<white>/essc version</white> <gray>- View plugin and server versions</gray>'
|
||||
workbench: '<white>/workbench</white> <gray>- Open a crafting table</gray>'
|
||||
anvil: '<white>/anvil</white> <gray>- Open an anvil</gray>'
|
||||
enchantingtable: '<white>/enchantingtable</white> <gray>- Open an enchanting table</gray>'
|
||||
cartographytable: '<white>/cartographytable</white> <gray>- Open a cartography table</gray>'
|
||||
grindstone: '<white>/grindstone</white> <gray>- Open a grindstone</gray>'
|
||||
loom: '<white>/loom</white> <gray>- Open a loom</gray>'
|
||||
smithingtable: '<white>/smithingtable</white> <gray>- Open a smithing table</gray>'
|
||||
stonecutter: '<white>/stonecutter</white> <gray>- Open a stonecutter</gray>'
|
||||
enderchest: '<white>/enderchest</white> <gray>- Open your ender chest</gray>'
|
||||
blocks: '<white>/blocks</white> <gray>- Open the shortcut menu</gray>'
|
||||
hat: '<white>/hat</white> <gray>- Wear the held item as a hat</gray>'
|
||||
suicide: '<white>/suicide</white> <gray>- Die by suicide</gray>'
|
||||
fly: '<white>/fly</white> <gray>- Toggle flight mode</gray>'
|
||||
nightvision: '<white>/nightvision</white> <gray>- Toggle night vision</gray>'
|
||||
glow: '<white>/glow</white> <gray>- Toggle glowing</gray>'
|
||||
heal: '<white>/heal [player]</white> <gray>- Restore health and hunger</gray>'
|
||||
vanish: '<white>/vanish</white> <gray>- Toggle vanish mode</gray>'
|
||||
seen: '<white>/seen [player]</white> <gray>- View player information</gray>'
|
||||
feed: '<white>/feed [player]</white> <gray>- Restore hunger</gray>'
|
||||
repair: '<white>/repair</white> <gray>- Repair held or all items</gray>'
|
||||
tpa: '<white>/tpa [player]</white> <gray>- Request to teleport to a player</gray>'
|
||||
tpahere: '<white>/tpahere [player]</white> <gray>- Request a player teleport to you</gray>'
|
||||
tpaall: '<white>/tpaall</white> <gray>- Request all players teleport to you</gray>'
|
||||
tpaccept: '<white>/tpaccept [player]</white> <gray>- Accept a teleport request</gray>'
|
||||
tpdeny: '<white>/tpdeny [player]</white> <gray>- Deny a teleport request</gray>'
|
||||
tpignore: '<white>/tpignore</white> <gray>- Toggle ignoring teleport requests</gray>'
|
||||
skin: '<white>/essc skin [status|refresh] [player]</white> <gray>- View or refresh SkinBridge status</gray>'
|
||||
admin: '<white>/essc admin</white> <gray>- Toggle admin mode</gray>'
|
||||
tpsbar: '<white>/tpsbar [player]</white> <gray>- Toggle TPS boss bar</gray>'
|
||||
|
||||
tpa:
|
||||
messages:
|
||||
usage-tpa: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpa [player]</#FF7E5E>'
|
||||
usage-tpahere: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpahere [player]</#FF7E5E>'
|
||||
usage-tpaall: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpaall</#FF7E5E>'
|
||||
usage-tpaccept: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpaccept [player]</#FF7E5E>'
|
||||
usage-tpdeny: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpdeny [player]</#FF7E5E>'
|
||||
self: '<#FF3300>Error:</#FF3300> <#FF7E5E>You cannot send a teleport request to yourself.</#FF7E5E>'
|
||||
sent-tpa: '<#00FB9A>You sent a teleport request asking to teleport to</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold><#00FB9A>.</#00FB9A>'
|
||||
sent-tpahere: '<#00FB9A>You sent a teleport request asking</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold> <#00FB9A>to teleport to you.</#00FB9A>'
|
||||
ignoring-requests: '<#FF3300>Error:</#FF3300> <#FF7E5E>You are currently ignoring teleport requests.</#FF7E5E> <#FF7E5E><click:run_command:/tpignore><hover:show_text:"<#FF7E5E>Click to listen for incoming teleport requests</#FF7E5E>">[Stop Ignoring...]</hover></click></#FF7E5E>'
|
||||
send-cooldown: '<#FF3300>Error:</#FF3300> <#FF7E5E>You must wait {seconds}s before doing that again.</#FF7E5E>'
|
||||
accept-cooldown: '<#FF3300>Error:</#FF3300> <#FF7E5E>You must wait {seconds}s before doing that again.</#FF7E5E>'
|
||||
received-tpa: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>has requested to teleport to you.</#00FB9A>'
|
||||
received-tpahere: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>has requested that you teleport to them.</#00FB9A>'
|
||||
response-buttons: '<gray>Options:</gray> <#00FB9A><click:run_command:''/tpaccept {requester}''><hover:show_text:"<#00FB9A>Accept teleport request\n<dark_gray>Click to accept {requester}''s request</dark_gray></#00FB9A>">[✔ Accept…]</hover></click></#00FB9A> <#FF3300><click:run_command:''/tpdeny {requester}''><hover:show_text:"<#FF3300>Decline teleport request\n<dark_gray>Click to decline {requester}''s request</dark_gray></#FF3300>">[❌ Decline…]</hover></click></#FF3300>'
|
||||
no-request: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have a pending teleport request.</#FF7E5E>'
|
||||
invalid-request: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have a pending teleport request from {requester}.</#FF7E5E>'
|
||||
accepted-target: '<#00FB9A>You accepted {requester}''s teleport request!</#00FB9A>'
|
||||
accepted-sender: '<#00FB9A>{target} has accepted your teleport request!</#00FB9A>'
|
||||
denied-target: '<#FF7E5E>You declined {requester}''s teleport request.</#FF7E5E>'
|
||||
denied-sender: '<#FF7E5E>{target} has declined your teleport request.</#FF7E5E>'
|
||||
expired: '<#FF3300>Error:</#FF3300> <#FF7E5E>Your pending teleport request has expired.</#FF7E5E>'
|
||||
player-offline: '<#FF3300>Error:</#FF3300> <#FF7E5E>The sender of your pending teleport request is no longer online.</#FF7E5E>'
|
||||
target-offline: '<#FF3300>Error:</#FF3300> <#FF7E5E>The teleport target could not be found.</#FF7E5E>'
|
||||
already-warming-up: '<#FF3300>Error:</#FF3300> <#FF7E5E>A related player is already warming up for teleportation.</#FF7E5E>'
|
||||
warmup-start: '<#00FB9A>You will be teleported in</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold> <#00FB9A>seconds, please stand still…</#00FB9A>'
|
||||
warmup-status: '<#00FB9A>Teleporting in</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold><#00FB9A>…</#00FB9A>'
|
||||
warmup-processing: '<#00FB9A>Teleporting…</#00FB9A>'
|
||||
warmup-cancelled-move: '<#FF7E5E>Teleportation cancelled—you moved!</#FF7E5E>'
|
||||
warmup-cancelled-damage: '<#FF7E5E>Teleportation cancelled—you took damage!</#FF7E5E>'
|
||||
warmup-cancelled-actionbar: '<#FF7E5E>Teleportation cancelled!</#FF7E5E>'
|
||||
warmup-stand-still: '<#FF3300>Error:</#FF3300> <#FF7E5E>You must be standing still before starting a teleport!</#FF7E5E>'
|
||||
teleport-complete: '<#00FB9A>Teleportation complete!</#00FB9A>'
|
||||
teleport-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Teleportation could not be completed. Please try again.</#FF7E5E>'
|
||||
ignore-enabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>ignoring</#00FB9A></bold> <#00FB9A>incoming teleport requests.</#00FB9A>'
|
||||
ignore-disabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>listening</#00FB9A></bold> <#00FB9A>to incoming teleport requests.</#00FB9A>'
|
||||
ignore-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save the teleport request ignore state; no changes were applied.</#FF7E5E>'
|
||||
ignore-notification: '<gray>You are currently ignoring teleport requests.</gray>'
|
||||
tpaall-sent: '<#00FB9A>You sent a teleport request to every player asking them to teleport to you.</#00FB9A>'
|
||||
tpaall-no-targets: '<#FF3300>Error:</#FF3300> <#FF7E5E>There are no other players online.</#FF7E5E>'
|
||||
|
||||
skin-bridge:
|
||||
notifications:
|
||||
detecting: '<#00FB9A>Detecting your skin source…</#00FB9A>'
|
||||
synced: '<#00FB9A>Skin synchronized through <bold>{provider}</bold>.</#00FB9A>'
|
||||
excluded: '<gray>You are excluded from SkinBridge detection; your current skin was kept.</gray>'
|
||||
queue-full: '<#FFC43B>Skin detection is busy; this check was skipped.</#FFC43B>'
|
||||
not-external: '<gray>No external skin provider matched; your current skin was kept.</gray>'
|
||||
failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Skin detection or synchronization failed. Please try again later.</#FF7E5E>'
|
||||
messages:
|
||||
usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /essc skin [status|refresh] [player]</#FF7E5E>'
|
||||
dependency-missing: '<#FF3300>Error:</#FF3300> <#FF7E5E>No valid MineSkin API key is configured in config.yml.</#FF7E5E>'
|
||||
no-providers: '<#FF3300>Error:</#FF3300> <#FF7E5E>No valid SkinBridge provider is enabled.</#FF7E5E>'
|
||||
status-external: '<#00FB9A>{player} is identified as an external skin provider player.</#00FB9A> <gray>Provider: <white>{provider}</white></gray>'
|
||||
status-excluded: '<gray>{player} is excluded from SkinBridge detection.</gray>'
|
||||
status-not-external: '<gray>{player} does not match any configured external skin provider.</gray>'
|
||||
status-pending: '<#FFC43B>SkinBridge is still detecting {player}''s login source.</#FFC43B>'
|
||||
status-unknown: '<gray>{player} has not been checked by SkinBridge yet.</gray>'
|
||||
refresh-queued: '<#00FB9A>SkinBridge is detecting and refreshing {player}''s skin.</#00FB9A>'
|
||||
refresh-cached: '<gray>{player} is using a valid skin cache entry.</gray>'
|
||||
refresh-running: '<#FFC43B>SkinBridge is already processing {player}.</#FFC43B>'
|
||||
refresh-excluded: '<gray>{player} is excluded from SkinBridge detection; no skin was changed.</gray>'
|
||||
refresh-cooldown: '<#FFC43B>Wait {seconds} seconds before refreshing {player} again.</#FFC43B>'
|
||||
queue-full: '<#FFC43B>The SkinBridge lookup queue is full. Please try again later.</#FFC43B>'
|
||||
|
||||
blocks-menu:
|
||||
title: '<#00FB9A><bold>Shortcut Menu</bold></#00FB9A>'
|
||||
items:
|
||||
workbench:
|
||||
name: '<#00FB9A>Workbench</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/workbench</gray>'
|
||||
- '<gray>Open a crafting table</gray>'
|
||||
enderchest:
|
||||
name: '<#00FB9A>Ender Chest</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/enderchest</gray>'
|
||||
- '<gray>Open your ender chest</gray>'
|
||||
anvil:
|
||||
name: '<#00FB9A>Anvil</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/anvil</gray>'
|
||||
- '<gray>Open an anvil</gray>'
|
||||
grindstone:
|
||||
name: '<#00FB9A>Grindstone</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/grindstone</gray>'
|
||||
- '<gray>Open a grindstone</gray>'
|
||||
smithingtable:
|
||||
name: '<#00FB9A>Smithing Table</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/smithingtable</gray>'
|
||||
- '<gray>Open a smithing table</gray>'
|
||||
stonecutter:
|
||||
name: '<#00FB9A>Stonecutter</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/stonecutter</gray>'
|
||||
- '<gray>Open a stonecutter</gray>'
|
||||
loom:
|
||||
name: '<#00FB9A>Loom</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/loom</gray>'
|
||||
- '<gray>Open a loom</gray>'
|
||||
cartographytable:
|
||||
name: '<#00FB9A>Cartography Table</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/cartographytable</gray>'
|
||||
- '<gray>Open a cartography table</gray>'
|
||||
nightvision:
|
||||
name: '<#00FB9A>Night Vision</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/nightvision</gray>'
|
||||
- '<gray>Toggle night vision</gray>'
|
||||
glow:
|
||||
name: '<#00FB9A>Glow</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/glow</gray>'
|
||||
- '<gray>Toggle your glowing effect</gray>'
|
||||
|
||||
admin-mode:
|
||||
actionbar: '<#FF7E5E><bold>Admin Mode</bold></#FF7E5E>'
|
||||
messages:
|
||||
enabled: '<#00FB9A>Admin mode enabled; normal inventory has been saved.</#00FB9A>'
|
||||
disabled: '<#FF7E5E>Admin mode disabled; normal inventory has been restored.</#FF7E5E>'
|
||||
crash-restored: '<#FFC43B>The previous admin mode session has been restored safely.</#FFC43B>'
|
||||
save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not safely save your inventory; admin mode was not enabled.</#FF7E5E>'
|
||||
|
||||
tpsbar:
|
||||
title-format: '<#00FB9A>TPS</#00FB9A><gray>: {tps_1m} | </gray><#00FB9A>MSPT</#00FB9A><gray>: {mspt} | </gray><#00FB9A>Ping</#00FB9A><gray>: {ping}</gray>'
|
||||
messages:
|
||||
enabled-self: '<#00FB9A>TPSBar enabled.</#00FB9A>'
|
||||
disabled-self: '<#FF7E5E>TPSBar disabled.</#FF7E5E>'
|
||||
enabled-other: '<#00FB9A>Enabled TPSBar for {player}.</#00FB9A>'
|
||||
disabled-other: '<#FF7E5E>Disabled TPSBar for {player}.</#FF7E5E>'
|
||||
usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpsbar [player]</#FF7E5E>'
|
||||
player-not-found: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not find the player {player}.</#FF7E5E>'
|
||||
no-targets: '<#FF3300>Error:</#FF3300> <#FF7E5E>No matching players were found to toggle.</#FF7E5E>'
|
||||
native-detected: '<gray>Detected a native /tpsbar command on this server; skipped plugin implementation.</gray>'
|
||||
plugin-enabled: '<gray>No native /tpsbar command was detected; plugin implementation enabled.</gray>'
|
||||
|
||||
mobdrops-menu:
|
||||
title: '<#00FB9A><bold>Mob Drop Control</bold></#00FB9A>'
|
||||
status:
|
||||
enabled: '<#00FB9A>Enabled</#00FB9A>'
|
||||
disabled: '<#FF7E5E>Disabled</#FF7E5E>'
|
||||
enderman:
|
||||
name: '<#00FB9A>Enderman Drops</#00FB9A>'
|
||||
status: '<gray>Current status: {status}</gray>'
|
||||
toggle: '<gray>Click to toggle</gray>'
|
||||
|
||||
@@ -1,63 +1,260 @@
|
||||
# Chinese Language File (zh_CN)
|
||||
# 中文语言文件
|
||||
# 简体中文语言文件
|
||||
# 支持 MiniMessage 格式,默认使用绿色成功、红色错误和灰色说明。
|
||||
|
||||
# 插件前缀
|
||||
prefix: "&6[EssentialsC] &r"
|
||||
prefix: '<#00FB9A><bold>[EssentialsC]</bold></#00FB9A><gray>: </gray>'
|
||||
|
||||
# 命令消息
|
||||
messages:
|
||||
no-permission: "&c你没有权限执行此命令!\n&7需要权限: {permission}"
|
||||
player-only: "&c该命令只能由玩家执行!"
|
||||
hat-success: "&a你现在将 {item} 戴在头上!"
|
||||
hat-failed: "&c无法将物品戴在头上!"
|
||||
hat-no-item: "&c你需要在手中持有物品!"
|
||||
suicide-message: "&e{player} 自杀了!"
|
||||
fly-enabled: "&a飞行模式已启用!"
|
||||
fly-disabled: "&c飞行模式已禁用!"
|
||||
vanish-enabled: "&a你已进入隐身模式!"
|
||||
vanish-disabled: "&c你已退出隐身模式!"
|
||||
seen-usage: "&c用法: /seen <玩家名>"
|
||||
anvil-opened: "&a已打开铁砧!"
|
||||
enchantingtable-opened: "&a已打开附魔台!"
|
||||
heal-self: "&a你的生命值和饱食度已补满!"
|
||||
heal-other: "&a你已治疗了玩家 {player}!"
|
||||
heal-by-other: "&a你被管理员 {admin} 治疗了!"
|
||||
feed-self: "&a你的饱食度已补满!"
|
||||
feed-other: "&a你已喂饱玩家 {player}!"
|
||||
feed-by-other: "&a你被管理员 {admin} 喂饱了!"
|
||||
repair-hand-success: "&a手中物品已修复!"
|
||||
repair-all-success: "&a已修复 {count} 件物品!"
|
||||
repair-not-damaged: "&c该物品没有损坏!"
|
||||
repair-no-item-in-hand: "&c你手中没有物品!"
|
||||
repair-no-items: "&c背包中没有可修复的物品!"
|
||||
no-permission-repair-all: "&c你没有权限修复所有物品!"
|
||||
player-not-found: "&c未找到玩家: {player}"
|
||||
no-permission-others: "&c你没有权限治疗其他玩家!"
|
||||
no-permission: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限执行此命令.</#FF7E5E> <gray>需要权限: {permission}</gray>'
|
||||
player-only: '<#FF3300>错误:</#FF3300> <#FF7E5E>此命令只能由玩家执行.</#FF7E5E>'
|
||||
console-name: '控制台'
|
||||
config-reloaded: '<#00FB9A>配置已重载.</#00FB9A>'
|
||||
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
||||
paper-version: '<gray>当前运行于 Paper {version}</gray>'
|
||||
unknown-subcommand: '<#FF3300>错误:</#FF3300> <#FF7E5E>未知子命令: {command}</#FF7E5E>'
|
||||
help-usage: '<gray>使用 <white>/essc help</white> 查看可用命令.</gray>'
|
||||
module-disabled: '<#FF3300>错误:</#FF3300> <#FF7E5E>该功能模块当前已关闭.</#FF7E5E>'
|
||||
blocks-menu-empty: '<#FF3300>错误:</#FF3300> <#FF7E5E>你当前没有可用的便捷菜单项目.</#FF7E5E>'
|
||||
|
||||
# 帮助命令
|
||||
hat-success: '<#00FB9A>你已将 <bold>{item}</bold> 戴在头上.</#00FB9A>'
|
||||
hat-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法将该物品戴在头上.</#FF7E5E>'
|
||||
hat-no-item: '<#FF3300>错误:</#FF3300> <#FF7E5E>你需要手持一个物品.</#FF7E5E>'
|
||||
suicide-message: '<#FF7E5E>{player} 自杀了.</#FF7E5E>'
|
||||
fly-enabled: '<#00FB9A>飞行模式已开启.</#00FB9A>'
|
||||
fly-disabled: '<#FF7E5E>飞行模式已关闭.</#FF7E5E>'
|
||||
fly-permission-removed: '<#FF7E5E>你的飞行权限已被移除,飞行模式已关闭.</#FF7E5E>'
|
||||
nightvision-enabled: '<#00FB9A>夜视已开启.</#00FB9A>'
|
||||
nightvision-disabled: '<#FF7E5E>夜视已关闭.</#FF7E5E>'
|
||||
nightvision-permission-removed: '<#FF7E5E>你的夜视权限已被移除,夜视已关闭.</#FF7E5E>'
|
||||
nightvision-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /nightvision [on|off|toggle]</#FF7E5E>'
|
||||
glow-enabled: '<#00FB9A>发光已开启.</#00FB9A>'
|
||||
glow-disabled: '<#FF7E5E>发光已关闭.</#FF7E5E>'
|
||||
glow-permission-removed: '<#FF7E5E>你的发光权限已被移除,发光已关闭.</#FF7E5E>'
|
||||
glow-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /glow [on|off|toggle]</#FF7E5E>'
|
||||
vanish-enabled: '<#00FB9A>你已进入隐身模式.</#00FB9A>'
|
||||
vanish-disabled: '<#FF7E5E>你已退出隐身模式.</#FF7E5E>'
|
||||
vanish-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法保存隐身状态,本次操作未生效.</#FF7E5E>'
|
||||
vanish-permission-removed: '<#FFC43B>你的隐身权限已被移除,隐身模式已自动关闭.</#FFC43B>'
|
||||
seen-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
||||
seen-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
||||
seen-header: '<#00FB9A>玩家信息:</#00FB9A> <white>{player}</white>'
|
||||
seen-status-online: '<gray>状态: <#00FB9A>在线</#00FB9A></gray>'
|
||||
seen-status-offline: '<gray>状态: <#FF7E5E>离线</#FF7E5E></gray>'
|
||||
seen-world: '<gray>所在世界: <white>{world}</white></gray>'
|
||||
seen-last-online: '<gray>最后在线: <white>{time}</white></gray>'
|
||||
seen-first-joined: '<gray>首次加入: <white>{time}</white></gray>'
|
||||
player-not-found: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有找到玩家 {player}.</#FF7E5E>'
|
||||
no-permission-others: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限影响其他玩家.</#FF7E5E>'
|
||||
|
||||
anvil-opened: '<#00FB9A>已打开铁砧.</#00FB9A>'
|
||||
enchantingtable-opened: '<#00FB9A>已打开附魔台.</#00FB9A>'
|
||||
heal-self: '<#00FB9A>你的生命值和饥饿值已恢复.</#00FB9A>'
|
||||
heal-other: '<#00FB9A>你已治疗玩家 <bold>{player}</bold>.</#00FB9A>'
|
||||
heal-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 治疗了你.</#00FB9A>'
|
||||
heal-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /heal [玩家]</#FF7E5E>'
|
||||
feed-self: '<#00FB9A>你的饥饿值已恢复.</#00FB9A>'
|
||||
feed-other: '<#00FB9A>你已喂饱玩家 <bold>{player}</bold>.</#00FB9A>'
|
||||
feed-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 喂饱了你.</#00FB9A>'
|
||||
feed-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /feed [玩家]</#FF7E5E>'
|
||||
repair-hand-success: '<#00FB9A>手中物品已修复.</#00FB9A>'
|
||||
repair-all-success: '<#00FB9A>已修复 <bold>{count}</bold> 个物品.</#00FB9A>'
|
||||
repair-not-damaged: '<#FF3300>错误:</#FF3300> <#FF7E5E>该物品没有损坏.</#FF7E5E>'
|
||||
repair-no-item-in-hand: '<#FF3300>错误:</#FF3300> <#FF7E5E>你手中没有物品.</#FF7E5E>'
|
||||
repair-no-items: '<#FF3300>错误:</#FF3300> <#FF7E5E>背包中没有可修复的物品.</#FF7E5E>'
|
||||
no-permission-repair-all: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限修复全部物品.</#FF7E5E>'
|
||||
|
||||
mobdrop-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>保存配置失败: {error}</#FF7E5E>'
|
||||
mobdrop-toggled: '<#00FB9A>末影人掉落已切换为 {status}.</#00FB9A>'
|
||||
shulkerbox-nested: '<#FF3300>错误:</#FF3300> <#FF7E5E>不能将潜影盒放入另一个潜影盒.</#FF7E5E>'
|
||||
shulkerbox-unstack-first: '<#FF3300>错误:</#FF3300> <#FF7E5E>请先将潜影盒拆分为单个后再快捷打开.</#FF7E5E>'
|
||||
shulkerbox-open-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>潜影盒打开失败,请稍后重试.</#FF7E5E>'
|
||||
shulkerbox-session-invalid: '<#FF3300>错误:</#FF3300> <#FF7E5E>潜影盒会话异常,已停止保存以避免物品复制.</#FF7E5E>'
|
||||
help:
|
||||
title: "&6========== &eEssentialsC 帮助 &6=========="
|
||||
version: "&7插件版本: &f{version}"
|
||||
section-blocks: "&6功能方块命令:"
|
||||
section-other: "&6其他功能命令:"
|
||||
footer: "&7需要权限才能使用各个命令"
|
||||
|
||||
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>命令帮助</gray>'
|
||||
version: '<gray>插件版本: <white>{version}</white></gray>'
|
||||
section-blocks: '<#00FB9A>功能方块命令</#00FB9A>'
|
||||
section-other: '<#00FB9A>其他命令</#00FB9A>'
|
||||
footer: '<gray>每个命令都需要对应权限.</gray>'
|
||||
|
||||
commands:
|
||||
workbench: " &f/workbench &7- 打开工作台"
|
||||
anvil: " &f/anvil &7- 打开铁砧"
|
||||
enchantingtable: " &f/enchantingtable &7- 打开附魔台"
|
||||
cartographytable: " &f/cartographytable &7- 打开制图台"
|
||||
grindstone: " &f/grindstone &7- 打开砂轮"
|
||||
loom: " &f/loom &7- 打开织布机"
|
||||
smithingtable: " &f/smithingtable &7- 打开锻造台"
|
||||
stonecutter: " &f/stonecutter &7- 打开切石机"
|
||||
enderchest: " &f/enderchest &7- 打开末影箱"
|
||||
hat: " &f/hat &7- 将手中物品戴在头上"
|
||||
suicide: " &f/suicide &7- 自杀"
|
||||
fly: " &f/fly &7- 切换飞行模式"
|
||||
heal: " &f/heal &7- 恢复生命值和饱食度"
|
||||
vanish: " &f/vanish &7- 切换隐身模式"
|
||||
seen: " &f/seen &7- 查看玩家信息"
|
||||
feed: " &f/feed &7- 补满饱食度"
|
||||
repair: " &f/repair &7- 修复手中或所有物品"
|
||||
blocks: " &f/blocks &7- 打开功能方块菜单"
|
||||
reload: '<white>/essc reload</white> <gray>- 重载插件配置</gray>'
|
||||
version: '<white>/essc version</white> <gray>- 查看插件与服务端版本</gray>'
|
||||
workbench: '<white>/workbench</white> <gray>- 打开工作台</gray>'
|
||||
anvil: '<white>/anvil</white> <gray>- 打开铁砧</gray>'
|
||||
enchantingtable: '<white>/enchantingtable</white> <gray>- 打开附魔台</gray>'
|
||||
cartographytable: '<white>/cartographytable</white> <gray>- 打开制图台</gray>'
|
||||
grindstone: '<white>/grindstone</white> <gray>- 打开砂轮</gray>'
|
||||
loom: '<white>/loom</white> <gray>- 打开织布机</gray>'
|
||||
smithingtable: '<white>/smithingtable</white> <gray>- 打开锻造台</gray>'
|
||||
stonecutter: '<white>/stonecutter</white> <gray>- 打开切石机</gray>'
|
||||
enderchest: '<white>/enderchest</white> <gray>- 打开末影箱</gray>'
|
||||
blocks: '<white>/blocks</white> <gray>- 打开便捷菜单</gray>'
|
||||
hat: '<white>/hat</white> <gray>- 将手持物品戴在头上</gray>'
|
||||
suicide: '<white>/suicide</white> <gray>- 自杀</gray>'
|
||||
fly: '<white>/fly</white> <gray>- 切换飞行模式</gray>'
|
||||
nightvision: '<white>/nightvision</white> <gray>- 切换夜视</gray>'
|
||||
glow: '<white>/glow</white> <gray>- 切换发光</gray>'
|
||||
heal: '<white>/heal [玩家]</white> <gray>- 恢复生命值和饥饿值</gray>'
|
||||
vanish: '<white>/vanish</white> <gray>- 切换隐身模式</gray>'
|
||||
seen: '<white>/seen [玩家]</white> <gray>- 查看玩家信息</gray>'
|
||||
feed: '<white>/feed [玩家]</white> <gray>- 恢复饥饿值</gray>'
|
||||
repair: '<white>/repair</white> <gray>- 修复手中或全部物品</gray>'
|
||||
tpa: '<white>/tpa [玩家]</white> <gray>- 请求传送到玩家身边</gray>'
|
||||
tpahere: '<white>/tpahere [玩家]</white> <gray>- 请求玩家传送到你身边</gray>'
|
||||
tpaall: '<white>/tpaall</white> <gray>- 向所有玩家发送传送到你身边的请求</gray>'
|
||||
tpaccept: '<white>/tpaccept [玩家]</white> <gray>- 接受传送请求</gray>'
|
||||
tpdeny: '<white>/tpdeny [玩家]</white> <gray>- 拒绝传送请求</gray>'
|
||||
tpignore: '<white>/tpignore</white> <gray>- 切换是否忽略传送请求</gray>'
|
||||
skin: '<white>/essc skin [status|refresh] [玩家]</white> <gray>- 查看或刷新皮肤桥接状态</gray>'
|
||||
admin: '<white>/essc admin</white> <gray>- 切换管理模式</gray>'
|
||||
tpsbar: '<white>/tpsbar [玩家]</white> <gray>- 切换 TPS 状态栏</gray>'
|
||||
|
||||
tpa:
|
||||
messages:
|
||||
usage-tpa: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpa [玩家]</#FF7E5E>'
|
||||
usage-tpahere: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpahere [玩家]</#FF7E5E>'
|
||||
usage-tpaall: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpaall</#FF7E5E>'
|
||||
usage-tpaccept: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpaccept [玩家]</#FF7E5E>'
|
||||
usage-tpdeny: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpdeny [玩家]</#FF7E5E>'
|
||||
self: '<#FF3300>错误:</#FF3300> <#FF7E5E>不能向自己发送传送请求</#FF7E5E>'
|
||||
sent-tpa: '<#00FB9A>已发送传送请求,请求传送到</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold>'
|
||||
sent-tpahere: '<#00FB9A>已发送传送请求,请求</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold> <#00FB9A>传送到你的位置</#00FB9A>'
|
||||
ignoring-requests: '<#FF3300>错误:</#FF3300> <#FF7E5E>你已忽略传送请求</#FF7E5E> <#FF7E5E><click:run_command:/tpignore><hover:show_text:"<#FF7E5E>点击恢复接收传送请求</#FF7E5E>">[恢复接收]</hover></click></#FF7E5E>'
|
||||
send-cooldown: '<#FF3300>错误:</#FF3300> <#FF7E5E>你需要等待 {seconds}s 才能再次进行此操作</#FF7E5E>'
|
||||
accept-cooldown: '<#FF3300>错误:</#FF3300> <#FF7E5E>你需要等待 {seconds}s 才能再次进行此操作</#FF7E5E>'
|
||||
received-tpa: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>请求传送到你的位置</#00FB9A>'
|
||||
received-tpahere: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>请求你传送到他的位置</#00FB9A>'
|
||||
response-buttons: '<gray>选项:</gray> <#00FB9A><click:run_command:''/tpaccept {requester}''><hover:show_text:''<#00FB9A>接受传送请求\n<dark_gray>点击接受 {requester} 的请求</dark_gray></#00FB9A>''>[✔ 接受]</hover></click></#00FB9A> <#FF3300><click:run_command:''/tpdeny {requester}''><hover:show_text:''<#FF3300>拒绝传送请求\n<dark_gray>点击拒绝 {requester} 的请求</dark_gray></#FF3300>''>[❌ 拒绝]</hover></click></#FF3300>'
|
||||
no-request: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有待处理的传送请求</#FF7E5E>'
|
||||
invalid-request: '<#FF3300>错误:</#FF3300> <#FF7E5E>目前没有来自 {requester} 的传送请求</#FF7E5E>'
|
||||
accepted-target: '<#00FB9A>已接受 {requester} 的传送请求</#00FB9A>'
|
||||
accepted-sender: '<#00FB9A>{target} 接受了你的传送请求</#00FB9A>'
|
||||
denied-target: '<#FF7E5E>已拒绝 {requester} 的传送请求</#FF7E5E>'
|
||||
denied-sender: '<#FF7E5E>{target} 拒绝了你的传送请求</#FF7E5E>'
|
||||
expired: '<#FF3300>错误:</#FF3300> <#FF7E5E>传送请求已过期</#FF7E5E>'
|
||||
player-offline: '<#FF3300>错误:</#FF3300> <#FF7E5E>你待处理的传送请求目标玩家不在线</#FF7E5E>'
|
||||
target-offline: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有找到目标玩家</#FF7E5E>'
|
||||
already-warming-up: '<#FF3300>错误:</#FF3300> <#FF7E5E>相关玩家已有一个正在预热的传送</#FF7E5E>'
|
||||
warmup-start: '<#00FB9A>你将在</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold> <#00FB9A>秒后被传送,请不要移动…</#00FB9A>'
|
||||
warmup-status: '<#00FB9A>将在</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold><#00FB9A>秒后传送…</#00FB9A>'
|
||||
warmup-processing: '<#00FB9A>传送中…</#00FB9A>'
|
||||
warmup-cancelled-move: '<#FF7E5E>传送取消: 你移动了!</#FF7E5E>'
|
||||
warmup-cancelled-damage: '<#FF7E5E>传送取消: 你受到了伤害!</#FF7E5E>'
|
||||
warmup-cancelled-actionbar: '<#FF7E5E>传送取消!</#FF7E5E>'
|
||||
warmup-stand-still: '<#FF3300>错误:</#FF3300> <#FF7E5E>在传送时你不能移动!</#FF7E5E>'
|
||||
teleport-complete: '<#00FB9A>传送完成!</#00FB9A>'
|
||||
teleport-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法完成传送,请稍后重试</#FF7E5E>'
|
||||
ignore-enabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>忽略</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
||||
ignore-disabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>恢复接收</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
||||
ignore-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法保存传送请求忽略状态,本次操作未生效.</#FF7E5E>'
|
||||
ignore-notification: '<gray>你当前正在忽略传送请求.</gray>'
|
||||
tpaall-sent: '<#00FB9A>你已向所有玩家发送传送请求,请求他们传送到你的位置</#00FB9A>'
|
||||
tpaall-no-targets: '<#FF3300>错误:</#FF3300> <#FF7E5E>当前没有其他在线玩家.</#FF7E5E>'
|
||||
|
||||
skin-bridge:
|
||||
notifications:
|
||||
detecting: '<#00FB9A>正在检测你的皮肤来源…</#00FB9A>'
|
||||
synced: '<#00FB9A>已通过 <bold>{provider}</bold> 同步皮肤.</#00FB9A>'
|
||||
excluded: '<gray>你位于 SkinBridge 排除名单中,已保留当前皮肤.</gray>'
|
||||
queue-full: '<#FFC43B>当前皮肤检测任务较多,已跳过本次检测.</#FFC43B>'
|
||||
not-external: '<gray>未匹配外置皮肤站,已保留当前皮肤.</gray>'
|
||||
failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>皮肤检测或同步失败,请稍后重试.</#FF7E5E>'
|
||||
messages:
|
||||
usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /essc skin [status|refresh] [玩家]</#FF7E5E>'
|
||||
dependency-missing: '<#FF3300>错误:</#FF3300> <#FF7E5E>未在 config.yml 中配置有效的 MineSkin API Key.</#FF7E5E>'
|
||||
no-providers: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有启用有效的 SkinBridge Provider.</#FF7E5E>'
|
||||
status-external: '<#00FB9A>{player} 已识别为外置皮肤站玩家.</#00FB9A> <gray>Provider: <white>{provider}</white></gray>'
|
||||
status-excluded: '<gray>{player} 位于 SkinBridge 排除名单中.</gray>'
|
||||
status-not-external: '<gray>{player} 未匹配任何已配置的外置皮肤站.</gray>'
|
||||
status-pending: '<#FFC43B>{player} 的皮肤站来源正在检测中.</#FFC43B>'
|
||||
status-unknown: '<gray>{player} 尚未进行 SkinBridge 检测.</gray>'
|
||||
refresh-queued: '<#00FB9A>已开始重新检测并刷新 {player} 的皮肤.</#00FB9A>'
|
||||
refresh-cached: '<gray>{player} 正在使用有效的皮肤缓存.</gray>'
|
||||
refresh-running: '<#FFC43B>{player} 的皮肤检测任务仍在运行.</#FFC43B>'
|
||||
refresh-excluded: '<gray>{player} 位于 SkinBridge 排除名单中,未修改皮肤.</gray>'
|
||||
refresh-cooldown: '<#FFC43B>请等待 {seconds} 秒后再刷新 {player} 的皮肤.</#FFC43B>'
|
||||
queue-full: '<#FFC43B>SkinBridge 查询队列已满,请稍后重试.</#FFC43B>'
|
||||
|
||||
blocks-menu:
|
||||
title: '<#00FB9A><bold>便捷菜单</bold></#00FB9A>'
|
||||
items:
|
||||
workbench:
|
||||
name: '<#00FB9A>工作台</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/workbench</gray>'
|
||||
- '<gray>打开工作台</gray>'
|
||||
enderchest:
|
||||
name: '<#00FB9A>末影箱</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/enderchest</gray>'
|
||||
- '<gray>打开末影箱</gray>'
|
||||
anvil:
|
||||
name: '<#00FB9A>铁砧</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/anvil</gray>'
|
||||
- '<gray>打开铁砧</gray>'
|
||||
grindstone:
|
||||
name: '<#00FB9A>砂轮</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/grindstone</gray>'
|
||||
- '<gray>打开砂轮</gray>'
|
||||
smithingtable:
|
||||
name: '<#00FB9A>锻造台</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/smithingtable</gray>'
|
||||
- '<gray>打开锻造台</gray>'
|
||||
stonecutter:
|
||||
name: '<#00FB9A>切石机</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/stonecutter</gray>'
|
||||
- '<gray>打开切石机</gray>'
|
||||
loom:
|
||||
name: '<#00FB9A>织布机</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/loom</gray>'
|
||||
- '<gray>打开织布机</gray>'
|
||||
cartographytable:
|
||||
name: '<#00FB9A>制图台</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/cartographytable</gray>'
|
||||
- '<gray>打开制图台</gray>'
|
||||
nightvision:
|
||||
name: '<#00FB9A>夜视开关</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/nightvision</gray>'
|
||||
- '<gray>切换夜视效果</gray>'
|
||||
glow:
|
||||
name: '<#00FB9A>发光开关</#00FB9A>'
|
||||
lore:
|
||||
- '<gray>/glow</gray>'
|
||||
- '<gray>切换自身发光效果</gray>'
|
||||
|
||||
admin-mode:
|
||||
actionbar: '<#FF7E5E><bold>管理模式</bold></#FF7E5E>'
|
||||
messages:
|
||||
enabled: '<#00FB9A>管理模式已开启,普通背包已保存.</#00FB9A>'
|
||||
disabled: '<#FF7E5E>管理模式已关闭,普通背包已恢复.</#FF7E5E>'
|
||||
crash-restored: '<#FFC43B>上一次管理模式会话已安全恢复.</#FFC43B>'
|
||||
save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法安全保存当前背包,管理模式未开启.</#FF7E5E>'
|
||||
|
||||
tpsbar:
|
||||
title-format: '<#00FB9A>TPS</#00FB9A><gray>: {tps_1m} | </gray><#00FB9A>MSPT</#00FB9A><gray>: {mspt} | </gray><#00FB9A>Ping</#00FB9A><gray>: {ping}</gray>'
|
||||
messages:
|
||||
enabled-self: '<#00FB9A>已开启 TPSBar.</#00FB9A>'
|
||||
disabled-self: '<#FF7E5E>已关闭 TPSBar.</#FF7E5E>'
|
||||
enabled-other: '<#00FB9A>已为 {player} 开启 TPSBar.</#00FB9A>'
|
||||
disabled-other: '<#FF7E5E>已为 {player} 关闭 TPSBar.</#FF7E5E>'
|
||||
usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpsbar [玩家]</#FF7E5E>'
|
||||
player-not-found: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有找到玩家 {player}.</#FF7E5E>'
|
||||
no-targets: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有匹配到可切换的玩家.</#FF7E5E>'
|
||||
native-detected: '<gray>检测到服务端已内置 /tpsbar,已跳过插件实现.</gray>'
|
||||
plugin-enabled: '<gray>未检测到服务端内置 /tpsbar,已启用插件实现.</gray>'
|
||||
|
||||
mobdrops-menu:
|
||||
title: '<#00FB9A><bold>生物掉落控制</bold></#00FB9A>'
|
||||
status:
|
||||
enabled: '<#00FB9A>开启</#00FB9A>'
|
||||
disabled: '<#FF7E5E>关闭</#FF7E5E>'
|
||||
enderman:
|
||||
name: '<#00FB9A>末影人掉落</#00FB9A>'
|
||||
status: '<gray>当前状态: {status}</gray>'
|
||||
toggle: '<gray>点击切换</gray>'
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# EssentialsC 模块配置
|
||||
#
|
||||
# modules.yml 用于控制功能模块是否在运行时加载。
|
||||
# 各功能的详细设置位于 config.yml 与 blocks-menu.yml。
|
||||
#
|
||||
# 修改模块开关后可使用 /essc reload 刷新运行期服务和监听器。
|
||||
# 直连命令的完整热增删仍建议通过重启服务器完成。
|
||||
|
||||
config-version: 1
|
||||
|
||||
modules:
|
||||
blocks:
|
||||
# 工作台、铁砧等便捷方块命令、/essc blocks 菜单和潜影盒快捷打开。
|
||||
enabled: true
|
||||
admin-mode:
|
||||
# /essc admin 管理模式,以及独立背包和状态管理。
|
||||
enabled: true
|
||||
tpsbar:
|
||||
# 插件版 TPSBar。检测到服务端原生命令时会自动避免冲突。
|
||||
enabled: true
|
||||
mob-drops:
|
||||
# 末影人掉落控制菜单和监听器;具体掉落状态可在游戏内切换。
|
||||
enabled: false
|
||||
skin-bridge:
|
||||
# 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
||||
enabled: false
|
||||
@@ -1,99 +1,189 @@
|
||||
name: EssentialsC
|
||||
description: 精简版基础插件
|
||||
version: '${version}'
|
||||
description: 高版本基础工具箱
|
||||
version: ${version}
|
||||
|
||||
main: cn.infstar.essentialsC.EssentialsC
|
||||
api-version: '1.21'
|
||||
api-version: '1.21.11'
|
||||
load: POSTWORLD
|
||||
folia-supported: false
|
||||
|
||||
authors: [ Coldsmiles_7 ]
|
||||
website: www.infstar.cn
|
||||
|
||||
permissions:
|
||||
essentialsc.command.workbench:
|
||||
description: Allows use of /workbench command
|
||||
description: 允许使用 /workbench
|
||||
default: op
|
||||
essentialsc.command.anvil:
|
||||
description: Allows use of /anvil command
|
||||
default: op
|
||||
essentialsc.command.enchantingtable:
|
||||
description: Allows use of /enchantingtable command
|
||||
description: 允许使用 /anvil
|
||||
default: op
|
||||
essentialsc.command.cartographytable:
|
||||
description: Allows use of /cartographytable command
|
||||
description: 允许使用 /cartographytable
|
||||
default: op
|
||||
essentialsc.command.grindstone:
|
||||
description: Allows use of /grindstone command
|
||||
description: 允许使用 /grindstone
|
||||
default: op
|
||||
essentialsc.command.loom:
|
||||
description: Allows use of /loom command
|
||||
description: 允许使用 /loom
|
||||
default: op
|
||||
essentialsc.command.smithingtable:
|
||||
description: Allows use of /smithingtable command
|
||||
description: 允许使用 /smithingtable
|
||||
default: op
|
||||
essentialsc.command.stonecutter:
|
||||
description: Allows use of /stonecutter command
|
||||
description: 允许使用 /stonecutter
|
||||
default: op
|
||||
essentialsc.command.enderchest:
|
||||
description: Allows use of /enderchest command
|
||||
default: op
|
||||
essentialsc.command.hat:
|
||||
description: Allows use of /hat command
|
||||
default: op
|
||||
essentialsc.command.suicide:
|
||||
description: Allows use of /suicide command
|
||||
default: op
|
||||
essentialsc.command.fly:
|
||||
description: Allows use of /fly command
|
||||
default: op
|
||||
essentialsc.command.heal:
|
||||
description: Allows use of /heal command
|
||||
default: op
|
||||
essentialsc.command.vanish:
|
||||
description: Allows use of /vanish command
|
||||
default: op
|
||||
essentialsc.command.seen:
|
||||
description: Allows use of /seen command
|
||||
default: op
|
||||
essentialsc.command.feed:
|
||||
description: Allows use of /feed command
|
||||
default: op
|
||||
essentialsc.command.repair:
|
||||
description: Allows use of /repair command
|
||||
description: 允许使用 /enderchest
|
||||
default: op
|
||||
essentialsc.command.blocks:
|
||||
description: Allows use of /essc blocks command
|
||||
description: 允许使用 /essc blocks
|
||||
default: true
|
||||
essentialsc.command.hat:
|
||||
description: 允许使用 /hat
|
||||
default: op
|
||||
essentialsc.command.suicide:
|
||||
description: 允许使用 /suicide
|
||||
default: op
|
||||
essentialsc.command.fly:
|
||||
description: 允许使用 /fly
|
||||
default: op
|
||||
essentialsc.command.nightvision:
|
||||
description: 允许使用 /nightvision
|
||||
default: op
|
||||
essentialsc.command.glow:
|
||||
description: 允许使用 /glow
|
||||
default: op
|
||||
essentialsc.command.heal:
|
||||
description: 允许使用 /heal
|
||||
default: op
|
||||
essentialsc.command.heal.others:
|
||||
description: 允许治疗其他玩家
|
||||
default: op
|
||||
essentialsc.command.vanish:
|
||||
description: 允许使用 /vanish
|
||||
default: op
|
||||
essentialsc.vanish.see:
|
||||
description: 允许看见隐身玩家
|
||||
default: op
|
||||
essentialsc.command.seen:
|
||||
description: 允许使用 /seen
|
||||
default: op
|
||||
essentialsc.command.feed:
|
||||
description: 允许使用 /feed
|
||||
default: op
|
||||
essentialsc.command.feed.others:
|
||||
description: 允许为其他玩家补充饥饿值
|
||||
default: op
|
||||
essentialsc.command.repair:
|
||||
description: 允许使用 /repair
|
||||
default: op
|
||||
essentialsc.command.repair.all:
|
||||
description: 允许使用 /repair all
|
||||
default: op
|
||||
essentialsc.command.tpa:
|
||||
description: 允许发送 /tpa 请求
|
||||
default: true
|
||||
essentialsc.command.tpahere:
|
||||
description: 允许发送 /tpahere 请求
|
||||
default: true
|
||||
essentialsc.command.tpaall:
|
||||
description: 允许向所有玩家发送 /tpahere 请求
|
||||
default: op
|
||||
essentialsc.command.tpaccept:
|
||||
description: 允许接受 TPA 请求
|
||||
default: true
|
||||
essentialsc.command.tpdeny:
|
||||
description: 允许拒绝 TPA 请求
|
||||
default: true
|
||||
essentialsc.command.tpignore:
|
||||
description: 允许切换是否忽略 TPA 请求
|
||||
default: true
|
||||
essentialsc.tpa.bypass-warmup:
|
||||
description: 允许绕过 TPA 传送预热
|
||||
default: op
|
||||
essentialsc.tpa.bypass-cooldown:
|
||||
description: 允许绕过 TPA 冷却
|
||||
default: op
|
||||
essentialsc.command.admin:
|
||||
description: 允许使用 /essc admin
|
||||
default: op
|
||||
essentialsc.command.help:
|
||||
description: Allows use of /essentialsc help command
|
||||
description: 允许使用 /essc help
|
||||
default: true
|
||||
essentialsc.command.reload:
|
||||
description: Allows use of /essc reload command
|
||||
description: 允许使用 /essc reload
|
||||
default: op
|
||||
essentialsc.command.tpsbar:
|
||||
description: 允许使用 /tpsbar
|
||||
default: op
|
||||
essentialsc.command.tpsbar.others:
|
||||
description: 允许为其他玩家切换 /tpsbar
|
||||
default: op
|
||||
essentialsc.command.skin:
|
||||
description: 允许使用 SkinBridge 管理命令
|
||||
default: op
|
||||
children:
|
||||
essentialsc.command.skin.status: true
|
||||
essentialsc.command.skin.refresh: true
|
||||
essentialsc.command.skin.others: true
|
||||
essentialsc.command.skin.status:
|
||||
description: 允许查看 SkinBridge 状态
|
||||
default: op
|
||||
essentialsc.command.skin.refresh:
|
||||
description: 允许强制刷新自己的皮肤
|
||||
default: op
|
||||
essentialsc.command.skin.others:
|
||||
description: 允许查看或刷新其他玩家的皮肤
|
||||
default: op
|
||||
essentialsc.shulkerbox.open:
|
||||
description: Allows right-click to open shulker boxes without placing them
|
||||
description: 允许通过 Shift+右键快捷打开潜影盒
|
||||
default: op
|
||||
essentialsc.mobdrops.enderman:
|
||||
description: 允许控制末影人死亡时是否掉落物品
|
||||
default: op
|
||||
essentialsc.*:
|
||||
description: All EssentialsC permissions
|
||||
description: 授予 EssentialsC 的全部权限
|
||||
default: false
|
||||
children:
|
||||
essentialsc.command.workbench: true
|
||||
essentialsc.command.anvil: true
|
||||
essentialsc.command.enchantingtable: true
|
||||
essentialsc.command.cartographytable: true
|
||||
essentialsc.command.grindstone: true
|
||||
essentialsc.command.loom: true
|
||||
essentialsc.command.smithingtable: true
|
||||
essentialsc.command.stonecutter: true
|
||||
essentialsc.command.enderchest: true
|
||||
essentialsc.command.blocks: true
|
||||
essentialsc.command.hat: true
|
||||
essentialsc.command.suicide: true
|
||||
essentialsc.command.fly: true
|
||||
essentialsc.command.nightvision: true
|
||||
essentialsc.command.glow: true
|
||||
essentialsc.command.heal: true
|
||||
essentialsc.command.heal.others: true
|
||||
essentialsc.command.vanish: true
|
||||
essentialsc.vanish.see: true
|
||||
essentialsc.command.seen: true
|
||||
essentialsc.command.reload: true
|
||||
essentialsc.command.feed: true
|
||||
essentialsc.command.feed.others: true
|
||||
essentialsc.command.repair: true
|
||||
essentialsc.command.repair.all: true
|
||||
essentialsc.command.tpa: true
|
||||
essentialsc.command.tpahere: true
|
||||
essentialsc.command.tpaall: true
|
||||
essentialsc.command.tpaccept: true
|
||||
essentialsc.command.tpdeny: true
|
||||
essentialsc.command.tpignore: true
|
||||
essentialsc.tpa.bypass-warmup: true
|
||||
essentialsc.tpa.bypass-cooldown: true
|
||||
essentialsc.command.admin: true
|
||||
essentialsc.command.help: true
|
||||
essentialsc.command.reload: true
|
||||
essentialsc.command.tpsbar: true
|
||||
essentialsc.command.tpsbar.others: true
|
||||
essentialsc.command.skin: true
|
||||
essentialsc.command.skin.status: true
|
||||
essentialsc.command.skin.refresh: true
|
||||
essentialsc.command.skin.others: true
|
||||
essentialsc.shulkerbox.open: true
|
||||
essentialsc.mobdrops.enderman: true
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package cn.infstar.essentialsC;
|
||||
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ConfigurationResourcesTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"config.yml",
|
||||
"modules.yml",
|
||||
"blocks-menu.yml",
|
||||
"paper-plugin.yml",
|
||||
"lang/zh_CN.yml",
|
||||
"lang/en_US.yml"
|
||||
})
|
||||
void bundledYamlIsValid(String resourcePath) throws Exception {
|
||||
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resourcePath)) {
|
||||
assertNotNull(input, resourcePath);
|
||||
YamlConfiguration configuration = new YamlConfiguration();
|
||||
configuration.load(new InputStreamReader(input, StandardCharsets.UTF_8));
|
||||
|
||||
if (resourcePath.equals("config.yml")) {
|
||||
assertEquals(2, configuration.getInt("config-version"));
|
||||
assertEquals(5, configuration.getInt("tpa.max-pending-requests"));
|
||||
assertEquals(500, configuration.getInt("skin-bridge.max-generated-cache-entries"));
|
||||
assertTrue(configuration.getString("skin-bridge.mineskin.api-key", "").isBlank());
|
||||
}
|
||||
if (resourcePath.equals("paper-plugin.yml")) {
|
||||
assertEquals("1.21.11", configuration.getString("api-version"));
|
||||
}
|
||||
if (resourcePath.startsWith("lang/")) {
|
||||
assertTrue(!configuration.getString("prefix", "").isBlank());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bundledLanguagesContainTheSameKeys() throws Exception {
|
||||
YamlConfiguration chinese = loadResource("lang/zh_CN.yml");
|
||||
YamlConfiguration english = loadResource("lang/en_US.yml");
|
||||
|
||||
assertEquals(chinese.getKeys(true), english.getKeys(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retiredJeiFeatureIsAbsentFromResources() throws Exception {
|
||||
assertFalse(loadResource("config.yml").contains("jei-sync", true));
|
||||
assertFalse(loadResource("modules.yml").contains("modules.jei-sync", true));
|
||||
assertFalse(loadResource("lang/zh_CN.yml").contains("messages.jei-sync-fabric", true));
|
||||
assertFalse(loadResource("lang/zh_CN.yml").contains("messages.jei-sync-neoforge", true));
|
||||
assertFalse(loadResource("lang/en_US.yml").contains("messages.jei-sync-fabric", true));
|
||||
assertFalse(loadResource("lang/en_US.yml").contains("messages.jei-sync-neoforge", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retiredMaintenanceFeatureIsAbsentFromResources() throws Exception {
|
||||
assertNull(getClass().getClassLoader().getResource("maintenance.yml"));
|
||||
assertFalse(loadResource("modules.yml").contains("modules.maintenance", true));
|
||||
assertFalse(loadResource("paper-plugin.yml").contains("dependencies.server.LuckPerms", true));
|
||||
assertFalse(loadResource("paper-plugin.yml").contains("permissions.essentialsc.command.maintenance", true));
|
||||
assertFalse(loadResource("paper-plugin.yml").contains("permissions.essentialsc.maintenance.bypass", true));
|
||||
assertFalse(loadResource("paper-plugin.yml").contains("permissions.essentialsc.maintenance.notify", true));
|
||||
assertFalse(loadResource("lang/zh_CN.yml").contains("maintenance", true));
|
||||
assertFalse(loadResource("lang/en_US.yml").contains("maintenance", true));
|
||||
assertNull(cn.infstar.essentialsC.commands.CommandRegistry.resolveCommandName("maintenance"));
|
||||
assertNull(cn.infstar.essentialsC.commands.CommandRegistry.resolveCommandName("maint"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniMessageTagNamesAreNormalized() {
|
||||
assertEquals("<gray>文本</gray>", LangManager.normalizeMiniMessageTags("<GRAY>文本</GRAY>"));
|
||||
assertEquals("\\<GRAY>", LangManager.normalizeMiniMessageTags("\\<GRAY>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyFormattingCanBeNestedInMiniMessage() {
|
||||
String message = LangManager.applyPlaceholders(
|
||||
"<gray>维护状态: {status}</gray>",
|
||||
java.util.Map.of("status", "§a开启")
|
||||
);
|
||||
String rendered = PlainTextComponentSerializer.plainText().serialize(
|
||||
MiniMessage.miniMessage().deserialize(message)
|
||||
);
|
||||
|
||||
assertEquals("维护状态: 开启", rendered);
|
||||
}
|
||||
|
||||
private YamlConfiguration loadResource(String resourcePath) throws Exception {
|
||||
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resourcePath)) {
|
||||
assertNotNull(input, resourcePath);
|
||||
YamlConfiguration configuration = new YamlConfiguration();
|
||||
configuration.load(new InputStreamReader(input, StandardCharsets.UTF_8));
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cn.infstar.essentialsC.admin;
|
||||
|
||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AdminModeStoreTest {
|
||||
|
||||
@TempDir
|
||||
Path temporaryDirectory;
|
||||
|
||||
@Test
|
||||
void migratesLegacyPlayersIntoIndependentFiles() throws Exception {
|
||||
UUID playerId = UUID.randomUUID();
|
||||
Path legacyFile = temporaryDirectory.resolve("admin-mode.yml");
|
||||
YamlConfiguration legacy = new YamlConfiguration();
|
||||
legacy.set("players." + playerId + ".active", true);
|
||||
legacy.set("players." + playerId + ".normal.level", 27);
|
||||
AtomicYamlWriter.save(legacy, legacyFile.toFile());
|
||||
|
||||
AdminModeStore store = new AdminModeStore(
|
||||
temporaryDirectory.resolve("admin-mode").toFile(), legacyFile.toFile(), Logger.getAnonymousLogger());
|
||||
|
||||
YamlConfiguration migrated = store.load(playerId);
|
||||
assertNotNull(migrated);
|
||||
assertTrue(migrated.getBoolean("active"));
|
||||
assertEquals(27, migrated.getInt("normal.level"));
|
||||
assertTrue(Files.exists(temporaryDirectory.resolve("admin-mode").resolve(playerId + ".yml")));
|
||||
assertFalse(Files.exists(legacyFile));
|
||||
try (var backups = Files.list(temporaryDirectory)) {
|
||||
assertTrue(backups.anyMatch(path -> path.getFileName().toString().startsWith("admin-mode.legacy-")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cn.infstar.essentialsC.listeners;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ShulkerBoxSessionPolicyTest {
|
||||
|
||||
@Test
|
||||
void identifiesOnlySlotsInsideTopInventory() {
|
||||
assertFalse(ShulkerBoxSessionPolicy.isTopSlot(-999, 27));
|
||||
assertTrue(ShulkerBoxSessionPolicy.isTopSlot(0, 27));
|
||||
assertTrue(ShulkerBoxSessionPolicy.isTopSlot(26, 27));
|
||||
assertFalse(ShulkerBoxSessionPolicy.isTopSlot(27, 27));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectsDragsThatTouchTopInventory() {
|
||||
assertTrue(ShulkerBoxSessionPolicy.touchesTopInventory(Set.of(5, 30), 27));
|
||||
assertFalse(ShulkerBoxSessionPolicy.touchesTopInventory(Set.of(27, 35), 27));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.infstar.essentialsC.teleport;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TeleportRequestQueuePolicyTest {
|
||||
|
||||
@Test
|
||||
void keepsNewestRequestsWithinConfiguredLimit() {
|
||||
Deque<String> requests = new ArrayDeque<>();
|
||||
|
||||
TeleportRequestQueuePolicy.addFirstBounded(requests, "first", 2);
|
||||
TeleportRequestQueuePolicy.addFirstBounded(requests, "second", 2);
|
||||
TeleportRequestQueuePolicy.addFirstBounded(requests, "third", 2);
|
||||
|
||||
assertEquals(java.util.List.of("third", "second"), java.util.List.copyOf(requests));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainsRecentlyExpiredRequestsForUserFeedback() {
|
||||
long now = 120_000L;
|
||||
|
||||
assertFalse(TeleportRequestQueuePolicy.shouldPrune(90_000L, now, 60_000L));
|
||||
assertTrue(TeleportRequestQueuePolicy.shouldPrune(60_000L, now, 60_000L));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package cn.infstar.essentialsC.util;
|
||||
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AtomicYamlWriterTest {
|
||||
|
||||
@TempDir
|
||||
Path temporaryDirectory;
|
||||
|
||||
@Test
|
||||
void createsParentDirectoriesAndWritesUtf8Yaml() throws Exception {
|
||||
Path target = temporaryDirectory.resolve("nested/data.yml");
|
||||
YamlConfiguration configuration = new YamlConfiguration();
|
||||
configuration.set("message", "中文内容");
|
||||
|
||||
AtomicYamlWriter.save(configuration, target.toFile());
|
||||
|
||||
assertTrue(Files.exists(target));
|
||||
assertTrue(Files.readString(target, StandardCharsets.UTF_8).contains("中文内容"));
|
||||
try (var files = Files.list(target.getParent())) {
|
||||
assertFalse(files.anyMatch(path -> path.getFileName().toString().endsWith(".tmp")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesExistingYamlWithoutRetainingOldValues() throws Exception {
|
||||
Path target = temporaryDirectory.resolve("state.yml");
|
||||
YamlConfiguration initial = new YamlConfiguration();
|
||||
initial.set("old-value", true);
|
||||
AtomicYamlWriter.save(initial, target.toFile());
|
||||
|
||||
YamlConfiguration replacement = new YamlConfiguration();
|
||||
replacement.set("new-value", 42);
|
||||
AtomicYamlWriter.save(replacement, target.toFile());
|
||||
|
||||
YamlConfiguration loaded = YamlConfiguration.loadConfiguration(target.toFile());
|
||||
assertFalse(loaded.contains("old-value"));
|
||||
assertEquals(42, loaded.getInt("new-value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void supportsShortTargetFileNames() throws Exception {
|
||||
Path target = temporaryDirectory.resolve("x");
|
||||
YamlConfiguration configuration = new YamlConfiguration();
|
||||
configuration.set("written", true);
|
||||
|
||||
AtomicYamlWriter.save(configuration, target.toFile());
|
||||
|
||||
assertTrue(YamlConfiguration.loadConfiguration(target.toFile()).getBoolean("written"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesParsedChineseComments() throws Exception {
|
||||
Path target = temporaryDirectory.resolve("commented.yml");
|
||||
YamlConfiguration configuration = new YamlConfiguration();
|
||||
configuration.options().parseComments(true);
|
||||
configuration.loadFromString("# 中文配置注释\nenabled: false\n");
|
||||
configuration.set("enabled", true);
|
||||
|
||||
AtomicYamlWriter.save(configuration, target.toFile());
|
||||
|
||||
String saved = Files.readString(target, StandardCharsets.UTF_8);
|
||||
assertTrue(saved.contains("# 中文配置注释"));
|
||||
assertTrue(saved.contains("enabled: true"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user