Compare commits

..
2 Commits
Author SHA1 Message Date
ypsdf1 b79754039f chore: 移除非项目文件,添加gitignore规则
- 从仓库追踪中移除txt/、工作簿1.xlsx、unnamed.patch等本地开发文件
- 更新.gitignore排除这些文件类型
2026-05-14 21:08:55 +08:00
ypsdf1 63d0a99cff Remove: 删除误传的radiopack.zip 2026-05-14 21:03:41 +08:00
115 changed files with 9753 additions and 103843 deletions
-123
View File
@@ -1,123 +0,0 @@
name: Auto Release
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Setup JDK 25
run: |
echo "Setting up JDK 25..."
apt-get update -qq
apt-get install -y -qq wget unzip
wget -q https://api.adoptium.net/v3/binary/latest/25/ga/linux/x64/jdk/hotspot/normal/eclipse?project=jdk -O /tmp/jdk25.tar.gz
tar -xzf /tmp/jdk25.tar.gz -C /opt
export JAVA_HOME=$(ls -d /opt/jdk-25* | head -1)
echo "JAVA_HOME=$JAVA_HOME" >> $GITHUB_ENV
echo "$JAVA_HOME/bin" >> $GITHUB_PATH
echo "JDK 25 installed: $($JAVA_HOME/bin/java -version 2>&1 | head -1)"
echo "Setup completed"
- name: Setup Maven
run: |
echo "Setting up Maven..."
apt-get install -y -qq maven
echo "Maven version: $(mvn -version 2>&1 | head -1)"
echo "Setup completed"
- name: Checkout code
run: |
echo "Checking out code..."
GIT_HOST=${GITHUB_SERVER_URL#http://}
GIT_HOST=${GIT_HOST#https://}
rm -rf /workspace/youpaishidifu/Sdf1_login/*
rm -rf /workspace/youpaishidifu/Sdf1_login/.[!.]*
git clone "http://${GIT_HOST}/$(echo ${GITHUB_REPOSITORY} | tr '[:upper:]' '[:lower:]').git" .
echo "Checkout completed"
- name: Build with Maven
run: |
echo "Building with Maven..."
mvn -B clean package -DskipTests
echo "Build completed"
- name: Verify JAR
run: |
echo "Verifying JAR..."
ls -la target/*.jar
echo "Verification completed"
- name: Generate Release Notes
run: |
echo "Generating release notes..."
VERSION=$(grep "^version:" src/main/resources/plugin.yml | awk '{print $2}' | tr -d '\r\n ')
TAG="v$VERSION"
# Generate release notes from last 10 commits
echo "## Changes in $TAG" > /tmp/release_body.md
echo "" >> /tmp/release_body.md
git log --format="- **%h** %s (%an, %ad)" --date=short -10 >> /tmp/release_body.md
echo "" >> /tmp/release_body.md
echo "### Full changelog" >> /tmp/release_body.md
echo "" >> /tmp/release_body.md
echo "[View all commits](/youpaishidifu/Sdf1_login/commits/main)" >> /tmp/release_body.md
echo "Release notes generated for $TAG"
cat /tmp/release_body.md
- name: Create Release
env:
GITEA_TOKEN: 194187cbdc8e1f1d3bc810b1b9e07ddc904a1f73
run: |
set -e
VERSION=$(grep "^version:" src/main/resources/plugin.yml | awk '{print $2}' | tr -d '\r\n ')
TAG="v$VERSION"
BASE="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
echo "Version: $VERSION, Tag: $TAG"
echo "=== Checking existing tag $TAG ==="
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_TOKEN" "$BASE/releases/tags/$TAG")
echo "Check tag HTTP: $HTTP_CODE"
if [ "$HTTP_CODE" = "200" ]; then
OLD_ID=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$BASE/releases/tags/$TAG" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))")
echo "Tag $TAG exists (release #$OLD_ID), deleting..."
curl -s -X DELETE -H "Authorization: token $GITEA_TOKEN" "$BASE/releases/$OLD_ID"
curl -s -X DELETE -H "Authorization: token $GITEA_TOKEN" "$BASE/tags/$TAG"
sleep 1
fi
echo "=== Creating release ==="
# Use python3 to construct proper JSON
python3 -c "
import json, sys
body = open('/tmp/release_body.md').read()
data = {'tag_name': '$TAG', 'name': '$TAG', 'body': body, 'draft': False, 'prerelease': False}
print(json.dumps(data))
" > /tmp/release_payload.json
RESP=$(curl -s -X POST \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
"$BASE/releases" \
-d @/tmp/release_payload.json)
RELEASE_ID=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))")
echo "Created release #$RELEASE_ID"
echo "=== Uploading artifact ==="
JAR=$(ls target/*.jar | head -1)
UPLOAD_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/jar" \
"$BASE/releases/$RELEASE_ID/assets?name=$(basename $JAR)" \
--data-binary "@$JAR")
echo "Upload HTTP: $UPLOAD_CODE"
echo "=== Release $TAG created successfully ==="
-32
View File
@@ -1,32 +0,0 @@
---
name: Bug 反馈
about: 报告一个 Bug 以帮助改进插件
title: "[Bug] "
labels: bug
assignees: ''
---
## Bug 描述
请简明扼要地描述 Bug 是什么。
## 复现步骤
1. 进入 ...
2. 点击 ...
3. 出现错误 ...
## 期望行为
描述你期望发生的事情。
## 实际行为
描述实际发生了什么。
## 服务端信息
- 服务器类型和版本(如 Paper 1.21.4):
- 插件版本:
## 截图 / 日志
如有相关截图或报错日志,请粘贴在此处。
## 其他信息
补充任何你认为有助于解决问题的信息。
-5
View File
@@ -1,5 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: 问题排查指南
url: https://github.com/ypsdf1/sdf1_login
about: 在提交 Bug 前,请先查阅文档确认是否已有相关说明。
@@ -1,20 +0,0 @@
---
name: 功能新增
about: 提出一个新功能的需求建议
title: "[Feature] "
labels: enhancement
assignees: ''
---
## 功能描述
请描述你希望添加的新功能。
## 动机
为什么需要这个功能?它能解决什么问题?
## 建议的实现方式
如果对实现方式有想法,请在此描述。
## 额外信息
补充任何你认为有助于理解需求的上下文。
-17
View File
@@ -1,17 +0,0 @@
---
name: 建议提交
about: 对插件提出改进建议或反馈
title: "[Suggestion] "
labels: suggestion
assignees: ''
---
## 建议内容
请描述你的建议或想法。
## 背景
什么场景下产生的这个建议?
## 预期效果
你认为采用这个建议后能达到什么效果?
-39
View File
@@ -1,39 +0,0 @@
name: Auto Release
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Extract version from plugin.yml
id: version
run: |
echo "version=$(grep '^version: ' src/main/resources/plugin.yml | sed 's/version: //')" >> $GITHUB_OUTPUT
- name: Set up JDK 26
uses: actions/setup-java@v4
with:
java-version: '26'
distribution: 'zulu'
- name: Build with Maven
run: mvn -B clean package -DskipTests
- name: Verify JAR exists
run: ls -la target/Sdf1_login.jar
- name: Create Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ steps.version.outputs.version }}
name: v${{ steps.version.outputs.version }}
files: target/Sdf1_login.jar
generate_release_notes: true
+1 -85
View File
@@ -39,91 +39,7 @@ build/
.DS_Store
# 开发辅助文件(本地保留,不推送到仓库)
/代码关联关系.md
txt/
*.xlsx
*.patch
backup/
新建*.txt
群戏归类.txt
upload_sftp.py
deploy_*.py
deploy_*.ps1
deploy_*.sh
# PHP Web 后端
web/Web.db
web/debug_log_tail.txt
web/upload_debug.ps1
web/api/*.bak*
# 敏感文件 - 禁止提交上传/调试脚本
web/upload_*.php
web/self_update.php
web/version_check.php
web/debug_*.php
web/db/debug_*.php
# 支付密钥 - 严禁提交 (double insurance,配合 Web/.gitignore)
Web/密钥文件_git拉黑.txt
web/密钥文件_git拉黑.txt
Web/pay_secrets.php
web/pay_secrets.php
# Windows 保留设备名(无法用普通 rm 删除)
nul
con
prn
aux
com1
com2
com3
com4
com5
com6
com7
com8
com9
lpt1
lpt2
lpt3
lpt4
lpt5
lpt6
lpt7
lpt8
lpt9hs_err_pid*.log
hs_err_pid*.log
replay_pid*.log
# 屏蔽patch文件
*.patch
# 屏蔽wb产生的工作文件
.workbuddy/
# 屏蔽备份文件
backup/
# 屏蔽根目录下的所有json
/*.json
# 屏蔽垃圾文件
*.idx
*.pack
*.rar
test.*
/*.rev
# 屏蔽全部日志文件
*.log
# 屏蔽开发计划相关文件
*.xlsx
*.docs
*.doc
*.txt
# 屏蔽全部部署脚本(wb用)
*.py
# 屏蔽其它文件
*.md
# 过滤readme和配置文件
!readme.md
!src/main/resources
!src/main/resources/**/*.*
# openai资源文件已启用(第58批 AI聊天功能)
!src/main/resources/openai/
!src/main/resources/openai/*.json
!src/main/resources/openai/*.txt
新建*.txt
+10 -10
View File
@@ -1,10 +1,10 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# 已忽略包含查询文件的默认文件夹
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# 已忽略包含查询文件的默认文件夹
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+6 -6
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
+13 -11
View File
@@ -1,12 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="26" project-jdk-type="JavaSDK" />
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
Generated
+5 -5
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+51 -1075
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 155 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 175 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 207 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 225 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

+11 -11
View File
@@ -11,7 +11,7 @@
<packaging>jar</packaging>
<properties>
<java.version>27</java.version>
<java.version>21</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -27,18 +27,18 @@
</repositories>
<dependencies>
<!-- ★ 与测试服/生产服运行时保持一致(Paper 26.x)。
26.x 的命令分发改走 Brigadier:PlayerCommandPreprocessEvent 已
@Deprecated 且不再是拦截入口,未命中的唯一拦截点是
UnknownCommandEvent;聊天事件是 AsyncChatEvent 而非
AsyncPlayerChatEvent。用 1.21.4 编译会因签名不匹配直接编不过。 -->
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>26.2.build.129-stable</version>
<version>1.21.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
@@ -54,10 +54,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<version>3.11.0</version>
<configuration>
<release>25</release>
<encoding>UTF-8</encoding>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
+197 -197
View File
@@ -1,197 +1,197 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
public class AFKManager {
// 玩家最后活动时间(空闲才开始计时)
private final Map<UUID, Long> lastAction =
new HashMap<>();
// 每个玩家当前的警告阶段
private final Map<UUID, Integer> lastStage =
new HashMap<>();
// 是否已进入挂机检测(false=还在活动,不计时)
private final Map<UUID, Boolean> afkTracking =
new HashMap<>();
private final ConfigManager config;
private final JavaPlugin plugin;
public AFKManager(ConfigManager config,
JavaPlugin plugin) {
this.config = config;
this.plugin = plugin;
}
public void startCheck() {
new BukkitRunnable() {
public void run() {
tick();
}
}.runTaskTimer(plugin, 20L, 20L);
}
private void tick() {
if (!config.afkEnabled) return;
long now = System.currentTimeMillis();
for (Player p : Bukkit.getOnlinePlayers()) {
String name = p.getName();
UUID uuid = p.getUniqueId();
if (!isLoggedIn(name)) continue;
if (config.getAfkWhitelist().contains(name))
continue;
// 确保有记录
if (!lastAction.containsKey(uuid)) {
lastAction.put(uuid, now);
afkTracking.put(uuid, false);
lastStage.put(uuid, 0);
continue;
}
long last = lastAction.get(uuid);
long idle = (now - last) / 1000;
int timeout = config.afkTimeout;
// 还在活动范围内:不进入挂机检测
if (idle < 60) {
afkTracking.put(uuid, false);
lastStage.put(uuid, 0);
continue;
}
// 超过60秒无活动:开始挂机检测
afkTracking.put(uuid, true);
long remain = timeout - idle;
// 已超时:踢出
if (remain <= 0) {
p.kickPlayer("§c§l你已挂机 "
+ fmtSec(idle) + ",被踢出");
lastAction.remove(uuid);
lastStage.remove(uuid);
afkTracking.remove(uuid);
continue;
}
int stage = lastStage.getOrDefault(uuid, 0);
// 阶段3:最后10秒
if (remain <= 10) {
if (stage < 3) {
lastStage.put(uuid, 3);
}
p.sendTitle(
"§e§l挂机了 " + fmtSec(idle),
"§c还剩 " + remain + " 秒踢出",
0, 22, 3);
playSound(p);
continue;
}
// 阶段2:1分钟~10秒
if (remain <= 60) {
if (stage < 2) {
lastStage.put(uuid, 2);
p.sendMessage(
"§e§l⚠ 挂机警告 ⚠ §f你已挂机 §c"
+ fmtSec(idle)
+ "§f,还剩 §c"
+ fmtSec(remain)
+ "§f踢出");
}
p.sendTitle(
"§e§l挂机了 " + fmtSec(idle),
"§c还剩 " + fmtSec(remain) + " 踢出",
5, 25, 5);
playSound(p);
continue;
}
// 阶段1:3分钟提醒
if (remain <= 180 && stage < 1) {
lastStage.put(uuid, 1);
p.sendMessage(
"§e§l⚠ 挂机警告 ⚠ §f你已挂机 §c"
+ fmtSec(idle)
+ "§f,还剩 §c"
+ fmtSec(remain)
+ "§f踢出");
p.sendTitle(
"§e§l挂机了 " + fmtSec(idle),
"§f还剩 " + fmtSec(remain) + " 踢出",
10, 60, 20);
for (int i = 0; i < 3; i++) {
final int delay = i * 10;
Bukkit.getScheduler().runTaskLater(
plugin, () -> {
if (p.isOnline()) playSound(p);
}, delay);
}
}
if (remain > 180) {
lastStage.remove(uuid);
}
}
}
/**
* 玩家有活动时调用(移动/交互/放置/挖掘等)
* 重置计时,退出挂机检测
*/
public void recordAction(UUID uuid) {
lastAction.put(uuid, System.currentTimeMillis());
afkTracking.put(uuid, false);
lastStage.put(uuid, 0);
}
/**
* 玩家下线时调用
* 彻底停止计时,清理所有数据
*/
public void remove(UUID uuid) {
lastAction.remove(uuid);
lastStage.remove(uuid);
afkTracking.remove(uuid);
}
/**
* 获取玩家当前是否在挂机检测中
*/
public boolean isAfkTracking(UUID uuid) {
return afkTracking.getOrDefault(uuid, false);
}
private boolean isLoggedIn(String name) {
return ((Main) plugin).getLoggedIn()
.contains(name);
}
private void playSound(Player p) {
p.playSound(p.getLocation(),
Sound.BLOCK_NOTE_BLOCK_CHIME,
1.0f, 0.79f);
p.playSound(p.getLocation(),
Sound.BLOCK_NOTE_BLOCK_BASS,
1.0f, 0.79f);
p.playSound(p.getLocation(),
Sound.BLOCK_NOTE_BLOCK_PLING,
1.0f, 0.79f);
}
private String fmtSec(long sec) {
if (sec < 60) return sec + "秒";
long m = sec / 60;
long s = sec % 60;
return m + "分" + (s > 0 ? s + "秒" : "");
}
}
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
public class AFKManager {
// 玩家最后活动时间(空闲才开始计时)
private final Map<UUID, Long> lastAction =
new HashMap<>();
// 每个玩家当前的警告阶段
private final Map<UUID, Integer> lastStage =
new HashMap<>();
// 是否已进入挂机检测(false=还在活动,不计时)
private final Map<UUID, Boolean> afkTracking =
new HashMap<>();
private final ConfigManager config;
private final JavaPlugin plugin;
public AFKManager(ConfigManager config,
JavaPlugin plugin) {
this.config = config;
this.plugin = plugin;
}
public void startCheck() {
new BukkitRunnable() {
public void run() {
tick();
}
}.runTaskTimer(plugin, 20L, 20L);
}
private void tick() {
if (!config.afkEnabled) return;
long now = System.currentTimeMillis();
for (Player p : Bukkit.getOnlinePlayers()) {
String name = p.getName();
UUID uuid = p.getUniqueId();
if (!isLoggedIn(name)) continue;
if (config.getAfkWhitelist().contains(name))
continue;
// 确保有记录
if (!lastAction.containsKey(uuid)) {
lastAction.put(uuid, now);
afkTracking.put(uuid, false);
lastStage.put(uuid, 0);
continue;
}
long last = lastAction.get(uuid);
long idle = (now - last) / 1000;
int timeout = config.afkTimeout;
// 还在活动范围内:不进入挂机检测
if (idle < 60) {
afkTracking.put(uuid, false);
lastStage.put(uuid, 0);
continue;
}
// 超过60秒无活动:开始挂机检测
afkTracking.put(uuid, true);
long remain = timeout - idle;
// 已超时:踢出
if (remain <= 0) {
p.kickPlayer("§c§l你已挂机 "
+ fmtSec(idle) + ",被踢出");
lastAction.remove(uuid);
lastStage.remove(uuid);
afkTracking.remove(uuid);
continue;
}
int stage = lastStage.getOrDefault(uuid, 0);
// 阶段3:最后10秒
if (remain <= 10) {
if (stage < 3) {
lastStage.put(uuid, 3);
}
p.sendTitle(
"§e§l挂机了 " + fmtSec(idle),
"§c还剩 " + remain + " 秒踢出",
0, 22, 3);
playSound(p);
continue;
}
// 阶段2:1分钟~10秒
if (remain <= 60) {
if (stage < 2) {
lastStage.put(uuid, 2);
p.sendMessage(
"§e§l⚠ 挂机警告 ⚠ §f你已挂机 §c"
+ fmtSec(idle)
+ "§f,还剩 §c"
+ fmtSec(remain)
+ "§f踢出");
}
p.sendTitle(
"§e§l挂机了 " + fmtSec(idle),
"§c还剩 " + fmtSec(remain) + " 踢出",
5, 25, 5);
playSound(p);
continue;
}
// 阶段1:3分钟提醒
if (remain <= 180 && stage < 1) {
lastStage.put(uuid, 1);
p.sendMessage(
"§e§l⚠ 挂机警告 ⚠ §f你已挂机 §c"
+ fmtSec(idle)
+ "§f,还剩 §c"
+ fmtSec(remain)
+ "§f踢出");
p.sendTitle(
"§e§l挂机了 " + fmtSec(idle),
"§f还剩 " + fmtSec(remain) + " 踢出",
10, 60, 20);
for (int i = 0; i < 3; i++) {
final int delay = i * 10;
Bukkit.getScheduler().runTaskLater(
plugin, () -> {
if (p.isOnline()) playSound(p);
}, delay);
}
}
if (remain > 180) {
lastStage.remove(uuid);
}
}
}
/**
* 玩家有活动时调用(移动/交互/放置/挖掘等)
* 重置计时,退出挂机检测
*/
public void recordAction(UUID uuid) {
lastAction.put(uuid, System.currentTimeMillis());
afkTracking.put(uuid, false);
lastStage.put(uuid, 0);
}
/**
* 玩家下线时调用
* 彻底停止计时,清理所有数据
*/
public void remove(UUID uuid) {
lastAction.remove(uuid);
lastStage.remove(uuid);
afkTracking.remove(uuid);
}
/**
* 获取玩家当前是否在挂机检测中
*/
public boolean isAfkTracking(UUID uuid) {
return afkTracking.getOrDefault(uuid, false);
}
private boolean isLoggedIn(String name) {
return ((Main) plugin).getLoggedIn()
.contains(name);
}
private void playSound(Player p) {
p.playSound(p.getLocation(),
Sound.BLOCK_NOTE_BLOCK_CHIME,
1.0f, 0.79f);
p.playSound(p.getLocation(),
Sound.BLOCK_NOTE_BLOCK_BASS,
1.0f, 0.79f);
p.playSound(p.getLocation(),
Sound.BLOCK_NOTE_BLOCK_PLING,
1.0f, 0.79f);
}
private String fmtSec(long sec) {
if (sec < 60) return sec + "秒";
long m = sec / 60;
long s = sec % 60;
return m + "分" + (s > 0 ? s + "秒" : "");
}
}
File diff suppressed because it is too large Load Diff
@@ -1,159 +1,146 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class AccountRequestManager {
public enum ApprovalMode { AUTO, MANUAL, HYBRID }
public static class Request {
public final int id;
public final String requester;
public final String target;
public final String ip;
public final long time;
public String status;
public String denyReason;
public Request(int id, String requester, String target, String ip) {
this.id = id;
this.requester = requester;
this.target = target;
this.ip = ip;
this.time = System.currentTimeMillis();
this.status = "PENDING";
this.denyReason = "";
}
}
private final Main plugin;
private final Map<Integer, Request> requests = new ConcurrentHashMap<>();
private final Map<String, Integer> pendingByPlayer = new ConcurrentHashMap<>();
private int nextId = 1;
private ApprovalMode mode = ApprovalMode.MANUAL;
private int autoDelayMinutes = 60;
public AccountRequestManager(Main plugin) {
this.plugin = plugin;
}
public ApprovalMode getMode() { return mode; }
public void setMode(String m) {
try { this.mode = ApprovalMode.valueOf(m.toUpperCase()); }
catch (Exception e) { this.mode = ApprovalMode.MANUAL; }
}
public void setAutoDelayMinutes(int min) {
this.autoDelayMinutes = min;
}
public Request createRequest(String requester, String target, String ip) {
int id = nextId++;
Request req = new Request(id, requester, target, ip);
requests.put(id, req);
pendingByPlayer.put(requester, id);
if (mode == ApprovalMode.AUTO) {
scheduleAutoApprove(id);
} else if (mode == ApprovalMode.HYBRID) {
String targetIp = (String) plugin.getDb().getField(target, "ip_address");
if (ip != null && ip.equals(targetIp)) {
scheduleAutoApprove(id);
}
}
return req;
}
private void scheduleAutoApprove(int id) {
long delayTicks = (long) autoDelayMinutes * 60L * 20L;
Request req = requests.get(id);
if (req == null) return;
String requesterName = req.requester;
String targetName = req.target;
plugin.getLogger().info("[Sdf1_login] OA#" + id + " 将在 " + autoDelayMinutes + " 分钟后自动通过");
Bukkit.getScheduler().runTaskLater(plugin, () -> {
Request r = requests.get(id);
if (r != null && "PENDING".equals(r.status)) {
approveRequest(id);
plugin.getLogger().info("[Sdf1_login] OA#" + id + " 自动通过");
Player requester = Bukkit.getPlayer(requesterName);
if (requester != null && requester.isOnline()) {
requester.sendMessage("§a[Sdf1_login] §f您的删除请求 #" + id + "(§e" + targetName + "§a)已自动通过!");
}
}
}, delayTicks);
}
public boolean approveRequest(int id) {
Request req = requests.get(id);
if (req == null || !"PENDING".equals(req.status)) return false;
// ★ 精准匹配:TEST 与 test 是两个人,名字必须完全相等才删
if (plugin.getDb().findExactUserName(req.target) == null) {
String twin = plugin.getDb()
.findSimilarUserNameIgnoreCase(req.target);
System.out.println("[Sdf1_login] 删号申请 #"+ id
+ " 未执行:账号 " + req.target
+ (twin != null ? " 不存在,仅存在大小写不同的账号 " + twin : " 不存在")
+ "(精准匹配,未误删)");
return false;
}
int deleted = plugin.getDb().deleteUser(req.target);
if (deleted <= 0) {
return false;
}
req.status = "APPROVED";
pendingByPlayer.remove(req.requester);
// 清背包+传送出生点+踢出(★ getPlayerExact:避免误伤大小写不同的在线玩家)
Player target = Bukkit.getPlayerExact(req.target);
if (target != null && target.isOnline()) {
target.getInventory().clear();
target.getInventory().setArmorContents(new org.bukkit.inventory.ItemStack[4]);
target.getInventory().setExtraContents(new org.bukkit.inventory.ItemStack[1]);
target.teleport(target.getWorld().getSpawnLocation());
target.kickPlayer("§c§l你的账号已被管理员删除,请重新注册");
}
return true;
}
public boolean denyRequest(int id, String reason) {
Request req = requests.get(id);
if (req == null || !"PENDING".equals(req.status)) return false;
req.status = "DENIED";
req.denyReason = reason;
pendingByPlayer.remove(req.requester);
return true;
}
public List<Request> getPendingRequests() {
List<Request> list = new ArrayList<>();
for (Request r : requests.values()) {
if ("PENDING".equals(r.status)) list.add(r);
}
return list;
}
public Request getRequest(int id) {
return requests.get(id);
}
public boolean hasPending(String player) {
return pendingByPlayer.containsKey(player);
}
public void cancelPending(String player) {
Integer id = pendingByPlayer.remove(player);
if (id != null) {
Request r = requests.get(id);
if (r != null) r.status = "CANCELLED";
}
}
}
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class AccountRequestManager {
public enum ApprovalMode { AUTO, MANUAL, HYBRID }
public static class Request {
public final int id;
public final String requester;
public final String target;
public final String ip;
public final long time;
public String status;
public String denyReason;
public Request(int id, String requester, String target, String ip) {
this.id = id;
this.requester = requester;
this.target = target;
this.ip = ip;
this.time = System.currentTimeMillis();
this.status = "PENDING";
this.denyReason = "";
}
}
private final Main plugin;
private final Map<Integer, Request> requests = new ConcurrentHashMap<>();
private final Map<String, Integer> pendingByPlayer = new ConcurrentHashMap<>();
private int nextId = 1;
private ApprovalMode mode = ApprovalMode.MANUAL;
private int autoDelayMinutes = 60;
public AccountRequestManager(Main plugin) {
this.plugin = plugin;
}
public ApprovalMode getMode() { return mode; }
public void setMode(String m) {
try { this.mode = ApprovalMode.valueOf(m.toUpperCase()); }
catch (Exception e) { this.mode = ApprovalMode.MANUAL; }
}
public void setAutoDelayMinutes(int min) {
this.autoDelayMinutes = min;
}
public Request createRequest(String requester, String target, String ip) {
int id = nextId++;
Request req = new Request(id, requester, target, ip);
requests.put(id, req);
pendingByPlayer.put(requester, id);
if (mode == ApprovalMode.AUTO) {
scheduleAutoApprove(id);
} else if (mode == ApprovalMode.HYBRID) {
String targetIp = (String) plugin.getDb().getField(target, "ip_address");
if (ip != null && ip.equals(targetIp)) {
scheduleAutoApprove(id);
}
}
return req;
}
private void scheduleAutoApprove(int id) {
long delayTicks = (long) autoDelayMinutes * 60L * 20L;
Request req = requests.get(id);
if (req == null) return;
String requesterName = req.requester;
String targetName = req.target;
plugin.getLogger().info("[Sdf1_login] OA#" + id + " 将在 " + autoDelayMinutes + " 分钟后自动通过");
Bukkit.getScheduler().runTaskLater(plugin, () -> {
Request r = requests.get(id);
if (r != null && "PENDING".equals(r.status)) {
approveRequest(id);
plugin.getLogger().info("[Sdf1_login] OA#" + id + " 自动通过");
Player requester = Bukkit.getPlayer(requesterName);
if (requester != null && requester.isOnline()) {
requester.sendMessage("§a[Sdf1_login] §f您的删除请求 #" + id + "(§e" + targetName + "§a)已自动通过!");
}
}
}, delayTicks);
}
public boolean approveRequest(int id) {
Request req = requests.get(id);
if (req == null || !"PENDING".equals(req.status)) return false;
req.status = "APPROVED";
plugin.getDb().deleteUser(req.target);
pendingByPlayer.remove(req.requester);
// 清背包+传送出生点+踢出
Player target = Bukkit.getPlayer(req.target);
if (target != null && target.isOnline()) {
target.getInventory().clear();
target.getInventory().setArmorContents(new org.bukkit.inventory.ItemStack[4]);
target.getInventory().setExtraContents(new org.bukkit.inventory.ItemStack[1]);
target.teleport(target.getWorld().getSpawnLocation());
target.kickPlayer("§c§l你的账号已被管理员删除,请重新注册");
}
return true;
}
public boolean denyRequest(int id, String reason) {
Request req = requests.get(id);
if (req == null || !"PENDING".equals(req.status)) return false;
req.status = "DENIED";
req.denyReason = reason;
pendingByPlayer.remove(req.requester);
return true;
}
public List<Request> getPendingRequests() {
List<Request> list = new ArrayList<>();
for (Request r : requests.values()) {
if ("PENDING".equals(r.status)) list.add(r);
}
return list;
}
public Request getRequest(int id) {
return requests.get(id);
}
public boolean hasPending(String player) {
return pendingByPlayer.containsKey(player);
}
public void cancelPending(String player) {
Integer id = pendingByPlayer.remove(player);
if (id != null) {
Request r = requests.get(id);
if (r != null) r.status = "CANCELLED";
}
}
}
@@ -1,376 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.advancement.Advancement;
import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPotionEffectEvent;
import com.destroystokyo.paper.event.player.PlayerAdvancementCriterionGrantEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* ★ 药水类成就防作弊(2026-10-04 用户要求)
*
* <p><b>需求原文</b>:「插件给的一定要做标记,原版成就判断出来就查,如果有人靠插件药水到手
* 获得,立即撤销。……两条关联成就必须要玩家手打。绝不能靠插件作弊。」</p>
*
* <p><b>为什么是这两条</b>:Java 版只有两条成就是「同时身上带着某一整套效果」即可完成,
* 触发器都是 {@code minecraft:effects_changed}(每次效果增删都触发,不看来源):</p>
* <ul>
* <li>{@code minecraft:nether/all_potions} —— A Furious Cocktail,需 17 种效果同时存在</li>
* <li>{@code minecraft:nether/all_effects} —— How Did We Get Here?,需 34 种效果同时存在</li>
* </ul>
*
* <p><b>为什么要撤销而不是拦 toast</b>:Toast 推送由客户端与服务端共同完成,
* 单靠服务端无法保证「不弹」,但可以在授予的同一 tick 内撤销进度——
* 玩家在成绩界面看到的就是「未完成」,这就满足了需求里的「服务端撤销即可」。</p>
*
* <p><b>判定口径</b>:只要玩家当前身上的效果集合里,<b>有任意一项</b>是本插件给出去的
* (即带插件标记),就撤销这两条成就。<b>不撤销别的成就</b>——只有这两条的判定完全由
* 效果集合构成,其他成就(酿造药水、击杀生物、探险家等)跟插件效果无关,误伤代价大。</p>
*
* <p><b>标记的建立</b>:插件每一次 {@code addPotionEffect} 成功后,都会把效果类型登记进
* {@link #pluginMarked}(见 {@code AreaProtection.markPluginEffects})。这份标记在玩家退出
* 领地、效果自然到期时统一清理,避免「插件给过一次就永久背锅」。</p>
*/
public class AchievementEffectGuard implements Listener {
// ==================== 成就效果清单(服务端 advancement json 原文) ====================
/**
* A Furious Cocktail({@code nether/all_potions})要求的 17 种效果。
* 取自 {@code data/minecraft/advancement/nether/all_potions.json} 的 criteria.effects 键集。
*/
private static final Set<String> ADV_SET_ALL_POTIONS = Set.of(
"fire_resistance", "infested", "invisibility", "jump_boost", "night_vision",
"oozing", "poison", "regeneration", "resistance", "slow_falling", "slowness",
"speed", "strength", "water_breathing", "weakness", "weaving", "wind_charged");
/**
* How Did We Get Here?({@code nether/all_effects})要求的 34 种效果。
* 注意这份清单里<b>混有负面效果</b>(中毒/缓慢/虚弱/凋零/反胃…),
* 所以 2026-10-04 把负面配置拆成独立子菜单之后,防作弊覆盖面反而更完整。
*/
private static final Set<String> ADV_SET_ALL_EFFECTS = Set.of(
"absorption", "bad_omen", "blindness", "breath_of_the_nautilus", "conduit_power",
"darkness", "dolphins_grace", "fire_resistance", "glowing", "haste",
"hero_of_the_village", "hunger", "infested", "invisibility", "jump_boost",
"levitation", "mining_fatigue", "nausea", "night_vision", "oozing", "poison",
"raid_omen", "regeneration", "resistance", "slow_falling", "slowness", "speed",
"strength", "trial_omen", "water_breathing", "weakness", "weaving", "wind_charged",
"wither");
/** 两条成就的 key(延迟解析,插件早期启动时 advancement 尚未加载完) */
private static final String ADV_KEY_ALL_POTIONS = "minecraft:nether/all_potions";
private static final String ADV_KEY_ALL_EFFECTS = "nether/all_effects";
private final Main plugin;
/** 插件给出去的效果标记:玩家 UUID → 本插件施加过的效果类型名(小写英文 ID) */
private final Map<UUID, Set<String>> pluginMarked = new HashMap<>();
/** 已完成撤销的玩家,避免每次事件都重复刷日志 */
private final Set<UUID> revokedLogged = new HashSet<>();
/** 每个玩家的判定冷却:同一玩家 1 秒内最多判一次,防抖 */
private final Map<UUID, Long> lastCheckTs = new HashMap<>();
private static final long CHECK_COOLDOWN_MS = 1000L;
public AchievementEffectGuard(Main plugin) {
this.plugin = plugin;
}
// ==================== 标记接口(供 AreaProtection 调用) ====================
/**
* 登记「这些效果是插件给的」。
*
* @param types 本插件刚刚施加成功的效果类型
*/
public void markPluginEffects(UUID uid, List<PotionEffectType> types) {
if (uid == null || types == null || types.isEmpty()) return;
Set<String> set = pluginMarked.computeIfAbsent(uid, k -> new HashSet<>());
for (PotionEffectType t : types) {
if (t == null) continue;
set.add(normalizeEffectId(t));
}
}
/**
* 清掉某玩家的插件效果标记(离开领地 / 插件不再持有该效果时调用)。
*
* @param keepStillApplied 仍由插件持有的效果,保留标记;其余标记删除
*/
public void clearPluginEffects(UUID uid, Set<PotionEffectType> keepStillApplied) {
if (uid == null) return;
Set<String> keep = new HashSet<>();
if (keepStillApplied != null) {
for (PotionEffectType t : keepStillApplied) {
if (t != null) keep.add(normalizeEffectId(t));
}
}
Set<String> cur = pluginMarked.get(uid);
if (cur == null) return;
cur.retainAll(keep);
if (cur.isEmpty()) pluginMarked.remove(uid);
}
/** 玩家退出时彻底清账 */
public void forgetPlayer(UUID uid) {
if (uid == null) return;
pluginMarked.remove(uid);
revokedLogged.remove(uid);
lastCheckTs.remove(uid);
}
/** 该玩家当前是否还带着插件给的效果(诊断用) */
public boolean hasPluginMarkedEffects(Player p) {
if (p == null) return false;
Set<String> marked = pluginMarked.get(p.getUniqueId());
if (marked == null || marked.isEmpty()) return false;
for (PotionEffect eff : p.getActivePotionEffects()) {
if (marked.contains(normalizeEffectId(eff.getType()))) return true;
}
return false;
}
// ==================== 事件监听 ====================
/**
* 每次效果变化都复核一遍。
*
* <p>用 LOWEST 优先级 + {@code ignoreCancelled = false}:即便别的插件把事件取消了
* (等于说效果最终会被加上),我们也已经先记录并撤销了。</p>
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
public void onPotionEffectChange(EntityPotionEffectEvent event) {
if (!(event.getEntity() instanceof Player)) return;
Player p = (Player) event.getEntity();
// 插件自己施加的:立刻打标记(与 AreaProtection 的登记互为兜底)
if (event.getCause() == EntityPotionEffectEvent.Cause.PLUGIN
&& event.getAction() != EntityPotionEffectEvent.Action.CLEARED
&& event.getAction() != EntityPotionEffectEvent.Action.REMOVED) {
PotionEffectType type = event.getModifiedType();
if (type != null) {
markPluginEffects(p.getUniqueId(), Collections.singletonList(type));
}
}
// 效果被移除/清除时,同步把标记里已经不生效的项剔掉
if (event.getAction() == EntityPotionEffectEvent.Action.CLEARED) {
pluginMarked.remove(p.getUniqueId());
} else if (event.getAction() == EntityPotionEffectEvent.Action.REMOVED) {
Set<String> marked = pluginMarked.get(p.getUniqueId());
if (marked != null && event.getModifiedType() != null) {
marked.remove(normalizeEffectId(event.getModifiedType()));
if (marked.isEmpty()) pluginMarked.remove(p.getUniqueId());
}
}
scheduleCheck(p);
}
/**
* 成就授予的那一刻直接撤销(兜底,覆盖 effects_changed 之外的授予路径)。
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onAdvancementCriterionGrant(PlayerAdvancementCriterionGrantEvent event) {
Advancement adv = event.getAdvancement();
if (adv == null || adv.getKey() == null) return;
String key = adv.getKey().toString(); // 形如 nether/all_potions
if (!isGuardedAdvancement(key)) return;
// 只有当玩家身上确实带着插件给的效果时才撤,避免误伤纯手打玩家
if (!hasPluginMarkedEffects(event.getPlayer())) return;
event.setCancelled(true);
revokeAll(event.getPlayer(), key, "成就授予时检测到插件来源效果");
}
/** 玩家进服立刻复核一次(防止插件重启期间拿到成就、或上次下线前漏撤) */
@EventHandler
public void onJoin(PlayerJoinEvent event) {
// 延后一 tick:刚进服时 effect / advancement 数据可能还没完全同步
Bukkit.getScheduler().runTaskLater(plugin, () -> {
Player p = event.getPlayer();
if (p != null && p.isOnline()) {
checkAndRevoke(p, false);
}
}, 20L);
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
forgetPlayer(event.getPlayer().getUniqueId());
}
// ==================== 核心判定 ====================
/**
* 排一个下一 tick 的复核任务(同一 tick 内插件可能批量加多个效果,
* 每次都全量扫描 34 项是浪费)。
*/
private void scheduleCheck(Player p) {
Bukkit.getScheduler().runTask(plugin, () -> {
if (p != null && p.isOnline()) {
checkAndRevoke(p, true);
}
});
}
/**
* 判定并撤销。
*
* @param useCooldown 是否走 1 秒冷却(进服复核不走冷却)
*/
private void checkAndRevoke(Player p, boolean useCooldown) {
UUID uid = p.getUniqueId();
long now = System.currentTimeMillis();
if (useCooldown) {
Long last = lastCheckTs.get(uid);
if (last != null && now - last < CHECK_COOLDOWN_MS) return;
lastCheckTs.put(uid, now);
}
Set<String> marked = pluginMarked.get(uid);
if (marked == null || marked.isEmpty()) return; // 没被插件碰过 → 绝不碰成就
// 玩家当前实际生效的效果集合
Set<String> active = new HashSet<>();
for (PotionEffect eff : p.getActivePotionEffects()) {
active.add(normalizeEffectId(eff.getType()));
}
// 已被自然到期/喝牛奶清掉的标记不参与判定
Set<String> live = new HashSet<>();
for (String m : marked) {
if (active.contains(m)) live.add(m);
}
if (live.isEmpty()) {
pluginMarked.remove(uid);
return;
}
// ★ 关键判定:两条成就要求的清单里,只要有任意一项在 live 里 → 撤销
List<String> hitAllPotions = new ArrayList<>();
for (String need : ADV_SET_ALL_POTIONS) {
if (live.contains(need)) hitAllPotions.add(need);
}
List<String> hitAllEffects = new ArrayList<>();
for (String need : ADV_SET_ALL_EFFECTS) {
if (live.contains(need)) hitAllEffects.add(need);
}
if (!hitAllPotions.isEmpty()) {
revokeAll(p, ADV_KEY_ALL_POTIONS, "插件来源效果 " + summarize(hitAllPotions));
}
if (!hitAllEffects.isEmpty()) {
revokeAll(p, ADV_KEY_ALL_EFFECTS, "插件来源效果 " + summarize(hitAllEffects));
}
}
/**
* 撤销一条受管控成就的全部条件。
*
* <p>用 {@code revokeCriteria} 逐条撤,而不是只撤当前触发的那个 criterion——
* 两条成就都只有 {@code all_effects} 一个 criterion,撤它即可让整条回到未完成。</p>
*/
private void revokeAll(Player p, String advKey, String reason) {
Advancement adv = resolveAdvancement(advKey);
if (adv == null) return;
AdvancementProgress progress = p.getAdvancementProgress(adv);
if (progress == null || !progress.isDone()) return; // 本来就没完成,不动
Set<String> remaining = new HashSet<>(progress.getRemainingCriteria());
int revoked = 0;
for (String crit : progress.getAwardedCriteria()) {
if (progress.revokeCriteria(crit)) revoked++;
}
// 少数情况 revokeCriteria 返回 false(条件本来就不成立),补一次兜底
if (revoked == 0 && !remaining.isEmpty()) {
for (String crit : progress.getRemainingCriteria()) {
remaining.remove(crit);
}
}
if (revokedLogged.add(p.getUniqueId())) {
plugin.getLogger().warning("[成就防作弊] 已撤销 " + advKey
+ " 玩家=" + p.getName()
+ " 原因=" + reason
+ " 撤销条件数=" + revoked
+ "(插件提供方便,不提供作弊;这两条成就必须手打)");
}
}
/**
* 解析 advancement:优先用 NamespacedKey({@code Bukkit.getAdvancement}),
* 失败则回退成 Bukkit 可识别的短 key。
*/
private Advancement resolveAdvancement(String key) {
String plain = key.startsWith("minecraft:") ? key.substring("minecraft:".length()) : key;
Advancement adv = null;
try {
adv = Bukkit.getAdvancement(NamespacedKey.minecraft(plain));
} catch (Throwable ignored) { }
if (adv == null) {
try {
adv = Bukkit.getAdvancement(new NamespacedKey("minecraft", plain));
} catch (Throwable ignored) { }
}
return adv;
}
/** 是否是本插件要管的成就(只管这两条 potion 类成就) */
private boolean isGuardedAdvancement(String key) {
if (key == null) return false;
String plain = key.startsWith("minecraft:") ? key.substring("minecraft:".length()) : key;
return plain.equals(ADV_KEY_ALL_POTIONS) || plain.equals(ADV_KEY_ALL_EFFECTS);
}
// ==================== 工具 ====================
/**
* 效果类型统一成小写英文 ID(如 {@code SLOWNESS} → {@code slowness})。
*
* <p>不同 Paper 版本的 {@code PotionEffectType#getKey()} 可能带命名空间,
* 这里只取 {@code :} 后半段,和 advancement json 的写法对齐。</p>
*/
private static String normalizeEffectId(PotionEffectType type) {
if (type == null) return "";
String key;
try {
key = type.getKey().toString(); // 形如 minecraft:speed
} catch (Throwable t) {
key = type.getName(); // 老版本退路
}
if (key == null) return "";
int idx = key.indexOf(':');
if (idx >= 0) key = key.substring(idx + 1);
return key.toLowerCase(java.util.Locale.ROOT);
}
/** 命中清单的可读化截断,避免日志刷屏 */
private static String summarize(List<String> hit) {
if (hit.size() <= 6) return String.join(",", hit);
return String.join(",", hit.subList(0, 6)) + " …共" + hit.size() + "项";
}
}
@@ -1,698 +0,0 @@
package Sdf1_login;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import io.papermc.paper.scoreboard.numbers.NumberFormat;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.scoreboard.Criteria;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import org.bukkit.scheduler.BukkitTask;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ★ 第35批:公告计分板(侧边栏)。
*
* <p><b>数据源</b>:{@code plugins/Sdf1_login/公告/公告.md}
* 头部 {@code ## ----公告区域开始----} ~ {@code ## ----公告区域结束----}
* 之间的 ```json 代码块。块的键是<b>排序位</b>,值是公告条目。
*
* <p><b>规则</b>:
* <ul>
* <li>键 = 排序位(升序,越小越靠上);键冲突 → <b>自动进位</b>
* (往后找第一个空位)。用 JsonReader 流式解析,
* 重复键不会被 Gson 的 Map 覆盖掉</li>
* <li>msg 为空 → 整条跳过(空白键值自动跳过)</li>
* <li>msg 超过 15 个字符 → 截断换行(每行最多 15 字,超出的另起一行)</li>
* <li>msg 是 http/https 链接 → 整条公告可点击(打开链接,悬停显示完整地址)</li>
* <li>color 支持 16 色英文名 / #RRGGBB / r=0 g=0 b=0;
* 未填或非法 → 回退 MC 原版白色</li>
* </ul>
*
* <p><b>渲染口径(paper-api 26.2 + 服务端 jar 字节码实测)</b>:
* <ul>
* <li>原版侧边栏<b>不解析 entry 里的 § 颜色码</b>(entry 只是纯文本标识),
* 所以颜色必须走 {@code Score.customName(Component)} 下发;
* entry 改用纯 ASCII 唯一串 {@code n0/n1/...},天然规避同名塌缩。</li>
* <li>侧边栏默认 <b>descending(高分在上)</b> → 分数<b>递减</b>赋值,
* 排序位小的排最上面。</li>
* <li>侧边栏<b>最多只显示 15 行</b> → 超出部分丢弃并告警。</li>
* <li>数字格式设 {@code NumberFormat.blank()} → 右侧不露分数。</li>
* </ul>
*
* <p><b>与 PVP 计分板共存</b>:PVP 区域 / 竞技场内由 PVP 模块接管计分板,
* 本类只在玩家空闲(不在 PVP 区域、不在竞技场)时把公告板挂上去。
*/
public class AnnouncementBoard implements Listener {
private final Main plugin;
/** 公告配置文件:plugins/Sdf1_login/公告/公告.md */
private File mdFile;
/** 上次解析时的文件修改时间(用于热重载检测) */
private long lastModified = 0L;
/** 公告区域标记 */
private static final String ZONE_START = "## ----公告区域开始----";
private static final String ZONE_END = "## ----公告区域结束----";
/** 计分板目标名(objective 名) */
private static final String OBJECTIVE = "sdf1_notice";
/** 单行最大字符数(超出截断换行) */
static final int MAX_LINE_CHARS = 15;
/** 原版侧边栏最多显示的行数(硬限制) */
static final int MAX_SIDEBAR_ROWS = 15;
/** 公告板标题 */
private static final String TITLE = "§6§l服务器公告";
/** 16 色英文名(与 JsonMessageGui 口径一致) */
private static final Set<String> NATIVE_COLORS = new LinkedHashSet<>(Arrays.asList(
"black", "dark_blue", "dark_green", "dark_aqua",
"dark_red", "dark_purple", "gold", "gray",
"dark_gray", "blue", "green", "aqua",
"red", "light_purple", "yellow", "white"));
/** 链接识别(整条 msg 是链接才算) */
private static final Pattern URL_PATTERN =
Pattern.compile("^(https?://\\S+)$", Pattern.CASE_INSENSITIVE);
/** ★ 第36批:公告板总开关(公告.md 顶层键 开关状态:true/1=开,false/0=关) */
private boolean enabled = true;
/** ★ 第36批:翻页秒数(公告.md 顶层键 翻页时间:纯数字=秒) */
private int pageSeconds = 15;
/** ★ 第36批:当前页码(0 起,全局统一页切) */
private int currentPage = 0;
/** ★ 第36批:翻页定时任务 */
private BukkitTask pagerTask = null;
/** ★ 第36批:翻页任务当前周期(秒),与配置不一致才重建 */
private int pagerSeconds = -1;
/** 解析出的公告条目(排序位 → 条目),按排序位升序 */
private final Map<Integer, Notice> notices = new LinkedHashMap<>();
/** 单条公告 */
public static final class Notice {
/** 排序位 */
public final int slot;
/** 原始文本 */
public final String msg;
/** 归一化后的颜色(合法色 / null=白色) */
public final TextColor color;
/** 链接地址(非链接时 null) */
public final String url;
Notice(int slot, String msg, TextColor color, String url) {
this.slot = slot;
this.msg = msg;
this.color = color;
this.url = url;
}
}
/** ★ 第36批:渲染用的一行(公告 + 该行文本),用于按页切片 */
private static final class Row {
final Notice n;
final String line;
Row(Notice n, String line) {
this.n = n;
this.line = line;
}
}
public AnnouncementBoard(Main plugin) {
this.plugin = plugin;
}
// ==================== 生命周期 ====================
/** 初始化:释放模板 → 解析 → 首次渲染 → 启动热重载监听 */
public void init() {
try {
File dir = new File(plugin.getDataFolder(), "公告");
if (!dir.exists()) dir.mkdirs();
mdFile = new File(dir, "公告.md");
if (!mdFile.exists()) {
try (InputStream in = plugin.getResource("公告/公告.md")) {
if (in != null) {
Files.copy(in, mdFile.toPath());
}
} catch (Exception e) {
plugin.getLogger().warning("[公告板] 模板释放失败: " + e.getMessage());
}
}
} catch (Exception e) {
plugin.getLogger().warning("[公告板] 初始化失败: " + e.getMessage());
return;
}
reload();
applyAll();
startAutoReload();
}
/** 启动文件热重载:每 30 秒比对一次修改时间 */
private void startAutoReload() {
Bukkit.getScheduler().runTaskTimer(plugin, () -> {
if (mdFile == null || !mdFile.exists()) return;
long mt = mdFile.lastModified();
if (mt == lastModified) return;
lastModified = mt;
reloadAndApply();
plugin.getLogger().info("[公告板] 检测到公告文件变更,已自动重载");
}, 600L, 600L);
}
/** 重新解析公告.md */
public void reload() {
// ★ 第36批:配置默认值每次重载重置(md 里没写对应键就回默认)
enabled = true;
pageSeconds = 15;
currentPage = 0;
List<Notice> list = parse();
notices.clear();
for (int i = 0; i < list.size(); i++) {
Notice n = list.get(i);
notices.put(n.slot, n);
}
if (mdFile != null && mdFile.exists()) {
lastModified = mdFile.lastModified();
}
int rows = totalRows();
int pages = (rows + MAX_SIDEBAR_ROWS - 1) / MAX_SIDEBAR_ROWS;
plugin.getLogger().info("[公告板] 已加载 " + notices.size()
+ " 条公告,开关=" + (enabled ? "开" : "关")
+ ",翻页=" + pageSeconds + "秒,共 " + rows
+ " 行 / " + pages + " 页");
// ★ 第36批:按当前翻页秒数启动/重建翻页任务
restartPager();
}
/** 重载并立即刷新所有玩家 */
public void reloadAndApply() {
reload();
applyAll();
}
public File getMdFile() {
return mdFile;
}
public int getNoticeCount() {
return notices.size();
}
// ==================== 解析 ====================
/**
* 解析公告.md 里的 JSON 块。
*
* <p>用 {@link JsonReader} 流式解析而非 {@code JsonObject}:
* 后者会把重复键覆盖掉,「键冲突自动进位」就无从谈起。
*
* @return 按排序位升序的公告列表
*/
private List<Notice> parse() {
List<Notice> out = new ArrayList<>();
if (mdFile == null || !mdFile.exists()) return out;
String text;
try {
text = new String(Files.readAllBytes(mdFile.toPath()), StandardCharsets.UTF_8);
} catch (Exception e) {
plugin.getLogger().warning("[公告板] 读取失败: " + e.getMessage());
return out;
}
// ★ 变量名避开 e/ex(否则遮蔽 catch 块里的 Exception e)
int zStart = text.indexOf(ZONE_START);
int zEnd = text.indexOf(ZONE_END);
if (zStart < 0 || zEnd < 0 || zEnd <= zStart) {
plugin.getLogger().warning("[公告板] 未找到公告区域标记("
+ ZONE_START + " ~ " + ZONE_END + "),公告板为空");
return out;
}
String zone = text.substring(zStart + ZONE_START.length(), zEnd);
String json = extractJsonBlock(zone);
// ★ 第38批:剥掉尾逗号(实测 Gson 连 lenient 都不认尾逗号,用户手抖多打
// 一个逗号就会让整块 json 解析失败、公告板一条都加载不出来)
if (json != null) json = ConfigManager.stripTrailingCommas(json);
if (json == null || json.trim().isEmpty()) {
plugin.getLogger().warning("[公告板] 公告区域内没有 json 代码块");
return out;
}
// ---- 流式解析:保留重复键 ----
List<Notice> raw = new ArrayList<>();
int autoSlot = 1000000; // 非数字键的兜底排序位(排在数字键之后)
JsonReader reader = null;
try {
reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
reader.beginObject();
while (reader.hasNext()) {
String key = reader.nextName();
// ★ 第36批:顶层配置键(开关状态/翻页时间)值是标量,
// 必须先识别 —— 否则对 true / 15 调 beginObject() 会抛
// IllegalStateException,整份解析失败、公告板全空。
if (isConfigKey(key)) {
readConfig(key, reader);
continue;
}
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
// 非对象值(标量/数组/NULL)→ 不是公告条目,跳过
reader.skipValue();
continue;
}
String msg = null;
String colorRaw = null;
reader.beginObject();
while (reader.hasNext()) {
String vk = reader.nextName();
// ★ 第36批:键名兼容中文(默认 msg/color,兼容 消息/颜色)
if ("msg".equals(vk) || "消息".equals(vk)) {
if (reader.peek() == JsonToken.NULL) reader.skipValue();
else msg = reader.nextString();
} else if ("color".equals(vk) || "颜色".equals(vk)) {
if (reader.peek() == JsonToken.NULL) reader.skipValue();
else colorRaw = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
if (msg == null) continue;
msg = msg.trim();
if (msg.isEmpty()) continue; // 空白键值自动跳过
if (colorRaw == null) colorRaw = "";
else colorRaw = colorRaw.trim();
int slot;
try {
slot = Integer.parseInt(key.trim());
} catch (Exception ex) {
slot = autoSlot++;
}
TextColor color = parseColor(colorRaw);
String url = null;
Matcher m = URL_PATTERN.matcher(msg);
if (m.matches()) url = m.group(1);
raw.add(new Notice(slot, msg, color, url));
}
reader.endObject();
} catch (Exception ex) {
plugin.getLogger().warning("[公告板] json 解析失败: " + ex.getMessage());
return out;
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception ignored) {
}
}
}
// ---- 排序(手动选择排序,不用 Comparator/lambda)----
sortBySlot(raw);
// ---- 排序位冲突 → 自动进位(往后找第一个空位)----
Set<Integer> used = new LinkedHashSet<>();
// ★ 第36批:color 继承(用户明令)—— 未填/非法 → 继承最近一条
// 合法 color;一条都没找到 → null(渲染回退 MC 原版白色)
TextColor inherit = null;
for (int i = 0; i < raw.size(); i++) {
Notice n = raw.get(i);
int s2 = n.slot;
if (s2 < 0) s2 = 0;
while (used.contains(s2)) s2++;
used.add(s2);
TextColor c = n.color;
if (c == null) c = inherit;
else inherit = c;
out.add(new Notice(s2, n.msg, c, n.url));
}
return out;
}
// ==================== 第36批:配置 / 翻页 ====================
/** ★ 第36批:顶层配置键识别(公告板开关 / 翻页秒数,中文键) */
private static boolean isConfigKey(String key) {
if (key == null) return false;
String k = key.trim();
return "开关状态".equals(k) || "开关".equals(k)
|| "翻页时间".equals(k) || "翻页".equals(k);
}
/**
* ★ 第36批:读标量配置值。
* JSON 的 true/false(BOOLEAN)、15(NUMBER)、"15"(STRING)
* 统一转成 String,交给 parseOnOff / parseInt 处理。
*/
private static String readScalar(JsonReader r) throws java.io.IOException {
JsonToken t = r.peek();
if (t == JsonToken.NULL) {
r.nextNull();
return null;
}
if (t == JsonToken.BOOLEAN) return String.valueOf(r.nextBoolean());
if (t == JsonToken.NUMBER || t == JsonToken.STRING) {
return r.nextString();
}
r.skipValue();
return null;
}
/** ★ 第36批:读取并应用一条顶层配置 */
private void readConfig(String key, JsonReader reader) {
String k = key.trim();
String v;
try {
v = readScalar(reader);
} catch (Exception ex) {
try { reader.skipValue(); } catch (Exception ignored) { }
return;
}
if ("开关状态".equals(k) || "开关".equals(k)) {
enabled = parseOnOff(v);
} else {
// 翻页时间:纯数字=秒(非法/<=0 → 保留默认15)
int sec = -1;
if (v != null) {
try { sec = Integer.parseInt(v.trim()); }
catch (Exception ignored) { }
}
if (sec > 0) pageSeconds = sec;
}
}
/**
* ★ 第36批:开关值解析(用户明令)——
* true / 1 → 开;false / 0 → 关;未识别 → 开(配置写错不至于把板关死)。
*/
static boolean parseOnOff(String v) {
if (v == null) return true;
String t = v.trim().toLowerCase(Locale.ROOT);
if (t.equals("0") || t.equals("false") || t.equals("off")
|| t.equals("no") || t.equals("关") || t.equals("否")) {
return false;
}
return true;
}
/** ★ 第36批:当前公告拆行后的总行数 */
private int totalRows() {
int rows = 0;
for (Notice n : notices.values()) {
rows += splitLine(n.msg).size();
}
return rows;
}
/**
* ★ 第36批:翻页任务 —— 总行数超过侧边栏 15 行时,
* 每「翻页时间」秒切下一页并刷新全员;只有一页时不动作。
*/
private void restartPager() {
int sec = Math.max(1, pageSeconds);
if (pagerTask != null && sec == pagerSeconds) return;
if (pagerTask != null) {
try { pagerTask.cancel(); } catch (Throwable ignored) { }
pagerTask = null;
}
pagerSeconds = sec;
pagerTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
if (!enabled || notices.isEmpty()) return;
int rows = totalRows();
int pages = (rows + MAX_SIDEBAR_ROWS - 1) / MAX_SIDEBAR_ROWS;
if (pages <= 1) return; // 只有一页 → 无需翻页
currentPage = (currentPage + 1) % pages;
applyAll();
}, 20L * sec, 20L * sec);
}
/** 按排序位升序(稳定,手动冒泡,规避 JDK26 javac lambda 类型推断崩溃) */
private static void sortBySlot(List<Notice> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(j).slot < list.get(i).slot) {
Notice tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
}
}
}
/** 从文本中提取 ```json ... ``` 代码块内容 */
private static String extractJsonBlock(String zone) {
int fence = zone.indexOf("```");
if (fence < 0) return null;
int bodyStart = zone.indexOf('\n', fence);
if (bodyStart < 0) return null;
int fence2 = zone.indexOf("```", bodyStart);
if (fence2 < 0) return null;
return zone.substring(bodyStart + 1, fence2);
}
/**
* 颜色解析:16 色英文名 / #RRGGBB / r=0 g=0 b=0。
*
* @return 合法色;空或非法返回 null(调用方回退白色)
*/
static TextColor parseColor(String s) {
if (s == null) return null;
String t = s.trim().toLowerCase(Locale.ROOT);
if (t.isEmpty()) return null;
// 16 色英文名(NamedTextColor.NAMES 的键就是小写下划线名)
if (NATIVE_COLORS.contains(t)) {
NamedTextColor c = NamedTextColor.NAMES.value(t);
return c != null ? c : NamedTextColor.WHITE;
}
// #RRGGBB
if (t.matches("#?[0-9a-f]{6}")) {
try {
return TextColor.fromHexString(t.startsWith("#") ? t : "#" + t);
} catch (Exception ignored) {
return null;
}
}
// r=0 g=0 b=0
Matcher m = Pattern.compile(
"(?i)(\\d{1,3})[^0-9]*(\\d{1,3})[^0-9]*(\\d{1,3})")
.matcher(t);
if (m.find()) {
try {
int r = Integer.parseInt(m.group(1));
int g = Integer.parseInt(m.group(2));
int b = Integer.parseInt(m.group(3));
if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {
return TextColor.color(r, g, b);
}
} catch (Exception ignored) {
return null;
}
}
return null;
}
// ==================== 渲染 ====================
/**
* 把公告板刷给单个玩家(PVP 侧边栏管辖范围内自动避让)。
*
* @param p 玩家
*/
public void applyTo(Player p) {
applyTo(p, false);
}
/**
* 把公告板刷给单个玩家。
*
* @param p 玩家
* @param force true=无视 PVP 区域/竞技场避让(PVP 模块交还侧边栏时用)
*/
public void applyTo(Player p, boolean force) {
if (p == null || !p.isOnline()) return;
if (!force && isInPVPSide(p)) return;
try {
ScoreboardManager mgr = Bukkit.getScoreboardManager();
if (mgr == null) return;
// ★ 第36批:开关关闭(开关状态=false/0)→ 归还原版主计分板
if (!enabled) {
p.setScoreboard(mgr.getMainScoreboard());
return;
}
// ★ 第36批:先把公告拆成「行」,再按当前页切片 ——
// 原版侧边栏最多 15 行,超过 15 行自动翻页(翻页时间 秒/页)
List<Row> rows = new ArrayList<>();
for (Notice n : notices.values()) {
List<String> lines = splitLine(n.msg);
for (int li = 0; li < lines.size(); li++) {
rows.add(new Row(n, lines.get(li)));
}
}
if (rows.isEmpty()) {
// 没有可显示的公告 → 归还原版主计分板
p.setScoreboard(mgr.getMainScoreboard());
return;
}
int pages = (rows.size() + MAX_SIDEBAR_ROWS - 1)
/ MAX_SIDEBAR_ROWS;
int page = currentPage;
if (page < 0) page = 0;
if (page >= pages) page = pages - 1;
int from = page * MAX_SIDEBAR_ROWS;
int to = Math.min(from + MAX_SIDEBAR_ROWS, rows.size());
Scoreboard sb = mgr.getNewScoreboard();
Objective obj = sb.registerNewObjective(
OBJECTIVE, Criteria.DUMMY, legacy(TITLE));
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
// 右侧不显示分数数字(公告板只展示内容)
try {
obj.numberFormat(NumberFormat.blank());
} catch (Throwable ignored) {
}
int row = 0; // 本页已渲染行数
for (int i = from; i < to; i++) {
Row r = rows.get(i);
// entry 用纯 ASCII 唯一串(避免同名条目塌缩)
String entry = "n" + row;
Score sc = obj.getScore(entry);
// 侧边栏默认 descending(高分在上)→ 分数递减,本页首行排最上
sc.setScore(MAX_SIDEBAR_ROWS - row);
try {
sc.customName(buildComponent(r.n, r.line));
} catch (Throwable ignored) {
}
row++;
}
p.setScoreboard(sb);
} catch (Exception e) {
plugin.getLogger().warning("[公告板] 渲染失败: " + e.getMessage());
}
}
/**
* 构建条目显示组件。
*
* <p>原版侧边栏<b>不解析 entry 里的 § 码</b>,所以颜色/点击事件
* 全部通过 {@code customName} 下发。msg 内部允许写 § 颜色码
* (legacy 解析),其优先级高于 color 参数 —— 与原版文本语义一致。
*/
private static Component buildComponent(Notice n, String line) {
Component comp = legacy(line);
if (n.color != null) {
comp = comp.color(n.color);
}
if (n.url != null) {
comp = comp.clickEvent(ClickEvent.openUrl(n.url))
.hoverEvent(HoverEvent.showText(
Component.text(n.url)));
}
return comp;
}
/** legacy § 文本 → Component(解析失败退化为纯文本) */
private static Component legacy(String s) {
if (s == null || s.isEmpty()) return Component.empty();
try {
return LegacyComponentSerializer.legacySection().deserialize(s);
} catch (Throwable t) {
return Component.text(s);
}
}
/** 刷新所有在线玩家 */
public void applyAll() {
for (Player p : Bukkit.getOnlinePlayers()) {
applyTo(p);
}
}
/**
* 玩家是否在 PVP 侧边栏管辖范围内(PVP 区域 / PVP 竞技场)。
* 公告板据此避让 —— PVP 模块的侧边栏优先。
*/
private boolean isInPVPSide(Player p) {
if (p == null) return false;
try {
if (plugin.getPVPManager() != null
&& plugin.getPVPManager().isInPVPRegion(p.getName())) {
return true;
}
} catch (Throwable ignored) {
}
try {
if (plugin.getPVPArenaManager() != null
&& plugin.getPVPArenaManager().isInPVPArena(p.getName())) {
return true;
}
} catch (Throwable ignored) {
}
return false;
}
// ==================== 事件 ====================
/**
* 切换世界后重刷公告板(部分世界/插件会重置玩家的计分板)。
*/
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent e) {
final Player p = e.getPlayer();
Bukkit.getScheduler().runTask(plugin, () -> applyTo(p));
}
/**
* 超过 15 个字符 → 截断换行(每行最多 15 字,超出的另起一行)。
*
* @return 该条公告占的行
*/
static List<String> splitLine(String msg) {
List<String> out = new ArrayList<>();
if (msg == null || msg.isEmpty()) return out;
int idx = 0;
while (idx < msg.length()) {
int end = Math.min(idx + MAX_LINE_CHARS, msg.length());
out.add(msg.substring(idx, end));
idx = end;
}
return out;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,949 +0,0 @@
package Sdf1_login;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ★ 第十六批:游戏内轮询封禁播报(耻辱台)
*
* 配置文件(plugins/Sdf1_login/ban/ 目录):
* - *.json 直接作为配置文件;
* - 规则配置.md 优先解 ```json 代码块,解不出再解 markdown 表格;
* - 解码全失败 → 备份原文件 + 释放一份新的。
* 配置丢失 → 自动补发(saveResource 自愈);
* 已存在的 md → 安全升级自动补齐模板新增行(safeUpgradeDoc,第二十一批)。
*
* ★ 第二十七批:数据源改为原版 banned-players.json(用户明令「这是 MC 唯一的封禁数据来源」)。
* 线上事故:旧实现读 Bukkit.getBanList(NAME) 的内存名单,而内存名单在重启/被
Web 后台批量改写后与磁盘 banned-players.json 严重不一致(文件里 [] 空,内存里
却有几十条)→ 玩家看到「一个都没封却公示一堆人」。
* 现改为:每轮播报都重新读 <worldContainer>/banned-players.json 到内存,
* 解析每条的 created,过滤掉插件数据目录创建时间之前的全部历史封禁;
* 文件缺失 / 语法坏 / 过滤后为空 → 一律闭嘴不播,绝不拿兜底假数据说话。
*
* 键值:轮播最低间隔(秒) / 轮播最大间隔(秒) / 播报模式 / 播报起点(插件安装之前的封禁不播)
* 播报模式:true=由近到远、false=由远到近、0=关闭;
* 表格值:由近到远 / 由远到近 / 0。
* 间隔或模式为 0 → 关闭播报。
*/
public class BanBroadcastManager implements Listener {
private final Main plugin;
private final Random rnd = new Random();
private File banDir;
private File mdFile;
private File jsonFile; // *.json 配置(存在则优先)
private int minInterval = 60;
private int maxInterval = 180;
private int mode = 1; // 0=关闭 1=由近到远 2=由远到近
private int pageSize = 6; // 每轮播报条数(耻辱台一页,一次发6个)
private int lastDelaySec = 0; // 本轮实际排定的随机间隔秒数(播报日志用)
private long startCutoffMs = 0; // 播报起点(毫秒):只播该时刻之后创建的封禁
private boolean startCutoffAuto = true; // 起点未配置 → 自动取插件数据目录创建时间(=插件安装时间)
private long autoCutoffMs = -1; // 自动起点缓存(-1=未取)
private boolean jsonSyntaxOk = false; // json 文本语法是否有效(区分「语法坏」与「语法好但值空」)
private String lastCfgSig = null; // 上轮配置签名(增量重载:无变更不打日志)
private volatile boolean timerRunning = false; // 已有待触发的排程(防重复拉起)
private volatile boolean stoppedByEmpty = false; // 全员下线导致的停机(等玩家上线恢复)
private static BanBroadcastManager instance; // 单插件单实例,供 WebManager 取播报起点
public BanBroadcastManager(Main plugin) {
this.plugin = plugin;
instance = this;
}
/** 单例访问(WebManager 推送封禁时取播报起点) */
public static BanBroadcastManager get() { return instance; }
/**
* 播报起点(毫秒),0=不过滤。与游戏内播报同一套语义(配置的播报起点 / 自动=插件数据目录创建时间),
* 供 PHP 端封禁公示过滤「插件上服务器之前的历史封禁」——两端同源,不各配一套。
*/
public long getStartCutoff() { return resolveStartCutoff(); }
// ==================== 27批:banned-players.json 数据模型 ====================
/** banned-players.json 的一条记录(只取公示需要的字段) */
private static final class JsonBan {
final String name;
final String reason;
final String source;
final long createdMs;
/** 到期毫秒;0 = 永久 */
final long expiresMs;
JsonBan(String name, String reason, String source,
long createdMs, long expiresMs) {
this.name = name;
this.reason = reason;
this.source = source;
this.createdMs = createdMs;
this.expiresMs = expiresMs;
}
}
/** 上次成功读到的原始文件签名(内容+长度),用于「数据有没有变」判定与日志 */
private String lastFileSig = null;
private int lastFileRawCount = 0;
private int lastFileKeptCount = 0;
// ==================== 生命周期 ====================
public void start() {
banDir = new File(plugin.getDataFolder(), "ban");
mdFile = new File(banDir, "规则配置.md");
jsonFile = findJsonConfig();
ensureConfigExists();
reloadConfig();
scheduleNext();
plugin.getServer().getPluginManager().registerEvents(this, plugin);
// ★ 二十二批:错位配置检测 —— 曾有人把 规则配置.md/json 放到
// plugins/ban/(插件只读 plugins/Sdf1_login/ban/),表现为
// 「安全升级没生效」。发现即警告并指明正确路径。
try {
File wrongDir = new File(
plugin.getDataFolder().getParentFile(),
"ban");
if (wrongDir.isDirectory()) {
String[] wrongs = wrongDir.list((d, n) ->
n.equals("规则配置.md")
|| n.toLowerCase(Locale.ROOT)
.endsWith(".json"));
if (wrongs != null && wrongs.length > 0) {
warn("检测到错位配置目录 plugins/ban/(含 "
+ String.join(", ", wrongs)
+ ")——本插件只读取 "
+ banDir.getPath()
+ ",该目录内的配置不会生效!");
}
}
} catch (Exception ignored) {}
long cut0 = resolveStartCutoff();
File bf0 = bannedPlayersFile();
ensureTimestampFile();
plugin.getLogger().info("[封禁播报] 已启动,模式=" + modeName()
+ " 间隔=" + minInterval + "~" + maxInterval + "s 每页" + pageSize + "条"
+ " 起点=" + (cut0 > 0 ? new SimpleDateFormat("yyyy-MM-dd").format(new Date(cut0)) : "不限")
+ " 数据源=" + (bf0 == null ? "未定位" : bf0.getPath()));
List<JsonBan> boot = collectBans();
log("启动首筛:banned-players.json 有效封禁 " + boot.size() + " 条");
}
public void shutdown() { /* BukkitRunnable 随插件卸载自动取消 */ }
/**
* ★ 第十九批:定时器生命周期 —— 停止条件只有两个:全员下线、服务器关机/插件卸载。
* 配置为「关闭」不停定时器:只静默本轮,下一轮醒来重读配置,
* 改回开启(或把间隔从 0 恢复)即自动续播,无需重启。
* 全员下线时 scheduleNext 的空服分支停掉排程,第一个玩家上线由此重新拉起。
* (start/runTaskLater/PlayerJoinEvent 都在主线程,状态无并发问题)
*/
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
if (!stoppedByEmpty || timerRunning) return;
stoppedByEmpty = false;
scheduleNext();
}
// ==================== 配置:自愈 + 双模式解析 ====================
/** 找 ban/ 目录下任意 *.json 配置文件 */
private File findJsonConfig() {
File[] fs = banDir == null ? null : banDir.listFiles(
(d, n) -> n.toLowerCase(Locale.ROOT).endsWith(".json"));
return (fs != null && fs.length > 0) ? fs[0] : null;
}
/** 配置文件丢失就补一份(自愈);已存在的 md 走安全升级补齐模板新增行 */
private void ensureConfigExists() {
jsonFile = findJsonConfig(); // ★ 每轮重查:运行中新增/删除的 json 都要跟上
try {
if (jsonFile != null) {
if (!banDir.exists()) banDir.mkdirs();
if (!jsonFile.exists()) {
plugin.saveResource("ban/" + jsonFile.getName(), false);
log("配置文件丢失,已自愈补发: " + jsonFile.getName());
}
} else if (!mdFile.exists()) {
banDir.mkdirs();
plugin.saveResource("ban/规则配置.md", false);
log("配置文件丢失,已自愈补发: 规则配置.md");
}
// ★ 第二十一批:已存在的 md 安全升级 —— saveResource(...,false) 对已存在文件
// 永不覆盖,jar 模板新增的配置行(如「播报起点」)借此补进原文件;
// 说明文字与用户改过的值原样保留(safeUpgradeDoc:先 .bak 逐字节校验,
// 备份失败整个取消不动原文件;原子写失败自动还原;无新增行幂等不写文件)。
// 有变更由 safeUpgradeDoc 打一条明细,无变更安静 —— 对齐增量日志要求。
if (mdFile != null && mdFile.exists()) {
java.util.List<String> tpl = ConfigManager.readJarResourceLines(
plugin.getResource("ban/规则配置.md"));
if (tpl != null) {
plugin.getConfig2().safeUpgradeDoc(mdFile, tpl, "封禁播报规则");
}
}
} catch (Exception e) {
warn("自愈补发失败: " + e.getMessage());
}
}
/** 重新加载配置(json 优先 → md json块 → md 表格 → 备份重置)。
* ★ 第二十批:增量重载 —— 生效配置与上一轮逐项对比:
* 无变更一个字不打(安静执行随机计时,到点该干嘛干嘛);
* 有变更才打一条明细(模式/间隔/起点/来源 哪里从什么变成什么)。 */
public void reloadConfig() {
// 进门快照(对比基线):上一轮生效值
final int oMin = minInterval, oMax = maxInterval, oMode = mode;
final long oCut = startCutoffMs;
final boolean oAuto = startCutoffAuto;
final String oldSig = lastCfgSig;
String src = null; // 本轮配置源(变更明细用)
try {
// ★ 懒重载(每次播报窗口执行一次):先回出厂默认再解析文件 ——
// 文件里新改的值、被删掉/清空的项都能如实读到(读到的就是文件里最新的);
// 开关(播报模式)决定这次报/不报,最新间隔用于播报完后的下次排程计时。
minInterval = 60;
maxInterval = 180;
mode = 1;
startCutoffAuto = true;
startCutoffMs = 0;
jsonFile = findJsonConfig(); // ★ 每轮重查(不再只在 null 时查一次)
if (jsonFile != null && jsonFile.exists()) {
String txt = readFile(jsonFile);
if (parseJsonText(txt)) {
src = "json:" + jsonFile.getName();
} else if (jsonSyntaxOk) {
// ★ 第十八批:语法有效但间隔值为空(文档语义「表格/json 二者选一填」)
// → 继承 json 里已解析的播报模式/播报起点,间隔回退 md 表格
// (只取间隔,绝不覆盖已继承的模式/起点)或出厂默认,不判损毁。
boolean iv = false;
if (mdFile != null && mdFile.exists()) {
String md0 = readFile(mdFile);
if (md0 != null) iv = parseIntervalTable(md0);
}
normalize();
src = "json继承" + (iv ? "+md间隔" : "+默认间隔") + ":" + jsonFile.getName();
} else {
// 语法真损坏 → 备份+移除,继续回退 md 分支(不再就此 return)
backupAndReset(jsonFile, jsonFile.getName());
jsonFile = null;
}
}
if (src == null) {
if (!mdFile.exists()) { ensureConfigExists(); }
String md = readFile(mdFile);
if (md != null) {
String jsonBlock = extractJsonBlock(md);
if (jsonBlock != null && parseJsonText(jsonBlock)) {
src = "md内嵌json";
} else if (parseTableText(md)) {
src = "md表格";
}
}
if (src == null) {
// 全部解码失败 → 备份原文件 + 释放一份新的(低频真事件,仍打日志)
backupAndReset(mdFile, "规则配置.md");
src = "出厂重置";
}
}
} catch (Exception e) {
warn("reloadConfig 异常: " + e.getMessage());
src = "异常";
}
// ★ 增量日志:签名 = 配置源 + 全部生效值;与上一轮完全一致 → 安静
String sig = src + "|" + mode + "|" + minInterval + "|" + maxInterval + "|"
+ (startCutoffAuto ? "auto" : startCutoffMs);
if (sig.equals(oldSig)) { return; }
lastCfgSig = sig;
if (oldSig == null) { return; } // 首轮只记基线(start()「已启动」总览已覆盖,不重复刷屏)
StringBuilder sb = new StringBuilder("配置变更(").append(src).append("):");
if (oMode != mode) {
sb.append(" 模式 ").append(modeNameOf(oMode)).append("→").append(modeName());
}
if (oMin != minInterval || oMax != maxInterval) {
sb.append(" 间隔 ").append(oMin).append("~").append(oMax).append("s→")
.append(minInterval).append("~").append(maxInterval).append("s");
}
if (oAuto != startCutoffAuto || oCut != startCutoffMs) {
sb.append(" 起点 ").append(cutText(oAuto, oCut))
.append("→").append(cutText(startCutoffAuto, startCutoffMs));
}
String oldSrc = oldSig.substring(0, oldSig.indexOf('|'));
if (!oldSrc.equals(src)) {
sb.append(" 来源 ").append(oldSrc).append("→").append(src);
}
log(sb.toString());
}
/** 模式码→文字(增量日志对比旧值用;modeName() 取当前字段) */
private String modeNameOf(int m) {
return m == 0 ? "关闭" : (m == 1 ? "由近到远" : "由远到近");
}
/** 起点状态→文字(增量日志用):auto=自动 / 时间戳=日期 / 0=不限 */
private String cutText(boolean auto, long ms) {
if (auto) return "自动";
return ms > 0 ? new SimpleDateFormat("yyyy-MM-dd").format(new Date(ms)) : "不限";
}
/** 从 md 提取 ```json 代码块内容(不含围栏) */
private String extractJsonBlock(String md) {
Pattern p = Pattern.compile("```json\\s*\\n(.*?)\\n\\s*```", Pattern.DOTALL);
Matcher m = p.matcher(md);
return m.find() ? m.group(1).trim() : null;
}
/**
* 解析 json 文本(键:最小间隔/最大间隔/播报模式)。
* 出厂 规则配置.md 的 json 块值为空字符串而表格有真值(文档语义:二者选一填),
* 因此仅当 json 里出现「非空间隔值」才认 json 生效;
* 只有播报模式、没有任何间隔键的纯 json 也认生效(间隔走默认)。
* @return true = json 配置生效;false = 视为未配置,调用方回退表格
*/
private boolean parseJsonText(String txt) {
jsonSyntaxOk = false;
try {
JsonObject o = JsonParser.parseString(txt).getAsJsonObject();
jsonSyntaxOk = true; // 语法解析成功(值是否为空另行判定)
boolean hasIntervalKey = o.has("最小间隔") || o.has("最大间隔")
|| o.has("轮播最低间隔") || o.has("轮播最大间隔");
boolean anyInterval = false;
Integer v;
if ((v = jsonInt(o, "最小间隔")) != null) { minInterval = v; anyInterval = true; }
if ((v = jsonInt(o, "最大间隔")) != null) { maxInterval = v; anyInterval = true; }
if ((v = jsonInt(o, "轮播最低间隔")) != null) { minInterval = v; anyInterval = true; }
if ((v = jsonInt(o, "轮播最大间隔")) != null) { maxInterval = v; anyInterval = true; }
boolean modePresent = false;
if (o.has("播报模式") && !o.get("播报模式").isJsonNull()) {
mode = parseMode(o.get("播报模式").getAsString());
modePresent = true;
}
if (o.has("播报起点") && !o.get("播报起点").isJsonNull()) {
parseStartCutoff(o.get("播报起点").getAsString());
}
if (anyInterval) { normalize(); return true; }
// 没有可用间隔值:纯「只有播报模式且无间隔键」的 json 也算生效
if (modePresent && !hasIntervalKey) { normalize(); return true; }
return false;
} catch (Exception e) {
return false;
}
}
/** json 取间隔值:键存在且非空才返回(空串/null → null,留给表格或默认值) */
private Integer jsonInt(JsonObject o, String key) {
try {
if (!o.has(key) || o.get(key).isJsonNull()) return null;
String s = o.get(key).getAsString();
if (s == null || s.trim().isEmpty()) return null;
int r = toSec(s);
return r >= 0 ? r : null;
} catch (Exception e) {
return null;
}
}
/** 解析 md 表格(| 名字 | 说明 | 参数值 |) */
private boolean parseTableText(String md) {
boolean any = false;
for (String line : md.split("\n")) {
String t = line.trim();
if (!t.startsWith("|") || t.startsWith("| ---") || t.startsWith("|---")) continue;
String[] cells = t.split("\\|");
if (cells.length < 4) continue;
String key = cells[1].trim();
String val = cells[cells.length - 1].trim();
if (key.equals("轮播最低间隔")) { minInterval = toSec(val); any = true; }
else if (key.equals("轮播最大间隔")) { maxInterval = toSec(val); any = true; }
else if (key.equals("播报模式")) { mode = parseMode(val); any = true; }
else if (key.equals("播报起点")) { parseStartCutoff(val); any = true; }
}
if (any) normalize();
return any;
}
/** 只从 md 表格取间隔值(不碰播报模式/播报起点 —— 继承 json 时仅回退间隔用) */
private boolean parseIntervalTable(String md) {
boolean any = false;
for (String line : md.split("\n")) {
String t = line.trim();
if (!t.startsWith("|") || t.startsWith("| ---") || t.startsWith("|---")) continue;
String[] cells = t.split("\\|");
if (cells.length < 4) continue;
String key = cells[1].trim();
String val = cells[cells.length - 1].trim();
if (key.equals("轮播最低间隔")) { minInterval = toSec(val); any = true; }
else if (key.equals("轮播最大间隔")) { maxInterval = toSec(val); any = true; }
}
if (any) {
if (minInterval < 0) minInterval = 0;
if (maxInterval < 0) maxInterval = 0;
if (maxInterval > 0 && minInterval > maxInterval) maxInterval = minInterval;
}
return any;
}
/** 播报模式文本/布尔/数字 → 0/1/2 */
private int parseMode(String s) {
if (s == null) return 1;
String v = s.trim();
// ★ 第十八批遗留修复:0 = 关闭(表格文档语义)。
// 原实现把 "0" 和 "false" 合并映射成 2(由远到近),
// 导致表格填 0 永远关不掉、一直播报 —— 现拆开各归各位。
if (v.equals("0")) return 0; // 0=关闭
if (v.equalsIgnoreCase("false")) return 2; // false=由远到近
if (v.equals("1") || v.equalsIgnoreCase("true")) return 1; // true=由近到远
if (v.contains("关闭")) return 0; // 容错:直接写「关闭」
if (v.contains("近到远")) return 1; // 由近到远
if (v.contains("远到近")) return 2; // 由远到近
return 1;
}
/** 秒数文本 → int(容错"60s"/"60秒"/"60") */
private int toSec(String s) {
String v = s == null ? "" : s.trim().replaceAll("[^0-9]", "");
if (v.isEmpty()) return 0;
try { return Integer.parseInt(v); } catch (Exception e) { return 0; }
}
/** 归一化:模式为0 或 最大最小间隔都为0 → 关闭;最大<最低 → 补齐(对齐配置说明语义) */
private void normalize() {
if (minInterval < 0) minInterval = 0;
if (maxInterval < 0) maxInterval = 0;
if (maxInterval > 0 && minInterval > maxInterval) maxInterval = minInterval;
if (mode != 0 && mode != 1 && mode != 2) mode = 1;
if (mode == 0 || (minInterval == 0 && maxInterval == 0)) mode = 0;
}
/**
* 解析「播报起点」:插件安装之前的封禁(历史封禁)不播报。
* 支持 yyyy-MM-dd[ HH:mm[:ss]] 日期、10/13 位时间戳;0/留空 = 自动
* (自动模式取插件数据目录创建时间,即插件安装上服务器的时间)
*/
private void parseStartCutoff(String s) {
String v = s == null ? "" : s.trim();
if (v.isEmpty() || v.equals("0")) {
startCutoffAuto = true;
startCutoffMs = 0;
return;
}
if (v.matches("\\d{10,13}")) {
long n = Long.parseLong(v);
startCutoffMs = v.length() <= 10 ? n * 1000L : n;
startCutoffAuto = false;
return;
}
String[] pats = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd"};
for (String p : pats) {
try {
java.text.ParsePosition pos = new java.text.ParsePosition(0);
Date d = new SimpleDateFormat(p, Locale.ROOT).parse(v, pos);
if (d != null && pos.getIndex() == v.length()) {
startCutoffMs = d.getTime();
startCutoffAuto = false;
return;
}
} catch (Exception ignored) { }
}
warn("播报起点无法解析,回退自动: " + v);
startCutoffAuto = true;
startCutoffMs = 0;
}
/**
* 取播报起点(毫秒):>0 表示只播该时刻之后创建的封禁。
*
* <p>★ 第二十七批:自动模式取插件数据目录(plugins/Sdf1_login)的创建时间
* = 插件安装上服务器的时间,插件上服之前的全部历史封禁一律不播。
*
* <p>★ 第二十八批:数据目录可能被重建/迁移/重装——creationTime 变成当天,
* 把之后创建的全部生效封禁一并滤光(实测起点=2026-10-16 → 2026-09-30
* 的封禁被滤 → 播报误报「当前无生效封禁」)。故自动起点加下限保护:
* 绝不晚于「距今 180 天」——既挡住古早历史封禁(半年前的一律不播),
* 又保证目录被重建时近半年内的生效封禁不被误杀。
* 手动配置的播报起点(startCutoffAuto=false)不受此保护,完全按配置走。
*
* <p>旧实现有「距今不足 7 天就放弃过滤」的守卫(当年担心 mtime 兜底不可信),
* 结果插件刚装上服务器时自动退化成「不过滤」,把上线前几年的历史封禁全播了出来
* —— 这正是用户看到的「一个都没封却公示一堆人」。
* 现改为无条件采用 creationTime:只有文件系统根本给不出创建时间(返回 0 /
* 抛异常)才退化为不过滤,宁可少播也不误播历史数据。
*/
private long resolveStartCutoff() {
if (!startCutoffAuto) return startCutoffMs;
if (autoCutoffMs < 0) {
autoCutoffMs = 0;
long tsFile = readTimestampFile();
if (tsFile > 0) {
autoCutoffMs = tsFile;
} else {
long folderCreated = 0;
try {
File df = plugin.getDataFolder();
if (df != null && df.exists()) {
long t = java.nio.file.Files.readAttributes(df.toPath(),
java.nio.file.attribute.BasicFileAttributes.class)
.creationTime().toMillis();
if (t > 0) folderCreated = t;
}
} catch (Exception e) {
warn("读取插件数据目录创建时间失败,本次不过滤历史封禁: "
+ e.getMessage());
}
if (folderCreated > 0) {
long cap = System.currentTimeMillis() - MAX_AUTO_CUTOFF_WINDOW_MS;
autoCutoffMs = Math.min(folderCreated, cap);
if (folderCreated > cap) {
warn("插件数据目录创建时间 " + fmtCutoff(folderCreated)
+ " 晚于180天前(目录可能被重建/迁移),"
+ "自动起点回退为 " + fmtCutoff(cap)
+ ",近半年内的生效封禁照常播报"
+ "(可在 ban/规则配置.md 手动填「播报起点」精确控制)");
}
}
if (autoCutoffMs <= 0) {
warn("取不到插件数据目录创建时间,历史封禁过滤已关闭"
+ "(可在 ban/规则配置.md 里手动填「播报起点」锁定时间)");
}
}
}
return autoCutoffMs;
}
/** ★ 第57批:读插件数据目录中的时间戳文件(10位数字无后缀)
* 优先级:用户配置 > 时间戳文件 > 插件数据目录创建时间
*/
private long readTimestampFile() {
try {
File df = plugin.getDataFolder();
if (df == null) return 0;
File[] files = df.listFiles();
if (files == null) return 0;
// ★ 第57批续:多份时间戳文件取最小值(用户手动放的固定值 < 插件启动创建的当前秒值)
long minTs = -1;
for (File f : files) {
String name = f.getName();
if (name.length() == 10 && name.chars().allMatch(Character::isDigit)) {
long ts = Long.parseLong(name);
if (ts > 0 && (minTs < 0 || ts < minTs)) minTs = ts;
}
}
if (minTs > 0) return minTs * 1000L;
} catch (Exception e) {
warn("读时间戳文件失败: " + e.getMessage());
}
return 0;
}
/** ★ 第57批:插件启动时创建时间戳文件(如果不存在)
* 文件名 = 当前时间戳(秒),内容为空
*/
private void ensureTimestampFile() {
try {
File df = plugin.getDataFolder();
if (df == null || !df.exists()) return;
// ★ 第57批续:目录里已有任意时间戳文件就跳过,不重复创建
File[] files = df.listFiles();
if (files != null) {
for (File f : files) {
String name = f.getName();
if (name.length() == 10 && name.chars().allMatch(Character::isDigit)) {
return; // 已有时间戳文件,不创建
}
}
}
long tsSec = System.currentTimeMillis() / 1000L;
File tsFile = new File(df, String.valueOf(tsSec));
if (!tsFile.exists()) {
java.nio.file.Files.createFile(tsFile.toPath());
plugin.getLogger().info("[封禁播报] 已创建时间戳文件: " + tsFile.getName());
}
} catch (Exception e) {
warn("创建时间戳文件失败: " + e.getMessage());
}
}
/** 28批:自动播报起点最多回溯 180 天(约半年)——数据目录重建时起点不得过新 */
private static final long MAX_AUTO_CUTOFF_WINDOW_MS = 180L * 24 * 3600 * 1000;
private static String fmtCutoff(long ms) {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date(ms));
}
// ==================== 调度 ====================
/** 排下一次窗口期:随机 [min,max] 秒后播报,再自我reschedule */
private void scheduleNext() {
int delaySec;
if (mode == 0) {
// 播报关闭时仍每 60 秒自检一次:配置文件被删则自愈补发、
// 运行中把 0 改回正常值可自动恢复播报(无需重启)。
// ★ 关闭 ≠ 停机:定时器只在全员下线/关服时才停(第十九批)
delaySec = 60;
} else {
// ★ 每次在[最小间隔,最大间隔]之间随机取一个秒数,不是固定值
int span = maxInterval - minInterval;
delaySec = minInterval + (span > 0 ? rnd.nextInt(span + 1) : 0);
lastDelaySec = delaySec;
}
long delayTicks = Math.max(20L, delaySec * 20L);
timerRunning = true;
new BukkitRunnable() {
@Override
public void run() {
timerRunning = false;
if (!plugin.isEnabled()) return;
// ★ 服务器没人就停机:全员下线是定时器的两个停止条件之一(另一个是关服),
// 不播报、不重载、不自愈、不打任何日志,直接停排程 ——
// 第一个玩家上线时 onPlayerJoin 重新拉起(配置为关闭同样只静默本轮)
if (Bukkit.getOnlinePlayers().isEmpty()) {
stoppedByEmpty = true;
return;
}
// ★ 懒重载:每次播报窗口重读配置 —— 开关决定这次报/不报,
// 最新间隔用于播报完后的下次排程计时;顺带自愈补发丢失的配置文件
ensureConfigExists();
reloadConfig();
if (mode != 0) {
try { broadcastOnce(); }
catch (Exception e) { warn("播报异常: " + e.getMessage()); }
}
scheduleNext();
}
}.runTaskLater(plugin, delayTicks);
}
// ==================== 播报 ====================
/**
* ★ 27批(用户明令的唯一数据源):每轮都重新读原版 banned-players.json,
* 加载到内存做筛选 —— 不再依赖任何内存名单,杜绝「文件是空的却公示一堆人」。
*
* <p>流程:定位文件 → 读全文 → 内存解析 → 过滤(过期 / created 早于播报起点)
* → 返回。文件缺失、为空、语法坏、过滤后一条不剩,一律返回空列表(=闭嘴)。
*
* <p>created/expires 两种格式都兼容:
* ISO「2026-10-16T13:32:58Z」、带时区「2026-10-16 21:06:20 +0800」、
* 「yyyy-MM-dd HH:mm:ss」、以及纯数字时间戳(秒/毫秒);
* 「forever」/空 = 永久。解析不了的条目按 created=0 处理,
* 起点过滤时会被当成历史封禁排除(宁可漏播不误播)。
*/
private List<JsonBan> collectBans() {
List<JsonBan> list = new ArrayList<>();
File f = bannedPlayersFile();
if (f == null || !f.exists()) {
log("未找到 banned-players.json,本轮闭嘴不播");
lastFileSig = null;
lastFileRawCount = 0;
lastFileKeptCount = 0;
return list;
}
String txt = readFile(f);
if (txt == null || txt.trim().isEmpty() || txt.trim().equals("[]")) {
log("banned-players.json 为空(" + f.length() + " 字节),本轮闭嘴不播");
lastFileSig = sigOf(f, txt);
lastFileRawCount = 0;
lastFileKeptCount = 0;
return list;
}
// 内存加载:解析成 JsonBan 列表
List<JsonBan> raw = new ArrayList<>();
try {
com.google.gson.JsonElement root = JsonParser.parseString(txt);
if (!root.isJsonArray()) {
warn("banned-players.json 根节点不是数组,本轮闭嘴不播");
lastFileSig = sigOf(f, txt);
return list;
}
long nowMs = System.currentTimeMillis();
for (com.google.gson.JsonElement el : root.getAsJsonArray()) {
if (el == null || !el.isJsonObject()) continue;
com.google.gson.JsonObject o = el.getAsJsonObject();
String name = str(o, "name");
if (name.isEmpty()) name = str(o, "uuid");
if (name.isEmpty()) continue;
raw.add(new JsonBan(name, str(o, "reason"), str(o, "source"),
parseBanTime(str(o, "created")),
parseBanTime(str(o, "expires"))));
}
} catch (Exception e) {
warn("banned-players.json 解析失败(" + e.getMessage()
+ "),本轮闭嘴不播");
lastFileSig = sigOf(f, txt);
return list;
}
// 内存筛选:未过期 + created 晚于播报起点(起点=插件数据目录创建时间)
long nowMs2 = System.currentTimeMillis();
long cutoff = resolveStartCutoff();
int expiredCnt = 0, historyCnt = 0, timeUnknownCnt = 0;
for (JsonBan b : raw) {
if (b.expiresMs > 0 && b.expiresMs <= nowMs2) { expiredCnt++; continue; }
if (b.createdMs <= 0) { timeUnknownCnt++; } // created 解析不了
if (cutoff > 0 && b.createdMs < cutoff) { historyCnt++; continue; }
list.add(b);
}
// 「每次都检查是不是最新」:文件签名变了才打日志,避免刷屏
String sig = sigOf(f, txt);
lastFileRawCount = raw.size();
lastFileKeptCount = list.size();
if (!sig.equals(lastFileSig)) {
lastFileSig = sig;
log("已重读 banned-players.json: 原始 " + raw.size() + " 条"
+ " → 过滤后 " + list.size() + " 条(起点 "
+ (cutoff > 0 ? new SimpleDateFormat("yyyy-MM-dd").format(new Date(cutoff)) : "§c未取到·不过滤")
+ ";过期 " + expiredCnt + ",历史 " + historyCnt
+ ",时间未知 " + timeUnknownCnt + ",文件 " + sig + ")");
}
return list;
}
/** 原版封禁名单文件:<worldContainer>/banned-players.json(MC 唯一封禁数据源) */
private File bannedPlayersFile() {
try {
File wc = Bukkit.getWorldContainer();
if (wc != null) {
return new File(wc, "banned-players.json");
}
} catch (Exception e) {
warn("取世界容器失败: " + e.getMessage());
}
return plugin.getDataFolder() == null ? null
: new File(plugin.getDataFolder().getParentFile() == null
? plugin.getDataFolder()
: plugin.getDataFolder().getParentFile().getParentFile(),
"banned-players.json");
}
/** 文件内容签名(长度+哈希),用于「数据有没有变」判定 */
private String sigOf(File f, String txt) {
int h = txt == null ? 0 : txt.hashCode();
return f.length() + "B/" + Integer.toHexString(h);
}
private static String str(com.google.gson.JsonObject o, String k) {
try {
if (o == null || !o.has(k) || o.get(k).isJsonNull()) return "";
String s = o.get(k).getAsString();
return s == null ? "" : s;
} catch (Exception e) {
return "";
}
}
/**
* banned-players.json 的时间字段 → 毫秒;解析不了返回 0。
* 兼容:ISO8601(带 Z/时区) / "yyyy-MM-dd HH:mm:ss Z" / "yyyy-MM-dd HH:mm:ss"
* / "yyyy-MM-dd" / 纯数字(10位=秒,13位=毫秒)。
*/
private long parseBanTime(String s) {
if (s == null) return 0L;
String v = s.trim();
if (v.isEmpty()) return 0L;
if (v.equalsIgnoreCase("forever") || v.equals("永久")) return 0L;
// 纯数字时间戳
if (v.matches("\\d{10,13}")) {
long n = Long.parseLong(v);
return v.length() <= 10 ? n * 1000L : n;
}
String[] pats = {
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"yyyy-MM-dd'T'HH:mm:ssXXX",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd HH:mm:ss Z",
"yyyy-MM-dd HH:mm:ss ZZZZ",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd"};
for (String pt : pats) {
try {
java.text.ParsePosition pos = new java.text.ParsePosition(0);
Date d = new SimpleDateFormat(pt, Locale.ROOT).parse(v, pos);
if (d != null && pos.getIndex() == v.length()) return d.getTime();
} catch (Exception ignored) { }
}
return 0L;
}
/**
* ★ 第30批:黑名单数据源(群控黑名单 = 软折磨,与封禁公示并列)。
* 复用 JsonBan 结构,source 标 "黑名单",理由取黑名单条目的理由。
*/
private List<JsonBan> collectBlacklistBans() {
List<JsonBan> out = new ArrayList<>();
BlacklistManager bl = plugin.getBlacklist();
if (bl == null) return out;
try {
for (BlacklistManager.BlackEntry e : bl.getActiveEntries()) {
if (e == null || e.name == null || e.name.isEmpty()) continue;
out.add(new JsonBan(e.name,
e.reason != null && !e.reason.isEmpty()
? e.reason : "违反服务器规则",
"黑名单",
e.createdMs > 0 ? e.createdMs : System.currentTimeMillis(),
e.expiresMs));
}
} catch (Exception ex) {
warn("读取黑名单失败: " + ex.getMessage());
}
return out;
}
/** 轮播当前页并广播给全服 */
private void broadcastOnce() {
List<JsonBan> bans = collectBans();
// ★ 第30批:并入黑名单玩家(独立数据源,不受 banned-players.json 是否存在影响)
int blackCount = 0;
try {
List<JsonBan> bl = collectBlacklistBans();
blackCount = bl.size();
bans.addAll(bl);
} catch (Exception ignored) {}
if (bans.isEmpty()) { log("当前无生效封禁,跳过本轮"); return; }
// 由近到远:最新封禁在前;由远到近:最早封禁在前
// ★ 第33批(#213):黑名单条目一律置顶(source="黑名单"),
// 防止其被分页轮播淹没 —— 短时拉黑等不到自己那一页。
bans.sort((a, b) -> {
boolean ab = "黑名单".equals(a.source);
boolean bb = "黑名单".equals(b.source);
if (ab != bb) return ab ? -1 : 1;
return mode == 1
? Long.compare(b.createdMs, a.createdMs) // 由近到远
: Long.compare(a.createdMs, b.createdMs); // 由远到近
});
int total = bans.size();
int start = cursor % total;
int end = Math.min(start + pageSize, total);
List<JsonBan> page = bans.subList(start, end);
cursor = end % total;
String head = "§c§l⚠ §6违规封禁公示 §7(共§f" + total + "§7人, 第§f"
+ (start / pageSize + 1) + "§7/" + ((total + pageSize - 1) / pageSize) + "§7页)";
Bukkit.broadcastMessage(head);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
for (JsonBan e : page) {
String target = e.name;
String reason = (e.reason != null && !e.reason.isEmpty())
? e.reason : "违反服务器规则";
String when = e.createdMs > 0 ? df.format(new Date(e.createdMs)) : "时间未知";
String expStr = e.expiresMs > 0 ? ("§7至§f" + df.format(new Date(e.expiresMs)))
: "§c永久";
Bukkit.broadcastMessage("§c☠ §f" + target + " §7- " + reason
+ " §8| §7封于§f" + when + " §8| " + expStr);
}
Bukkit.broadcastMessage("§7§o请各位玩家引以为戒,遵守服务器规则。");
log("本轮已播报 " + page.size() + "/" + total + " 条封禁"
+ "(含黑名单 " + blackCount + " 条)"
+ "(本次随机间隔 " + lastDelaySec + "s,区间 "
+ minInterval + "~" + maxInterval + "s;banned-players.json 原始 "
+ lastFileRawCount + " 条,过滤后 " + lastFileKeptCount + " 条)");
}
/** 轮播游标(下一页起点) */
private int cursor = 0;
// ==================== 管理员命令 ====================
/** 手动重载配置并汇报当前生效值 */
public void report(CommandSender to) {
reloadConfig();
long cut = resolveStartCutoff();
to.sendMessage("§a[封禁播报] §7模式=§f" + modeName()
+ " §7间隔=§f" + minInterval + "~" + maxInterval + "s"
+ " §7每页=§f" + pageSize + "条"
+ " §7起点=§f" + (cut > 0 ? new SimpleDateFormat("yyyy-MM-dd").format(new Date(cut)) : "不限")
+ (startCutoffAuto ? "§7(自动)" : "")
+ (mode == 0 ? " §c(已关闭)" : ""));
File bf = bannedPlayersFile();
List<JsonBan> now = collectBans();
to.sendMessage("§a[封禁播报] §7数据源=§f" + (bf == null ? "未定位"
: bf.getName() + (bf.exists() ? "(§f" + bf.length() + "§7字节)" : "(§c不存在§7)"))
+ " §7有效封禁=§f" + now.size() + "§7条"
+ (now.isEmpty() ? " §8(无数据,保持沉默)" : ""));
}
private String modeName() {
return mode == 0 ? "关闭" : (mode == 1 ? "由近到远" : "由远到近");
}
// ==================== 工具 ====================
private String readFile(File f) {
if (f == null || !f.exists()) return null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(f), StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append('\n');
return sb.toString();
} catch (Exception e) {
warn("读取失败 " + f.getName() + ": " + e.getMessage());
return null;
}
}
/** 备份原配置文件 + 释放一份新的(自愈) */
private void backupAndReset(File f, String resourceName) {
try {
if (f != null && f.exists()) {
String bak = f.getAbsolutePath() + ".bak." + System.currentTimeMillis();
copyFile(f, new File(bak));
warn("配置解码失败,已备份原文件: " + new File(bak).getName());
}
// 先删旧文件再从 jar 释放新的
if (f != null && f.exists()) f.delete();
plugin.saveResource("ban/" + resourceName, false);
log("已释放一份新配置: " + resourceName);
} catch (IllegalArgumentException e) {
// jar 里没有同名模板(如用户自建 cfg.json):原文件已备份并移除,
// 不算失败 —— 调用方会继续回退 md / 出厂默认
warn("jar 内无模板资源 ban/" + resourceName
+ ",原文件已备份并移除,回退其它配置源");
} catch (Exception e) {
warn("备份/重置失败: " + e.getMessage());
}
}
private void copyFile(File src, File dst) throws IOException {
try (FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
}
}
private void log(String s) { plugin.getLogger().info("[封禁播报] " + s); }
private void warn(String s) { plugin.getLogger().warning("[封禁播报] " + s); }
}
@@ -1,769 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
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.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* ★ 第30批:群控黑名单(软折磨)。
*
* <p>数据源:{@code plugins/Sdf1_login/black/黑名单.md} 的「配置区域」表格。
*
* <p>拉黑时长口径:空 / 0 / 终身 / 永久 = 永久;
* {@code yyyy-MM-dd HH:mm} = 到期即该时刻;{@code yyyy-MM-dd} = 当天 23:59:59。
*
* <p>生效规则:每 5 秒比对文件 mtime+size 做增量重载。
* 新增条目 → 立即生效(备份并清空背包 + 冻结债券账户 + 撤销领地管理员身份);
* 删除条目 → 立即恢复(解冻债券 + 从最新自动备份恢复背包)。
*
* <p>指令:{@code /addblack <玩家> [时长] [理由]}、{@code /removeblack <玩家>}。
*/
public class BlacklistManager {
private final Main plugin;
/** 黑名单配置文件:plugins/Sdf1_login/black/黑名单.md */
private File mdFile;
/** 配置区域起止标记 */
private static final String ZONE_START = "### ----配置区域开始----";
private static final String ZONE_END = "### ----配置区域结束";
/** 内存黑名单:玩家名 → 条目 */
private final Map<String, BlackEntry> entries = new LinkedHashMap<>();
/** 已施加处罚的玩家 —— 防重复应用(备份/清空只做一次) */
private final Set<String> applied = ConcurrentHashMap.newKeySet();
/** 上次读取的文件签名(mtime + size),用于增量重载判定 */
private long lastMtime = -1L;
private long lastSize = -1L;
/** 写回 md 时使用的行尾风格(true=CRLF) */
private boolean crlfStyle = true;
public BlacklistManager(Main plugin) {
this.plugin = plugin;
}
// ==================== 条目模型 ====================
/** 黑名单条目 */
public static final class BlackEntry {
/** 玩家名(原始拼写,写回 md 用) */
public final String name;
/** 拉黑时长原文 */
public final String timeText;
/** 理由 */
public final String reason;
/** 到期毫秒;0 = 永久 */
public final long expiresMs;
/** 记录时间毫秒 */
public final long createdMs;
BlackEntry(String name, String timeText, String reason,
long expiresMs, long createdMs) {
this.name = name;
this.timeText = timeText;
this.reason = reason;
this.expiresMs = expiresMs;
this.createdMs = createdMs;
}
public boolean isExpired(long nowMs) {
return expiresMs > 0L && expiresMs <= nowMs;
}
}
// ==================== 生命周期 ====================
/** 初始化:定位/释放配置文件 → 首次加载 → 启动 5 秒增量重载 */
public void init() {
try {
File dir = new File(plugin.getDataFolder(), "black");
if (!dir.exists()) dir.mkdirs();
mdFile = new File(dir, "黑名单.md");
if (!mdFile.exists()) {
try (InputStream in = plugin.getResource("black/黑名单.md")) {
if (in != null) {
Files.copy(in, mdFile.toPath());
}
} catch (IOException e) {
plugin.getLogger().warning("[黑名单] 模板释放失败: " + e.getMessage());
}
}
} catch (Exception e) {
plugin.getLogger().warning("[黑名单] 初始化失败: " + e.getMessage());
return;
}
reload();
// ★ 每 5 秒增量重载(mtime+size 变化才重新解析)
Bukkit.getScheduler().runTaskTimer(plugin, () -> {
try {
if (mdFile == null || !mdFile.exists()) return;
long mt = mdFile.lastModified();
long sz = mdFile.length();
if (mt != lastMtime || sz != lastSize) {
reload();
}
// ★ 第33批(#213):文件没动也要扫 wall-clock 到期
// (原实现只比 mtime+size,时长拉黑永远不自动解除)
sweepExpired();
} catch (Exception ignored) {}
}, 100L, 100L);
}
public File getMdFile() {
return mdFile;
}
// ==================== 查询 ====================
/**
* 该玩家是否在生效中的黑名单里。
* <p>★ 精确匹配(本服离线模式,大小写不同 = 不同玩家)。
*/
public boolean isBlacklisted(String playerName) {
if (playerName == null || playerName.isEmpty()) return false;
return findEntry(playerName) != null;
}
/** 精确查条目(过期返回 null) */
public BlackEntry findEntry(String playerName) {
if (playerName == null || playerName.isEmpty()) return null;
BlackEntry e = entries.get(playerName);
if (e == null) return null;
if (e.isExpired(System.currentTimeMillis())) {
entries.remove(playerName);
return null;
}
return e;
}
/** 归一化查询(大小写不敏感兜底,仅用于 md 写回定位) */
public BlackEntry findEntryLoose(String playerName) {
if (playerName == null) return null;
BlackEntry exact = findEntry(playerName);
if (exact != null) return exact;
String want = AreaProtection.normName(playerName);
for (BlackEntry e : new ArrayList<>(entries.values())) {
if (AreaProtection.normName(e.name).equals(want)) return e;
}
return null;
}
/** 当前生效中的黑名单条目快照(供耻辱台播报) */
public List<BlackEntry> getActiveEntries() {
long now = System.currentTimeMillis();
List<BlackEntry> out = new ArrayList<>();
for (BlackEntry e : new ArrayList<>(entries.values())) {
if (e.isExpired(now)) {
entries.remove(e.name);
continue;
}
out.add(e);
}
return out;
}
public int size() {
return getActiveEntries().size();
}
// ==================== 增删(写回 md) ====================
/**
* 添加黑名单条目并写回 md。
*
* @param timeText 拉黑时长(空/0/终身=永久,日期或日期+时间=到期)
* @param reason 理由(可空)
* @return null=成功,否则为错误原因
*/
public String addBlacklist(String playerName, String timeText, String reason) {
if (playerName == null || playerName.trim().isEmpty()) {
return "玩家名不能为空";
}
String name = playerName.trim();
if (mdFile == null) return "黑名单文件未初始化";
List<String> lines = readLines();
if (lines == null) return "读取黑名单文件失败";
// 定位配置区域 + 表头
int[] zone = locateZone(lines);
if (zone == null) return "黑名单文件缺少配置区域标记";
int zoneStart = zone[0], zoneEnd = zone[1];
int headerIdx = locateHeader(lines, zoneStart, zoneEnd);
if (headerIdx < 0) return "黑名单文件缺少表头(| 玩家名字 | 拉黑时长 | 理由 |)";
// 去掉同名旧行(大小写不敏感)
String want = AreaProtection.normName(name);
List<String> cleaned = new ArrayList<>();
for (int i = 0; i < lines.size(); i++) {
if (i > zoneStart && i < zoneEnd && isRowOf(lines.get(i), want)) {
continue;
}
cleaned.add(lines.get(i));
}
lines = cleaned;
// 行数变了 → 重新定位
zone = locateZone(lines);
if (zone == null) return "黑名单文件缺少配置区域标记";
zoneStart = zone[0];
zoneEnd = zone[1];
headerIdx = locateHeader(lines, zoneStart, zoneEnd);
if (headerIdx < 0) return "黑名单文件缺少表头";
// 插入点 = 表头 + 分隔行之后
int insertAt = headerIdx + 1;
if (insertAt < zoneEnd && isSeparatorRow(lines.get(insertAt))) {
insertAt++;
}
String safeTime = (timeText == null || timeText.trim().isEmpty()) ? "终身" : timeText.trim();
String safeReason = (reason == null || reason.trim().isEmpty()) ? "违反服务器规则" : reason.trim();
// 理由里的竖线会破坏表格 → 替换
safeReason = safeReason.replace("|", "/").replace("\r", " ").replace("\n", " ");
lines.add(insertAt, "| " + name + " | " + safeTime + " | " + safeReason + " |");
if (!writeLines(lines)) return "写回黑名单文件失败";
reload();
return null;
}
/**
* 移除黑名单条目并写回 md。
*
* @return null=成功(或本来就没有),否则为错误原因
*/
public String removeBlacklist(String playerName) {
if (playerName == null || playerName.trim().isEmpty()) {
return "玩家名不能为空";
}
if (mdFile == null) return "黑名单文件未初始化";
List<String> lines = readLines();
if (lines == null) return "读取黑名单文件失败";
int[] zone = locateZone(lines);
if (zone == null) return "黑名单文件缺少配置区域标记";
int zoneStart = zone[0], zoneEnd = zone[1];
String want = AreaProtection.normName(playerName.trim());
List<String> out = new ArrayList<>();
boolean removed = false;
for (int i = 0; i < lines.size(); i++) {
if (i > zoneStart && i < zoneEnd && isRowOf(lines.get(i), want)) {
removed = true;
continue;
}
out.add(lines.get(i));
}
if (!removed) {
// 文件里没有 → 仍要解冻(可能只冻了账户没进表)
restoreBlacklist(playerName.trim());
return null;
}
if (!writeLines(out)) return "写回黑名单文件失败";
reload();
return null;
}
// ==================== 解析 ====================
/** 重新解析 md 并应用差异(新增→处罚,移除→恢复) */
public synchronized void reload() {
if (mdFile == null) return;
Map<String, BlackEntry> parsed = new LinkedHashMap<>();
long now = System.currentTimeMillis();
List<String> lines = readLines();
if (lines != null) {
int[] zone = locateZone(lines);
if (zone != null) {
int zoneStart = zone[0], zoneEnd = zone[1];
for (int i = zoneStart + 1; i < zoneEnd; i++) {
String line = lines.get(i).trim();
if (!line.startsWith("|")) continue;
if (isSeparatorRow(line)) continue;
String[] cells = splitRow(line);
if (cells.length < 1) continue;
String name = cells[0].trim();
if (name.isEmpty() || name.contains("玩家名字")) continue;
String timeText = cells.length > 1 ? cells[1].trim() : "";
String reason = cells.length > 2 ? cells[2].trim() : "";
long expires = parseExpireMs(timeText, now);
if (expires > 0 && expires <= now) continue; // 已过期
BlackEntry old = parsed.get(name);
long created = old != null ? old.createdMs : now;
parsed.put(name, new BlackEntry(name, timeText, reason, expires, created));
}
}
}
// ===== 差异应用 =====
boolean changed = parsed.size() != entries.size();
// 1) 新增 → 施加处罚
for (BlackEntry e : parsed.values()) {
if (!entries.containsKey(e.name)) {
applyBlacklist(e);
changed = true;
} else {
BlackEntry old = entries.get(e.name);
if (old == null || old.expiresMs != e.expiresMs
|| !old.timeText.equals(e.timeText)
|| !old.reason.equals(e.reason)) {
changed = true; // 条目内容改了(理由/时长)
}
}
}
// 2) 移除 → 恢复
for (BlackEntry e : new ArrayList<>(entries.values())) {
if (!parsed.containsKey(e.name)) {
restoreBlacklist(e.name);
changed = true;
}
}
entries.clear();
entries.putAll(parsed);
if (mdFile.exists()) {
lastMtime = mdFile.lastModified();
lastSize = mdFile.length();
}
plugin.getLogger().info("[黑名单] 已重载,当前生效 " + parsed.size() + " 人");
// ★ 第32批(#208):名单变化 → 立即回响PHP(异步;syncBlacklist 内部 hash 门控兜底)
if (changed) {
try {
WebManager wm = plugin.webManager;
if (wm != null) wm.forceSyncBlacklist();
} catch (Exception ignored) {}
}
}
/**
* ★ 第33批(#213):墙钟到期扫描 —— 时长拉黑自动解除。
* <p>根因:5 秒定时器只比对 mtime+size,md 文件不动就永不 reload,
* 而 reload 里只在「解析时」过滤已过期行 —— 于是绝对日期/相对时长
* 到期后,处罚(applied、债券冻结、md 行)永远挂着 = 用户反馈的
* 「配置时长不生效」。本方法独立于文件变化,每 5 秒按当前时间扫。
* <p>到期条目:内存移除 → 恢复处罚 → 删 md 对应行 → 回响 PHP。
*/
private synchronized void sweepExpired() {
if (entries.isEmpty()) return;
long now = System.currentTimeMillis();
List<BlackEntry> expired = new ArrayList<>();
for (BlackEntry e : new ArrayList<>(entries.values())) {
if (e.isExpired(now)) expired.add(e);
}
if (expired.isEmpty()) return;
List<String> names = new ArrayList<>();
for (BlackEntry e : expired) {
entries.remove(e.name);
names.add(e.name);
plugin.getLogger().info("[黑名单] 拉黑到期自动解除: " + e.name
+ "(" + e.timeText + ")");
restoreBlacklist(e.name);
}
// 同步删 md 里对应行(防止文件签名不变、行永远留着)
try {
List<String> lines = readLines();
if (lines != null) {
int[] zone = locateZone(lines);
if (zone != null) {
List<String> out = new ArrayList<>();
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
boolean drop = false;
if (i > zone[0] && i < zone[1] && line.trim().startsWith("|")
&& !isSeparatorRow(line.trim())) {
for (String n : names) {
if (isRowOf(line, AreaProtection.normName(n))) {
drop = true;
break;
}
}
}
if (!drop) out.add(line);
}
if (out.size() != lines.size() && writeLines(out)) {
// 写回成功 → 立即刷新签名,免得下个 tick 又整表 reload 一遍
if (mdFile.exists()) {
lastMtime = mdFile.lastModified();
lastSize = mdFile.length();
}
}
}
}
} catch (Exception ex) {
plugin.getLogger().warning("[黑名单] 删除到期 md 行失败: " + ex.getMessage());
}
// 名单变了 → 回响 PHP(web_player_blacklist 同步移除)
try {
WebManager wm = plugin.webManager;
if (wm != null) wm.forceSyncBlacklist();
} catch (Exception ignored) {}
}
/**
* 拉黑时长 → 到期毫秒;0 = 永久。
* <p>空 / 0 / 终身 / 永久 / forever → 永久;
* {@code yyyy-MM-dd HH:mm[:ss]} → 该时刻;
* {@code yyyy-MM-dd} → 当天 23:59:59。
*/
public static long parseExpireMs(String timeText, long now) {
if (timeText == null) return 0L;
String t = timeText.trim();
if (t.isEmpty()) return 0L;
if ("0".equals(t) || "终身".equals(t) || "永久".equals(t)
|| "forever".equalsIgnoreCase(t) || "never".equalsIgnoreCase(t)) {
return 0L;
}
String[] pats = {
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyy/MM/dd HH:mm:ss",
"yyyy/MM/dd HH:mm"};
for (String p : pats) {
long v = parseStrict(p, t);
if (v > 0L) return v;
}
// 仅日期 → 当天 23:59:59
String[] datePats = {"yyyy-MM-dd", "yyyy/MM/dd"};
for (String p : datePats) {
long v = parseStrict(p, t);
if (v > 0L) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(v);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTimeInMillis();
}
}
// ★ 第33批(#213):相对时长(3天 / 7d / 2小时 / 30分 …)——
// 「配置了时长 = 临时拉黑,到期自动解除」。交 DurationParser 统一解析。
// 两个护栏:
// ① 只认「数字+单位」形态 —— DurationParser 的纯数字分支=Unix秒时间戳(1970),
// 裸写 "100" 会从原语义「永久」变成「立即过期」,比不识别更危险;
// ② 排除含「年」的中文日期(2026年10月20日)—— 那属绝对日期语义,
// DurationParser 会取当天 00:00 = 配完即过期。
if (t.matches(".*\\d+\\s*(周|天|日|时|分|秒|小时|分钟|星期|礼拜|w|d|h|m|s|W|D|H|M|S).*")
&& !t.contains("年")) {
try {
long v = DurationParser.parseToExpireMs(t);
if (v > 0L) return v;
} catch (Throwable ignored) {
}
}
// 解析不了 → 永久(宁可拉黑也不放过)
return 0L;
}
private static long parseStrict(String pattern, String value) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.ROOT);
sdf.setLenient(false);
ParsePosition pos = new ParsePosition(0);
Date d = sdf.parse(value, pos);
if (d != null && pos.getIndex() == value.length()) return d.getTime();
} catch (Exception ignored) {}
return 0L;
}
// ==================== 处罚 / 恢复 ====================
/**
* 施加拉黑处罚:备份并清空背包 + 冻结债券账户 + 撤销领地管理员身份(降级访客)。
*/
public void applyBlacklist(BlackEntry e) {
if (e == null) return;
final String name = e.name;
if (!applied.add(name)) {
return; // 已施加过,不重复备份/清空
}
plugin.getLogger().info("[黑名单] 拉黑生效: " + name
+ "(" + e.timeText + " / " + e.reason + ")");
// ★ 第33批(#213):拉黑当下即时插播一条「拉黑公示」。
// 根因:耻辱台轮播 6 页 × 110~400s 随机间隔,短时拉黑
// (如测试用 30 秒/13 秒)永远轮不到那一页 = 用户反馈
// 「没能进入耻辱台」。插播保证拉黑瞬间全服可见。
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String when = df.format(new Date(e.createdMs > 0 ? e.createdMs
: System.currentTimeMillis()));
String expStr = e.expiresMs > 0 ? ("§7至§f" + df.format(new Date(e.expiresMs)))
: "§c永久";
Bukkit.broadcastMessage("§c§l⚠ §6拉黑公示 §c☠ §f" + name
+ " §7- " + (e.reason == null || e.reason.isEmpty()
? "违反服务器规则" : e.reason)
+ " §8| §7拉黑于§f" + when + " §8| " + expStr);
} catch (Exception ignored) {}
// 1) 冻结债券账户(按拉黑到期时间;永久=0)
try {
BondManager bm = plugin.getBonds();
if (bm != null) bm.freezeAccount(name, e.expiresMs);
} catch (Exception ex) {
plugin.getLogger().warning("[黑名单] 冻结债券失败 (" + name + "): " + ex.getMessage());
}
// 2) 撤销其在所有领地的管理员身份(降级访客)
try {
AreaProtection ap = plugin.getAreaProtection();
if (ap != null) {
int n = ap.demoteBlacklistAdmins(name);
if (n > 0) {
plugin.getLogger().info("[黑名单] 已撤销 " + name + " 的 " + n + " 个领地管理员身份");
}
}
} catch (Exception ex) {
plugin.getLogger().warning("[黑名单] 撤销领地权限失败 (" + name + "): " + ex.getMessage());
}
// 3) 在线玩家:备份并清空背包
Player p = Bukkit.getPlayerExact(name);
if (p == null || !p.isOnline()) return;
backupAndClear(p, name);
}
/**
* 解除拉黑:解冻债券 + 从最新自动备份恢复背包。
*/
public void restoreBlacklist(String playerName) {
if (playerName == null || playerName.isEmpty()) return;
if (!applied.remove(playerName)) {
// 未必处罚过,但仍确保解冻
try {
BondManager bm = plugin.getBonds();
if (bm != null) bm.unfreezeAccount(playerName);
} catch (Exception ignored) {}
return;
}
plugin.getLogger().info("[黑名单] 拉黑解除: " + playerName);
try {
BondManager bm = plugin.getBonds();
if (bm != null) bm.unfreezeAccount(playerName);
} catch (Exception ex) {
plugin.getLogger().warning("[黑名单] 解冻债券失败 (" + playerName + "): " + ex.getMessage());
}
Player p = Bukkit.getPlayerExact(playerName);
if (p == null || !p.isOnline()) return;
restoreInventory(p, playerName);
}
/**
* 备份并清空背包。
* <p>已有备份时不覆盖(保留拉黑时刻那一份),只清空。
*/
private void backupAndClear(final Player p, final String name) {
boolean hasBackup = false;
try {
hasBackup = plugin.getDb() != null
&& plugin.getDb().getLatestAutoBackup(name) != null;
} catch (Exception ignored) {}
if (!hasBackup) {
final ItemStack[] contents = p.getInventory().getContents();
final ItemStack[] armor = p.getInventory().getArmorContents();
final ItemStack[] extra = p.getInventory().getExtraContents();
final int level = p.getLevel();
final double exp = p.getExp();
final String c64, a64, e64;
try {
c64 = InventorySerializer.toBase64(contents);
a64 = InventorySerializer.toBase64(armor);
e64 = InventorySerializer.toBase64(extra);
} catch (IOException ex) {
plugin.getLogger().warning("[黑名单] 背包序列化失败 (" + name + "): " + ex.getMessage());
return;
}
// ★ 落库是阻塞 DB 写 → 异步;写完再回主线程清空(保证备份的是拉黑前快照)
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
plugin.getDb().saveAutoBackup(name, c64, a64, e64, level, exp);
} catch (Throwable t) {
plugin.getLogger().warning("[黑名单] 背包备份落库失败 (" + name + "): " + t.getMessage());
}
Bukkit.getScheduler().runTask(plugin, () -> {
Player cur = Bukkit.getPlayerExact(name);
if (cur == null || !cur.isOnline()) return;
clearInventory(cur);
cur.sendMessage("§c§l[罪人] §f你已被拉黑,背包已清空(已备份)");
cur.sendMessage("§7背包物品将在解除拉黑后自动返还");
});
});
return;
}
// 已有备份 → 只清空,不覆盖
Bukkit.getScheduler().runTask(plugin, () -> {
Player cur = Bukkit.getPlayerExact(name);
if (cur == null || !cur.isOnline()) return;
clearInventory(cur);
cur.sendMessage("§c§l[罪人] §f你已被拉黑,背包已清空");
});
}
/** 从最新自动备份恢复背包 */
private void restoreInventory(Player p, String name) {
String[] data;
try {
data = plugin.getDb() == null ? null : plugin.getDb().getLatestAutoBackup(name);
} catch (Exception ex) {
plugin.getLogger().warning("[黑名单] 读取背包备份失败 (" + name + "): " + ex.getMessage());
return;
}
if (data == null) {
p.sendMessage("§e§l[罪人] §f拉黑已解除,但没有找到可返还的背包备份");
return;
}
try {
ItemStack[] contents = InventorySerializer.fromBase64(data[0]);
ItemStack[] armor = InventorySerializer.fromBase64(data[1]);
ItemStack[] extra = InventorySerializer.fromBase64(data[2]);
p.getInventory().setContents(contents);
p.getInventory().setArmorContents(armor);
p.getInventory().setExtraContents(extra);
if (data.length > 3) {
try { p.setLevel(Integer.parseInt(data[3])); } catch (Exception ignored) {}
}
if (data.length > 4) {
try { p.setExp((float) Double.parseDouble(data[4])); } catch (Exception ignored) {}
}
p.sendMessage("§a§l[罪人] §f拉黑已解除,背包已返还");
} catch (IOException ex) {
plugin.getLogger().warning("[黑名单] 背包反序列化失败 (" + name + "): " + ex.getMessage());
p.sendMessage("§e§l[罪人] §f拉黑已解除,但背包返还失败,请联系管理员");
}
}
private void clearInventory(Player p) {
p.getInventory().clear();
p.getInventory().setArmorContents(null);
p.getInventory().setExtraContents(null);
p.setLevel(0);
p.setExp(0);
}
// ==================== md 读写工具 ====================
/** 读全部行(去掉行尾 \r) */
private List<String> readLines() {
if (mdFile == null || !mdFile.exists()) return null;
List<String> out = new ArrayList<>();
try {
byte[] raw = Files.readAllBytes(mdFile.toPath());
crlfStyle = new String(raw, StandardCharsets.UTF_8).contains("\r\n");
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(raw), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
out.add(line);
}
}
} catch (IOException e) {
plugin.getLogger().warning("[黑名单] 读取失败: " + e.getMessage());
return null;
}
return out;
}
/** 写回全部行(保持原行尾风格) */
private boolean writeLines(List<String> lines) {
if (mdFile == null) return false;
String sep = crlfStyle ? "\r\n" : "\n";
StringBuilder sb = new StringBuilder();
for (String l : lines) {
sb.append(l).append(sep);
}
try {
File parent = mdFile.getParentFile();
if (parent != null && !parent.exists()) parent.mkdirs();
Files.write(mdFile.toPath(), sb.toString().getBytes(StandardCharsets.UTF_8));
return true;
} catch (IOException e) {
plugin.getLogger().warning("[黑名单] 写入失败: " + e.getMessage());
return false;
}
}
/** 定位配置区域,返回 {起始行, 结束行};找不到返回 null */
private int[] locateZone(List<String> lines) {
int zoneStart = -1, zoneEnd = -1;
for (int i = 0; i < lines.size(); i++) {
String t = lines.get(i).trim();
if (t.startsWith(ZONE_START)) {
zoneStart = i;
} else if (t.startsWith(ZONE_END) && zoneStart >= 0) {
zoneEnd = i;
break;
}
}
if (zoneStart < 0 || zoneEnd < 0) return null;
return new int[]{zoneStart, zoneEnd};
}
/** 定位表头行索引;找不到返回 -1 */
private int locateHeader(List<String> lines, int zoneStart, int zoneEnd) {
for (int i = zoneStart + 1; i < zoneEnd; i++) {
String t = lines.get(i).trim();
if (t.startsWith("|") && t.contains("玩家名字")) {
return i;
}
}
return -1;
}
/** 表格行是否属于该玩家(第一列匹配,大小写不敏感) */
private boolean isRowOf(String line, String wantNorm) {
String[] cells = splitRow(line.trim());
if (cells.length < 1) return false;
String c0 = cells[0].trim();
if (c0.isEmpty() || c0.contains("玩家名字")) return false;
return AreaProtection.normName(c0).equals(wantNorm);
}
/** 分隔行判断(| --- | --- |) */
private boolean isSeparatorRow(String line) {
String t = line.trim();
if (!t.startsWith("|")) return false;
String[] cells = splitRow(t);
for (String c : cells) {
String v = c.trim();
if (!v.isEmpty() && !v.startsWith("---") && !v.matches("[-:]+")) return false;
}
return true;
}
/** 拆表格行(去掉首尾竖线,按 | 切分) */
private String[] splitRow(String line) {
String t = line.trim();
if (t.startsWith("|")) t = t.substring(1);
if (t.endsWith("|")) t = t.substring(0, t.length() - 1);
return t.split("\\|", -1);
}
}
File diff suppressed because it is too large Load Diff
-380
View File
@@ -1,380 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
public class BondPrinter {
private final Main plugin;
private final File outputDir;
private static final SimpleDateFormat FILE_SDF =
new SimpleDateFormat(
"yyyy-MM-dd_HH-mm-ss");
private static final SimpleDateFormat CELL_SDF =
new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
private static final LinkedHashMap<String, String>
TYPE_NAMES = new LinkedHashMap<>();
static {
TYPE_NAMES.put("admin_give", "管理员发放");
TYPE_NAMES.put("admin_deduct", "管理员扣除");
TYPE_NAMES.put("transfer_out", "转出");
TYPE_NAMES.put("transfer_in", "转入");
TYPE_NAMES.put("redeem", "CDK兑换");
TYPE_NAMES.put("shop_buy", "商城购买");
TYPE_NAMES.put("shop_sell", "商城出售"); // ← 补上
TYPE_NAMES.put("daily_sign", "签到奖励");
TYPE_NAMES.put("freeze", "冻结");
TYPE_NAMES.put("unfreeze", "解冻");
TYPE_NAMES.put("ticket_reward", "工单奖励");
TYPE_NAMES.put("ticket_service", "工单服务奖励");
}
public BondPrinter(Main plugin) {
this.plugin = plugin;
this.outputDir = new File(
plugin.getDataFolder(), "printer");
if (!this.outputDir.exists()) {
this.outputDir.mkdirs();
}
}
// ============ 打印单个玩家 ============
public void printPlayer(String player,
CommandSender sender) {
Bukkit.getScheduler()
.runTaskAsynchronously(plugin,
() -> doPrintPlayer(
player, sender));
}
private void doPrintPlayer(String player,
CommandSender sender) {
try {
List<Map<String, Object>> txs =
plugin.getBonds()
.getAllTransactions(player);
String fileName = player + "_"
+ FILE_SDF.format(new Date())
+ ".xls";
File file = new File(outputDir, fileName);
deleteOld(player);
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(file),
StandardCharsets.UTF_8));
try {
writeXmlHeader(pw,
escXml(player));
writeXmlRow(pw,
new String[]{
"时间", "类型",
"金额", "对象",
"操作者", "理由",
"操作前余额",
"操作后余额"});
for (Map<String, Object> tx : txs) {
writeXmlRow(pw, new String[]{
txTime(tx),
txTypeName(tx),
String.valueOf(
txInt(tx,
"amount")),
txStr(tx,
"target_player"),
txStr(tx, "operator"),
txStr(tx, "reason"),
String.valueOf(
txInt(tx,
"balance_before")),
String.valueOf(
txInt(tx,
"balance_after"))
});
}
writeXmlFooter(pw);
pw.flush();
} finally {
pw.close();
}
if (sender != null) {
sender.sendMessage("§a[打印] §f"
+ player + " §a流水已导出");
sender.sendMessage("§7文件: §f"
+ fileName);
sender.sendMessage("§7共 §f"
+ txs.size()
+ " §7条,§724小时后删除");
}
} catch (Exception e) {
if (sender != null) {
sender.sendMessage("§c导出失败: "
+ e.getMessage());
}
plugin.getLogger().severe(
"[Printer] " + e.getMessage());
}
}
// ============ 打印全服 ============
public void printAll(CommandSender sender) {
Bukkit.getScheduler()
.runTaskAsynchronously(plugin,
() -> doPrintAll(sender));
}
private void doPrintAll(CommandSender sender) {
try {
List<String> players =
plugin.getBonds()
.getAllPlayerNames();
if (players.isEmpty()) {
if (sender != null) {
sender.sendMessage("§c没有流水数据");
}
return;
}
String fileName = "全服流水_"
+ FILE_SDF.format(new Date())
+ ".xls";
File file = new File(outputDir, fileName);
// ===== 收集所有流水 =====
// key = 时间戳+玩家+金额,用于去重
// value = 一行数据
List<String[]> allRows = new ArrayList<>();
Set<String> seenKeys = new HashSet<>();
for (String player : players) {
List<Map<String, Object>> txs =
plugin.getBonds()
.getAllTransactions(player);
for (Map<String, Object> tx : txs) {
int txId = ((Number) tx.get("id"))
.intValue();
String dedupKey =
String.valueOf(txId);
if (!seenKeys.add(dedupKey)) {
continue;
}
String timeStr = txTime(tx);
long timeMs = 0;
Object t = tx.get("time");
if (t != null) {
timeMs =
((Number) t).longValue();
}
allRows.add(new String[]{
player,
timeStr,
txTypeName(tx),
String.valueOf(
txInt(tx, "amount")),
txStr(tx, "target_player"),
txStr(tx, "operator"),
txStr(tx, "reason"),
String.valueOf(
txInt(tx,
"balance_before")),
String.valueOf(
txInt(tx,
"balance_after")),
// 额外存时间戳用于排序
String.valueOf(timeMs)
});
}
}
// ===== 按时间戳排序 =====
allRows.sort((a, b) -> {
long ta = Long.parseLong(
a[a.length - 1]);
long tb = Long.parseLong(
b[b.length - 1]);
return Long.compare(ta, tb);
});
// ===== 写入文件 =====
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(file),
StandardCharsets.UTF_8));
try {
writeXmlHeader(pw, "全服流水");
writeXmlRow(pw, new String[]{
"玩家", "时间", "类型",
"金额", "对象", "操作者",
"理由", "操作前余额",
"操作后余额"
});
for (String[] row : allRows) {
// 去掉最后的时间戳列
String[] cells =
new String[row.length - 1];
System.arraycopy(row, 0,
cells, 0, cells.length);
writeXmlRow(pw, cells);
}
writeXmlFooter(pw);
pw.flush();
if (sender != null) {
sender.sendMessage(
"§a[打印] §f全服流水 §a已导出");
sender.sendMessage("§7文件: §f"
+ fileName);
sender.sendMessage("§7共 §f"
+ players.size()
+ " 名玩家,§f"
+ allRows.size() + " §7条");
sender.sendMessage(
"§7按时间从早到晚排序");
sender.sendMessage(
"§724小时后自动删除");
}
} finally {
pw.close();
}
} catch (Exception e) {
if (sender != null) {
sender.sendMessage("§c导出失败: "
+ e.getMessage());
}
plugin.getLogger().severe(
"[Printer] " + e.getMessage());
}
}
// ============ 清理 ============
public void cleanupOldFiles() {
long now = System.currentTimeMillis();
long maxAge = 24L * 60 * 60 * 1000;
File[] files = outputDir.listFiles(
(d, n) -> n.endsWith(".xls"));
if (files == null) {
return;
}
int count = 0;
for (File f : files) {
if (now - f.lastModified() > maxAge) {
if (f.delete()) {
count++;
}
}
}
if (count > 0) {
plugin.getLogger().info(
"[Printer] 清理 "
+ count + " 个过期文件");
}
}
private void deleteOld(String player) {
File[] old = outputDir.listFiles(
(d, n) -> n.startsWith(player + "_")
&& n.endsWith(".xls"));
if (old != null) {
for (File f : old) {
f.delete();
}
}
}
// ============ XML工具 ============
private void writeXmlHeader(PrintWriter pw,
String sheetName) {
pw.println("<?xml version=\"1.0\"?>");
pw.println("<?mso-application "
+ "progid=\"Excel.Sheet\"?>");
pw.println("<Workbook xmlns="
+ "\"urn:schemas-microsoft-com"
+ ":office:spreadsheet\"");
pw.println(" xmlns:ss="
+ "\"urn:schemas-microsoft-com"
+ ":office:spreadsheet\">");
pw.println(" <Worksheet ss:Name=\""
+ sheetName + "\">");
pw.println(" <Table>");
}
private void writeXmlRow(PrintWriter pw,
String[] cells) {
pw.println(" <Row>");
for (String cell : cells) {
pw.println(" <Cell>"
+ "<Data ss:Type=\"String\">"
+ escXml(cell != null ? cell : "")
+ "</Data></Cell>");
}
pw.println(" </Row>");
}
private void writeXmlFooter(PrintWriter pw) {
pw.println(" </Table>");
pw.println(" </Worksheet>");
pw.println("</Workbook>");
}
private String escXml(String val) {
if (val == null) {
return "";
}
return val.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;");
}
private String txTime(Map<String, Object> tx) {
Object t = tx.get("time");
if (t == null) return "";
long ms = ((Number) t).longValue();
return CELL_SDF.format(new Date(ms));
}
private String txTypeName(
Map<String, Object> tx) {
String type = (String) tx.get("type");
return TYPE_NAMES.getOrDefault(type, type);
}
private int txInt(Map<String, Object> tx,
String key) {
Object v = tx.get(key);
if (v == null) return 0;
return ((Number) v).intValue();
}
private String txStr(Map<String, Object> tx,
String key) {
Object v = tx.get(key);
return v != null ? v.toString() : "";
}
}
-312
View File
@@ -1,312 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.nio.charset.StandardCharsets;
public class CDKManager {
private final Main plugin;
private Connection db;
private final Map<String, CDKInput> pendingInputs
= new ConcurrentHashMap<>();
public CDKManager(Main plugin) {
this.plugin = plugin;
initDB();
}
private void initDB() {
try {
Class.forName("org.sqlite.JDBC");
File dbFile = new File(
new File(plugin.getDataFolder(), "财务债券"),
"bond.db");
dbFile.getParentFile().mkdirs();
db = DriverManager.getConnection(
"jdbc:sqlite:" + dbFile.getAbsolutePath());
Statement st = db.createStatement();
st.execute("PRAGMA journal_mode=WAL");
st.execute("CREATE TABLE IF NOT EXISTS cdk ("
+ "code TEXT PRIMARY KEY,"
+ "amount INTEGER DEFAULT 0,"
+ "type TEXT DEFAULT 'bond',"
+ "used INTEGER DEFAULT 0,"
+ "used_by TEXT DEFAULT '',"
+ "created_time INTEGER DEFAULT 0,"
+ "used_time INTEGER DEFAULT 0)");
st.close();
} catch (Exception e) {
throw new RuntimeException(
"[CDK] DB init failed: "
+ e.getMessage(), e);
}
}
// ===== CDK兑换(供SDF1调用) =====
/**
* 兑换CDK,返回结果字符串
* @return "success:金额:余额前:余额后"
* 或 "fail:原因"
*/
public String redeem(String code, String player) {
try {
// ★ 第32批:拉黑检查提到查码之前 —— 被拉黑玩家一律拒绝,
// 不管码在本地是否存在,绝不放行进远程验证链
if (plugin.getBlacklist() != null
&& plugin.getBlacklist().isBlacklisted(player))
return "fail:blacklisted";
// ★ 第63批:信誉积分低于-10分禁止使用CDK
if (plugin.getCreditManager() != null
&& plugin.getCreditManager().isRestricted(player, "block_cdk_and_bond"))
return "fail:credit_restricted";
PreparedStatement ps = db.prepareStatement(
"SELECT amount,type,used FROM cdk "
+ "WHERE code=?");
ps.setString(1, code);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
rs.close(); ps.close();
return "fail:not_found";
}
int amount = rs.getInt("amount");
String type = rs.getString("type");
int used = rs.getInt("used");
rs.close(); ps.close();
if (used == 1)
return "fail:already_used";
if (plugin.getBonds()
.isFrozen(player))
return "fail:frozen";
PreparedStatement up = db.prepareStatement(
"UPDATE cdk SET used=1,"
+ "used_by=?,used_time=? "
+ "WHERE code=?");
up.setString(1, player);
up.setLong(2,
System.currentTimeMillis());
up.setString(3, code);
up.executeUpdate(); up.close();
if ("bond".equals(type)) {
int bef = plugin.getBonds()
.getBonds(player);
plugin.getBonds().addBonds(player,
amount,
BondManager.TX_REDEEM,
"", "CDK系统",
"CDK兑换: " + code);
int aft = plugin.getBonds()
.getBonds(player);
return "success:" + amount
+ ":" + bef + ":" + aft;
}
return "fail:unknown_type";
} catch (SQLException e) {
return "fail:" + e.getMessage();
}
}
// ===== 聊天输入系统 =====
public void requestInput(Player p,
String type,
String context) {
CDKInput input = new CDKInput();
input.type = type;
input.context = context;
input.time = System.currentTimeMillis();
pendingInputs.put(p.getName(), input);
}
public boolean isListening(String playerName) {
return pendingInputs
.containsKey(playerName);
}
public void onChat(Player p, String msg) {
CDKInput input = pendingInputs
.remove(p.getName());
if (input == null) return;
if (System.currentTimeMillis()
- input.time > 60000) {
p.sendMessage("§c输入超时");
return;
}
if ("cdk".equals(input.type)) {
String result = redeem(
msg.trim(), p.getName());
if (result != null
&& result.startsWith("success:")) {
String[] parts = result.split(":");
int amt = Integer.parseInt(parts[1]);
int bef = Integer.parseInt(parts[2]);
int aft = Integer.parseInt(parts[3]);
p.sendMessage("§e§l[CDK] §f兑换成功!"
+ "获得 §c" + amt + "§f债券");
p.sendMessage("§7余额: §e" + bef
+ " §7-> §a" + aft);
} else {
p.sendMessage("§c§l[CDK] §f"
+ (result != null
? result.replace("fail:", "")
: "无效的兑换码"));
}
return;
}
if ("econ".equals(input.type)) {
handleEconInput(p, msg.trim(),
input.context);
return;
}
if ("bond".equals(input.type)) {
handleBondInput(p, msg.trim(),
input.context);
return;
}
if ("points".equals(input.type)) {
handlePointsInput(p, msg.trim(),
input.context);
return;
}
if ("gift_target".equals(input.type)) {
// 赠予用户组:输入目标玩家名
String targetName = msg.trim();
if (!targetName.isEmpty()) {
GUIManager guiMgr = plugin.getGui();
if (guiMgr != null) {
guiMgr.handleGiftTargetInput(p, targetName);
}
} else {
p.sendMessage("§c请输入有效的玩家名");
}
return;
}
}
private void handleEconInput(Player admin,
String msg,
String target) {
// Economy已移除,所有经济操作改用债券系统
admin.sendMessage("§c[经济操作] 功能已移除,请使用债券系统");
}
private void handleBondInput(Player admin,
String msg,
String target) {
if (!msg.startsWith("+")
&& !msg.startsWith("-")) {
admin.sendMessage("§c格式: §a+100"
+ " §7或 §c-50");
return;
}
try {
String sign = msg.substring(0, 1);
String rest =
msg.substring(1).trim();
String[] parts =
rest.split("\\s+", 2);
int amount = Integer.parseInt(parts[0]);
String reason = parts.length >= 2
? parts[1].trim()
: "管理员手动调整";
if (amount <= 0) {
admin.sendMessage("§c金额必须>0");
return;
}
String opName = admin.getName();
String txType = "-".equals(sign)
? BondManager.TX_ADMIN_DEDUCT
: BondManager.TX_ADMIN_GIVE;
if ("-".equals(sign)) {
if (plugin.getBonds()
.isFrozen(target)) {
admin.sendMessage("§c账户冻结");
return;
}
if (plugin.getBonds().deductBonds(
target, amount, txType,
"", opName, reason)) {
admin.sendMessage("§a扣除成功");
} else {
admin.sendMessage("§c债券不足");
}
} else {
if (plugin.getBonds()
.isFrozen(target)) {
admin.sendMessage("§c账户冻结");
return;
}
plugin.getBonds().addBonds(target,
amount, txType,
"", opName, reason);
admin.sendMessage("§a发放成功");
}
} catch (NumberFormatException e) {
admin.sendMessage("§c格式错误");
}
}
private void handlePointsInput(Player admin,
String msg,
String target) {
if (!msg.startsWith("+")
&& !msg.startsWith("-")) {
admin.sendMessage("§c格式: §a+100"
+ " §7或 §c-50");
return;
}
try {
String sign = msg.substring(0, 1);
String rest =
msg.substring(1).trim();
int amount = Integer.parseInt(rest);
if (amount <= 0) {
admin.sendMessage("§c金额必须>0");
return;
}
if ("-".equals(sign)) {
if (plugin.getDb().deductPoints(
target, amount)) {
admin.sendMessage("§a扣除成功");
} else {
admin.sendMessage("§c积分不足");
}
} else {
plugin.getDb().addPoints(
target, amount);
admin.sendMessage("§a发放成功");
}
} catch (NumberFormatException e) {
admin.sendMessage("§c格式错误");
}
}
public void cancelInput(String player) {
pendingInputs.remove(player);
}
static class CDKInput {
String type;
String context;
long time;
}
}
File diff suppressed because it is too large Load Diff
+36 -144
View File
@@ -15,7 +15,6 @@ public class ChatInputManager {
SET_EMAIL,
SET_EMAIL_VERIFY,
ADMIN_AUTH,
SH_ADMIN_AUTH, // ★ 问题2:二手管理面板密码(ShopManager.onPublishChat 消费)
ADMIN_SET_POINTS,
ADMIN_SET_PWD,
ADMIN_DELETE_CONFIRM,
@@ -37,11 +36,8 @@ public class ChatInputManager {
TICKET_ADMIN_TYPE,
TICKET_ADMIN_TITLE,
TICKET_ADMIN_DESC,
TICKET_ADMIN_PROVIDER,
BACK_CHECK_ECONOMY_CONFIRM,
USER_MGMT_SEARCH,
}
TICKET_ADMIN_PROVIDER
}
public static class PlayerState {
public InputType type = InputType.NONE;
@@ -52,7 +48,6 @@ public class ChatInputManager {
public int ticketId = 0;
public int smtpStep = 0;
public int scoreValue = 0;
}
private final Map<String, PlayerState> states =
@@ -68,11 +63,6 @@ public class ChatInputManager {
public void reset(Player p) {
states.remove(p.getName());
}
public boolean isInFlow(Player p) {
PlayerState state = states.get(p.getName());
return state != null
&& state.type != InputType.NONE;
}
public void handleInput(Player p, String msg,
Main mainPlugin) {
@@ -91,9 +81,9 @@ public class ChatInputManager {
name, "password_salt");
String hash =
PasswordUtils.hash(msg, salt);
// ★ 同时校验真实密码 + 临时密码(改密不受临时密码5分钟有效期限制)
String result = db.checkPasswordForChange(name, hash);
if ("main".equals(result)) {
boolean mainOk =
db.checkPassword(name, hash);
if (mainOk) {
state.type =
InputType.CHANGE_PWD_STEP2;
state.ticketTitle = "main";
@@ -101,7 +91,10 @@ public class ChatInputManager {
"§e请输入新密码:");
return;
}
if ("temp".equals(result)) {
boolean tempOk =
db.checkPasswordOrTemp(
name, hash);
if (tempOk) {
state.type =
InputType.CHANGE_PWD_STEP2;
state.ticketTitle = "temp";
@@ -145,26 +138,11 @@ public class ChatInputManager {
"password_hash", newHash);
db.setField(name,
"password_salt", newSalt);
// ★ 改密成功:作废旧的临时密码
db.clearTempPassword(name);
// ★ 同步新密码到Web端(异步,不阻塞主线程)
final Main self = mainPlugin;
Bukkit.getScheduler().runTaskAsynchronously(self, () -> {
if (self.webManager != null) {
self.webManager.pushWebLoginCredentials();
}
});
mainPlugin
.getNeedsPasswordChange()
.remove(name);
p.sendMessage(config.msg(
"password_changed"));
// ★ 改密成功:actionbar 提示1分钟保存账号密码
mainPlugin.showCredentialSaveReminder(
p, name, msg);
if ("temp".equals(state.ticketTitle)) {
p.sendMessage("§7(本次是用临时密码改的,临时密码已作废)");
}
reset(p);
return;
}
@@ -177,21 +155,10 @@ public class ChatInputManager {
reset(p);
return;
}
String emailAddr = msg.trim();
// 邮箱后缀黑白名单校验
if (!config.isEmailSuffixAllowed(emailAddr)) {
String mode = config.getEmailValidationMode();
if ("白名单".equals(mode)) {
p.sendMessage("§c该邮箱后缀不在允许列表中");
} else if ("黑名单".equals(mode)) {
p.sendMessage("§c该邮箱后缀被禁止使用");
}
reset(p);
return;
}
String oldEmail = (String)
db.getField(p.getName(),
"email");
String emailAddr = msg.trim();
// 已绑定邮箱:验证登录密码
if (oldEmail != null
&& !oldEmail.isEmpty()) {
@@ -378,33 +345,14 @@ public class ChatInputManager {
case ADMIN_DELETE_CONFIRM: {
if (msg.equals(
state.targetPlayer)) {
// ★ 精准匹配:TEST 与 test 是两个人,只有名字完全相等才删
if (db.findExactUserName(state.targetPlayer) == null) {
String twin = db.findSimilarUserNameIgnoreCase(
state.targetPlayer);
p.sendMessage("§c账号 " + state.targetPlayer
+ " 不存在"
+ (twin != null
? "(仅存在大小写不同的账号 §e" + twin
+ "§c,已按精准匹配跳过)" : "")
+ ",未执行删除");
reset(p);
return;
}
int deleted = db.deleteUser(
db.deleteUser(
state.targetPlayer);
if (plugin.webManager != null && deleted > 0) {
plugin.webManager.deleteWebUser(state.targetPlayer);
}
p.sendMessage(deleted > 0
? "§a已删除 " + state.targetPlayer
: "§c删除失败:账号 "
+ state.targetPlayer + " 不存在");
// ★ getPlayerExact:只踢名字完全相同的在线玩家,
// 避免把 TEST 误当成 test 踢下线
Player tgt = Bukkit.getPlayerExact(
state.targetPlayer);
if (deleted > 0 && tgt != null
p.sendMessage("§a已删除 "
+ state.targetPlayer);
Player tgt =
Bukkit.getPlayer(
state.targetPlayer);
if (tgt != null
&& tgt.isOnline())
tgt.kickPlayer(
"§c账号已被删除");
@@ -594,33 +542,24 @@ public class ChatInputManager {
}
case BACK_CHECKIN: {
String result =
mainPlugin.getCheckIn()
.backCheckIn(p, msg);
if (result == null) {
// 等待选择(NEED_CONFIRM)
int cost = 20;
if (!mainPlugin.getDb()
.deductPoints(
p.getName(), cost)) {
p.sendMessage(
"§c积分不足,补签需 "
+ cost + " 积分");
reset(p);
return;
}
if (result.startsWith(
"NEED_CONFIRM:")) {
String[] parts =
result.split(":");
// 存储到Main的Map
mainPlugin.pendingBackCheck.put(
p.getName(),
parts[1] + ":" + parts[2]);
return;
}
if (result.startsWith("§c")) {
p.sendMessage(result);
} else {
p.sendMessage(result);
}
p.sendMessage(
"§a补签成功!扣除 "
+ cost + " 积分。"
+ "日期: " + msg);
reset(p);
return;
}
case INVITE_INPUT_CODE: {
String code = msg.trim();
String myName = p.getName();
@@ -640,18 +579,6 @@ public class ChatInputManager {
reset(p);
return;
}
// ★ 第八批(2026-10-12):邀请码一次性——已绑定过邀请人的
// 禁止重复使用(invited_by 持久落库,重启后依然拦截)
Object bound = db.getField(
myName, "invited_by");
if (bound != null
&& !bound.toString().isEmpty()) {
p.sendMessage(
"§c你已绑定过邀请人(" + bound
+ "),邀请码仅能使用一次");
reset(p);
return;
}
boolean found = false;
for (Map<String, Object> u :
db.getAllUsers()) {
@@ -663,52 +590,17 @@ public class ChatInputManager {
u.get("player_name");
db.setField(myName,
"invited_by", inv);
// ★ 第九批:绑定时间落库(供邀请GUI显示
// 「邀请成功时间+邀请人」)
db.setField(myName, "invited_at",
System.currentTimeMillis());
// ★ 第九批(配置懒更新):玩家绑定邀请码时
// 自动重载 规则.md,实时刷新奖励信息
// (不再依赖启动加载或定时热重载)
mainPlugin.getCommission().loadRules();
// ★ 第九批:绑定即计入邀请人「本月邀请」
// (修复旧逻辑在签到才计数导致恒 0 人)
mainPlugin.getInvite().onInviteeBind(
inv, myName);
// ★ 第八批(2026-10-12):绑定奖励改按
// 邀请好友赢债券/规则.md 发债券;
// 旧 addPoints(inv,50) 积分随提成规则体系废弃
// ★ 第九批:奖励单向改双向——邀请人 + 被邀请人
int bondGive = mainPlugin
.getCommission()
.payInviteBond(inv, myName);
int bondGet = mainPlugin
.getCommission()
.payInviteeBond(myName, inv);
String bMsg =
"§a邀请成功!邀请人: " + inv;
if (bondGet > 0) {
bMsg += "§7,你获得 §e" + bondGet
+ " §a债券";
}
p.sendMessage(bMsg);
db.addPoints(inv, 50);
p.sendMessage(
"§a邀请成功!邀请人: "
+ inv);
Player ip =
Bukkit.getPlayerExact(inv);
Bukkit.getPlayer(inv);
if (ip != null
&& ip.isOnline()) {
String extra = "";
if (bondGive > 0) {
extra = "§7,你获得 §e"
+ bondGive
+ " §a债券";
} else if (bondGive == 0) {
extra = "§7(今日邀请债券已达上限)";
}
&& ip.isOnline())
ip.sendMessage("§a"
+ myName
+ " 使用了您的邀请码"
+ extra);
}
+ " 使用了您的邀请码");
found = true;
break;
}
+114 -305
View File
@@ -1,305 +1,114 @@
package Sdf1_login;
import org.bukkit.entity.Player;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CheckInManager {
private final Main plugin;
public CheckInManager(Main plugin) {
this.plugin = plugin;
}
// ===== 今日是否已签到 =====
public boolean isCheckedInToday(
String name) {
String last = (String) plugin.getDb()
.getField(name,
"last_checkin_date");
String today = new SimpleDateFormat(
"yyyy-MM-dd")
.format(new Date());
return today.equals(last);
}
// ===== 签到 =====
// ===== 签到 =====
public String checkIn(Player p) {
String name = p.getName();
if (isCheckedInToday(name)) {
return plugin.getConfig2()
.msg("checkin_already");
}
Object streakObj = plugin.getDb()
.getField(name, "checkin_streak");
int streak = streakObj != null
? ((Number) streakObj).intValue()
: 0;
String lastDate = (String) plugin.getDb()
.getField(name, "last_checkin_date");
String today = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date());
if (lastDate != null && !lastDate.isEmpty()) {
try {
java.util.Date lastD =
new SimpleDateFormat("yyyy-MM-dd")
.parse(lastDate);
java.util.Date todayD =
new SimpleDateFormat("yyyy-MM-dd")
.parse(today);
long diff = todayD.getTime()
- lastD.getTime();
if (diff > 86400000L * 2) {
// 间隔超过2天,重置连续天数
streak = 1;
} else if (diff > 86400000L) {
// 间隔1-2天(连续签到),天数+1
streak++;
}
// 间隔<=1天(同一天),不改变连续天数
} catch (Exception ignored) {
}
} else {
// 首次签到
streak = 1;
}
double multi = 1.0;
if (streak >= 21) multi = 1.5;
else if (streak >= 14) multi = 1.3;
else if (streak >= 7) multi = 1.1;
int basePoints =
plugin.getConfig2().checkinPoints;
int points = (int) (basePoints * multi);
plugin.getDb().addPoints(name, points);
plugin.getDb().setField(name,
"checkin_streak", streak);
plugin.getDb().setField(name,
"last_checkin_date", today);
Object totalObj = plugin.getDb()
.getField(name, "total_checkin_days");
int total = totalObj != null
? ((Number) totalObj).intValue()
: 0;
plugin.getDb().setField(name,
"total_checkin_days", total + 1);
// ★ 债券盲盒奖励(6参数版,写入流水)★
int bondMin =
plugin.getConfig2().checkinBondMin;
int bondMax =
plugin.getConfig2().checkinBondMax;
if (bondMin <= 0) bondMin = 1;
if (bondMax < bondMin) bondMax = bondMin;
int bondReward = bondMin
+ new java.util.Random()
.nextInt(bondMax - bondMin + 1);
plugin.getBonds().addBonds(name, bondReward,
"daily_sign", "", "签到系统",
"每日签到连续" + streak + "天");
return plugin.getConfig2()
.msg("checkin_success")
.replace("{points}",
String.valueOf(points))
.replace("{streak}",
String.valueOf(streak))
.replace("{multi}",
String.valueOf(multi))
+ " §e+" + bondReward + "债券";
}
// ===== 获取连续天数 =====
public int getStreak(String name) {
Object val = plugin.getDb()
.getField(name,
"checkin_streak");
if (val instanceof Number) {
return ((Number) val)
.intValue();
}
return 0;
}
// 标准化日期
private String normalizeDate(String input) {
String s = input.trim().replace("/", "-");
if (s.matches("\\d{8}")) {
return s.substring(0, 4) + "-"
+ s.substring(4, 6) + "-"
+ s.substring(6, 8);
}
return s;
}
// ===== 补签入口 =====
public String backCheckIn(
Player p, String dateStr) {
String name = p.getName();
String normalized =
normalizeDate(dateStr);
// 严格日期验证
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat(
"yyyy-MM-dd");
sdf.setLenient(false);
java.util.Date target;
try {
target = sdf.parse(normalized);
} catch (Exception ex) {
return "§c无效日期: " + dateStr;
}
String reformat = sdf.format(target);
if (!reformat.equals(normalized)) {
return "§c无效日期: " + dateStr;
}
String today = sdf.format(new Date());
if (normalized.compareTo(today) >= 0) {
return "§c今天不需要补签";
}
String threeDaysAgo = getPastDate(3);
if (normalized.compareTo(
threeDaysAgo) < 0) {
return "§c只能补签3天内"
+ "(最多到 " + threeDaysAgo + ")";
}
Object val = plugin.getDb()
.getField(name, "backcheck_dates");
String existing = val != null
? val.toString() : "";
boolean alreadyBacked = false;
if (!existing.isEmpty()) {
for (String d : existing.split(",")) {
if (normalizeDate(d.trim())
.equals(normalized)) {
alreadyBacked = true;
break;
}
}
}
if (alreadyBacked) {
return "§c该日期已补签: " + normalized;
}
Object normalCheck =
plugin.getDb().getField(
name, "last_checkin_date");
String lastCheckin = normalCheck != null
? normalCheck.toString() : "";
if (lastCheckin.equals(normalized)) {
return "§c该日期已签到: " + normalized;
}
// ★ 补签消耗:3债券 + 10积分
// 积分不够时:用 9债券(3倍)代替 ★
int bondCost = 3;
int pointCost = 10;
int bondAltCost = 9; // 3倍债券替代
int myBonds = plugin.getBonds()
.getBonds(name);
Object ptsObj = plugin.getDb()
.getField(name, "points");
int myPoints = ptsObj != null
? ((Number) ptsObj).intValue()
: 0;
// 方案A:3债券 + 10积分
boolean canA = myBonds >= bondCost
&& myPoints >= pointCost;
// 方案B:9债券(积分不够时)
boolean canB = myBonds >= bondAltCost
&& myPoints < pointCost;
if (!canA && !canB) {
if (myPoints < pointCost
&& myBonds < bondAltCost) {
return "§c补签费用不足"
+ "(需3债券+10积分,"
+ "或9债券代替)"
+ " 当前: "
+ myBonds + "债券 "
+ myPoints + "积分";
}
if (myBonds < bondCost) {
return "§c债券不足(需"
+ bondCost + "枚)";
}
return "§c积分不足(需"
+ pointCost + "分)";
}
// 执行扣款
if (canA) {
// 方案A:3债券 + 10积分
plugin.getBonds().deductBonds(
name, bondCost,
"admin_deduct", "",
"补签系统", "补签扣款");
plugin.getDb().deductPoints(
name, pointCost);
} else {
// 方案B:9债券代替
plugin.getBonds().deductBonds(
name, bondAltCost,
"admin_deduct", "",
"补签系统", "补签扣款(债券替代)");
}
doBackCheckIn(p, normalized);
String costMsg = canA
? bondCost + "债券+" + pointCost + "积分"
: bondAltCost + "债券(替代)";
return "§a补签成功!日期: "
+ normalized
+ " §7消耗: " + costMsg;
}
// ===== 执行补签 =====
// ===== 执行补签 =====
public void doBackCheckIn(
Player p, String dateStr) {
String name = p.getName();
Object val = plugin.getDb()
.getField(name, "backcheck_dates");
String existing = val != null
? val.toString() : "";
String updated = existing.isEmpty()
? dateStr
: existing + "," + dateStr;
plugin.getDb().setField(name,
"backcheck_dates", updated);
int streak = getStreak(name);
plugin.getDb().setField(name,
"checkin_streak", streak + 1);
// ★ 补签不发放奖励,只记录
}
// ===== 获取N天前日期 =====
private String getPastDate(
int daysAgo) {
Calendar cal =
Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH,
-daysAgo);
return new SimpleDateFormat(
"yyyy-MM-dd")
.format(cal.getTime());
}
}
package Sdf1_login;
import org.bukkit.entity.Player;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CheckInManager {
private final Main plugin;
public CheckInManager(Main plugin) {
this.plugin = plugin;
}
public boolean isCheckedInToday(String name) {
String last = (String) plugin.getDb()
.getField(name, "last_checkin_date");
String today = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date());
return today.equals(last);
}
public String checkIn(Player p) {
String name = p.getName();
if (isCheckedInToday(name)) {
return plugin.getConfig2()
.msg("checkin_already");
}
Object streakObj = plugin.getDb()
.getField(name, "checkin_streak");
int streak = streakObj != null
? ((Number) streakObj).intValue() : 0;
String lastDate = (String) plugin.getDb()
.getField(name, "last_checkin_date");
String today = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date());
if (lastDate != null && !lastDate.isEmpty()) {
try {
java.util.Date lastD = new SimpleDateFormat(
"yyyy-MM-dd").parse(lastDate);
java.util.Date todayD = new SimpleDateFormat(
"yyyy-MM-dd").parse(today);
long diff = todayD.getTime() - lastD.getTime();
if (diff > 86400000L * 2) {
streak = 0;
} else if (diff > 86400000L) {
streak++;
}
} catch (Exception ignored) {
}
}
if (streak == 0) streak = 1;
else streak++;
double multi = 1.0;
if (streak >= 21) multi = 1.5;
else if (streak >= 14) multi = 1.3;
else if (streak >= 7) multi = 1.1;
int points = (int) (1 * multi);
plugin.getDb().addPoints(name, points);
plugin.getDb().setField(
name, "checkin_streak", streak);
plugin.getDb().setField(
name, "last_checkin_date", today);
Object totalObj = plugin.getDb()
.getField(name, "total_checkin_days");
int total = totalObj != null
? ((Number) totalObj).intValue() : 0;
plugin.getDb().setField(
name, "total_checkin_days", total + 1);
return plugin.getConfig2()
.msg("checkin_success")
.replace("{points}",
String.valueOf(points))
.replace("{streak}",
String.valueOf(streak))
.replace("{multi}",
String.valueOf(multi));
}
public String backCheckIn(Player p, String dateStr) {
String name = p.getName();
if (!plugin.getDb().deductPoints(name, 10)) {
return plugin.getConfig2()
.msg("checkin_already");
}
try {
java.util.Date target = new SimpleDateFormat(
"yyyy-MM-dd").parse(dateStr);
java.util.Date now = new SimpleDateFormat(
"yyyy-MM-dd").parse(
new SimpleDateFormat("yyyy-MM-dd")
.format(new Date()));
long diff = now.getTime() - target.getTime();
if (diff < 0 || diff > 3 * 86400000L) {
plugin.getDb().addPoints(name, 10);
return plugin.getConfig2()
.msg("checkin_already");
}
plugin.getDb().addPoints(name, 1);
return "§a补签成功!日期: " + dateStr;
} catch (Exception e) {
plugin.getDb().addPoints(name, 10);
return "§c日期格式错误,请用 yyyy-MM-dd";
}
}
}
File diff suppressed because it is too large Load Diff
+164 -249
View File
@@ -1,44 +1,18 @@
package Sdf1_login;
import org.bukkit.entity.Player;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 邀请好友赢债券奖励(配置:邀请好友赢债券/规则.md)。
*
* <p>★ 2026-10-12 第八批(用户决策):旧「提成规则.txt」体系整体废弃,
* 奖励改由新 md 规则控制,绑定邀请码成功时立即结算债券。</p>
*
* <p>★ 2026-10-12 第九批(用户需求)三点改造:
* ① 解析键改用新 md 4 键(旧「单次邀请奖励上限」→「邀请人单次奖励」),
* 新增「被邀请人单次奖励」「单日邀请翻倍额度」;
* ② 奖励单向改<b>双向</b>——payInviteBond 给邀请人、payInviteeBond 给被邀请人;
* 翻倍额度作用于邀请人(每邀请 X 人,奖金翻 Y 倍);
* ③ 支持<b>懒更新</b>——玩家绑定邀请码时调用 loadRules() 实时重载规则,
* 不再依赖启动时一次性加载或定时热重载。</p>
*/
public class CommissionManager {
private final Main main;
private final Logger logger;
/** 邀请人单次奖励(债券数,绑定成功立即结算) */
private volatile int perInviteReward = 10;
/** 被邀请人单次奖励(债券数,绑定成功立即结算) */
private volatile int perInviteeReward = 5;
/** 单日邀请奖励上限(债券数,自然日重置,仅针对邀请人) */
private volatile int dailyInviteCap = 100;
/** 单日邀请翻倍额度:每邀请 X 人(>0 生效,0=关闭翻倍) */
private volatile int doubleEveryX = 0;
/** 单日邀请翻倍额度:奖金翻 Y 倍(翻 Y 倍 = 每满 X 人基数加 Y 倍) */
private volatile int doubleByY = 0;
private final List<double[]> rules =
new ArrayList<>();
public CommissionManager(Main main) {
this.main = main;
@@ -46,259 +20,200 @@ public class CommissionManager {
loadRules();
}
/**
* 重载规则(★ 第九批:绑定邀请码时懒调用,实时刷新奖励信息)。
*/
public void loadRules() {
// ★ 代码层面删除旧提成规则.txt(手删会被再次释放,故写文件
// 逻辑已移除,这里负责清理存量文件)
File legacy = new File(main.getDataFolder(),
rules.clear();
File f = new File(
main.getDataFolder(),
"提成规则.txt");
if (legacy.exists() && legacy.delete()) {
logger.info("[Commission] 已删除旧版 提成规则.txt"
+ "(改由 邀请好友赢债券/规则.md 控制)");
}
File f = new File(main.getDataFolder(),
"邀请好友赢债券/规则.md");
if (!f.exists()) {
try {
main.saveResource(
"邀请好友赢债券/规则.md", false);
} catch (Exception e) {
logger.warning("[Commission] 规则文件释放失败: "
+ e.getMessage());
}
writeDefault(f);
}
if (!f.exists()) {
logger.warning("[Commission] 规则文件缺失,使用默认值"
+ " 邀请人=" + perInviteReward
+ " 被邀请人=" + perInviteeReward
+ " 单日=" + dailyInviteCap);
return;
}
// ★ 安全交换(2026-10-13):jar 模板多出的配置行补进原文件,
// 说明文本与用户改过的值原样保留(旧菜新菜一起端上桌)
java.util.List<String> inviteTpl =
ConfigManager.readJarResourceLines(
main.getResource("邀请好友赢债券/规则.md"));
if (inviteTpl != null) {
main.getConfig2().safeUpgradeDoc(f, inviteTpl, "邀请债券规则");
}
boolean inCfg = false;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(f),
StandardCharsets.UTF_8))) {
try (BufferedReader br =
new BufferedReader(
new InputStreamReader(
new FileInputStream(f),
StandardCharsets
.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
String t = line.trim();
if (t.startsWith("##") && t.contains("配置区")
&& t.contains("开始")) {
inCfg = true;
line = line.trim();
if (line.isEmpty()
|| line.startsWith("#"))
continue;
}
if (t.startsWith("##") && t.contains("配置区")
&& t.contains("结束")) {
break;
}
if (!inCfg || !t.startsWith("|")) continue;
String[] cols = t.split("\\|", -1);
if (cols.length < 4) continue; // | 键 | 解释 | 值 |
String key = cols[1].trim();
String val = cols[cols.length - 2].trim()
.replace("`", "");
// ★ 第九批:适配新 md 4 键
if ("邀请人单次奖励".equals(key)) {
perInviteReward = parseIntSafe(val,
perInviteReward);
} else if ("被邀请人单次奖励".equals(key)) {
perInviteeReward = parseIntSafe(val,
perInviteeReward);
} else if ("单日邀请奖励上限".equals(key)) {
dailyInviteCap = parseIntSafe(val,
dailyInviteCap);
} else if ("单日邀请翻倍额度".equals(key)) {
parseDoubleRule(val);
// 格式: 邀请人数:提成百分比
// 如 "5:15" = 邀请5人提成15%
String[] parts =
line.split(":");
if (parts.length >= 2) {
try {
int count = Integer.parseInt(
parts[0].trim());
double rate = Double
.parseDouble(
parts[1]
.trim()) / 100.0;
rules.add(new double[]{
count, rate});
} catch (Exception ignored) {
}
}
}
logger.info("[Commission] 邀请债券规则: 邀请人="
+ perInviteReward
+ " 被邀请人=" + perInviteeReward
+ " 单日=" + dailyInviteCap
+ " 翻倍=" + (doubleEveryX > 0
? ("每" + doubleEveryX + "人翻"
+ doubleByY + "倍")
: "关闭"));
// 按人数排序(从大到小)
rules.sort((a, b) ->
Double.compare(b[0], a[0]));
logger.info(
"[Commission] 加载 "
+ rules.size() + " 条提成规则");
} catch (Exception e) {
logger.warning("[Commission] 规则解析失败: "
+ e.getMessage());
logger.warning(
"[Commission] 加载失败: "
+ e.getMessage());
}
}
/** 解析「每邀请X人,奖金翻Y倍」格式 */
private void parseDoubleRule(String v) {
// 默认关闭
doubleEveryX = 0;
doubleByY = 0;
if (v == null) return;
Matcher m = Pattern.compile(
"每邀请\\s*(\\d+)\\s*人\\s*[,,]\\s*奖金翻\\s*(\\d+)\\s*倍")
.matcher(v);
if (m.find()) {
doubleEveryX = parseIntSafe(m.group(1), 0);
doubleByY = parseIntSafe(m.group(2), 0);
} else {
logger.warning("[Commission] 翻倍额度格式无法解析: "
+ v + "(示例:每邀请2人,奖金翻1倍)");
private void writeDefault(File f) {
try (PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(f),
StandardCharsets.UTF_8))) {
pw.println("# 邀请提成规则");
pw.println("# 格式: 邀请人数:提成百分比");
pw.println("# 邀请10人提成20%");
pw.println("10:20");
pw.println("# 邀请5人提成15%");
pw.println("5:15");
pw.println("# 邀请1人提成10%");
pw.println("1:10");
} catch (IOException ignored) {
}
}
private static int parseIntSafe(String s, int def) {
try {
return (int) Double.parseDouble(s.trim());
} catch (Exception e) {
return def;
}
}
/** 邀请人单次奖励(债券) */
public int getPerInviteReward() {
return perInviteReward;
}
/** 被邀请人单次奖励(债券) */
public int getPerInviteeReward() {
return perInviteeReward;
}
/** 单日邀请奖励上限(债券) */
public int getDailyInviteCap() {
return dailyInviteCap;
}
/**
* 邀请绑定成功 → 给<b>邀请人</b>发债券(★ 第九批:含翻倍额度)。
* 规则见 邀请好友赢债券/规则.md:每次按单次上限结算(每满 X 人翻 Y 倍),
* 当日累计不超单日上限。
*
* @param inviter 邀请人(收款方)
* @param invitee 被邀请人(绑定者)
* @return &gt;0 实发债券数;0 = 今日已达上限或规则为0;
* -1 = 异常/冻结未发
* 获取邀请人的提成比例
* 根据已邀请人数匹配最高规则
*/
public int payInviteBond(String inviter, String invitee) {
if (inviter == null || inviter.isEmpty()) return -1;
if (perInviteReward <= 0) return 0;
int used = inviteBondToday(inviter);
int room = dailyInviteCap - used;
if (room <= 0) {
logger.info("[Commission] " + inviter
+ " 今日邀请债券已达上限(" + dailyInviteCap + ")");
return 0;
public double getCommissionRate(
String inviter) {
int inviteCount = getInviteCount(
inviter);
for (double[] rule : rules) {
if (inviteCount >= (int) rule[0]) {
return rule[1];
}
}
// ★ 第九批:单日邀请翻倍额度——每邀请 X 人,奖金翻 Y 倍
// nToday = 今日已发放的邀请奖励笔数(≈已成功邀请人数)
// mult = 1 + (nToday / X) * Y(整数除法,每满 X 人加 Y 倍)
int nToday = inviteBondCountToday(inviter);
int mult = 1;
if (doubleEveryX > 0) {
mult = 1 + (nToday / doubleEveryX) * doubleByY;
if (mult < 1) mult = 1;
}
int base = perInviteReward * mult;
int give = Math.min(base, room);
int after = main.getBonds().addBonds(inviter, give,
"invite_reward", invitee, "system",
"邀请好友绑定奖励(" + invitee + ")");
if (after < 0) return -1; // 冻结期未入账
logger.info("[Commission] 邀请债券: " + inviter + " ← "
+ invitee + " | +" + give + "(基数"
+ perInviteReward + "×" + mult + ",今日累计 "
+ (used + give) + "/" + dailyInviteCap + ")");
return give;
return 0;
}
/**
* 邀请绑定成功 → 给<b>被邀请人</b>发债券(★ 第九批:双向奖励)。
* 被邀请人奖励为固定单次数额,不受单日上限约束(上限仅针对邀请人)。
*
* @param invitee 被邀请人(绑定者,收款方)
* @param inviter 邀请人(被邀请人的邀请来源)
* @return &gt;0 实发债券数;0 = 规则为0;-1 = 异常/冻结未发
* 获取邀请人数
*/
public int payInviteeBond(String invitee, String inviter) {
if (invitee == null || invitee.isEmpty()) return -1;
if (perInviteeReward <= 0) return 0;
// 用独立 type='invitee_reward',避免污染邀请人日上限统计
int after = main.getBonds().addBonds(invitee,
perInviteeReward, "invitee_reward", inviter,
"system",
"被邀请人绑定奖励(邀请人:" + inviter + ")");
if (after < 0) return -1; // 冻结期未入账
logger.info("[Commission] 被邀请人债券: " + invitee
+ " ← " + inviter + " | +" + perInviteeReward);
return perInviteeReward;
public int getInviteCount(
String inviter) {
try {
Object val =
main.getDb().getField(
inviter,
"monthly_invite_count");
if (val instanceof Number) {
return ((Number) val).intValue();
}
Object total =
main.getDb().getField(
inviter,
"total_invite_count");
if (total instanceof Number) {
return ((Number) total).intValue();
}
} catch (Exception ignored) {
}
return 0;
}
/** 今日 0 点起该玩家已发放的邀请债券总数(金额) */
private int inviteBondToday(String inviter) {
long dayStart = LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant().toEpochMilli();
try {
PreparedStatement ps = main.getBonds()
.getConnection().prepareStatement(
"SELECT COALESCE(SUM(amount),0) "
+ "FROM bond_transaction "
+ "WHERE player_name=? "
+ "AND type='invite_reward' "
+ "AND time>=?");
ps.setString(1, inviter);
ps.setLong(2, dayStart);
ResultSet rs = ps.executeQuery();
int v = rs.next() ? rs.getInt(1) : 0;
rs.close();
ps.close();
return v;
} catch (Exception e) {
logger.warning("[Commission] 查询当日邀请债券失败: "
+ e.getMessage());
return 0;
/**
* 发放提成
* 被邀请人获得奖励时,邀请人获得提成
*/
public void payCommission(
String invitee,
double originalAmount) {
// 查找邀请人
String inviter = getInviter(invitee);
if (inviter == null
|| inviter.isEmpty()) return;
double rate = getCommissionRate(
inviter);
if (rate <= 0) return;
double commission =
originalAmount * rate;
if (commission <= 0) return;
// 通过 Vault 发放
var rsp = main.getServer()
.getServicesManager()
.getRegistration(
net.milkbowl.vault
.economy.Economy.class);
if (rsp == null) return;
net.milkbowl.vault.economy.Economy econ =
rsp.getProvider();
if (econ == null) return;
econ.depositPlayer(inviter, commission);
// 通知邀请人
Player inviterP =
main.getServer()
.getPlayer(inviter);
if (inviterP != null
&& inviterP.isOnline()) {
inviterP.sendMessage(
"§a§l[邀请提成] §f"
+ invitee + " 完成任务,"
+ "你获得 §e"
+ String.format("%.2f",
commission)
+ " §f游戏币提成 ("
+ (int)(rate * 100) + "%)");
}
logger.info(
"[Commission] 提成: "
+ inviter + " ← "
+ invitee + " | "
+ String.format("%.2f",
originalAmount)
+ " × "
+ (int)(rate * 100) + "% = "
+ String.format("%.2f",
commission));
}
/** 今日 0 点起该玩家已成功邀请人数(发奖笔数,用于翻倍档位) */
private int inviteBondCountToday(String inviter) {
long dayStart = LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant().toEpochMilli();
/**
* 获取邀请人
*/
private String getInviter(String player) {
try {
PreparedStatement ps = main.getBonds()
.getConnection().prepareStatement(
"SELECT COUNT(*) "
+ "FROM bond_transaction "
+ "WHERE player_name=? "
+ "AND type='invite_reward' "
+ "AND time>=?");
ps.setString(1, inviter);
ps.setLong(2, dayStart);
ResultSet rs = ps.executeQuery();
int v = rs.next() ? rs.getInt(1) : 0;
rs.close();
ps.close();
return v;
} catch (Exception e) {
logger.warning("[Commission] 查询当日邀请人数失败: "
+ e.getMessage());
return 0;
Object val =
main.getDb().getField(
player,
"invited_by");
if (val != null
&& !val.toString()
.isEmpty()) {
return val.toString();
}
} catch (Exception ignored) {
}
return null;
}
/**
* 判断金额是否包含经济内容
*/
public boolean hasEconomyContent(String text) {
public boolean hasEconomyContent(
String text) {
String t = text.toLowerCase();
return t.contains("游戏币")
|| t.contains("金币")
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-653
View File
@@ -1,653 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class CypayCommand
implements CommandExecutor, TabCompleter {
private final Main plugin;
private static final SimpleDateFormat SDF =
new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public CypayCommand(Main plugin) {
this.plugin = plugin;
}
private boolean hasAdminPerm(CommandSender s) {
if (s.isOp()) return true;
if (!(s instanceof Player)) return true;
Player p = (Player) s;
String tag =
plugin.getConfig2().adminTag;
return !tag.isEmpty()
&& p.getScoreboardTags().contains(tag);
}
private int parseAmount(String s) {
return Integer.parseInt(
s.trim().replaceAll("[+]", ""));
}
private List<String> filter(
List<String> list, String prefix) {
String low = prefix.toLowerCase();
return list.stream()
.filter(x -> x.toLowerCase()
.startsWith(low))
.collect(Collectors.toList());
}
@Override
public boolean onCommand(CommandSender sender,
Command cmd,
String label,
String[] args) {
// ===== /cypay — 查自己 =====
if (args.length == 0) {
String name = sender instanceof Player
? sender.getName() : "Console";
int bonds =
plugin.getBonds().getBonds(name);
String status = plugin.getBonds()
.getAccountStatus(name);
sender.sendMessage(
"§e§l[债券] §f" + name
+ " 余额: §a" + bonds);
sender.sendMessage(
"§e§l[债券] §f状态: "
+ freezeText(name));
return true;
}
// ===== /cypay import =====
/* if (args.length == 2
&& "import".equalsIgnoreCase(
args[0])) {
if (!hasAdminPerm(sender)) {
sender.sendMessage("§c权限不足");
return true;
}
String file = args[1];
if (!file.endsWith(".txt"))
file += ".txt";
int result = plugin.getCDK()
.importFromFile(file);
if (result == -1)
sender.sendMessage("§c文件不存在: "
+ file);
else
sender.sendMessage("§a导入完成: "
+ result + " 条");
return true;
}*/
// ===== /cypay freeze <玩家> [时长] =====
// ★ 2026-10-04 改版:时长可选,硬编封顶 30 天,
// 不传时长 = 永久冻结;支持 1分钟/壹分钟/one min/时间戳
if (args.length >= 2
&& "freeze".equalsIgnoreCase(
args[0])) {
if (!hasAdminPerm(sender)) {
sender.sendMessage("§c权限不足");
return true;
}
String target = args[1];
long until = 0L; // 0 = 永久冻结
String durNote = "永久";
if (args.length >= 3) {
String durStr = String.join(" ",
Arrays.copyOfRange(args, 2,
args.length));
long expireMs;
try {
expireMs = DurationParser
.parseToExpireMs(durStr);
} catch (IllegalArgumentException ex) {
sender.sendMessage("§c时长格式无法解析: "
+ ex.getMessage());
sender.sendMessage("§7可用写法: 30分钟 / "
+ "壹小时 / one min / 7天 / "
+ "253402271999(时间戳)");
sender.sendMessage("§7不传时长 = 永久冻结,"
+ "时长封顶 30 天");
return true;
}
long now = System.currentTimeMillis();
long MAX_MS =
30L * 24 * 3600 * 1000L; // 封顶30天
if (expireMs <= now) {
// 过期/为零的时间戳(如 0000000000)-> 永久
sender.sendMessage("§7该时间点已过期,"
+ "按 §c永久冻结 §7处理");
until = 0L;
} else if (expireMs - now > MAX_MS) {
until = now + MAX_MS;
sender.sendMessage("§7时长超过 30 天,"
+ "已按封顶 §e30天 §7处理");
} else {
until = expireMs;
}
durNote = until <= 0L ? "永久"
: "至 " + DurationParser
.formatExpire(until);
}
plugin.getBonds().freezeAccount(target, until);
sender.sendMessage("§a已冻结 " + target
+ " 的债券账户(" + durNote + ")");
Player tp = plugin.getServer()
.getPlayerExact(target);
if (tp != null)
tp.sendMessage(
"§c§l[系统] 你的债券账户已被管理员冻结"
+ (until <= 0L ? ""
: ",到期时间: "
+ DurationParser
.formatExpire(until)));
return true;
}
// ===== /cypay unfreeze =====
if (args.length == 2
&& "unfreeze".equalsIgnoreCase(
args[0])) {
if (!hasAdminPerm(sender)) {
sender.sendMessage("§c权限不足");
return true;
}
String target = args[1];
if (!plugin.getBonds()
.isFrozen(target)) {
sender.sendMessage("§c" + target
+ " 未被冻结");
return true;
}
plugin.getBonds().unfreezeAccount(target);
sender.sendMessage("§a已解冻 " + target
+ " 的债券账户");
Player tp = plugin.getServer()
.getPlayerExact(target);
if (tp != null)
tp.sendMessage(
"§a§l[系统] 你的债券账户"
+ "已被解冻");
return true;
}
// ===== /cypay water [days] =====
if (args.length >= 2
&& "water".equalsIgnoreCase(
args[0])) {
if (!hasAdminPerm(sender)) {
sender.sendMessage("§c权限不足");
return true;
}
String target = args[1];
int days = 7;
if (args.length >= 3) {
try {
days = Integer.parseInt(args[2]);
} catch (NumberFormatException ignored) {
}
}
days = Math.min(days,
BondManager.ADMIN_MAX_WATER_DAYS);
if (days <= 0) days = 1;
List<Map<String, Object>> txs =
plugin.getBonds()
.getTransactions(
target, days);
sender.sendMessage(
"§e§l===== " + target
+ " 流水记录 (近"
+ days + "天) =====");
sender.sendMessage("§f当前余额: §a"
+ plugin.getBonds()
.getBonds(target)
+ " §f状态: "
+ freezeText(target));
if (txs.isEmpty()) {
sender.sendMessage("§7 (暂无记录)");
} else {
for (Map<String, Object> tx : txs) {
sender.sendMessage(
formatTxLine(tx));
}
}
sender.sendMessage(
"§e§l=========================="
+ "==========");
return true;
}
// ===== /cypay printer [player] =====
if ("printer".equalsIgnoreCase(args[0])) {
if (!hasAdminPerm(sender)
&& !(sender instanceof Player)
== false) {
// 控制台也可以用
if (!(sender instanceof Player))
; // 放行
else if (!hasAdminPerm(sender)) {
sender.sendMessage("§c权限不足");
return true;
}
}
if (args.length == 1) {
// 打印全服
sender.sendMessage(
"§e正在导出全服流水...");
plugin.getBonds(); // 确保实例就绪
if (plugin.getBondPrinter() != null) {
plugin.getBondPrinter()
.printAll(sender);
} else {
sender.sendMessage("§cPrinter未初始化");
}
return true;
}
if (args.length == 2) {
// 打印指定玩家
String target = args[1];
sender.sendMessage("§e正在导出 "
+ target + " 的流水...");
if (plugin.getBondPrinter() != null) {
plugin.getBondPrinter()
.printPlayer(target, sender);
} else {
sender.sendMessage("§cPrinter未初始化");
}
return true;
}
}
// ===== /cypay give/remove =====
if (args.length >= 3 && args.length <= 4) {
String action = args[0].toLowerCase();
if ("give".equals(action)
|| "remove".equals(action)) {
if (!hasAdminPerm(sender)) {
sender.sendMessage("§c权限不足");
return true;
}
String target = args[1];
try {
int amount =
parseAmount(args[2]);
if (amount <= 0) {
sender.sendMessage(
"§c金额必须大于0");
return true;
}
String txType =
"give".equals(action)
? BondManager
.TX_ADMIN_GIVE
: BondManager
.TX_ADMIN_DEDUCT;
String opName =
sender instanceof Player
? sender.getName()
: "Console";
// 自定义理由(可选)
String reason = args.length == 4
? args[3]
: ("give".equals(action)
? "管理员发放"
: "管理员扣除");
if ("give".equals(action)) {
// ★ 冻结期豁免:管理员手动 give 允许动账
plugin.getBonds().addBondsAdmin(
target, amount,
txType, "",
opName, reason);
sender.sendMessage(
"§a已给 " + target
+ " " + amount
+ " 债券");
Player tp = plugin.getServer()
.getPlayerExact(target);
if (tp != null)
tp.sendMessage(
"§a管理员给了你 "
+ amount
+ " 债券");
} else {
// ★ 冻结期豁免:管理员手动 remove
// 允许动账(deductBondsAdmin 不查冻结)
if (plugin.getBonds()
.deductBondsAdmin(target,
amount,
txType, "",
opName,
reason)) {
sender.sendMessage(
"§a已扣除 " + target
+ " " + amount
+ " 债券");
Player tp = plugin
.getServer()
.getPlayerExact(
target);
if (tp != null)
tp.sendMessage(
"§c管理员扣除了"
+ "你的 "
+ amount
+ " 债券");
} else {
sender.sendMessage(
"§c" + target
+ " 债券不足");
}
}
} catch (NumberFormatException e) {
sender.sendMessage(
"§c金额格式错误");
}
return true;
}
}
// ===== /cypay <player> <amount> — 仅玩家转账 =====
if (args.length == 2) {
try {
int amount = parseAmount(args[1]);
if (amount <= 0) {
sender.sendMessage(
"§c金额必须大于0");
return true;
}
// ★ 控制台禁止转账
if (!(sender instanceof Player)) {
sender.sendMessage(
"§c控制台不能转账,请使用 "
+ "/cypay give <玩家> <金额>");
return true;
}
Player p = (Player) sender;
String target = args[0];
BondManager.TransferResult r =
plugin.getBonds().transfer(
p.getName(),
target, amount);
if (r.success) {
p.sendMessage("§e§l[债券转账] §f向 §a"
+ target + " §f转出 §c"
+ amount + " §f枚债券");
Player tp = plugin.getServer()
.getPlayerExact(target);
if (tp != null)
tp.sendMessage("§e§l[债券转账] §f收到 §a"
+ p.getName()
+ " §f转入 §a"
+ amount + " §f枚债券");
} else {
p.sendMessage("§c" + r.message
+ ",当前: "
+ plugin.getBonds()
.getBonds(p.getName()));
}
return true;
} catch (NumberFormatException ignored) {
}
}
// ===== /cypay <player> — 查指定玩家 =====
if (args.length == 1) {
String target = args[0];
// ★ 验证玩家在 login.db 中存在 ★
if (!plugin.getDb().userExists(target)) {
sender.sendMessage("§c玩家 " + target
+ " 不存在于服务器");
return true;
}
// String target = args[0];
if (hasAdminPerm(sender)) {
int bonds = plugin.getBonds()
.getBonds(target);
String status = plugin.getBonds()
.getAccountStatus(target);
sender.sendMessage(
"§e§l[债券] §f" + target
+ " 余额: §a"
+ bonds);
sender.sendMessage(
"§e§l[债券] §f状态: "
+ freezeText(target));
} else {
int bonds = plugin.getBonds()
.getBonds(
sender.getName());
sender.sendMessage(
"§e§l[债券] §f你的余额: §a"
+ bonds);
}
return true;
}
showHelp(sender);
return true;
}
// ===== 冻结状态文案(含到期时间) =====
/** 正常 / 冻结中(永久) / 冻结中(至 yyyy年M月d日 HH:mm) */
private String freezeText(String target) {
if (!plugin.getBonds().isFrozen(target))
return "§a正常";
long until = plugin.getBonds()
.getFreezeUntil(target);
if (until <= 0L) return "§c冻结中(永久)";
return "§c冻结中(至 "
+ DurationParser.formatExpire(until) + ")";
}
// ===== 流水行格式化 =====
private String formatTxLine(
Map<String, Object> tx) {
String type = (String) tx.get("type");
int amount = ((Number) tx.get("amount"))
.intValue();
String tgt = (String) tx.get("target_player");
String reason = (String) tx.get("reason");
int bal = ((Number) tx.get("balance_after"))
.intValue();
long time = ((Number) tx.get("time"))
.longValue();
boolean pos = amount > 0;
String sign = pos ? "+" : "";
String color = pos ? "§a" : "§c";
StringBuilder sb = new StringBuilder();
sb.append("§7[")
.append(SDF.format(new Date(time)))
.append("] ")
.append(formatTxType(type))
.append(" ")
.append(color).append(sign)
.append(amount).append("§7");
if (tgt != null && !tgt.isEmpty())
sb.append(" §e↔ ").append(tgt);
if (reason != null && !reason.isEmpty())
sb.append(" §7(").append(reason)
.append(")");
sb.append(" §7余额:§f").append(bal);
return sb.toString();
}
private String formatTxType(String type) {
if (type == null) return "§7未知";
switch (type) {
case BondManager.TX_ADMIN_GIVE:
return "§a管理员发放";
case BondManager.TX_ADMIN_DEDUCT:
return "§c管理员扣除";
case BondManager.TX_TRANSFER_OUT:
return "§c转出";
case BondManager.TX_TRANSFER_IN:
return "§a转入";
case BondManager.TX_REDEEM:
return "§aCDK兑换";
case BondManager.TX_SHOP_BUY:
return "§e商城购买";
case BondManager.TX_DAILY_SIGN:
return "§a签到奖励";
case BondManager.TX_FREEZE:
return "§c冻结";
case BondManager.TX_UNFREEZE:
return "§a解冻";
default:
return "§7" + type;
}
}
private void showHelp(CommandSender sender) {
sender.sendMessage("§e§l债券命令帮助:");
sender.sendMessage(
"§e/cypay §7- 查询自己余额");
sender.sendMessage(
"§e/cypay <玩家> §7- 查余额(管理员)");
sender.sendMessage(
"§e/cypay <玩家> <金额> §7- 转账");
if (hasAdminPerm(sender)) {
sender.sendMessage(
"§e/cypay give <玩家> <金额> [理由] §7- 给债券");
sender.sendMessage(
"§e/cypay remove <玩家> <金额> [理由] §7- 扣债券");
sender.sendMessage(
"§e/cypay import <文件> §7- 导入CDK");
sender.sendMessage(
"§e/cypay freeze <玩家> [时长] §7- 冻结"
+ "(不填=永久,封顶30天)");
sender.sendMessage(
"§e/cypay unfreeze <玩家> §7- 解冻");
sender.sendMessage(
"§e/cypay water <玩家> [天数] §7- 流水");
sender.sendMessage(
"§e/cypay printer §7- 导出全服流水xlsx");
sender.sendMessage(
"§e/cypay printer <玩家> §7- 导出指定玩家xlsx");
}
}
@Override
public List<String> onTabComplete(
CommandSender sender, Command command,
String label, String[] args) {
List<String> list = new ArrayList<>();
if (args.length == 1) {
String last = args[0].toLowerCase();
if (hasAdminPerm(sender)) {
list.add("give");
list.add("remove");
list.add("import");
list.add("freeze");
list.add("unfreeze");
list.add("water");
list.add("printer");
File cdkDir = new File(
plugin.getDataFolder(),
"cdk");
if (cdkDir.exists()) {
File[] files = cdkDir.listFiles(
(d, n) -> n
.endsWith(".txt"));
if (files != null)
for (File f : files)
list.add(f.getName());
}
}
for (Player o :
Bukkit.getOnlinePlayers())
list.add(o.getName());
return filter(list, last);
}
if (args.length == 2) {
String first = args[0].toLowerCase();
if ("give".equals(first)
|| "remove".equals(first)
|| "freeze".equals(first)
|| "unfreeze".equals(first)
|| "water".equals(first)) {
for (Player o :
Bukkit.getOnlinePlayers())
list.add(o.getName());
return filter(list,
args[1].toLowerCase());
}
list.add("10");
list.add("50");
list.add("100");
return filter(list,
args[1].toLowerCase());
}
if (args.length == 3) {
String first = args[0].toLowerCase();
if ("freeze".equals(first)) {
list.add("10分钟");
list.add("1小时");
list.add("one min");
list.add("7天");
list.add("30天");
return filter(list,
args[2].toLowerCase());
}
if ("give".equals(first)
|| "remove".equals(first)) {
list.add("10");
list.add("50");
list.add("100");
list.add("999");
return filter(list,
args[2].toLowerCase());
}
if ("water".equals(first)) {
list.add("1");
list.add("3");
list.add("7");
list.add("14");
return filter(list,
args[2].toLowerCase());
}
}
if (args.length == 4) {
String first = args[0].toLowerCase();
if ("give".equals(first)
|| "remove".equals(first)) {
list.add("管理员发放");
list.add("管理员扣除");
list.add("工单奖励");
list.add("活动奖励");
return filter(list,
args[3].toLowerCase());
}
}
return list;
}
}
File diff suppressed because it is too large Load Diff
-176
View File
@@ -1,176 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.scheduler.BukkitRunnable;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 死亡报告系统
* - 记录玩家死亡坐标(一次性,新死亡覆盖)
* - 死亡后发送包含坐标的消息
*/
public class DeathReport implements Listener {
private final Main plugin;
// 内存缓存: player_name → DeathData
private final ConcurrentHashMap<String, DeathData> deathReports = new ConcurrentHashMap<>();
public static class DeathData {
public final String playerName;
public String worldName;
public final double x, y, z;
public long deathTime;
public final UUID playerId;
DeathData(String playerName, UUID playerId, Location loc) {
this.playerName = playerName;
this.playerId = playerId;
this.worldName = loc.getWorld() != null ? loc.getWorld().getName() : "world";
this.x = loc.getX();
this.y = loc.getY();
this.z = loc.getZ();
this.deathTime = System.currentTimeMillis();
}
}
public DeathReport(Main plugin) {
this.plugin = plugin;
initTable();
loadAllFromDB();
}
// ==================== 事件监听 ====================
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getPlayer();
Location deathLoc = player.getLocation();
if (deathLoc == null) return;
DeathData data = new DeathData(player.getName(), player.getUniqueId(), deathLoc);
deathReports.put(player.getName(), data);
saveToDB(data);
// 发送死亡报告消息,带可点击的返回按钮
String timeStr = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(data.deathTime));
Component header = Component.text("§c✦ 你已死亡 ✦ ").append(
Component.text("世界: §f" + data.worldName + " §| §7坐标: §e" +
String.format("%.1f, %.1f, %.1f", data.x, data.y, data.z) + " §7时间: §f" + timeStr)
);
// "返回死亡地点" 按钮 - 通过 /back 命令
Component backButton = Component.text("§e[点击返回死亡地点] ")
.clickEvent(ClickEvent.runCommand("/back"))
.hoverEvent(HoverEvent.showText(Component.text("§7传送到你死亡的位置")));
player.sendMessage(header);
player.sendMessage(backButton);
}
// ==================== 查询/获取 ====================
/**
* 获取玩家的最新死亡坐标(如果有的话)
*/
public DeathData getDeathReport(String playerName) {
return deathReports.get(playerName);
}
/**
* 清除玩家的死亡报告
*/
public void clearDeathReport(String playerName) {
deathReports.remove(playerName);
}
// ==================== 数据库操作 ====================
private void loadAllFromDB() {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return;
PreparedStatement ps = conn.prepareStatement(
"SELECT player_name, player_uuid, world, x, y, z, death_time FROM death_reports");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
DeathData data = new DeathData(
rs.getString("player_name"),
UUID.fromString(rs.getString("player_uuid")),
new Location(null, rs.getDouble("x"), rs.getDouble("y"), rs.getDouble("z"))
);
data.worldName = rs.getString("world");
data.deathTime = rs.getLong("death_time");
deathReports.put(data.playerName, data);
}
rs.close();
ps.close();
} catch (SQLException e) {
// 表可能不存在,忽略(会在第一次死亡时自动创建)
}
}
private void saveToDB(DeathData data) {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return;
PreparedStatement ps = conn.prepareStatement(
"INSERT OR REPLACE INTO death_reports (player_name, player_uuid, world, x, y, z, death_time) VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, data.playerName);
ps.setString(2, data.playerId.toString());
ps.setString(3, data.worldName);
ps.setDouble(4, data.x);
ps.setDouble(5, data.y);
ps.setDouble(6, data.z);
ps.setLong(7, data.deathTime);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
plugin.getLogger().warning("[死亡报告] 保存失败: " + e.getMessage());
}
}
private void persistAll() {
for (DeathData data : deathReports.values()) {
saveToDB(data);
}
}
// ==================== 初始化 ====================
public void initTable() {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return;
java.sql.Statement st = conn.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS death_reports ("
+ "player_name TEXT PRIMARY KEY, "
+ "player_uuid TEXT NOT NULL, "
+ "world TEXT, "
+ "x REAL, y REAL, z REAL, "
+ "death_time LONG)");
st.close();
} catch (SQLException e) {
plugin.getLogger().warning("[死亡报告] 建表失败: " + e.getMessage());
}
}
}
@@ -1,338 +0,0 @@
package Sdf1_login;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 统一时长解析器(供 /tempban 与 /chat mute 共用)
*
* parseToExpireMs(String) 返回「绝对到期时间戳(毫秒)」,调用方自行校验最小/最大区间。
*
* 支持的写法:
* 1) 纯数字(Unix 秒时间戳): 253402271999
* 2) 中文日期(绝对): 2026年7月9日
* 3) ISO 日期(绝对): 2025-07-09
* 4) 相对时长(中文/英文单位): 1秒 / 1s / 1年 / 1年2月3天 / 2天12小时
* 5) 英文数字词(2026-10-04 新增,供 /cypay freeze 用):
* one min / two hours / twenty days / twenty one minutes
*
* <p>注意:纯数字仍按「Unix 秒时间戳」处理(如 0000000000);
* 过期时间戳由调用方自行判定(/cypay freeze 视为永久冻结)。
*
* 解析规则优先级:纯数字 → 时间戳;含「年/月/日」且为完整日期格式 → 绝对日期;
* 否则按「数字+单位」逐段累加为相对时长。
*/
public class DurationParser {
private static final Map<String, Long> UNIT_MS = new HashMap<>();
static {
// 秒
UNIT_MS.put("秒", 1000L);
UNIT_MS.put("秒钟", 1000L);
UNIT_MS.put("s", 1000L);
UNIT_MS.put("sec", 1000L);
// 分
UNIT_MS.put("分", 60000L);
UNIT_MS.put("分钟", 60000L);
UNIT_MS.put("mins", 60000L);
UNIT_MS.put("min", 60000L);
UNIT_MS.put("m", 60000L);
// 时
UNIT_MS.put("时", 3600000L);
UNIT_MS.put("小时", 3600000L);
UNIT_MS.put("钟头", 3600000L);
UNIT_MS.put("h", 3600000L);
UNIT_MS.put("hr", 3600000L);
// 天
UNIT_MS.put("天", 86400000L);
UNIT_MS.put("日", 86400000L);
UNIT_MS.put("d", 86400000L);
// 周
UNIT_MS.put("周", 604800000L);
UNIT_MS.put("星期", 604800000L);
UNIT_MS.put("礼拜", 604800000L);
UNIT_MS.put("w", 604800000L);
// 月(按30天近似)
UNIT_MS.put("个月", 2592000000L);
UNIT_MS.put("月", 2592000000L);
UNIT_MS.put("mo", 2592000000L);
// 年(按365天近似)
UNIT_MS.put("年", 31536000000L);
UNIT_MS.put("y", 31536000000L);
}
/** 解析为绝对到期毫秒;无法解析抛出 IllegalArgumentException */
public static long parseToExpireMs(String input)
throws IllegalArgumentException {
if (input == null || input.trim().isEmpty())
throw new IllegalArgumentException("时长为空");
String in = input.trim();
// ★ 0) 日期+时间(绝对):26-10-08 14:43 / 2026-10-08 14:43 / 2026年10月8日 14:43
// 必须在去空格之前解析:否则日期与时间粘连(26-10-08 14:43 → 26-10-0814:43)无法区分
long dt = parseDateTime(in);
if (dt >= 0) return dt;
// ★ 先把英文数字词换成阿拉伯数字(one min -> 1 min)
String s = normalizeEnglishNumber(in).replace(" ", "");
// 1) 纯数字 → Unix 秒时间戳
if (s.matches("\\d+")) {
long ts = Long.parseLong(s);
return ts * 1000L;
}
// 2) 中文日期 YYYY年M月D日
Matcher mc = Pattern.compile(
"(\\d{4})年(\\d{1,2})月(\\d{1,2})日").matcher(s);
if (mc.find()) {
return buildDateMillis(Integer.parseInt(mc.group(1)),
Integer.parseInt(mc.group(2)),
Integer.parseInt(mc.group(3)));
}
// 3) ISO 日期 YYYY-MM-DD / YYYY/MM/DD
Matcher mi = Pattern.compile(
"(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})").matcher(s);
if (mi.find()) {
return buildDateMillis(Integer.parseInt(mi.group(1)),
Integer.parseInt(mi.group(2)),
Integer.parseInt(mi.group(3)));
}
// 4) 相对时长(可多段组合)
long rel = parseRelative(s);
if (rel >= 0) {
return System.currentTimeMillis() + rel;
}
throw new IllegalArgumentException("无法解析时长: " + input);
}
/** 英文数字词 -> 阿拉伯数字(zero..ninety,支持 twenty one / twenty-one 连写) */
private static String normalizeEnglishNumber(String in) {
try {
String[] words = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};
StringBuilder alt = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i > 0) alt.append('|');
alt.append(words[i]);
}
Pattern p = Pattern.compile(
"(?i)\\b(" + alt + ")(?:[\\s-]+(" + alt + "))?\\b");
Matcher m = p.matcher(in);
StringBuffer sb = new StringBuffer();
while (m.find()) {
int v = enWordValue(m.group(1));
if (m.group(2) != null) v += enWordValue(m.group(2));
m.appendReplacement(sb, Matcher.quoteReplacement(
String.valueOf(v)));
}
m.appendTail(sb);
return sb.toString();
} catch (Exception e) {
return in; // 归一化失败就原样返回
}
}
private static int enWordValue(String w) {
switch (w.toLowerCase(java.util.Locale.ROOT)) {
case "zero": return 0;
case "one": return 1;
case "two": return 2;
case "three": return 3;
case "four": return 4;
case "five": return 5;
case "six": return 6;
case "seven": return 7;
case "eight": return 8;
case "nine": return 9;
case "ten": return 10;
case "eleven": return 11;
case "twelve": return 12;
case "thirteen": return 13;
case "fourteen": return 14;
case "fifteen": return 15;
case "sixteen": return 16;
case "seventeen": return 17;
case "eighteen": return 18;
case "nineteen": return 19;
case "twenty": return 20;
case "thirty": return 30;
case "forty": return 40;
case "fifty": return 50;
case "sixty": return 60;
case "seventy": return 70;
case "eighty": return 80;
case "ninety": return 90;
default: return 0;
}
}
// ===== 日期+时间绝对解析(2026-10-08 新增:支持 26-10-08 14:43 写法) =====
/** 中文日期+时间:2026年10月8日 14:43(“日”已界定日期边界,时间可紧贴) */
private static final Pattern DT_CN = Pattern.compile(
"(\\d{4})年(\\d{1,2})月(\\d{1,2})日(?:[ T" + UnicodeChars.IDEOGRAPHIC_SPACE_TEXT + "]+)?"
+ "(\\d{1,2}):(\\d{2})(?::(\\d{2}))?(?!\\d|[A-Za-z])");
/** 分隔日期+时间:26-10-08 14:43 / 2026-10-08 14:43 / 2026.10.08T14:43:00
* 两位年份按 20xx 解释;日期与时间之间必须有空格或 T,
* 防止 2026-1-8 14:43 被粘连误读成「日=81、时=4」 */
private static final Pattern DT_SEP = Pattern.compile(
"(?<!\\d)(\\d{4}|\\d{2})[-/.](\\d{1,2})[-/.](\\d{1,2})"
+ "[ T" + UnicodeChars.IDEOGRAPHIC_SPACE_TEXT + "]+(\\d{1,2}):(\\d{2})(?::(\\d{2}))?(?!\\d|[A-Za-z])");
/** 两位年份无时间:26-10-08
* lookbehind 防止吃掉 4 位年份的后半段(2026-07-09 不能被读成 07-09) */
private static final Pattern DT_YMD2 = Pattern.compile(
"(?<!\\d{2}[-/.])(\\d{2})[-/.](\\d{1,2})[-/.](\\d{1,2})(?!\\d|[A-Za-z])");
/** 解析「日期+时间」为绝对毫秒;认不出来返回 -1 交后续分支处理 */
private static long parseDateTime(String in) {
Matcher m = DT_CN.matcher(in);
if (m.find()) {
return buildDateTimeMillis(Integer.parseInt(m.group(1)),
Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)),
timeOf(m.group(4), m.group(5), m.group(6)));
}
m = DT_SEP.matcher(in);
if (m.find()) {
int year = Integer.parseInt(m.group(1));
if (year < 100) year += 2000; // 26 → 2026
return buildDateTimeMillis(year, Integer.parseInt(m.group(2)),
Integer.parseInt(m.group(3)),
timeOf(m.group(4), m.group(5), m.group(6)));
}
m = DT_YMD2.matcher(in);
if (m.find()) {
return buildDateTimeMillis(2000 + Integer.parseInt(m.group(1)),
Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)),
new int[]{-1, -1, -1});
}
return -1;
}
/** 解析 HH:mm[:ss];无时间(null)返回 {-1,-1,-1} 表示取 00:00:00 */
private static int[] timeOf(String h, String mi, String s) {
if (h == null) return new int[]{-1, -1, -1};
int H = Integer.parseInt(h), M = Integer.parseInt(mi);
int S = (s == null) ? 0 : Integer.parseInt(s);
if (H > 23 || M > 59 || S > 59)
throw new IllegalArgumentException("无效的时间: " + h + ":" + mi);
return new int[]{H, M, S};
}
/** 绝对日期+时间(t[0..2] 为 -1 表示 00:00:00) */
private static long buildDateTimeMillis(int y, int mo, int d, int[] t) {
if (mo < 1 || mo > 12 || d < 1 || d > 31)
throw new IllegalArgumentException("无效的日期: " + y + "-" + mo + "-" + d);
Calendar c = Calendar.getInstance();
c.set(y, mo - 1, d,
t[0] < 0 ? 0 : t[0],
t[1] < 0 ? 0 : t[1],
t[2] < 0 ? 0 : t[2]);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis();
}
private static long parseRelative(String s) {
// 按「数字 + 单位」逐段匹配并累加
StringBuilder units = new StringBuilder();
for (String u : UNIT_MS.keySet()) {
if (units.length() > 0) units.append("|");
// 转义,避免正则特殊字符
units.append(Pattern.quote(u));
}
Pattern p = Pattern.compile(
"([0-9零〇一二两三四五六七八九十百千万壹贰叁肆伍陆柒捌玖]+)(" + units + ")");
Matcher m = p.matcher(s);
long total = 0;
int found = 0;
while (m.find()) {
found++;
long num = parseNumber(m.group(1));
Long u = UNIT_MS.get(m.group(2));
if (u == null) continue;
total += num * u;
}
return found > 0 ? total : -1;
}
private static long buildDateMillis(int y, int mo, int d) {
Calendar c = Calendar.getInstance();
c.set(y, mo - 1, d, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis();
}
/** 解析数字(阿拉伯数字优先,其次中文数字 零-九/十百千万/两/壹贰叁…) */
private static long parseNumber(String s) {
if (s.matches("\\d+")) return Long.parseLong(s);
Map<Character, Long> cn = new HashMap<>();
cn.put('零', 0L); cn.put('〇', 0L);
cn.put('一', 1L); cn.put('壹', 1L);
cn.put('二', 2L); cn.put('贰', 2L); cn.put('两', 2L);
cn.put('三', 3L); cn.put('叁', 3L);
cn.put('四', 4L); cn.put('肆', 4L);
cn.put('五', 5L); cn.put('伍', 5L);
cn.put('六', 6L); cn.put('陆', 6L);
cn.put('七', 7L); cn.put('柒', 7L);
cn.put('八', 8L); cn.put('捌', 8L);
cn.put('九', 9L); cn.put('玖', 9L);
long section = 0, num = 0;
boolean hasNum = false;
for (char ch : s.toCharArray()) {
if (cn.containsKey(ch)) {
num = cn.get(ch);
hasNum = true;
} else if (ch == '十') {
if (!hasNum) num = 1;
section += num * 10; hasNum = false; num = 0;
} else if (ch == '百') {
if (!hasNum) num = 1;
section += num * 100; hasNum = false; num = 0;
} else if (ch == '千') {
if (!hasNum) num = 1;
section += num * 1000; hasNum = false; num = 0;
} else if (ch == '万') {
if (!hasNum) num = 1;
section = (section + num) * 10000; hasNum = false; num = 0;
} else {
num = 0;
}
}
return section + (hasNum ? num : 0);
}
/** ★ 第十一批(2026-10-12):秒/毫秒混合时间戳归一化为毫秒。
* login.db 的 register_time/last_login_time/invited_at 两种单位
* 混存(Java 本地注册写毫秒、PHP 同步拉回写秒),凡显示、比较、
* 回填前一律先过这里。幂等:已是毫秒的原样返回。
* 阈值 10^12:秒级时间戳到 33658 年才到 10^12,安全。 */
public static long toMs(long ts) {
return (ts > 0 && ts < 1000000000000L) ? ts * 1000L : ts;
}
/** 格式化绝对到期时间戳为「yyyy年M月d日 HH:mm」 */
public static String formatExpire(long ms) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(ms);
return String.format("%d年%d月%d日 %02d:%02d",
c.get(Calendar.YEAR),
c.get(Calendar.MONTH) + 1,
c.get(Calendar.DAY_OF_MONTH),
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE));
}
}
+275 -284
View File
@@ -1,284 +1,275 @@
package Sdf1_login;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Base64;
import java.util.logging.Logger;
public class EmailManager {
private final ConfigManager config;
private final Logger logger;
public EmailManager(ConfigManager config) {
this.config = config;
this.logger = Logger.getLogger("Sdf1_login");
}
public boolean isConfigured() {
String host = config.getSmtp("smtp地址");
String user = config.getSmtp("smtp账号");
String pass = config.getSmtp("smtp密码");
return host != null && !host.isEmpty()
&& user != null && !user.isEmpty()
&& pass != null && !pass.isEmpty();
}
public boolean sendVerifyCode(String to,
String code) {
if (!isConfigured()) {
logger.warning(
"[Sdf1_login] SMTP未配置,"
+ "无法发送验证码");
return false;
}
logger.info("[Sdf1_login] 发送验证码到 " + to);
return sendEmailSync(to,
"[Sdf1_login] 验证码",
"您的验证码: " + code
+ "\n5分钟内有效。\n"
+ "如非本人操作请忽略。");
}
public boolean sendTempPassword(String to,
String player, String tempPwd) {
if (!isConfigured()) {
logger.warning(
"[Sdf1_login] SMTP未配置");
return false;
}
return sendEmailSync(to,
"[Sdf1_login] 临时密码",
"玩家 " + player
+ " 的临时密码: " + tempPwd
+ "\n请尽快登录并修改密码!");
}
public boolean sendBody(String to, String subject, String body) {
if (!isConfigured()) {
logger.warning("[Sdf1_login] SMTP未配置");
return false;
}
return sendEmailSync(to, subject, body);
}
private boolean sendEmailSync(String to,
String subject, String body) {
final boolean[] result = {false};
Thread t = new Thread(() -> {
try {
result[0] = sendEmail(
to, subject, body);
} catch (Exception e) {
logger.severe(
"[Sdf1_login] 邮件线程异常: "
+ e.getMessage());
}
}, "Sdf1_login-SMTP");
t.setDaemon(true);
t.start();
try {
t.join(15000);
} catch (InterruptedException ignored) {
}
if (t.isAlive()) {
t.interrupt();
logger.severe(
"[Sdf1_login] SMTP超时(15秒)");
return false;
}
return result[0];
}
private boolean sendEmail(String to,
String subject, String body) {
String host = config.getSmtp("smtp地址");
String portStr = config.getSmtp("smtp端口");
String user = config.getSmtp("smtp账号");
String pass = config.getSmtp("smtp密码");
String fromName = config.getSmtp(
"发件人名称");
int port;
try {
port = Integer.parseInt(portStr);
} catch (Exception e) {
port = 465;
}
try {
String encSubject = "=?UTF-8?B?"
+ Base64.getEncoder()
.encodeToString(
subject.getBytes("UTF-8"))
+ "?=";
String encBody = Base64.getEncoder()
.encodeToString(
body.getBytes("UTF-8"));
if (port == 465) {
SSLSocketFactory factory =
(SSLSocketFactory)
SSLSocketFactory
.getDefault();
SSLSocket socket = (SSLSocket)
factory.createSocket(
host, port);
socket.setSoTimeout(10000);
doSmtp(socket, host, user, pass,
to, encSubject, encBody,
fromName);
socket.close();
} else {
Socket plainSocket =
new Socket(host, port);
plainSocket.setSoTimeout(10000);
BufferedReader preReader =
new BufferedReader(
new InputStreamReader(
plainSocket
.getInputStream(),
"UTF-8"));
PrintWriter preWriter =
new PrintWriter(
plainSocket
.getOutputStream(),
true);
checkResponse(preReader, "220");
sendLine(preWriter,
"EHLO " + host);
checkResponse(preReader, "250");
sendLine(preWriter, "STARTTLS");
checkResponse(preReader, "220");
SSLSocketFactory factory =
(SSLSocketFactory)
SSLSocketFactory
.getDefault();
SSLSocket sslSocket = (SSLSocket)
factory.createSocket(
plainSocket, host,
port, true);
sslSocket.startHandshake();
doSmtp(sslSocket, host, user, pass,
to, encSubject, encBody,
fromName);
sslSocket.close();
}
logger.info(
"[Sdf1_login] 邮件发送成功 -> "
+ to);
return true;
} catch (Exception e) {
logger.severe(
"[Sdf1_login] 邮件异常: "
+ e.getClass()
.getSimpleName()
+ ": " + e.getMessage());
if (e.getCause() != null) {
logger.severe(
"[Sdf1_login] 根因: "
+ e.getCause()
.getMessage());
}
return false;
}
}
private void doSmtp(SSLSocket socket,
String host, String user, String pass,
String to, String subject, String body,
String fromName) throws Exception {
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
socket.getInputStream(),
"UTF-8"));
OutputStream rawOut =
socket.getOutputStream();
PrintWriter writer =
new PrintWriter(
new java.io.BufferedOutputStream(
rawOut), true);
checkResponse(reader, "220");
sendLine(writer, "EHLO " + host);
checkResponse(reader, "250");
sendLine(writer, "AUTH LOGIN");
checkResponse(reader, "334");
sendLine(writer, Base64.getEncoder()
.encodeToString(
user.getBytes("UTF-8")));
checkResponse(reader, "334");
sendLine(writer, Base64.getEncoder()
.encodeToString(
pass.getBytes("UTF-8")));
checkResponse(reader, "235");
sendLine(writer,
"MAIL FROM:<" + user + ">");
checkResponse(reader, "250");
sendLine(writer,
"RCPT TO:<" + to + ">");
checkResponse(reader, "250");
sendLine(writer, "DATA");
checkResponse(reader, "354");
sendLine(writer,
"From: " + fromName
+ " <" + user + ">");
sendLine(writer,
"To: <" + to + ">");
sendLine(writer,
"Reply-To: <" + user + ">");
sendLine(writer,
"Subject: " + subject);
sendLine(writer, "MIME-Version: 1.0");
sendLine(writer,
"Content-Type: text/plain; "
+ "charset=UTF-8");
sendLine(writer,
"Content-Transfer-Encoding: "
+ "base64");
sendLine(writer, "");
sendLine(writer, body);
sendLine(writer, ".");
checkResponse(reader, "250");
sendLine(writer, "QUIT");
}
private void sendLine(PrintWriter writer,
String line) {
writer.print(line + "\r\n");
writer.flush();
}
private void checkResponse(
BufferedReader reader,
String expected) throws Exception {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
if (line.length() >= 4
&& Character.isDigit(
line.charAt(0))
&& line.charAt(3) == ' ')
break;
}
String resp = sb.toString().trim();
if (!resp.startsWith(expected)) {
if (resp.startsWith("535"))
logger.severe(
"[Sdf1_login] SMTP 535 "
+ "认证失败");
throw new Exception(
"SMTP响应异常: 期望 "
+ expected
+ ",实际: " + resp);
}
}
}
package Sdf1_login;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Base64;
import java.util.logging.Logger;
public class EmailManager {
private final ConfigManager config;
private final Logger logger;
public EmailManager(ConfigManager config) {
this.config = config;
this.logger = Logger.getLogger("Sdf1_login");
}
public boolean isConfigured() {
String host = config.getSmtp("smtp地址");
String user = config.getSmtp("smtp账号");
String pass = config.getSmtp("smtp密码");
return host != null && !host.isEmpty()
&& user != null && !user.isEmpty()
&& pass != null && !pass.isEmpty();
}
public boolean sendVerifyCode(String to,
String code) {
if (!isConfigured()) {
logger.warning(
"[Sdf1_login] SMTP未配置,"
+ "无法发送验证码");
return false;
}
logger.info("[Sdf1_login] 发送验证码到 " + to);
return sendEmailSync(to,
"[Sdf1_login] 验证码",
"您的验证码: " + code
+ "\n5分钟内有效。\n"
+ "如非本人操作请忽略。");
}
public boolean sendTempPassword(String to,
String player, String tempPwd) {
if (!isConfigured()) {
logger.warning(
"[Sdf1_login] SMTP未配置");
return false;
}
return sendEmailSync(to,
"[Sdf1_login] 临时密码",
"玩家 " + player
+ " 的临时密码: " + tempPwd
+ "\n请尽快登录并修改密码!");
}
private boolean sendEmailSync(String to,
String subject, String body) {
final boolean[] result = {false};
Thread t = new Thread(() -> {
try {
result[0] = sendEmail(
to, subject, body);
} catch (Exception e) {
logger.severe(
"[Sdf1_login] 邮件线程异常: "
+ e.getMessage());
}
}, "Sdf1_login-SMTP");
t.setDaemon(true);
t.start();
try {
t.join(15000);
} catch (InterruptedException ignored) {
}
if (t.isAlive()) {
t.interrupt();
logger.severe(
"[Sdf1_login] SMTP超时(15秒)");
return false;
}
return result[0];
}
private boolean sendEmail(String to,
String subject, String body) {
String host = config.getSmtp("smtp地址");
String portStr = config.getSmtp("smtp端口");
String user = config.getSmtp("smtp账号");
String pass = config.getSmtp("smtp密码");
String fromName = config.getSmtp(
"发件人名称");
int port;
try {
port = Integer.parseInt(portStr);
} catch (Exception e) {
port = 465;
}
try {
String encSubject = "=?UTF-8?B?"
+ Base64.getEncoder()
.encodeToString(
subject.getBytes("UTF-8"))
+ "?=";
String encBody = Base64.getEncoder()
.encodeToString(
body.getBytes("UTF-8"));
if (port == 465) {
SSLSocketFactory factory =
(SSLSocketFactory)
SSLSocketFactory
.getDefault();
SSLSocket socket = (SSLSocket)
factory.createSocket(
host, port);
socket.setSoTimeout(10000);
doSmtp(socket, host, user, pass,
to, encSubject, encBody,
fromName);
socket.close();
} else {
Socket plainSocket =
new Socket(host, port);
plainSocket.setSoTimeout(10000);
BufferedReader preReader =
new BufferedReader(
new InputStreamReader(
plainSocket
.getInputStream(),
"UTF-8"));
PrintWriter preWriter =
new PrintWriter(
plainSocket
.getOutputStream(),
true);
checkResponse(preReader, "220");
sendLine(preWriter,
"EHLO " + host);
checkResponse(preReader, "250");
sendLine(preWriter, "STARTTLS");
checkResponse(preReader, "220");
SSLSocketFactory factory =
(SSLSocketFactory)
SSLSocketFactory
.getDefault();
SSLSocket sslSocket = (SSLSocket)
factory.createSocket(
plainSocket, host,
port, true);
sslSocket.startHandshake();
doSmtp(sslSocket, host, user, pass,
to, encSubject, encBody,
fromName);
sslSocket.close();
}
logger.info(
"[Sdf1_login] 邮件发送成功 -> "
+ to);
return true;
} catch (Exception e) {
logger.severe(
"[Sdf1_login] 邮件异常: "
+ e.getClass()
.getSimpleName()
+ ": " + e.getMessage());
if (e.getCause() != null) {
logger.severe(
"[Sdf1_login] 根因: "
+ e.getCause()
.getMessage());
}
return false;
}
}
private void doSmtp(SSLSocket socket,
String host, String user, String pass,
String to, String subject, String body,
String fromName) throws Exception {
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
socket.getInputStream(),
"UTF-8"));
OutputStream rawOut =
socket.getOutputStream();
PrintWriter writer =
new PrintWriter(
new java.io.BufferedOutputStream(
rawOut), true);
checkResponse(reader, "220");
sendLine(writer, "EHLO " + host);
checkResponse(reader, "250");
sendLine(writer, "AUTH LOGIN");
checkResponse(reader, "334");
sendLine(writer, Base64.getEncoder()
.encodeToString(
user.getBytes("UTF-8")));
checkResponse(reader, "334");
sendLine(writer, Base64.getEncoder()
.encodeToString(
pass.getBytes("UTF-8")));
checkResponse(reader, "235");
sendLine(writer,
"MAIL FROM:<" + user + ">");
checkResponse(reader, "250");
sendLine(writer,
"RCPT TO:<" + to + ">");
checkResponse(reader, "250");
sendLine(writer, "DATA");
checkResponse(reader, "354");
sendLine(writer,
"From: " + fromName
+ " <" + user + ">");
sendLine(writer,
"To: <" + to + ">");
sendLine(writer,
"Reply-To: <" + user + ">");
sendLine(writer,
"Subject: " + subject);
sendLine(writer, "MIME-Version: 1.0");
sendLine(writer,
"Content-Type: text/plain; "
+ "charset=UTF-8");
sendLine(writer,
"Content-Transfer-Encoding: "
+ "base64");
sendLine(writer, "");
sendLine(writer, body);
sendLine(writer, ".");
checkResponse(reader, "250");
sendLine(writer, "QUIT");
}
private void sendLine(PrintWriter writer,
String line) {
writer.print(line + "\r\n");
writer.flush();
}
private void checkResponse(
BufferedReader reader,
String expected) throws Exception {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
if (line.length() >= 4
&& Character.isDigit(
line.charAt(0))
&& line.charAt(3) == ' ')
break;
}
String resp = sb.toString().trim();
if (!resp.startsWith(expected)) {
if (resp.startsWith("535"))
logger.severe(
"[Sdf1_login] SMTP 535 "
+ "认证失败");
throw new Exception(
"SMTP响应异常: 期望 "
+ expected
+ ",实际: " + resp);
}
}
}
File diff suppressed because it is too large Load Diff
+120 -598
View File
@@ -1,6 +1,7 @@
package Sdf1_login;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Item;
@@ -9,23 +10,16 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;
public class GarbageManager implements Listener {
public class GarbageManager {
private final Main plugin;
private Connection db;
@@ -33,53 +27,9 @@ public class GarbageManager implements Listener {
private int maxRounds = 1;
private boolean enabled = true;
private int currentRound = 0;
/**
* ★ 第42批:自动清理任务引用(BukkitRunnable)。
* 热停用时 cancel 该任务;applyEnabledState() 用它判断是否已在跑。
*/
private BukkitRunnable cleanupTask = null;
/**
* ★ 第36批:上一轮「清扫」进回收站的掉落物数量(血条展示)。
* -1 = 还没跑过任何一轮(血条不显示该字段)。
*/
private int lastCleaned = -1;
/**
* ★ 第36批:上一轮「永久倒掉」的过期物品数量(血条展示)。
* -1 = 还没跑过任何一轮;非倒垃圾轮固定为 0。
*/
private int lastDumped = -1;
private final Map<String, Integer>
recyclePages = new HashMap<>();
/**
* ★ 第31批:本轮开始的墙钟时间戳(毫秒)。
* 血条色段按真实时间判定,与 tick 计数解耦,
* 避免“第3分30秒还是绿色”的漂移。0 = 本轮未开始。
*/
private long roundStartMs = 0L;
/**
* ★ 第34批:已广播的倒计时节点位图。
* 墙钟口径下 remain 可能跨值(如 301→299),原来的 `remain == 300`
* 式判断会漏播;改用「<= 命中一次 + 位图去重」,卡顿也不漏。
* bit0=5分钟 bit1=3分钟 bit2=1分钟 bit3=30秒 bit4=10秒
*/
private int announcedMask = 0;
/**
* ★ 第30批:顶部血条(玩家 UUID → BossBar)
*/
private final Map<UUID, BossBar> bossBars = new HashMap<>();
/**
* ★ 第30批:双击 Q 确认丢弃的首次按键时间(玩家 UUID → 毫秒)
*/
private final Map<UUID, Long> pendingDrops = new HashMap<>();
public GarbageManager(Main plugin) {
this.plugin = plugin;
@@ -89,9 +39,8 @@ public class GarbageManager implements Listener {
try {
Class.forName("org.sqlite.JDBC");
File dbFile = new File(
new File(plugin.getDataFolder(), "垃圾箱"),
plugin.getDataFolder(),
"garbage.db");
dbFile.getParentFile().mkdirs();
db = DriverManager.getConnection(
"jdbc:sqlite:"
+ dbFile.getAbsolutePath());
@@ -184,500 +133,83 @@ public class GarbageManager implements Listener {
public void startAutoCleanup() {
if (!enabled) return;
// ★ 第42批:已在跑则不再重复调度(applyEnabledState 可能被多路热重载同时触发)
if (cleanupTask != null) return;
cleanupTask = new BukkitRunnable() {
new BukkitRunnable() {
int countdown = 0;
@Override
public void run() {
// ★ 第42批:启停状态热更兜底 —— ConfigManager.garbageEnabled 变 false 后
// (插件设置.txt 热重载),任务自己收摊:撤血条+清状态+取消自身。
// 反向 false→true 时任务已不存在,靠 applyEnabledState() 重新拉起。
if (!plugin.getConfig2().garbageEnabled) {
enabled = false;
hideAllBossBars();
roundStartMs = 0L;
announcedMask = 0;
pendingDrops.clear();
cleanupTask = null;
plugin.getLogger().info(
"[Garbage] 垃圾站_启用 热更关闭:自动清理任务已自停、血条已撤");
this.cancel();
return;
}
enabled = true;
// 在线人数≤0时暂停
if (Bukkit.getOnlinePlayers()
.isEmpty()) {
// ★ 第34批:墙钟口径 —— 全员离线则本轮暂停,
// 玩家回来时重新记录起点(重新计时)
roundStartMs = 0L;
announcedMask = 0;
countdown = 0;
return;
}
// ★ 第31批:本轮墙钟起点(0=新轮开始,色段按真实时间判定)
if (roundStartMs == 0L)
roundStartMs = System.currentTimeMillis();
// 重新读取配置(支持热更)
cleanupInterval =
plugin.getConfig2()
.garbageInterval;
// ★ 第37批:保留轮数同样纳入热更(节点重载 插件设置.txt 后
// 垃圾站_保留轮数 即时生效,无需重启)
maxRounds =
plugin.getConfig2()
.garbageMaxRounds;
// ★ 第34批:唯一时间源(墙钟)—— 血条 / 广播 / 抢救打印 /
// 丢弃拦截 全部读 remainSeconds(),误差 ±0 秒。
int remain = remainSeconds();
// ★ 第34批:节点广播改「<= 命中一次 + 位图去重」
// (墙钟口径 remain 可能跨值,== 判断会漏播)
boolean nodeHit = false;
if (cleanupInterval >= 300
&& remain <= 300
&& (announcedMask & 1) == 0) {
announcedMask |= 1;
nodeHit = true;
int remain =
cleanupInterval - countdown;
if (remain == 300)
broadcast("§e§l[垃圾站] §f距离清理还有 §e5分钟");
}
if (cleanupInterval >= 180
&& remain <= 180
&& (announcedMask & 2) == 0) {
announcedMask |= 2;
nodeHit = true;
else if (remain == 180)
broadcast("§e§l[垃圾站] §f距离清理还有 §e3分钟");
}
if (cleanupInterval >= 60
&& remain <= 60
&& (announcedMask & 4) == 0) {
announcedMask |= 4;
nodeHit = true;
else if (remain == 60)
broadcast("§e§l[垃圾站] §f距离清理还有 §e1分钟");
}
if (cleanupInterval >= 30
&& remain <= 30
&& (announcedMask & 8) == 0) {
announcedMask |= 8;
nodeHit = true;
else if (remain == 30)
broadcast("§e§l[垃圾站] §f距离清理还有 §e30秒");
}
if (cleanupInterval >= 10
&& remain <= 10
&& (announcedMask & 16) == 0) {
announcedMask |= 16;
nodeHit = true;
else if (remain == 10)
broadcast("§e§l[垃圾站] §f距离清理还有 §e10秒");
}
if (nodeHit) {
// ★ 第31批(#204/#205):垃圾箱进入下一节点 → 查一次 插件设置.txt,
// 有变化整份重载(ConfigManager 内部比对,无变化静默、有变化打日志)
// ★ 第42批:重载成功后把「垃圾站_启用」应用到运行态 ——
// 此前只更新 ConfigManager 字段,GarbageManager.enabled 没人回写,
// 导致日志喊了「true→false」但任务照跑、血条照显示(用户截图根因)。
if (plugin.getConfig2()
.reloadSettingsIfChanged()) {
applyEnabledState();
if (!enabled) return; // 本轮已被热停 → 不再往下跑
}
}
if (remain <= 5 && remain > 0)
else if (remain <= 5 && remain > 0)
broadcast("§e§l[垃圾站] §c" + remain + "§f...");
if (remain == 0) {
else if (remain == 0) {
doCleanup();
// ★ 第34批:新一轮开始 —— 清墙钟起点与节点位图
roundStartMs = 0L;
announcedMask = 0;
countdown = 0;
return;
}
// ★ 第30批:顶部血条常驻倒计时(软提醒)
// ★ 第32批:血条只受 垃圾站_启用 控制,与启发式开关解耦
// ★ 第34批:remain 取自墙钟唯一时间源,与广播/抢救打印同源
updateBossBars(remain);
countdown++;
}
};
cleanupTask.runTaskTimer(plugin, 20L, 20L);
}
/**
* ★ 第42批:停止自动清理任务并复位运行态(热停用时用)。
* 撤血条 + 清按键状态 + 复位墙钟起点与节点位图,下次启用从满格重新计时。
*/
public void stopAutoCleanup() {
if (cleanupTask != null) {
try {
cleanupTask.cancel();
} catch (IllegalStateException ignored) {
}
cleanupTask = null;
}
enabled = false;
hideAllBossBars();
roundStartMs = 0L;
announcedMask = 0;
pendingDrops.clear();
}
/**
* ★ 第42批:把 ConfigManager.garbageEnabled(插件设置.txt 的「垃圾站_启用」)
* 应用到 GarbageManager 运行态(双向:false→true 重新拉起任务 / true→false 停任务撤血条)。
*
* <p>根因(第42批用户截图):reloadSettingsIfChanged() 整份重载后只更新了
* ConfigManager 的字段并打了「已整份重载」日志,但 GarbageManager.enabled
* 是启动时 loadConfig() 拷贝的运行态快照,没人回写 → 日志喊了 true→false,
* 垃圾站照常运行。反向(false→true)更糟:启动时任务就没创建,
* 之后改 true 也没人调 startAutoCleanup(),垃圾站永远起不来。
*
* <p>调用点:Web 热重载 / 垃圾站节点热重载 / /sdf1_login reload 命令。
* 非主线程调用会自动切回主线程(BossBar 撤除必须主线程)。
*/
public void applyEnabledState() {
if (!Bukkit.isPrimaryThread()) {
Bukkit.getScheduler().runTask(plugin, this::applyEnabledState);
return;
}
boolean want = plugin.getConfig2().garbageEnabled;
if (want == enabled) return; // 状态一致 → no-op(防多路触发重复打日志)
if (want) {
enabled = true;
startAutoCleanup();
plugin.getLogger().info(
"[Garbage] 垃圾站_启用 热更生效:自动清理任务已启动");
} else {
stopAutoCleanup();
plugin.getLogger().info(
"[Garbage] 垃圾站_启用 热更生效:自动清理任务已停止、血条已撤");
}
}
/**
* ★ 第30批:顶部血条常驻倒计时 + 色段软提醒。
*
* <p>★ 第33批(#211):色段改按「剩余时间」纯数值分段(用户明令):
* <ul>
* <li>剩余 ≥ 180 秒 → 绿 = 安全期</li>
* <li>30 秒 < 剩余 < 180 秒 → 黄 = 警告(只提示快动作了,
* 丢的时候注意安全控好量,不误导「别丢」)</li>
* <li>剩余 ≤ 30 秒 → 红 = 危险</li>
* </ul>
* 第31批的「墙钟绝对时刻」方案废弃;百分比方案更早废弃(间隔一改就漂移)。
*
* <p>★ 第32批:血条与启发式开关解耦 —— 只要垃圾站启用,血条常驻显示;
* 启发式开关(垃圾站_启发式拦截)关闭时只关掉「黄/红区title警告 + 末5秒双击Q拦截」,
* 不再撤血条(否则玩家对清理状态一无所知)。
*/
private void updateBossBars(int remain) {
int interval = Math.max(1, cleanupInterval);
double progress = (double) remain / (double) interval;
if (progress < 0.0D) progress = 0.0D;
if (progress > 1.0D) progress = 1.0D;
BossBar.Color color;
String label;
if (remain <= 30) {
color = BossBar.Color.RED;
label = "§c§l危险 §7| §c马上清理,抓紧捡";
} else if (remain < 180) {
color = BossBar.Color.YELLOW;
label = "§e§l注意 §7| §e快动作了,注意安全控好量";
} else {
color = BossBar.Color.GREEN;
label = "§a§l安全期 §7| §a还早,放心丢";
}
String title = "§6§l垃圾站 §8| " + label
+ " §8| §f剩余 " + fmtRemain(remain);
// ★ 第36批:血条插一个字段 —— 上一轮清扫数 / 上一轮倒垃圾数
// (还没跑过任何一轮时不显示,避免出现"上轮扫-1个")
if (lastCleaned >= 0 && lastDumped >= 0) {
title += " §8| §7上轮扫§e" + lastCleaned
+ "§7个、倒§e" + lastDumped + "§7个";
}
Component comp = LegacyComponentSerializer
.legacySection().deserialize(title);
for (Player p : Bukkit.getOnlinePlayers()) {
UUID uuid = p.getUniqueId();
BossBar bar = bossBars.get(uuid);
if (bar == null) {
// Adventure 的 BossBar 按观众分发,必须每人一份
bar = BossBar.bossBar(comp, (float) progress,
color, BossBar.Overlay.NOTCHED_10);
bossBars.put(uuid, bar);
p.showBossBar(bar);
} else {
bar.name(comp);
bar.color(color);
if (Math.abs(bar.progress() - progress) > 0.001D) {
bar.progress((float) progress);
}
}
}
}
/** 撤掉所有玩家的顶部血条(插件关闭/停服时用;启发式开关不再触发) */
private void hideAllBossBars() {
for (Player p : Bukkit.getOnlinePlayers()) {
BossBar bar = bossBars.get(p.getUniqueId());
if (bar != null) {
try {
p.hideBossBar(bar);
} catch (Throwable ignored) {
}
}
}
bossBars.clear();
}
/** 剩余秒数格式化为 mm:ss */
private String fmtRemain(int remain) {
if (remain < 0) remain = 0;
int m = remain / 60;
int s = remain % 60;
return (m < 10 ? "0" + m : String.valueOf(m))
+ ":" + (s < 10 ? "0" + s : String.valueOf(s));
}
/**
* ★ 第34批:剩余秒数「唯一时间源」(墙钟推算)。
*
* <p>根因:旧实现里「血条 / 广播」读的是 tick 计数(increment 前的值),
* 而「抢救打印 / 指令显示 / 丢弃拦截」读的是 increment 后的值,
* 两者恒差 1 秒(用户截图:血条 02:47 vs 打印 02:46)。
*
* <p>现统一按墙钟推算:距本轮结束 = roundStartMs + 清理间隔 - now,
* 向上取整到秒。血条标题、抢救提示、指令显示、丢弃拦截全部读本方法,
* 保证 ±0 秒误差。
*
* @return 剩余秒数(0 = 本轮已到点 / 未开始)
*/
private int remainSeconds() {
if (roundStartMs <= 0L) {
// 本轮尚未开始(刚启动 / 抢救后 / 全员离线)→ 视为满格
return Math.max(0, cleanupInterval);
}
long endMs = roundStartMs + (long) cleanupInterval * 1000L;
long leftMs = endMs - System.currentTimeMillis();
if (leftMs <= 0L) return 0;
// 向上取整到秒:剩余 2.001s 显示 3 秒,2.000s 显示 2 秒
return (int) ((leftMs + 999L) / 1000L);
}
/**
* ★ 第30批:抢救模式 —— 跳过本轮清理并重新开始计时。
* 玩家物品被错误投入垃圾箱时可急停抢救。
*
* @return true=抢救成功(本轮清理已取消)
*/
public boolean rescueRound(Player p) {
if (!enabled) {
if (p != null)
p.sendMessage("§c§l[垃圾站] §f垃圾站未启用,无法抢救");
return false;
}
// ★ 第34批:改用墙钟唯一时间源(与头顶血条显示值完全一致)
if (remainSeconds() <= 0) {
if (p != null)
p.sendMessage("§c§l[垃圾站] §f本轮清理已经结束了,来不及抢救");
return false;
}
// ★ 第31批(#203):抢救窗口 = 本轮最后 1 分钟;未到时间不可触发
// ★ 第34批:与血条同源(墙钟)—— 打印值 = 头顶血条值(±0 秒)
int remainSec = remainSeconds();
if (remainSec > 60) {
if (p != null)
p.sendMessage("§c§l[垃圾站] §f未到抢救窗口:本轮清理还剩 §e"
+ fmtRemain(remainSec)
+ "§f,最后 1 分钟内才能发起抢救");
else
plugin.getLogger().info(
"[垃圾站] 抢救被拒:还剩 " + remainSec
+ " 秒,未进入最后1分钟窗口");
return false;
}
// ★ 第34批:取消本轮 —— 清墙钟起点与节点位图,计时重新开始
roundStartMs = 0L;
announcedMask = 0;
pendingDrops.clear();
String who = p != null ? p.getName() : "控制台";
broadcast("§a§l[垃圾站] §f玩家 §e" + who
+ " §f发起抢救,本轮清理已取消,计时重新开始");
if (p != null)
p.sendMessage("§a§l[垃圾站] §f抢救成功!本轮清理已取消,"
+ "倒计时重新开始");
return true;
}
/**
* 当前剩余秒数(指令/UI 显示用)。
* ★ 第34批:与头顶血条、抢救打印完全同源(墙钟),不再有 ±1 秒差。
*/
public int getRemainSeconds() {
return remainSeconds();
}
/**
* ★ 第30批:垃圾箱丢弃拦截。
*
* <p>★ 第33批(#211)三处改造:
* <ul>
* <li>警告期(黄区 30~180 秒)不加任何 title 干预 —— 该期的提示
* 只走头顶血条(updateBossBars 文案已改「注意安全控好量」);</li>
* <li>拦截窗口从末 10 秒收窄到末 5 秒,且仅启发式开关启用时生效;</li>
* <li>确认窗口从 2 秒收窄到 1 秒:拦下第一次 Q,1 秒内连按
* 第二次 = 确认丢弃放行;超过 1 秒视为过期跳过(重新计时)。</li>
* </ul>
*/
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent e) {
if (!enabled) return;
if (!plugin.getConfig2().garbageHeuristic) return;
// ★ 第34批:与血条同源(墙钟)
int remain = remainSeconds();
if (remain > 30) return; // 安全区+警告期(>30秒)→ 不干涉
Player p = e.getPlayer();
// 危险期(红区 ≤30秒)小标题:按用户口径「注意安全控好量」,不写「别丢」
p.sendTitle("", "§c§l垃圾站警告 §f马上清理了,注意安全控好量!",
3, 30, 5);
if (remain > 5) return; // ★ 拦截仅在最后 5 秒窗口
long now = System.currentTimeMillis();
UUID uuid = p.getUniqueId();
Long first = pendingDrops.get(uuid);
if (first != null && now - first <= 1000L) {
pendingDrops.remove(uuid);
return; // ★ 1 秒窗口内连按 2 次 Q = 确认丢弃 → 放行
}
// 首次按键(或上次按键已超 1 秒窗口 → 视为过期,重新计时)
pendingDrops.put(uuid, now);
e.setCancelled(true);
p.sendMessage("§e§l[垃圾站] §e马上清理了!1秒内再按一次 §eQ§f 确认丢弃,"
+ "或用 §e/垃圾抢救§f 取消本轮清理");
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
// 下一轮 tick 会自动建血条(第32批:不再受启发式开关守卫),
// 这里只清掉可能残留的按键状态
pendingDrops.remove(e.getPlayer().getUniqueId());
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e) {
UUID uuid = e.getPlayer().getUniqueId();
pendingDrops.remove(uuid);
BossBar bar = bossBars.remove(uuid);
if (bar != null) {
try {
e.getPlayer().hideBossBar(bar);
} catch (Throwable ignored) {
}
}
}.runTaskTimer(plugin, 20L, 20L);
}
private void doCleanup() {
// ★ 过期轮次删除是阻塞 DB -> 先异步执行;
// 轮次递增 / 实体收集 / 广播 必须主线程 -> 异步完成后回主线程
// ★ 第34批(#217):保留轮次语义按用户思维导图重写 ——
// N = 目标保留轮次(配置 垃圾站_保留轮数)
// k = 当前轮次(本方法入口时 currentRound = k-1)
// 公式余数 = N - k;余数为 0(k % N == 0)的那一轮才「永久倒垃圾」,
// 其余轮次只把地面掉落物收进回收站,跳过永久删除。
// N=3 → k=1(余2)跳过 / k=2(余1)跳过 / k=3(余0)倒垃圾。
// 到期批次 = 存活满 N 轮的批次(批次 j 存于第 j 轮,
// 到第 j+N 轮才满 N 轮)→ j <= k - N。
// 验证 N=2:k=1 跳过;k=2 倒垃圾(第1批尚未满2轮,删0件);
// k=3 跳过;k=4 倒垃圾(第1、2批满2轮,删除)。
// 验证 N=3:k=1/2 跳过;k=3 倒垃圾(无到期);k=6 倒垃圾(删第1、2、3批)。
// 性质:每个倒垃圾轮次结束后,回收站恰好保留 N 个批次的垃圾。
final int k = currentRound + 1; // 当前轮次(1 起)
final int n = Math.max(1, maxRounds); // 目标保留轮次
final boolean purgeThisRound = (k % n == 0);
final int deleteRound = k - n; // <= 该批次的都存活满 n 轮
Bukkit.getScheduler().runTaskAsynchronously(
plugin, () -> {
final int deleted =
(purgeThisRound && deleteRound >= 0)
? deleteOldItems(deleteRound)
: 0;
Bukkit.getScheduler().runTask(
plugin, () -> {
// ★ 第39批:倒垃圾轮的「永久清理」播报保留,
// 轮次提示改为**恒发**(原来只写在 else 分支
// → 倒垃圾轮整轮静默,用户看不到任何轮次信息)。
if (purgeThisRound && deleted > 0) {
broadcast("§7[垃圾站] §f永久清理了 §e"
+ deleted + " §f个过期物品");
}
// 递增轮次
currentRound++;
final int roundNow =
currentRound;
// ★ 轮次落库是 DB -> 异步
Bukkit.getScheduler()
.runTaskAsynchronously(
plugin, () ->
setConfigValue("round",
String.valueOf(roundNow)));
// 删除过期轮次的物品
int deleteRound =
currentRound - maxRounds;
if (deleteRound >= 0) {
int deleted = deleteOldItems(
deleteRound);
if (deleted > 0) {
broadcast("§7[垃圾站] §f永久清理了 §e"
+ deleted + " §f个过期物品");
}
}
// 收集当前掉落物
// (实体移除必须主线程,落库已在内部转异步)
int count = collectItems();
// ★ 第36批:记录上一轮统计(血条展示)——
// 清扫 = 本轮收进回收站的掉落物数;
// 倒垃圾 = 本轮永久删除的过期物品数(非倒垃圾轮为0)
lastCleaned = count;
lastDumped = deleted;
broadcast("§a§l[垃圾站] §f清理完成,"
+ "共清理 §e" + count
+ " §f个掉落物,存入回收站");
// 递增轮次
currentRound++;
setConfigValue("round",
String.valueOf(currentRound));
// ★ 第39批:轮次提示**恒发**,且口径改「刚开启的新一轮」。
// 原实现算的是*刚跑完*的轮次 k(r=((k-1)%n)+1),
// 而玩家屏幕上正在倒计时的其实是**刚开启的新一轮 k+1**
// → 播报与实际轮次差一轮(用户截图那轮:k=25402 跑完,
// 开启 25403 = 周期内第1轮 → 应播「当前是第1轮,
// 第2轮倒垃圾,还剩1轮倾倒垃圾」)。
// 周期内轮次 r = ((nextRound-1) % n) + 1 ∈ [1, n];
// r == n 即「本轮结束时倾倒垃圾」(下一轮才真正倒)。
final int nextRound = roundNow + 1; // 清理后开启的新一轮
final int r = ((nextRound - 1) % n) + 1;
// ★ 第45批:保留只有1轮(n==1)时
// 每一轮都是倒垃圾轮,「本轮结束时
// 倾倒垃圾」无增量信息 → 不播报;
// 仅保留>1才提示轮次进度(用户
// 2026-10-22 截图反馈)。
if (n > 1) {
if (r < n) {
broadcast("§7[垃圾站] §f当前是第 §e" + r
+ " §f轮,第 §e" + n
+ " §f轮倒垃圾,还剩 §e" + (n - r)
+ " §f轮倾倒垃圾");
} else {
broadcast("§7[垃圾站] §f当前是第 §e" + n
+ " §f轮,本轮结束时倾倒垃圾");
}
}
// 收集当前掉落物
int count = collectItems();
broadcast("§a§l[垃圾站] §f清理完成,"
+ "共清理 §e" + count
+ " §f个掉落物,存入回收站");
// 打印下次清理时间
long nextMs = System.currentTimeMillis()
+ (long) cleanupInterval * 1000L;
String nextTime =
new SimpleDateFormat("HH:mm:ss")
.format(new Date(nextMs));
broadcast("§e§l[垃圾站] §f下次清理时间: §a"
+ nextTime);
});
});
// 打印下次清理时间
long nextMs = System.currentTimeMillis()
+ (long) cleanupInterval * 1000L;
String nextTime =
new SimpleDateFormat("HH:mm:ss")
.format(new Date(nextMs));
broadcast("§e§l[垃圾站] §f下次清理时间: §a"
+ nextTime);
}
public int collectItems() {
int count = 0;
List<ItemStack> picked = new ArrayList<>();
for (org.bukkit.World w :
Bukkit.getWorlds()) {
Collection<Item> items =
@@ -689,49 +221,36 @@ public class GarbageManager implements Listener {
|| stack.getType()
== Material.AIR)
continue;
// ★ 先取快照再移除实体(实体移除必须主线程)
picked.add(stack.clone());
saveItem(stack);
item.remove();
count++;
}
}
// ★ 落库是阻塞 DB(含 SN 脱管登记)-> 丢异步批量写
if (!picked.isEmpty()) {
final List<ItemStack> toSave = picked;
Bukkit.getScheduler()
.runTaskAsynchronously(plugin, () -> {
for (ItemStack s : toSave)
saveItem(s);
});
}
return count;
}
public void saveItem(ItemStack stack) {
try {
// ★ SN 物品进垃圾箱 = 脱离玩家本人管控,起算 12 小时找回期。
// shift 投入 / 光标放入 / 拖拽 / 扫地机收地面掉落全走这里。
if (plugin.getSnManager() != null) {
plugin.getSnManager().onConfiscated(stack, "垃圾站");
}
String data = stackToBase64(stack);
if (data.isEmpty()) return;
PreparedStatement ps = db.prepareStatement(
"INSERT INTO items "
+ "(item_data, amount, "
+ "round, create_time) "
+ "VALUES (?,?,?,?)");
ps.setString(1, data);
ps.setInt(2, stack.getAmount());
ps.setInt(3, currentRound);
ps.setLong(4,
System.currentTimeMillis());
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveItem(ItemStack stack) {
{
try {
String data =
stackToBase64(stack);
if (data.isEmpty()) return;
PreparedStatement ps = db.prepareStatement(
"INSERT INTO items "
+ "(item_data, amount, "
+ "round, create_time) "
+ "VALUES (?,?,?,?)");
ps.setString(1, data);
ps.setInt(2, stack.getAmount());
ps.setInt(3, currentRound);
ps.setLong(4,
System.currentTimeMillis());
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}}
private int deleteOldItems(int beforeRound) {
try {
@@ -769,8 +288,11 @@ public class GarbageManager implements Listener {
.decode(base64);
String json = new String(bytes,
StandardCharsets.UTF_8);
Type type = new TypeToken<
Map<String, Object>>() {}
.getType();
Map<String, Object> map =
new Gson().fromJson(json, Map.class);
new Gson().fromJson(json, type);
map = fixNumberTypes(map);
return ItemStack.deserialize(map);
} catch (Exception e) {
@@ -822,9 +344,11 @@ public class GarbageManager implements Listener {
}
public void openRecyclePage(Player p, int page) {
Inventory g = Bukkit.createInventory(
null, 54, "§6§l垃圾回收站");
// 获取全部存储物品
List<Map<String, Object>> allItems =
getStoredItems(999);
int total = allItems.size();
@@ -857,6 +381,38 @@ public class GarbageManager implements Listener {
.get("amount")).intValue();
ItemStack stack = base64ToStack(data);
if (stack != null) {
try {
byte[] bytes =
stack.serializeAsBytes();
String b64 = java.util.Base64
.getEncoder()
.encodeToString(bytes);
int len = b64.length();
String f = len > 15
? b64.substring(10, 15) : "短";
String m = len >= 5
? b64.substring(len / 2,
Math.min(len / 2 + 5, len))
: "短";
String b = len > 10
? b64.substring(len - 10, len - 5)
: "短";
plugin.getLogger().info(
"[垃圾站加载] ID#" + id
+ " " + stack.getType()
+ " x" + amount
+ " base64[" + len + "]"
+ " 前=" + f
+ " 中=" + m
+ " 后=" + b);
} catch (Exception ex) {
plugin.getLogger().warning(
"[垃圾站加载] 序列化异常: "
+ ex.getMessage());
}
}
if (stack != null) {
stack.setAmount(amount);
ItemMeta im =
stack.getItemMeta();
@@ -873,7 +429,10 @@ public class GarbageManager implements Listener {
slot++;
}
// 49 格:上一页
// 45-48 格:额外投放区(空位)
// 52-53 格:额外投放区(空位)
// 49 格:翻页-上一页
if (page > 0) {
g.setItem(49, mk(Material.ARROW,
"§e上一页 §7("
@@ -892,8 +451,9 @@ public class GarbageManager implements Listener {
"§7当前页: §f" + (page + 1)
+ "/" + totalPages));
// 51 格:下一页
boolean canNext = page < totalPages - 1;
// 51 格:翻页-下一页
boolean canNext = total >= pageSize
&& page < totalPages - 1;
if (canNext) {
g.setItem(51, mk(Material.ARROW,
"§e下一页 §7("
@@ -903,15 +463,13 @@ public class GarbageManager implements Listener {
g.setItem(51, mk(Material.ARROW,
"§7已是最后一页"));
}
// 52 格:返回主菜单
// 52格:返回按钮
g.setItem(52, mk(Material.ARROW,
"§7返回",
"§7返回主菜单"));
p.openInventory(g);
}
public int getRecyclePage(String name) {
return recyclePages
.getOrDefault(name, 0);
@@ -998,38 +556,6 @@ public class GarbageManager implements Listener {
}
}
/**
* 取回前按 id 读原始存档(含原 lore 与 PDC)。
* GUI 展示副本的 lore 已被覆盖成
* 「ID/点击取出」,取回必须用这个还原,
* 否则 §8SN 行与物品说明 lore 会丢。
*
* @param id items 表主键
* @return 原始物品;读不到返回 null
*/
public ItemStack fetchItem(int id) {
try {
PreparedStatement ps = db.prepareStatement(
"SELECT item_data, amount FROM items "
+ "WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
ItemStack result = null;
if (rs.next()) {
result = base64ToStack(
rs.getString("item_data"));
if (result != null) {
result.setAmount(rs.getInt("amount"));
}
}
rs.close();
ps.close();
return result;
} catch (Exception e) {
return null;
}
}
public int getItemCount() {
try {
Statement st = db.createStatement();
@@ -1075,14 +601,10 @@ public class GarbageManager implements Listener {
}
public void close() {
try {
hideAllBossBars();
pendingDrops.clear();
} catch (Exception ignored) {
}
try {
if (db != null && !db.isClosed())
db.close();
} catch (Exception ignored) {}
} catch (Exception ignored) {
}
}
}
}
+32 -21
View File
@@ -22,7 +22,7 @@ public class GiftManager {
public GiftManager(Main plugin) {
this.plugin = plugin;
this.giftFolder = new File(
plugin.getDataFolder(), "任务面板");
plugin.getDataFolder(), "新人礼包");
}
public void loadStages() {
@@ -59,7 +59,7 @@ public class GiftManager {
|| line.contains("任务内容")) {
int colon = line.indexOf(':');
if (colon < 0)
colon = line.indexOf(':');
colon = line.indexOf('\uff1a');
if (colon >= 0) {
rewards.add(
line.substring(colon + 1)
@@ -194,21 +194,28 @@ public class GiftManager {
giveItem(p, Material.WOODEN_AXE);
giveItem(p, Material.WOODEN_SHOVEL);
} else if (stage == 2) {
// 游戏币改为债券
BondManager bm = plugin.getBonds();
if (bm != null) {
int before = bm.getBonds(p.getName());
bm.addBonds(p.getName(), 500, "gift_stage2", "", "新手礼包", "阶段2奖励");
int after = bm.getBonds(p.getName());
p.sendMessage("§a§l[礼包] §f债券: §e" + before + "§f → §a" + after);
if (plugin.getEconomy() != null) {
double before = plugin.getEconomy()
.getBalance(p);
plugin.getEconomy()
.depositPlayer(p, 500);
double after = plugin.getEconomy()
.getBalance(p);
p.sendMessage("§a§l[礼包] §f游戏币: §e"
+ (long) before
+ "§f → §a" + (long) after);
}
} else if (stage == 3) {
BondManager bm = plugin.getBonds();
if (bm != null) {
int before = bm.getBonds(p.getName());
bm.addBonds(p.getName(), 1500, "gift_stage3", "", "新手礼包", "阶段3奖励");
int after = bm.getBonds(p.getName());
p.sendMessage("§a§l[礼包] §f债券: §e" + before + "§f → §a" + after);
if (plugin.getEconomy() != null) {
double before = plugin.getEconomy()
.getBalance(p);
plugin.getEconomy()
.depositPlayer(p, 1500);
double after = plugin.getEconomy()
.getBalance(p);
p.sendMessage("§a§l[礼包] §f游戏币: §e"
+ (long) before
+ "§f → §a" + (long) after);
}
giveItem(p, Material.IRON_PICKAXE);
giveItem(p, Material.IRON_AXE);
@@ -218,12 +225,16 @@ public class GiftManager {
giveItem(p, Material.IRON_LEGGINGS);
giveItem(p, Material.IRON_BOOTS);
} else if (stage == 4) {
BondManager bm = plugin.getBonds();
if (bm != null) {
int before = bm.getBonds(p.getName());
bm.addBonds(p.getName(), 2000, "gift_stage4", "", "新手礼包", "阶段4奖励");
int after = bm.getBonds(p.getName());
p.sendMessage("§a§l[礼包] §f债券: §e" + before + "§f → §a" + after);
if (plugin.getEconomy() != null) {
double before = plugin.getEconomy()
.getBalance(p);
plugin.getEconomy()
.depositPlayer(p, 2000);
double after = plugin.getEconomy()
.getBalance(p);
p.sendMessage("§a§l[礼包] §f游戏币: §e"
+ (long) before
+ "§f → §a" + (long) after);
}
giveItem(p, Material.DIAMOND_HELMET);
giveItem(p, Material.DIAMOND_CHESTPLATE);
-770
View File
@@ -1,770 +0,0 @@
package Sdf1_login;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.data.type.Bed;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
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.BlockBreakEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Home传送点管理器
* 支持: sethome, delhome, home, homes
* 集成用户组系统: home_limit (0=全局默认, >0=组限制, -1=无限)
*/
public class HomeManager implements Listener {
private final Main plugin;
// 床位置缓存: player_name → Location (用于自动记录床位置)
private final Map<String, Location> bedLocations = new ConcurrentHashMap<>();
public HomeManager(Main plugin) {
this.plugin = plugin;
initDatabase();
}
// ==================== 数据结构 ====================
public static class HomeData {
public String name;
public String world;
public double x, y, z;
public float yaw, pitch;
public long createdAt;
public Location toLocation(World world) {
return new Location(world, x, y, z, yaw, pitch);
}
}
// ==================== 数据库初始化 ====================
private void initDatabase() {
try {
java.sql.Connection db = plugin.getDb().getConnection();
if (db == null) {
plugin.getLogger().warning("[Home] 无法获取数据库连接");
return;
}
java.sql.Statement st = db.createStatement();
// homes表已在DatabaseManager中创建,此处确保索引
st.execute("CREATE INDEX IF NOT EXISTS idx_homes_player ON homes(player_name)");
st.close();
plugin.getLogger().info("[Home] 数据库初始化完成");
} catch (Exception e) {
plugin.getLogger().warning("[Home] 数据库初始化失败: " + e.getMessage());
}
}
// ==================== 命令处理 ====================
public boolean handleCommand(Player player, String label, String[] args) {
String lowerLabel = label.toLowerCase();
switch (lowerLabel) {
case "sethome":
return handleSetHome(player, args);
case "delhome":
return handleDelHome(player, args);
case "home":
return handleHome(player, args);
case "homes":
return handleHomes(player, args);
default:
return false;
}
}
/**
* /sethome <名称> - 设置家
*/
private boolean handleSetHome(Player player, String[] args) {
if (args.length == 0) {
player.sendMessage("§c用法: /sethome <名称>");
return true;
}
String homeName = args[0].toLowerCase();
// 校验名称格式
if (!homeName.matches("^[a-zA-Z0-9_]{1,16}$")) {
player.sendMessage("§c家名只能包含字母、数字、下划线,长度1-16");
return true;
}
// 检查家数量限制
int maxHomes = getMaxHomes(player);
if (maxHomes != -1) {
List<HomeData> homes = getHomes(player.getName());
if (homes.size() >= maxHomes) {
player.sendMessage("§c你已达到家数量上限 (" + maxHomes + "个)");
return true;
}
}
// 检查是否已存在同名家
if (homeExists(player.getName(), homeName)) {
player.sendMessage("§c你已有一个名为 §e" + homeName + " §c的家");
return true;
}
// 保存家
Location loc = player.getLocation();
saveHome(player.getName(), homeName, loc);
player.sendMessage("§a家 §e" + homeName + " §a已设置!");
player.sendMessage("§7使用 §e/home " + homeName + " §7传送回家");
player.sendMessage("§a§l欢迎来到草原探险服务器,服务器ip:mc2.ypshidifu.cn 端口(基岩版需要):30679");
return true;
}
/**
* /delhome <名称> - 删除家
*/
private boolean handleDelHome(Player player, String[] args) {
if (args.length == 0) {
player.sendMessage("§c用法: /delhome <名称>");
return true;
}
String homeName = args[0].toLowerCase();
if (!homeExists(player.getName(), homeName)) {
player.sendMessage("§c你没有名为 §e" + homeName + " §c的家");
return true;
}
deleteHome(player.getName(), homeName);
player.sendMessage("§a家 §e" + homeName + " §a已删除!");
player.sendMessage("§a§l欢迎来到草原探险服务器,服务器ip:mc2.ypshidifu.cn 端口(基岩版需要):30679");
return true;
}
/**
* /home [名称] - 传送到家
*/
private boolean handleHome(Player player, String[] args) {
if (args.length == 0) {
// 无参数: 传送到第一个家
List<HomeData> homes = getHomes(player.getName());
if (homes.isEmpty()) {
player.sendMessage("§c你还没有设置任何家");
player.sendMessage("§7使用 §e/sethome <名称> §7设置一个家");
player.sendMessage("§a§l欢迎来到草原探险服务器,服务器ip:mc2.ypshidifu.cn 端口(基岩版需要):30679");
return true;
}
teleportToHome(player, homes.get(0));
return true;
}
String homeName = args[0].toLowerCase();
HomeData home = getHome(player.getName(), homeName);
if (home == null) {
player.sendMessage("§c你没有名为 §e" + homeName + " §c的家");
return true;
}
teleportToHome(player, home);
return true;
}
/**
* /homes - 查看所有家
*/
private boolean handleHomes(Player player, String[] args) {
List<HomeData> homes = getHomes(player.getName());
if (homes.isEmpty()) {
player.sendMessage("§e你还没有设置任何家");
player.sendMessage("§7使用 §e/sethome <名称> §7设置一个家");
return true;
}
int maxHomes = getMaxHomes(player);
player.sendMessage("§6§l你的家 §7(" + homes.size() + (maxHomes == -1 ? "/" + "∞" : "/" + maxHomes) + ")");
player.sendMessage("§7────────────────────");
for (HomeData home : homes) {
String worldName = home.world != null ? home.world : "未知";
player.sendMessage("§e • " + home.name + " §7[" + worldName + "]");
}
player.sendMessage("§7────────────────────");
player.sendMessage("§7使用 §e/home <名称> §7传送");
player.sendMessage("§7使用 §e/sethome <名称> §7设置新家");
player.sendMessage("§7使用 §e/delhome <名称> §7删除家");
player.sendMessage("§7—————————————————————");
player.sendMessage("§a§l欢迎来到草原探险服务器,服务器ip:mc2.ypshidifu.cn 端口(基岩版需要):30679");
return true;
}
// ==================== 床事件监听 ====================
private static final org.bukkit.block.BlockFace[] HORIZ_FACES = {
org.bukkit.block.BlockFace.NORTH, org.bukkit.block.BlockFace.SOUTH,
org.bukkit.block.BlockFace.EAST, org.bukkit.block.BlockFace.WEST };
/** 危险方块:落点优先级判断用 */
private static final Set<Material> DANGEROUS = EnumSet.of(
Material.LAVA, Material.FIRE, Material.SOUL_FIRE, Material.MAGMA_BLOCK,
Material.CACTUS, Material.CAMPFIRE, Material.SOUL_CAMPFIRE,
Material.SWEET_BERRY_BUSH, Material.WITHER_ROSE, Material.POWDER_SNOW,
Material.POINTED_DRIPSTONE);
/** 是否是床方块 */
private static boolean isBed(Block b) {
return b.getBlockData() instanceof Bed;
}
/** 取床头方块(配对缺失时返回原方块);非床返回 null */
private static Block getBedHead(Block b) {
if (!isBed(b)) return null;
if (((Bed) b.getBlockData()).getPart() == Bed.Part.HEAD) return b;
Block head = horizontalNeighborWithPart(b, Bed.Part.HEAD);
return head != null ? head : b;
}
private static Block horizontalNeighborWithPart(Block b, Bed.Part part) {
for (org.bukkit.block.BlockFace f : HORIZ_FACES) {
Block n = b.getRelative(f);
if (isBed(n) && ((Bed) n.getBlockData()).getPart() == part) return n;
}
return null;
}
/** 床的两半 [head, foot(可能为null)];非床返回 null */
private static Block[] getBedParts(Block b) {
if (!isBed(b)) return null;
if (((Bed) b.getBlockData()).getPart() == Bed.Part.HEAD) {
return new Block[]{ b, horizontalNeighborWithPart(b, Bed.Part.FOOT) };
}
Block head = horizontalNeighborWithPart(b, Bed.Part.HEAD);
return new Block[]{ head != null ? head : b, b };
}
/**
* 玩家与床交互(上床/白天点床)→ bed 传送点始终更新为该床的精确坐标
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerBedEnter(PlayerBedEnterEvent event) {
// 下界/末地床爆炸、怪物附近、距离过远等未真正交互的情况不记录
PlayerBedEnterEvent.BedEnterResult r = event.getBedEnterResult();
if (r != PlayerBedEnterEvent.BedEnterResult.OK
&& r != PlayerBedEnterEvent.BedEnterResult.NOT_POSSIBLE_NOW
&& r != PlayerBedEnterEvent.BedEnterResult.OBSTRUCTED) {
return;
}
Player player = event.getPlayer();
Block head = getBedHead(event.getBed());
if (head == null) return;
Location bedLoc = head.getLocation();
bedLocations.put(player.getName(), bedLoc);
HomeData existing = getHome(player.getName(), "bed");
if (existing == null) {
saveHome(player.getName(), "bed", bedLoc);
player.sendMessage("§a床位置已自动保存为 §e/home bed");
} else if (!sameBlock(existing, bedLoc)) {
// 与其它床交互 → 更新传送点坐标
updateHome(player.getName(), "bed", bedLoc);
player.sendMessage("§a床传送点已更新为该床的位置");
player.sendMessage("§a§l欢迎来到草原探险服务器,服务器ip:mc2.ypshidifu.cn 端口(基岩版需要):30679");
}
}
/**
* 玩家复活 → 抓取重生点附近的精确床坐标并更新 bed 传送点
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location respawnLoc = event.getRespawnLocation();
if (respawnLoc == null || respawnLoc.getWorld() == null) return;
Block bed = findNearbyBed(respawnLoc);
if (bed == null) return; // 世界出生点复活等,不碰传送点
Block head = getBedHead(bed);
Location exact = (head != null ? head : bed).getLocation();
HomeData existing = getHome(player.getName(), "bed");
if (existing == null) {
saveHome(player.getName(), "bed", exact);
} else if (!sameBlock(existing, exact)) {
updateHome(player.getName(), "bed", exact);
}
bedLocations.put(player.getName(), exact);
}
/** 在重生点附近(水平±3、垂直-1~+2)寻找最近的床方块 */
private Block findNearbyBed(Location loc) {
World w = loc.getWorld();
if (w == null) return null;
int bx = loc.getBlockX(), by = loc.getBlockY(), bz = loc.getBlockZ();
Block best = null;
double bestD = Double.MAX_VALUE;
for (int dx = -3; dx <= 3; dx++)
for (int dy = -1; dy <= 2; dy++)
for (int dz = -3; dz <= 3; dz++) {
Block b = w.getBlockAt(bx + dx, by + dy, bz + dz);
if (!isBed(b)) continue;
double d = (double) dx * dx + (double) dy * dy + (double) dz * dz;
if (d < bestD) { bestD = d; best = b; }
}
return best;
}
private boolean sameBlock(HomeData home, Location loc) {
return home.world != null && loc.getWorld() != null
&& home.world.equals(loc.getWorld().getName())
&& Math.floor(home.x) == loc.getBlockX()
&& Math.floor(home.y) == loc.getBlockY()
&& Math.floor(home.z) == loc.getBlockZ();
}
/**
* 床没了 → 自动删除对应玩家的 bed 传送点(破坏/爆炸均触发)
*/
private void removeBedHomesFor(Block bedPart) {
Block[] parts = getBedParts(bedPart);
if (parts == null) return;
Set<String> owners = new HashSet<>();
for (Block part : parts) {
if (part == null) continue;
owners.addAll(queryBedHomeOwners(part));
}
for (String owner : owners) {
deleteHome(owner, "bed");
bedLocations.remove(owner);
Player p = Bukkit.getPlayerExact(owner);
if (p != null && p.isOnline()) {
p.sendMessage("§c你的床已被破坏,/home bed 传送点已自动删除");
p.sendMessage("§a§l欢迎来到草原探险服务器,服务器ip:mc2.ypshidifu.cn 端口(基岩版需要):30679");
}
}
}
/** 查询 bed 传送点坐标与指定床方块重合的玩家列表 */
private Set<String> queryBedHomeOwners(Block bedBlock) {
Set<String> owners = new HashSet<>();
try {
java.sql.Connection db = plugin.getDb().getConnection();
if (db == null) return owners;
PreparedStatement ps = db.prepareStatement(
"SELECT player_name FROM homes WHERE home_name='bed' AND world=? "
+ "AND ABS(x-?)<0.01 AND ABS(y-?)<0.01 AND ABS(z-?)<0.01");
ps.setString(1, bedBlock.getWorld().getName());
ps.setDouble(2, bedBlock.getX());
ps.setDouble(3, bedBlock.getY());
ps.setDouble(4, bedBlock.getZ());
ResultSet rs = ps.executeQuery();
while (rs.next()) owners.add(rs.getString(1));
rs.close();
ps.close();
} catch (SQLException e) {
plugin.getLogger().warning("[Home] 查询bed传送点失败: " + e.getMessage());
}
return owners;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (isBed(event.getBlock())) removeBedHomesFor(event.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityExplode(EntityExplodeEvent event) {
for (Block b : event.blockList()) {
if (isBed(b)) removeBedHomesFor(b);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockExplode(BlockExplodeEvent event) {
for (Block b : event.blockList()) {
if (isBed(b)) removeBedHomesFor(b);
}
}
// ==================== 家数量限制 ====================
/**
* 获取玩家最大家数量
* @return -1=无限, 0=使用全局默认, >0=用户组独立限制
*/
private int getMaxHomes(Player player) {
UserGroupManager userGroupMgr = plugin.getUserGroup();
if (userGroupMgr == null) {
return getGlobalHomeLimit();
}
// 获取玩家最高优先级用户组
UserGroupManager.UserGroupConfig highestGroup = userGroupMgr.getHighestGroup(player.getName());
if (highestGroup == null) {
return getGlobalHomeLimit();
}
// 获取用户组的home_limit配置
int groupLimit = userGroupMgr.getHomeLimit(highestGroup.name);
if (groupLimit == -1) {
// 无限
return -1;
} else if (groupLimit == 0) {
// 跟随全局
return getGlobalHomeLimit();
} else {
// 独立限制
return groupLimit;
}
}
/**
* 获取全局家数量限制
* 读取area_config中的max_home_per_player配置(管理员可在Web后台调整)
* 解析失败或值<=0时回退到默认5
*/
private int getGlobalHomeLimit() {
try {
if (plugin.areaProtection != null) {
int limit = plugin.areaProtection.getGlobalMaxHomePerPlayer();
if (limit > 0) {
return limit;
}
}
} catch (Exception ignored) {}
// 默认5个家
return 5;
}
// ==================== 数据库操作 ====================
private boolean homeExists(String playerName, String homeName) {
try {
java.sql.Connection db = plugin.getDb().getConnection();
if (db == null) return false;
PreparedStatement ps = db.prepareStatement(
"SELECT COUNT(*) FROM homes WHERE player_name=? AND home_name=?");
ps.setString(1, playerName);
ps.setString(2, homeName);
ResultSet rs = ps.executeQuery();
boolean exists = rs.next() && rs.getInt(1) > 0;
rs.close();
ps.close();
return exists;
} catch (SQLException e) {
return false;
}
}
private List<HomeData> getHomes(String playerName) {
List<HomeData> homes = new ArrayList<>();
try {
java.sql.Connection db = plugin.getDb().getConnection();
if (db == null) return homes;
PreparedStatement ps = db.prepareStatement(
"SELECT * FROM homes WHERE player_name=? ORDER BY created_at");
ps.setString(1, playerName);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
HomeData home = new HomeData();
home.name = rs.getString("home_name");
home.world = rs.getString("world");
home.x = rs.getDouble("x");
home.y = rs.getDouble("y");
home.z = rs.getDouble("z");
home.yaw = rs.getFloat("yaw");
home.pitch = rs.getFloat("pitch");
home.createdAt = rs.getLong("created_at");
homes.add(home);
}
rs.close();
ps.close();
} catch (SQLException e) {
plugin.getLogger().warning("[Home] 获取家列表失败: " + e.getMessage());
}
return homes;
}
private HomeData getHome(String playerName, String homeName) {
List<HomeData> homes = getHomes(playerName);
for (HomeData home : homes) {
if (home.name.equalsIgnoreCase(homeName)) {
return home;
}
}
return null;
}
private void saveHome(String playerName, String homeName, Location loc) {
try {
java.sql.Connection db = plugin.getDb().getConnection();
if (db == null) return;
PreparedStatement ps = db.prepareStatement(
"INSERT OR REPLACE INTO homes (player_name, home_name, world, x, y, z, yaw, pitch, created_at) "
+ "VALUES (?,?,?,?,?,?,?,?,?)");
ps.setString(1, playerName);
ps.setString(2, homeName);
ps.setString(3, loc.getWorld() != null ? loc.getWorld().getName() : "world");
ps.setDouble(4, loc.getX());
ps.setDouble(5, loc.getY());
ps.setDouble(6, loc.getZ());
ps.setFloat(7, loc.getYaw());
ps.setFloat(8, loc.getPitch());
ps.setLong(9, System.currentTimeMillis());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
plugin.getLogger().warning("[Home] 保存家失败: " + e.getMessage());
}
}
private void updateHome(String playerName, String homeName, Location loc) {
saveHome(playerName, homeName, loc); // INSERT OR REPLACE 自动更新
}
private void deleteHome(String playerName, String homeName) {
try {
java.sql.Connection db = plugin.getDb().getConnection();
if (db == null) return;
PreparedStatement ps = db.prepareStatement(
"DELETE FROM homes WHERE player_name=? AND home_name=?");
ps.setString(1, playerName);
ps.setString(2, homeName);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
plugin.getLogger().warning("[Home] 删除家失败: " + e.getMessage());
}
}
/**
* 传送玩家到家
*/
private void teleportToHome(Player player, HomeData home) {
// bed 家走原版复活落点算法(自写,不模拟死亡、无死亡提示)
if ("bed".equalsIgnoreCase(home.name)) {
teleportToBedHome(player, home);
return;
}
World world = Bukkit.getWorld(home.world);
if (world == null) {
player.sendMessage("§c世界 §e" + home.world + " §c不存在");
return;
}
Location loc = home.toLocation(world);
// 安全检查: 确保位置安全
if (loc.getBlock().getType().isSolid()) {
// 向上寻找安全位置
for (int y = (int) loc.getY(); y < 256; y++) {
Location safeLoc = new Location(world, loc.getX(), y + 1, loc.getZ());
if (!safeLoc.getBlock().getType().isSolid()) {
loc = safeLoc;
break;
}
}
}
player.teleport(loc);
player.sendMessage("§a已传送到家 §e" + home.name);
}
/**
* 回床:先校验床还在(没了自动删传送点),再用自写算法模拟原版复活落点
* (床周合法站位 + 视线水平看向床头),直接传送,不模拟死亡。
*/
private void teleportToBedHome(Player player, HomeData home) {
World world = Bukkit.getWorld(home.world);
if (world == null) {
player.sendMessage("§c世界 §e" + home.world + " §c不存在");
return;
}
Location saved = home.toLocation(world);
Block savedBlock = world.getBlockAt(saved);
Block head = getBedHead(savedBlock);
// 保存坐标上没有床 → 床已没,自动删传送点
if (head == null) {
deleteHome(player.getName(), "bed");
bedLocations.remove(player.getName());
player.sendMessage("§c你的床已不存在,/home bed 传送点已自动删除");
return;
}
Location dest = findVanillaRespawnSpot(world, head);
if (dest == null) {
player.sendMessage("§c床周围被阻挡,暂时无法回到床边");
return;
}
// 若坐标与记录不一致(床被重摆),顺手修正传送点
if (!sameBlock(home, head.getLocation())) {
updateHome(player.getName(), "bed", head.getLocation());
bedLocations.put(player.getName(), head.getLocation());
}
player.teleport(dest);
player.sendMessage("§a已回到床边");
}
/**
* 自写算法模拟原版床复活落点:
* 1. 候选 = 床头8邻(原版7块优先区,排除床自身占位)→ 床尾8邻兜底;
* 排序遵循原版"西北(低X低Z)最先,其次向南(+Z)再向东(+X)"。
* 2. 合法性 = 落点方块及上方一格无碰撞 + 下方一格有碰撞(可站立),
* 优先无危险方块的落点(火/岩浆/仙人掌等降级为次选)。
* 3. 落地朝向:视线水平看向床头。
* 全部被阻挡时回退到床位置向上找安全格。
*/
private Location findVanillaRespawnSpot(World world, Block head) {
Block[] parts = getBedParts(head);
Block foot = (parts != null && parts.length > 1) ? parts[1] : null;
int bedY = head.getY();
// 收集候选:床头邻格(排除床两半自身),再床尾邻格
List<Block> candidates = new ArrayList<>();
collectRing(head, foot, candidates);
if (foot != null) collectRing(foot, head, candidates);
// 排序:先床头环(保持顺序),床尾环在后;环内按 X→Z 升序(西北优先、南先于东)
candidates.sort(Comparator
.comparingInt((Block b) -> b.getY() == bedY ? 0 : 1)
.thenComparingInt(Block::getX)
.thenComparingInt(Block::getZ));
// 两轮:先无危险落点,再放宽(原版同样优先安全位)
for (int pass = 0; pass < 2; pass++) {
for (Block c : candidates) {
if (!isStandable(world, c.getX(), c.getY(), c.getZ())) continue;
boolean dangerous = isDangerous(world, c.getX(), c.getY(), c.getZ())
|| DANGEROUS.contains(world.getBlockAt(c.getX(), c.getY() - 1, c.getZ()).getType());
if (pass == 0 && dangerous) continue;
float yaw = faceBlockYaw(c, head);
return new Location(world, c.getX() + 0.5, c.getY(), c.getZ() + 0.5, yaw, 0f);
}
}
// 全被阻挡:回退到床本身向上找安全格
Location loc = new Location(world, head.getX() + 0.5, head.getY(), head.getZ() + 0.5);
for (int y = head.getY(); y < world.getMaxHeight(); y++) {
if (isStandable(world, head.getX(), y, head.getZ())) {
float yaw = faceBlockYaw(head.getX(), y, head.getZ(), head);
return new Location(world, head.getX() + 0.5, y, head.getZ() + 0.5, yaw, 0f);
}
loc.setY(y + 1);
}
return null;
}
/** 收集 center 的8个水平邻格(排除 exclude 床块及其配对半块) */
private void collectRing(Block center, Block exclude, List<Block> out) {
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
if (dx == 0 && dz == 0) continue;
Block n = center.getRelative(dx, 0, dz);
if (isBed(n)) continue;
if (exclude != null && isBedPartOf(n, exclude)) continue;
out.add(n);
}
}
}
private boolean isBedPartOf(Block b, Block anyBedPart) {
Block[] parts = getBedParts(anyBedPart);
if (parts == null) return false;
for (Block p : parts) {
if (p != null && p.equals(b)) return true;
}
return false;
}
/** 站位合法性:落点与上方一格无碰撞,脚下有支撑 */
private boolean isStandable(World world, int x, int y, int z) {
if (y - 1 < world.getMinHeight()) return false;
Block feet = world.getBlockAt(x, y, z);
Block headSpace = world.getBlockAt(x, y + 1, z);
Block ground = world.getBlockAt(x, y - 1, z);
if (feet.getType() == Material.LAVA || feet.getType() == Material.WATER) return false;
if (!feet.isPassable() || !headSpace.isPassable()) return false;
return !ground.isPassable() || ground.getType() == Material.LADDER
|| ground.getType() == Material.VINE;
}
private boolean isDangerous(World world, int x, int y, int z) {
return DANGEROUS.contains(world.getBlockAt(x, y, z).getType());
}
private float faceBlockYaw(Block from, Block target) {
return faceBlockYaw(from.getX(), from.getY(), from.getZ(), target);
}
private float faceBlockYaw(int x, int y, int z, Block target) {
double dx = (target.getX() + 0.5) - (x + 0.5);
double dz = (target.getZ() + 0.5) - (z + 0.5);
return (float) Math.toDegrees(Math.atan2(-dx, dz));
}
// ==================== Tab补全 ====================
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (!(sender instanceof Player)) {
return Collections.emptyList();
}
Player player = (Player) sender;
String cmdName = command.getName().toLowerCase();
if (cmdName.equals("home") || cmdName.equals("delhome")) {
if (args.length == 1) {
List<String> homes = new ArrayList<>();
for (HomeData home : getHomes(player.getName())) {
if (home.name.toLowerCase().startsWith(args[0].toLowerCase())) {
homes.add(home.name);
}
}
return homes;
}
} else if (cmdName.equals("sethome") || cmdName.equals("homes")) {
return Collections.emptyList();
}
return Collections.emptyList();
}
// ==================== 清理 ====================
public void shutdown() {
bedLocations.clear();
}
}
+67 -114
View File
@@ -1,114 +1,67 @@
package Sdf1_login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class IPGroupManager {
private final Main plugin;
private final int maxAccounts;
public IPGroupManager(Main plugin, int maxAccounts) {
this.plugin = plugin;
this.maxAccounts = maxAccounts;
}
public boolean canRegister(String ip) {
if (maxAccounts <= 0) return true;
if (ip == null || ip.isEmpty()) return true;
int count = getAccountCount(ip);
boolean can = count < maxAccounts;
plugin.getLogger().info(
"[IP限制] IP=" + ip
+ " 已注册=" + count
+ " 上限=" + maxAccounts
+ " 允许=" + can);
return can;
}
public int getMaxAccounts() {
return maxAccounts;
}
public int getAccountCount(String ip) {
if (ip == null || ip.isEmpty()) return 0;
return queryAccountsByIP(ip).size();
}
public List<String> getAccounts(String ip) {
return queryAccountsByIP(ip);
}
private List<String> queryAccountsByIP(String ip) {
List<String> accounts = new ArrayList<>();
Connection conn = plugin.getDb().getDb();
if (conn == null) return accounts;
try {
// 主查询:ip_address 列
PreparedStatement ps = conn.prepareStatement(
"SELECT player_name FROM users "
+ "WHERE ip_address = ?");
ps.setString(1, ip);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
accounts.add(
rs.getString("player_name"));
}
rs.close();
ps.close();
// 兜底:如果主列没数据,查 last_login_ip
if (accounts.isEmpty()) {
PreparedStatement ps2 = conn.prepareStatement(
"SELECT player_name FROM users "
+ "WHERE last_login_ip = ? "
+ "AND (ip_address IS NULL "
+ "OR ip_address = '' "
+ "OR ip_address != ?)");
ps2.setString(1, ip);
ps2.setString(2, ip);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
String name = rs2.getString("player_name");
if (!accounts.contains(name))
accounts.add(name);
}
rs2.close();
ps2.close();
}
// 兜底2:查 register_ip
if (accounts.isEmpty()) {
PreparedStatement ps3 = conn.prepareStatement(
"SELECT player_name FROM users "
+ "WHERE register_ip = ? "
+ "AND (ip_address IS NULL "
+ "OR ip_address = '') "
+ "AND (last_login_ip IS NULL "
+ "OR last_login_ip = '' "
+ "OR last_login_ip != ?)");
ps3.setString(1, ip);
ps3.setString(2, ip);
ResultSet rs3 = ps3.executeQuery();
while (rs3.next()) {
String name = rs3.getString("player_name");
if (!accounts.contains(name))
accounts.add(name);
}
rs3.close();
ps3.close();
}
plugin.getLogger().info(
"[IP限制] 查询IP=" + ip
+ " 结果数=" + accounts.size()
+ " 账号=" + accounts);
} catch (Exception e) {
e.printStackTrace();
}
return accounts;
}
}
package Sdf1_login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class IPGroupManager {
private final Main plugin;
private final int maxAccounts;
public IPGroupManager(Main plugin, int maxAccounts) {
this.plugin = plugin;
this.maxAccounts = maxAccounts;
}
/**
* 检查该IP是否还能注册新账号
*/
public boolean canRegister(String ip) {
if (maxAccounts <= 0) return true;
if (ip == null || ip.isEmpty()) return true;
return queryAccountsByIP(ip).size() < maxAccounts;
}
/**
* 获取该IP下已注册的账号数量
*/
public int getAccountCount(String ip) {
if (ip == null || ip.isEmpty()) return 0;
return queryAccountsByIP(ip).size();
}
/**
* 获取该IP下所有账号名
*/
public List<String> getAccounts(String ip) {
return queryAccountsByIP(ip);
}
/**
* 直接通过数据库连接查询指定IP下的所有账号
*/
private List<String> queryAccountsByIP(String ip) {
List<String> accounts = new ArrayList<>();
Connection conn = plugin.getDb().getDb();
if (conn == null) return accounts;
try {
PreparedStatement ps = conn.prepareStatement(
"SELECT player_name FROM users "
+ "WHERE ip_address = ?");
ps.setString(1, ip);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
accounts.add(
rs.getString("player_name"));
}
rs.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
return accounts;
}
}
@@ -1,93 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.io.IOException;
/**
* 背包滚动自动备份。
* <p>
* ★ 功能:
* 1. 由 Main 的准点定时任务驱动(第26批:每小时 0/15/30/45 分墙钟对齐,不再按启动时刻漂移),遍历所有在线玩家。
* 2. 在 PVP 竞技场 / 练习场(测试场)的玩家不备份 —— 避免竞技场装备覆盖真实背包。
* 3. 序列化 主背包 / 护甲 / 副手(extra) / 等级 / 经验,写入 inv_backup_auto 表。
* 4. 每玩家保留最近 3 份(滚动覆盖),由 DatabaseManager.saveAutoBackup 负责清理。
* <p>
* 与登录时的 saveInventoryBackup 共用同一套存储语义(level=玩家等级,
* experience=当前等级进度 p.getExp()),便于后续统一还原。
*/
public class InventoryAutoBackup {
private final Main plugin;
/** 备份周期:15 分钟(单位 tick)。★ 第26批起 Main 改墙钟对齐调度(:00/:15/:30/:45 分),此常量仅作周期语义参考,不再直接作调度入参。 */
public static final long INTERVAL_TICKS = 15L * 60L * 20L;
public InventoryAutoBackup(Main plugin) {
this.plugin = plugin;
}
/** 对所有在线玩家执行一次滚动备份 */
public void runBackup() {
for (Player p : Bukkit.getOnlinePlayers()) {
try {
backupPlayer(p);
} catch (Exception e) {
plugin.getLogger().warning(
"[自动备份] 玩家 " + p.getName()
+ " 备份失败: " + e.getMessage());
}
}
}
private void backupPlayer(Player p) {
String name = p.getName();
// ★ 第30批:黑名单玩家跳过自动备份
// (拉黑时的背包快照由 BlacklistManager 单独落库,不能被自动备份覆盖)
if (plugin.getBlacklist() != null
&& plugin.getBlacklist().isBlacklisted(name)) {
return;
}
// ★ 跳过 PVP 竞技场:竞技场内不备份,避免 PVP 装备覆盖真实背包
if (plugin.getPVPArenaManager().isInPVPArena(name)) {
return;
}
// ★ 跳过练习场 / 测试世界
if (plugin.getPVPTestManager().isInTestWorld(p)) {
return;
}
ItemStack[] contents = p.getInventory().getContents();
ItemStack[] armor = p.getInventory().getArmorContents();
ItemStack[] extra = p.getInventory().getExtraContents();
String contentsB64, armorB64, extraB64;
try {
contentsB64 = InventorySerializer.toBase64(contents);
armorB64 = InventorySerializer.toBase64(armor);
extraB64 = InventorySerializer.toBase64(extra);
} catch (IOException e) {
plugin.getLogger().warning(
"[自动备份] 序列化失败 (" + name + "): "
+ e.getMessage());
return;
}
final int level = p.getLevel();
final double experience = p.getExp(); // 当前等级进度 0.0~1.0
// ★ 读背包/等级必须主线程;落库是阻塞 DB 写 -> 投递异步执行
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
plugin.getDb().saveAutoBackup(
name, contentsB64, armorB64, extraB64,
level, experience);
plugin.getLogger().info("[自动备份] " + name + " 背包已备份");
} catch (Throwable t) {
plugin.getLogger().warning("[自动备份] 落库失败 (" + name + "): " + t.getMessage());
}
});
}
}
@@ -1,46 +1,46 @@
package Sdf1_login;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
public class InventorySerializer {
public static String toBase64(ItemStack[] items) throws IOException {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeInt(items.length);
for (ItemStack item : items) {
dataOutput.writeObject(item);
}
dataOutput.close();
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
} catch (Exception e) {
throw new IOException("Unable to serialize item stacks.", e);
}
}
public static ItemStack[] fromBase64(String data) throws IOException {
if (data == null || data.isEmpty()) {
return new ItemStack[0];
}
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
ItemStack[] items = new ItemStack[dataInput.readInt()];
for (int i = 0; i < items.length; i++) {
items[i] = (ItemStack) dataInput.readObject();
}
dataInput.close();
return items;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to deserialize item stacks.", e);
}
}
}
package Sdf1_login;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
public class InventorySerializer {
public static String toBase64(ItemStack[] items) throws IOException {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeInt(items.length);
for (ItemStack item : items) {
dataOutput.writeObject(item);
}
dataOutput.close();
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
} catch (Exception e) {
throw new IOException("Unable to serialize item stacks.", e);
}
}
public static ItemStack[] fromBase64(String data) throws IOException {
if (data == null || data.isEmpty()) {
return new ItemStack[0];
}
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
ItemStack[] items = new ItemStack[dataInput.readInt()];
for (int i = 0; i < items.length; i++) {
items[i] = (ItemStack) dataInput.readObject();
}
dataInput.close();
return items;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to deserialize item stacks.", e);
}
}
}
+33 -232
View File
@@ -21,51 +21,55 @@ public class InviteManager {
return code;
}
/**
* ★ 第九批(2026-10-12):绑定邀请码成功时立即计入邀请人
* 「本月邀请」计数(带月度重置)。
*
* <p>旧逻辑把计数放在 onInviteeCheckIn(被邀请人签到)里,
* 导致「绑定成功但未签到」时 GUI 恒显示「已邀请 0 人」(用户反馈
* 的计数 bug 根因)。现改为绑定即计数——绑定才是「邀请成功」
* 的真正时点,与债券发放同一时机,语义一致。</p>
*
* @param inviter 邀请人(被计数方)
* @param invitee 被邀请人(绑定者)
*/
public void onInviteeBind(String inviter, String invitee) {
if (inviter == null || inviter.isEmpty()) return;
public void onInviteeCheckIn(String inviteeName) {
String invitedBy = (String) plugin.getDb()
.getField(inviteeName, "invited_by");
if (invitedBy == null || invitedBy.isEmpty())
return;
String month = new SimpleDateFormat("yyyy-MM")
.format(new Date());
String lastMonth = (String) plugin.getDb()
.getField(inviter, "invite_month");
.getField(invitedBy, "invite_month");
if (!month.equals(lastMonth)) {
plugin.getDb().setField(
inviter, "invite_month", month);
invitedBy, "invite_month", month);
plugin.getDb().setField(
inviter, "monthly_invite_count", 0);
invitedBy, "monthly_invite_count", 0);
}
int count = ((Number) plugin.getDb()
.getField(inviter,
.getField(invitedBy,
"monthly_invite_count"))
.intValue();
plugin.getDb().setField(
inviter, "monthly_invite_count",
invitedBy, "monthly_invite_count",
count + 1);
}
/**
* ★ 第九批:签到链路不再重复计数——「本月邀请」计数已在
* 绑定邀请码时由 onInviteeBind 完成(见上)。若此处再 +1,
* 同一被邀请人每签到一次都会重复累加,造成计数虚高。
* 方法保留以兼容既有三处签到调用点(Main.dailySign 等),
* 但已清空计数逻辑。
*/
public void onInviteeCheckIn(String inviteeName) {
// 计数已迁移至 onInviteeBind(绑定时),签到不再计数
double rate = 0.10;
if (count + 1 > 15) {
rate = 0.60;
} else if (count + 1 > 10) {
rate = 0.35;
} else if (count + 1 > 5) {
rate = 0.15;
}
int bonus = (int) (1 * rate);
if (bonus > 0) {
plugin.getDb().addPoints(invitedBy, bonus);
Player inviterPlayer = Bukkit
.getPlayerExact(invitedBy);
if (inviterPlayer != null
&& inviterPlayer.isOnline()) {
inviterPlayer.sendMessage(
plugin.getConfig2()
.msg("invite_referral_bonus")
.replace("{points}",
String.valueOf(bonus)));
}
}
}
public List<Map<String, Object>> getAllInviteData() {
@@ -89,207 +93,4 @@ public class InviteManager {
}
return result;
}
// ==================== 第十批(2026-10-12)存量自愈 + 派生口径 ====================
/** 本月 1 号 00:00(本地时区)毫秒时间戳 */
private long monthStartTime() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis();
}
private static String str(Object o) {
return o == null ? "" : o.toString();
}
private static long lng(Object o) {
return (o instanceof Number)
? ((Number) o).longValue() : 0L;
}
/**
* ★ 第十批(2026-10-12):存量邀请数据自愈,
* onEnable 启动时调用一次(幂等)。
*
* <p>① 回填 invited_at=0 的存量绑定时间——绑定功能自项目
* 初始化(2026-05)就存在但没记时间,用户 GUI 看到
* 「绑定时间: 未知」。回填优先级:</p>
* <ol>
* <li>bond_transaction type='invitee_reward'
* (第九批起被邀请人收款,time=绑定时刻,最精确)</li>
* <li>bond_transaction type='invite_reward' 且
* target_player=被邀请人(第八批起邀请人收款)</li>
* <li>注册时间(早期绑定大多发生在注册前后,最佳代理)</li>
* <li>最后登录时间 → 当前时间</li>
* </ol>
*
* <p>② 按回填后的口径重算 monthly_invite_count / invite_month
* ——修复存量绑定不计入导致的「已邀请 0 人」。</p>
*/
public void reconcileInviteData() {
try {
List<Map<String, Object>> users =
plugin.getDb().getAllUsers();
long now = System.currentTimeMillis();
int fixedAt = 0;
// ---- ① 回填存量绑定时间 ----
for (Map<String, Object> u : users) {
String name = str(u.get("player_name"));
if (name.isEmpty()) continue;
if (str(u.get("invited_by")).isEmpty()) continue;
long invAt = lng(u.get("invited_at"));
if (invAt > 0 && invAt < 1000000000000L) {
// ★ 第十一批:秒级存量(回填时继承了秒级
// register_time)→ 原地转毫秒
plugin.getDb().setField(name, "invited_at",
invAt * 1000L);
u.put("invited_at", invAt * 1000L);
fixedAt++;
}
if (lng(u.get("invited_at")) > 0) continue;
long ts = lookupBondTx(
"player_name", name,
"invitee_reward");
if (ts <= 0) ts = lookupBondTx(
"target_player", name,
"invite_reward");
if (ts <= 0) ts = DurationParser.toMs(
lng(u.get("register_time")));
if (ts <= 0) ts = DurationParser.toMs(
lng(u.get("last_login_time")));
if (ts <= 0) ts = now;
plugin.getDb().setField(
name, "invited_at", ts);
u.put("invited_at", ts);
fixedAt++;
}
// ---- ② 重算月度计数(仅维护邀请人,与 GUI 派生口径同源) ----
long monthStart = monthStartTime();
Map<String, Integer> counter = new HashMap<>();
for (Map<String, Object> u : users) {
String inviter = str(u.get("invited_by"));
if (inviter.isEmpty()) continue;
if (DurationParser.toMs(
lng(u.get("invited_at"))) >= monthStart) {
counter.merge(inviter, 1, Integer::sum);
}
}
String curMonth = new SimpleDateFormat("yyyy-MM")
.format(new Date());
int fixedCnt = 0;
for (Map<String, Object> u : users) {
String name = str(u.get("player_name"));
if (name.isEmpty()) continue;
// 只维护邀请人(有邀请码的玩家)
if (str(u.get("invite_code")).isEmpty()) {
continue;
}
int want = counter.getOrDefault(name, 0);
if (lng(u.get("monthly_invite_count")) != want) {
plugin.getDb().setField(
name, "monthly_invite_count",
want);
fixedCnt++;
}
if (!curMonth.equals(
str(u.get("invite_month")))) {
plugin.getDb().setField(
name, "invite_month", curMonth);
}
}
if (fixedAt > 0 || fixedCnt > 0) {
plugin.getLogger().info(
"[Invite] 存量自愈: 回填绑定时间 "
+ fixedAt + " 条, 重算月度计数 "
+ fixedCnt + " 人");
}
} catch (Exception e) {
plugin.getLogger().warning(
"[Invite] 存量邀请数据自愈失败: "
+ e.getMessage());
}
}
/**
* 在 bond.db 的 bond_transaction 里查该玩家某类流水的最早时间
* (跨库:必须走 BondManager.getConnection(),
* bond_transaction 不在 login.db)
*/
private long lookupBondTx(String col, String player,
String type) {
try {
java.sql.PreparedStatement ps = plugin.getBonds()
.getConnection().prepareStatement(
"SELECT MIN(time) "
+ "FROM bond_transaction "
+ "WHERE type=? AND "
+ col + "=?");
ps.setString(1, type);
ps.setString(2, player);
java.sql.ResultSet rs = ps.executeQuery();
long t = rs.next() ? rs.getLong(1) : 0L;
rs.close();
ps.close();
// 兼容以秒为单位的历史行
if (t > 0 && t < 1000000000000L) t *= 1000L;
return t;
} catch (Exception e) {
return 0L;
}
}
/**
* ★ 第十批:派生口径的「本月邀请人数」——
* 按 invited_at >= 本月 1 号实时统计(GUI 显示用,
* 跨月自愈,不依赖增量列 monthly_invite_count)。
*/
public int getMonthlyInviteCount(String inviter) {
if (inviter == null || inviter.isEmpty()) return 0;
long monthStart = monthStartTime();
int n = 0;
for (Map<String, Object> u
: plugin.getDb().getAllUsers()) {
if (!inviter.equals(
str(u.get("invited_by")))) continue;
// ★ 第十一批:秒/毫秒归一化后再比较
if (DurationParser.toMs(
lng(u.get("invited_at"))) >= monthStart) n++;
}
return n;
}
/**
* ★ 第十批:本月绑定该玩家邀请码的玩家列表(头颅明细 GUI)。
*
* @return 每项含 name(被邀请人)与 at(绑定时间戳),
* 按绑定时间倒序
*/
public List<Map<String, Object>> getMonthlyInvitedPlayers(
String inviter) {
List<Map<String, Object>> result =
new ArrayList<>();
if (inviter == null || inviter.isEmpty()) return result;
long monthStart = monthStartTime();
for (Map<String, Object> u
: plugin.getDb().getAllUsers()) {
if (!inviter.equals(
str(u.get("invited_by")))) continue;
// ★ 第十一批:秒/毫秒归一化后再比较与展示
long ts = DurationParser.toMs(
lng(u.get("invited_at")));
if (ts < monthStart) continue;
Map<String, Object> row = new LinkedHashMap<>();
row.put("name", str(u.get("player_name")));
row.put("at", ts);
result.add(row);
}
result.sort((a, b) -> Long.compare(
lng(b.get("at")), lng(a.get("at"))));
return result;
}
}
@@ -1,95 +0,0 @@
package Sdf1_login;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class IronBlockElevator implements Listener {
private static final int MAX_RANGE = 64;
private static final int MIN_RANGE = 5; // 屏蔽±5格以内的铁块
private final Set<UUID> cooldown = new HashSet<>();
/**
* 检查指定位置脚下是否是铁块
*/
private boolean isIronBlockBelow(Location loc) {
Block block = loc.getWorld().getBlockAt(
loc.getBlockX(), loc.getBlockY() - 1,
loc.getBlockZ());
return block.getType() == Material.IRON_BLOCK;
}
/**
* 从起始位置向上或向下搜索铁块并传送
* @param dir 1=向上 -1=向下
*/
private boolean tryTeleport(Player p, int dir) {
Location loc = p.getLocation();
int baseY = loc.getBlockY();
for (int i = MIN_RANGE; i < MAX_RANGE; i++) {
int y = baseY + i * dir;
Block block = loc.getWorld().getBlockAt(
loc.getBlockX(), y, loc.getBlockZ());
if (block.getType() == Material.IRON_BLOCK) {
cooldown.add(p.getUniqueId());
Location dest = new Location(
loc.getWorld(),
loc.getX(),
block.getY() + 1,
loc.getZ());
p.teleport(dest);
org.bukkit.Bukkit.getScheduler()
.runTaskLater(
org.bukkit.Bukkit.getPluginManager()
.getPlugin("Sdf1_login"),
() -> cooldown.remove(
p.getUniqueId()),
15L);
return true;
}
}
return false;
}
// ===== 下蹲 → 向下传送 =====
@EventHandler
public void onSneak(PlayerToggleSneakEvent e) {
if (!e.isSneaking()) return;
Player p = e.getPlayer();
if (cooldown.contains(p.getUniqueId())) return;
// 必须站在铁块上
if (!isIronBlockBelow(p.getLocation())) return;
tryTeleport(p, -1);
}
// ===== 跳跃 → 向上传送 =====
@EventHandler
public void onMove(PlayerMoveEvent e) {
Player p = e.getPlayer();
if (cooldown.contains(p.getUniqueId())) return;
if (p.isSneaking()) return;
Location from = e.getFrom();
Location to = e.getTo();
if (to == null) return;
if (to.getY() <= from.getY()) return;
if (p.getVelocity().getY() <= 0) return;
// 关键:检查跳跃前的位置(from)脚下是否是铁块
// 跳跃后玩家已离开铁块上方,检查 to 会失败
if (!isIronBlockBelow(from)) return;
tryTeleport(p, 1);
}
}
@@ -1,118 +0,0 @@
package Sdf1_login;
import org.bukkit.Material;
import java.util.List;
import java.util.Map;
/**
* 物品名翻译中间人(2026-10-11,v2 改用官方 zh_cn.json)。
* <p>
* 玩家在聊天栏输入物品 ID 时,不是人人都能背下 MC 每个物品的英文 ID。
* 本类把中文名(如「钻石」)翻译为标准英文 Material 名(如 diamond),
* 入库统一用英文标准名,回收/匹配时按英文名比对。
* <p>
* 数据来源:{@link OfficialTranslations#reverseMap()} —— 官方原版 zh_cn.json
* (plugins/Sdf1_login/zh_cn.json,启动时自动加载/下载,领地容器查询等已在用)。
* 不再维护手工中文映射表。
* <p>
* 解析顺序:
* 1. 英文直通(Material.matchMaterial,支持 minecraft: 前缀与 legacy 名)
* 2. 官方中文精确(zh_cn.json 反向索引)
* 3. 归一化后精确(去空格、去 minecraft: 前缀)
* 4. 唯一前缀匹配(输入「钻」时,若全表只有一个候选以它开头则放行并回填提示)
*/
public final class ItemNameResolver {
private ItemNameResolver() {}
/**
* 解析玩家输入为 Material。
*
* @param input 玩家输入(英文 ID / minecraft: 前缀 / 官方中文名)
* @return Material;无法解析返回 null
*/
public static Material resolve(String input) {
return resolveWithHint(input, null);
}
/**
* 解析并附带「实际匹配到的中文名」用于提示(如输入「钻」且唯一命中「钻石剑」时回填)。
*/
public static Material resolveWithHint(String input, StringBuilder hintOut) {
if (input == null) return null;
String raw = input.trim();
if (raw.isEmpty()) return null;
// 1. 英文直通(含 minecraft: 前缀与 legacy 名)
Material m = Material.matchMaterial(raw);
if (m != null) return m;
Map<String, List<String>> rev = OfficialTranslations.reverseMap();
if (rev.isEmpty()) return null; // zh_cn.json 未加载,仅支持英文
// 2. 官方中文精确
Material hit = byChinese(rev, raw);
if (hit != null) return hit;
// 3. 归一化后再查(去空格、去 minecraft: 前缀、小写)
String norm = raw.replace(" ", "");
if (!norm.equals(raw)) {
m = Material.matchMaterial(norm);
if (m != null) return m;
hit = byChinese(rev, norm);
if (hit != null) return hit;
} else {
norm = raw;
}
// 4. 唯一前缀匹配(全表只有一个候选以它开头才放行)
String firstKey = null;
int hits = 0;
for (String zh : rev.keySet()) {
if (zh.startsWith(norm) && !zh.equals(norm)) {
hits++;
if (hits == 1) firstKey = zh;
if (hits > 1) break;
}
}
if (hits == 1 && firstKey != null) {
Material cand = byChinese(rev, firstKey);
if (cand != null) {
if (hintOut != null) hintOut.append(firstKey);
return cand;
}
}
return null;
}
/** 用中文名查反向索引并转 Material;未命中或非法返回 null。 */
private static Material byChinese(Map<String, List<String>> rev, String zh) {
List<String> names = rev.get(zh);
if (names == null) return null;
for (String en : names) {
Material m = Material.matchMaterial(en);
if (m != null) return m;
}
return null;
}
/**
* 英文标准名 → 中文显示名。
* 优先官方 zh_cn.json(OfficialTranslations),未命中回退 Title Case。
*/
public static String toChinese(Material mat) {
if (mat == null) return "";
String official = OfficialTranslations.lookUp(mat.name());
if (official != null && !official.isEmpty()) return official;
// 回退:下划线转空格的 Title Case
String[] parts = mat.name().split("_");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
if (sb.length() > 0) sb.append(" ");
sb.append(part.substring(0, 1).toUpperCase())
.append(part.substring(1).toLowerCase());
}
return sb.toString();
}
}
File diff suppressed because it is too large Load Diff
@@ -1,650 +0,0 @@
package Sdf1_login;
import Sdf1_login.AreaProtection.AreaConfig;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 领地方块/容器记录系统 —— 回声碎片(echo_shard)工具。
* <p>
* ★ 功能:
* 1. 领地内方块破坏/放置 → 自动写入 land_block_log
* 2. 领地内容器打开/拿取 → 自动写入 land_container_log
* 3. 玩家手持回声碎片右键/左键方块或容器 → 聊天栏打印该坐标的历史记录
* 4. /landrec give [玩家] → 发放回声碎片(由插件/管理员发放)
* <p>
* 记录保留 7 天滚动(由 Main 的每日清理定时器调用 prune)。
*/
public class LandRecordManager implements Listener {
private final Main plugin;
/** 回声碎片物品的 NBT 标识 key */
public static final String ECHO_SHARD_KEY = "sdf1_echo_shard";
/** 回声碎片物品材质(1.19+ 存在) */
public static final Material ECHO_SHARD_MATERIAL = Material.ECHO_SHARD;
/** 玩家最后一次查询的坐标缓存,翻页导航时复用,避免 getTargetBlockExact 不准 */
private final Map<UUID, Location> lastQueryLocations = new ConcurrentHashMap<>();
/** 记录查询默认条数 */
private static final int QUERY_LIMIT = 20;
/** 记录保留天数 */
public static final int RETENTION_DAYS = 7;
private final SimpleDateFormat sdf =
new SimpleDateFormat("MM-dd HH:mm");
/**
* 容器打开时的快照:用于关闭时计算"拿了什么"。
* key = 玩家名(MC 同一时刻只能打开一个容器 GUI,故按玩家唯一即可)。
*/
private final Map<String, ContainerSnapshot> openSnapshots =
new ConcurrentHashMap<>();
static class ContainerSnapshot {
String landName;
int landId;
String world;
int x, y, z;
String containerType;
Map<String, Integer> before = new HashMap<>();
}
public LandRecordManager(Main plugin) {
this.plugin = plugin;
}
// ==================== 回声碎片物品 ====================
/** 创建一枚回声碎片(带 NBT 标识,便于精准识别) */
public ItemStack createEchoShard() {
ItemStack item = new ItemStack(ECHO_SHARD_MATERIAL);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setDisplayName("§b§l回声碎片");
meta.setLore(Arrays.asList(
"§7右键/左键 方块或容器",
"§7查看领地内的破坏/拿取记录",
"§8(领地监控工具)"));
NamespacedKey key =
new NamespacedKey(plugin, ECHO_SHARD_KEY);
meta.getPersistentDataContainer().set(
key, PersistentDataType.BYTE, (byte) 1);
item.setItemMeta(meta);
}
return item;
}
/** 判断物品是否为回声碎片(材质 + NBT 双重校验) */
public boolean isEchoShard(ItemStack item) {
if (item == null || item.getType() != ECHO_SHARD_MATERIAL)
return false;
ItemMeta meta = item.getItemMeta();
if (meta == null) return false;
NamespacedKey key =
new NamespacedKey(plugin, ECHO_SHARD_KEY);
return meta.getPersistentDataContainer().has(
key, PersistentDataType.BYTE);
}
/** 直接发放一枚回声碎片给玩家(GUI 菜单调用) */
public void giveEchoShard(Player p) {
// ★ SN 管控:1人同种类仅限1个
if (plugin.getSnManager() != null
&& plugin.getSnManager().isBlocked(
p, SnManager.TYPE_ECHO)) {
long cdMin = plugin.getSnManager().cooldownMinutesLeft(p.getName());
if (cdMin > 0) {
p.sendMessage("§c§l[回声碎片] §f注销冷静期未结束,还剩约 §e" + cdMin + " §f分钟,期间无法申领新设备");
} else {
p.sendMessage("§c§l[回声碎片] §f你已有回声碎片的有效登记,"
+ "旧SN未注销前不能重新申领");
}
return;
}
ItemStack shard = createEchoShard();
if (plugin.getSnManager() != null) {
String sn = plugin.getSnManager().applySn(
p, SnManager.TYPE_ECHO, "回声碎片");
if (sn == null) {
p.sendMessage("§c§l[回声碎片] §f申领被SN系统拒绝");
return;
}
plugin.getSnManager().writeSn(
shard, sn, SnManager.TYPE_ECHO);
}
HashMap<Integer, ItemStack> left =
p.getInventory().addItem(shard);
if (!left.isEmpty()) {
p.sendMessage("§c§l[回声碎片] §f你的背包已满,无法发放");
} else {
p.sendMessage("§a§l[回声碎片] §f你获得了§b回声碎片§f,右键/左键方块或容器查看领地记录");
}
}
// ==================== 记录写入(由 AreaProtection 钩子调用)====================
/** 记录方块破坏 */
public void recordBlockBreak(AreaConfig ac, Player p,
Block block) {
recordBlock(ac, p, block, "break");
}
/** 记录方块放置 */
public void recordBlockPlace(AreaConfig ac, Player p,
Block block) {
recordBlock(ac, p, block, "place");
}
/** 记录红石元器件状态变化(压力板、按钮、拉杆等) */
public void recordRedstoneStateChange(AreaConfig ac, Player p,
Block block) {
recordBlock(ac, p, block, "state_change");
}
/** ★ 记录告示牌放置/编辑(含内容) */
public void recordSignEdit(AreaConfig ac, Player p, Block block,
String[] lines, boolean isEdit) {
try {
int landId = plugin.areaProtection.getLandIdFromDb(ac.name);
// 拼接4行内容,空行跳过
StringBuilder sb = new StringBuilder();
for (String line : lines) {
if (line != null && !line.isEmpty()) {
if (sb.length() > 0) sb.append(" | ");
sb.append(line);
}
}
String detail = sb.toString();
String action = isEdit ? "sign_edit" : "sign_place";
plugin.getDb().recordLandBlockWithDetail(
ac.name, landId,
block.getWorld().getName(),
block.getX(), block.getY(), block.getZ(),
p.getName(), action,
block.getType().name(), detail);
} catch (Exception e) {
e.printStackTrace();
}
}
private void recordBlock(AreaConfig ac, Player p, Block block,
String action) {
try {
int landId = plugin.areaProtection.getLandIdFromDb(
ac.name);
plugin.getDb().recordLandBlock(
ac.name, landId,
block.getWorld().getName(),
block.getX(), block.getY(), block.getZ(),
p.getName(), action,
block.getType().name());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 记录容器打开,并保存打开瞬间容器快照(用于关闭时计算拿取差量)。
* 仅在容器确实被允许打开时调用(钩子位于 AreaProtection
* 权限/取消检查之后)。
*/
public void recordContainerOpen(AreaConfig ac, Player p,
Location loc, String containerType,
Inventory inv) {
try {
int landId = plugin.areaProtection.getLandIdFromDb(
ac.name);
plugin.getDb().recordLandContainer(
ac.name, landId,
loc.getWorld().getName(),
loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(),
p.getName(), "open", containerType, "", 0);
ContainerSnapshot snap = new ContainerSnapshot();
snap.landName = ac.name;
snap.landId = landId;
snap.world = loc.getWorld().getName();
snap.x = loc.getBlockX();
snap.y = loc.getBlockY();
snap.z = loc.getBlockZ();
snap.containerType = containerType;
snap.before = scanInventory(inv);
openSnapshots.put(p.getName(), snap);
} catch (Exception e) {
e.printStackTrace();
}
}
// ==================== 容器关闭:计算拿取差量 ====================
@EventHandler
public void onContainerClose(InventoryCloseEvent e) {
if (!(e.getPlayer() instanceof Player)) return;
Player p = (Player) e.getPlayer();
ContainerSnapshot snap = openSnapshots.remove(p.getName());
if (snap == null) return;
Map<String, Integer> after = scanInventory(e.getInventory());
// 1. 拿取:before > after
for (Map.Entry<String, Integer> en : snap.before.entrySet()) {
int taken = en.getValue() - after.getOrDefault(en.getKey(), 0);
if (taken > 0) {
recordContainerChange(snap, p.getName(), "take",
en.getKey(), taken);
}
}
// 2. 存入:after > before
for (Map.Entry<String, Integer> en : after.entrySet()) {
int put = en.getValue() - snap.before.getOrDefault(en.getKey(), 0);
if (put > 0) {
recordContainerChange(snap, p.getName(), "put",
en.getKey(), put);
}
}
}
private void recordContainerChange(ContainerSnapshot snap,
String playerName, String action,
String detail, int amount) {
try {
plugin.getDb().recordLandContainer(
snap.landName, snap.landId,
snap.world, snap.x, snap.y, snap.z,
playerName, action, snap.containerType,
detail, amount);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** 扫描容器库存,按"类型名"聚合数量 */
private Map<String, Integer> scanInventory(Inventory inv) {
Map<String, Integer> map = new HashMap<>();
for (ItemStack it : inv.getContents()) {
if (it == null || it.getType() == Material.AIR)
continue;
map.merge(it.getType().name(),
it.getAmount(), Integer::sum);
}
return map;
}
// ==================== 回声碎片查询(右键/左键)====================
@EventHandler
public void onShardInteract(PlayerInteractEvent e) {
ItemStack item = e.getItem();
if (item == null || !isEchoShard(item)) return;
Action a = e.getAction();
if (a != Action.RIGHT_CLICK_BLOCK && a != Action.LEFT_CLICK_BLOCK
&& a != Action.RIGHT_CLICK_AIR
&& a != Action.LEFT_CLICK_AIR) return;
Player p = e.getPlayer();
// 阻止误触方块/打开容器
e.setCancelled(true);
Block target = e.getClickedBlock();
if (target == null) {
// 视线选中的方块(非 deprecated 的 getTargetBlockExact)
Block sight = p.getTargetBlockExact(6);
if (sight != null && sight.getType() != Material.AIR)
target = sight;
}
if (target == null) {
p.sendMessage("§c§l[回声碎片] §f你面前没有可查询的方块或容器");
return;
}
Location loc = target.getLocation();
lastQueryLocations.put(p.getUniqueId(), loc);
queryAndPrint(p, loc);
}
private void queryAndPrint(Player p, Location loc) {
queryAndPrint(p, loc, 0);
}
/**
* ★ 收集查询坐标组:大箱子(double chest)由两个方块组成,
* 记录写入时用"被点击的那一半"坐标,查询时用"准心对准的那一半"坐标,
* 两边坐标不一致就会查不到记录。这里沿同层同类型箱子扩展,
* 把整只大箱子的所有坐标一起查出来再合并。
*/
private List<Location> collectQueryLocations(Location loc) {
List<Location> result = new ArrayList<>();
result.add(loc);
Block start;
try {
start = loc.getBlock();
} catch (Exception ex) {
return result; // 世界未加载等异常,退回单点查询
}
Material type = start.getType();
// 只有能拼成大箱子的类型才需要扩展
if (type != Material.CHEST && type != Material.TRAPPED_CHEST) {
return result;
}
Set<String> seen = new LinkedHashSet<>();
seen.add(keyOf(start));
Deque<Block> queue = new ArrayDeque<>();
queue.add(start);
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()) {
Block cur = queue.poll();
for (int[] d : dirs) {
Block n = cur.getRelative(d[0], 0, d[1]);
if (n.getType() != type) continue;
if (seen.add(keyOf(n))) {
result.add(n.getLocation());
queue.add(n);
}
}
}
return result;
}
private String keyOf(Block b) {
return b.getX() + "," + b.getY() + "," + b.getZ();
}
private void queryAndPrint(Player p, Location loc, int page) {
String world = loc.getWorld().getName();
int x = loc.getBlockX(), y = loc.getBlockY(),
z = loc.getBlockZ();
// ★ 大箱子:把整只箱子的所有半边坐标都查一遍
List<Location> group = collectQueryLocations(loc);
// 按天分页:page=0今日,1昨日,2前日...
List<Map<String, Object>> rawBlocks = new ArrayList<>();
List<Map<String, Object>> rawContainers = new ArrayList<>();
for (Location g : group) {
int gx = g.getBlockX(), gy = g.getBlockY(), gz = g.getBlockZ();
rawBlocks.addAll(plugin.getDb().getLandBlockLogAt(
world, gx, gy, gz, QUERY_LIMIT, page));
rawContainers.addAll(plugin.getDb().getLandContainerLogAt(
world, gx, gy, gz, QUERY_LIMIT, page));
}
sortByTimeDesc(rawBlocks);
sortByTimeDesc(rawContainers);
List<Map<String, Object>> blocks = truncate(rawBlocks);
List<Map<String, Object>> containers = truncate(rawContainers);
if (blocks.isEmpty() && containers.isEmpty()) {
if (page > 0) {
p.sendMessage("§6§l[回声碎片] §e坐标 ("
+ x + "," + y + "," + z + ") 第" + (page + 1) + "页无记录");
} else {
p.sendMessage("§6§l[回声碎片] §f坐标 ("
+ x + "," + y + "," + z + ") 暂无领地记录");
}
return;
}
// 收集所有需要翻译的材料名
Set<String> materials = new LinkedHashSet<>();
for (Map<String, Object> r : blocks) {
materials.add((String) r.get("material"));
}
for (Map<String, Object> r : containers) {
if ("take".equals(r.get("action")) || "put".equals(r.get("action"))) {
materials.add((String) r.get("detail"));
}
String ct = (String) r.get("container_type");
if (ct != null && !ct.isEmpty()) {
materials.add(ct);
}
}
// 检查下一页是否有数据(决定是否显示"下一页"链接)
boolean hasNext = false;
for (Location g : group) {
int gx = g.getBlockX(), gy = g.getBlockY(), gz = g.getBlockZ();
if (!plugin.getDb().getLandBlockLogAt(world, gx, gy, gz, 1, page + 1).isEmpty()) {
hasNext = true;
break;
}
if (!plugin.getDb().getLandContainerLogAt(world, gx, gy, gz, 1, page + 1).isEmpty()) {
hasNext = true;
break;
}
}
final int currentPage = page;
final boolean hasNextPage = hasNext;
// 异步批量翻译
MaterialTranslator.translateBatch(materials)
.thenAccept(translations -> {
plugin.getServer().getScheduler().runTask(plugin, () -> {
printResults(p, x, y, z, blocks, containers, translations, currentPage, hasNextPage);
});
});
}
/** 按 time 倒序(新→旧),兼容 Long/Number 两种取值 */
private void sortByTimeDesc(List<Map<String, Object>> list) {
list.sort((a, b) -> Long.compare(timeOf(b), timeOf(a)));
}
private long timeOf(Map<String, Object> r) {
Object v = r.get("time");
return v instanceof Number ? ((Number) v).longValue() : 0L;
}
/** 截断到 QUERY_LIMIT 条,返回新列表 */
private List<Map<String, Object>> truncate(List<Map<String, Object>> list) {
if (list.size() <= QUERY_LIMIT) return list;
return new ArrayList<>(list.subList(0, QUERY_LIMIT));
}
private void printResults(Player p, int x, int y, int z,
List<Map<String, Object>> blocks,
List<Map<String, Object>> containers,
Map<String, String> translations) {
printResults(p, x, y, z, blocks, containers, translations, 0, false);
}
private void printResults(Player p, int x, int y, int z,
List<Map<String, Object>> blocks,
List<Map<String, Object>> containers,
Map<String, String> translations,
int page, boolean hasNext) {
String pageLabel = page == 0 ? "今日" : (page == 1 ? "昨日" : (page + 1) + "日前");
p.sendMessage("§6§l[回声碎片] §e坐标 ("
+ x + "," + y + "," + z + ") 的记录§7(" + pageLabel + "):");
if (!blocks.isEmpty()) {
p.sendMessage("§b— 方块记录 —");
for (Map<String, Object> r : blocks) {
String action = (String) r.get("action");
String act;
if ("break".equals(action)) {
act = "§c破坏";
} else if ("place".equals(action)) {
act = "§a放置";
} else if ("state_change".equals(action)) {
act = "§e状态变化";
} else if ("sign_place".equals(action)) {
act = "§a放置告示牌";
} else if ("sign_edit".equals(action)) {
act = "§b编辑告示牌";
} else {
act = "§7" + action;
}
String mat = (String) r.get("material");
String zh = translations.getOrDefault(mat, MaterialTranslator.toReadable(mat));
StringBuilder msg = new StringBuilder();
msg.append(" §7").append(fmt((Long) r.get("time")))
.append(" §f").append(r.get("player_name"))
.append(" ").append(act)
.append(" §e").append(mat).append(" §a").append(zh);
String detail = (String) r.get("detail");
if (detail != null && !detail.isEmpty()
&& ("sign_place".equals(action) || "sign_edit".equals(action))) {
msg.append(" §7[§f").append(detail).append("§7]");
}
p.sendMessage(msg.toString());
}
}
if (!containers.isEmpty()) {
p.sendMessage("§b— 容器记录 §7(" + pageLabel + ")—");
for (Map<String, Object> r : containers) {
String act = (String) r.get("action");
if ("open".equals(act)) {
String ct = (String) r.get("container_type");
String ctZh = translations.getOrDefault(ct, MaterialTranslator.toReadable(ct));
p.sendMessage(" §7" + fmt((Long) r.get("time"))
+ " §f" + r.get("player_name")
+ " §d打开§7[" + ct + "] §a" + ctZh);
} else if ("take".equals(act)) {
String mat = (String) r.get("detail");
String zh = translations.getOrDefault(mat, MaterialTranslator.toReadable(mat));
p.sendMessage(" §7" + fmt((Long) r.get("time"))
+ " §f" + r.get("player_name")
+ " §c拿取 §e" + mat + " §a" + zh
+ " §7x" + r.get("amount"));
} else if ("put".equals(act)) {
String mat = (String) r.get("detail");
String zh = translations.getOrDefault(mat, MaterialTranslator.toReadable(mat));
p.sendMessage(" §7" + fmt((Long) r.get("time"))
+ " §f" + r.get("player_name")
+ " §a存入 §e" + mat + " §a" + zh
+ " §7x" + r.get("amount"));
}
}
}
// ★ 可点击翻页导航
Component nav = Component.text(" §7[ ");
if (page > 0) {
nav = nav.append(Component.text("§e← 上一页")
.clickEvent(ClickEvent.runCommand("/landrec log " + page))
.hoverEvent(HoverEvent.showText(Component.text("§7点击查看前一日记录"))));
nav = nav.append(Component.text(" §7| "));
}
nav = nav.append(Component.text("§f第" + (page + 1) + "页"));
if (hasNext) {
nav = nav.append(Component.text(" §7| ")
.append(Component.text("§e下一页 →")
.clickEvent(ClickEvent.runCommand("/landrec log " + (page + 2)))
.hoverEvent(HoverEvent.showText(Component.text("§7点击查看后一日记录")))));
}
nav = nav.append(Component.text(" §7]"));
p.sendMessage(nav);
}
private String fmt(long ms) {
return sdf.format(new Date(ms));
}
// ==================== 命令:/landrec ====================
public boolean handleCommand(CommandSender sender,
String[] args) {
if (args.length == 0) {
sendHelp(sender);
return true;
}
String sub = args[0];
if (sub.equalsIgnoreCase("give")) {
// 发放权限...
boolean isOp = sender.isOp();
boolean isAreaAdmin = (sender instanceof Player)
&& plugin.areaProtection.isAreaAdmin((Player) sender);
Player target;
if (args.length >= 2) {
if (!isOp && !isAreaAdmin) {
sender.sendMessage("§c§l[回声碎片] §f你无权向他人发放回声碎片");
return true;
}
target = Bukkit.getPlayerExact(args[1]);
if (target == null) {
sender.sendMessage("§c§l[回声碎片] §f玩家 " + args[1] + " 不在线");
return true;
}
} else if (sender instanceof Player) {
target = (Player) sender;
} else {
sender.sendMessage("§c§l[回声碎片] §f请指定要发放的玩家");
return true;
}
giveEchoShard(target);
if (target != sender)
sender.sendMessage("§a§l[回声碎片] §f已发放回声碎片给 " + target.getName());
return true;
}
if (sub.equalsIgnoreCase("log")) {
if (!(sender instanceof Player)) {
sender.sendMessage("§c§l[回声碎片] §f此命令仅限玩家使用");
return true;
}
Player p = (Player) sender;
int page = 0; // 默认今日
boolean isNav = false; // true=从翻页链接跳转,复用 lastQueryLocations
if (args.length >= 2) {
try {
page = Math.max(0, Integer.parseInt(args[1]) - 1);
isNav = true;
} catch (NumberFormatException ignored) {
sender.sendMessage("§c§l[回声碎片] §f页码格式错误");
return true;
}
}
// 翻页时复用上次查询坐标,避免 getTargetBlockExact 玩家未对准
Location navLoc = isNav ? lastQueryLocations.get(p.getUniqueId()) : null;
if (navLoc != null) {
queryAndPrint(p, navLoc, page);
return true;
}
// 首次查询或缓存过期,取准心方块
Block target = p.getTargetBlockExact(6);
if (target == null || target.getType() == Material.AIR) {
sender.sendMessage("§c§l[回声碎片] §f你面前没有可查询的方块或容器");
return true;
}
Location loc = target.getLocation();
if (!isNav) {
lastQueryLocations.put(p.getUniqueId(), loc);
}
queryAndPrint(p, loc, page);
return true;
}
sendHelp(sender);
return true;
}
private void sendHelp(CommandSender sender) {
sender.sendMessage("§6§l[回声碎片] §e指令:");
sender.sendMessage(" §7/landrec give §f- 给自己发放一枚回声碎片");
sender.sendMessage(" §7/landrec give <玩家> §f- 向他人发放(需 OP/领地管理员)");
sender.sendMessage(" §7/landrec log §f- 查看当前方块今日记录");
sender.sendMessage(" §7/landrec log <页码> §f- 查看指定日期的记录(1=今日 2=昨日 ...)");
sender.sendMessage(" §7手持回声碎片右键/左键方块或容器 §f- 查看该处今日记录");
}
}
+42 -222
View File
@@ -12,13 +12,6 @@ public class LoginManager {
this.plugin = plugin;
}
/** ★第48批#244:/login 失败自动对账重试的每人限流(值=上次对账触发时刻) */
private final java.util.Map<String, Long> pwSyncRetryAt =
new java.util.concurrent.ConcurrentHashMap<>();
/** ★第48批#244:正在对账重试中的玩家(防递归) */
private final java.util.Set<String> pwSyncRetrying =
java.util.concurrent.ConcurrentHashMap.newKeySet();
public boolean handleRegister(Player p,
String[] args) {
String name = p.getName();
@@ -73,16 +66,6 @@ public class LoginManager {
plugin.getDb().createUser(
name, hash, salt);
plugin.getLoggedIn().add(name);
// ★ 记录Java手动登录:5分钟内重连可直接放行(检查点1)
if (plugin.webManager != null) {
plugin.webManager.recordJavaLogin(name, plugin.getPlayerIP(p));
// ★ 第57批:/login 成功后推送 login_verified=1 给 PHP
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
plugin.webManager.pushLoginVerified(name);
});
}
p.setAllowFlight(false);
p.setFlying(false);
plugin.getDb().setLoggedIn(name, true);
plugin.getDb().setField(name,
"last_login_time",
@@ -94,16 +77,13 @@ public class LoginManager {
plugin.getDb().setField(name,
"register_time",
System.currentTimeMillis());
// ★ 二十二批:DB 读挪异步线程,菜单雪球延后到恢复完成回调
plugin.restoreInventory(p,
() -> plugin.giveMenuSnowball(p));
plugin.restoreInventory(p);
plugin.recordIPLogin(p);
plugin.giveMenuSnowball(p);
p.sendMessage(plugin.getConfig2()
.msg("reg_success"));
playRegisterSound(p);
// ★ 注册成功:actionbar 提示1分钟保存刚才的账号和密码
plugin.showCredentialSaveReminder(p, name, pwd);
try {
org.bukkit.plugin.Plugin cy =
@@ -118,17 +98,6 @@ public class LoginManager {
}
} catch (Exception ignored) {
}
// ★ 注册后立即同步用户数据到PHP
if (plugin.webManager != null) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try { plugin.webManager.syncUserRegistrations(); }
catch (Exception e) {
plugin.getLogger().warning("[Web通信] 注册后同步用户异常: " + e.getMessage());
}
});
}
return true;
}
@@ -147,16 +116,7 @@ public class LoginManager {
public boolean handleLogin(Player p,
String[] args) {
String name = p.getName();
// ★ 在 handleLogin 方法开头
if (plugin.getNeedsPasswordChange().contains(name)
&& plugin.getLoggedIn().contains(name)) {
// 已登录但还没改密码,只允许执行 /sdf1_login pw
p.sendMessage("§c请先修改密码: /sdf1_login pw <旧密码> <新密码>");
return true;
}
try {
if (plugin.getLoggedIn().contains(name)) {
p.sendMessage(plugin.getConfig2()
@@ -168,16 +128,6 @@ public class LoginManager {
.msg("not_registered"));
return true;
}
// ★ 风控检查:封禁期内拒绝登录
if (plugin.getRiskControl().isBanned(name)) {
int remaining = plugin.getRiskControl()
.getBanRemainingSeconds(name);
p.sendMessage("§c§l[安全风控] §f账号因密码错误过多已被封禁,"
+ "剩余 §e" + remaining + " §f秒");
return true;
}
if (args.length < 1) {
p.sendMessage("§c用法: /login <密码>");
return true;
@@ -200,45 +150,57 @@ public class LoginManager {
plugin.getDb().checkPassword(
name, hash);
if (matchMain) {
// ★ IP风控双验证第一步:只认密码,不解冻、不恢复背包
if (markDualStep1(p, false)) return true;
// ★第48批#249:已绑定2FA → 密码过后强制第二关 /2fa code
if (requireTwoFaIfEnabled(p, false)) return true;
finishPasswordLogin(p, false);
plugin.getLoggedIn().add(name);
plugin.getDb().setLoggedIn(
name, true);
plugin.getDb().setField(name,
"last_login_time",
System.currentTimeMillis());
plugin.getDb().setField(name,
"last_online_check",
System.currentTimeMillis());
// 只在有有效备份时恢复
plugin.restoreInventory(p);
plugin.recordIPLogin(p);
plugin.giveMenuSnowball(p);
p.sendMessage(plugin.getConfig2()
.msg("login_success"));
activateCY(p, name);
return true;
}
String pwdResult =
boolean matchTemp =
plugin.getDb()
.checkPasswordWithFallback(
.checkPasswordOrTemp(
name, hash);
if (pwdResult != null) {
// ★ IP风控双验证第一步:只认密码,不解冻、不恢复背包
if (markDualStep1(p, true)) return true;
// ★第48批#249:已绑定2FA → 密码过后强制第二关 /2fa code
if (requireTwoFaIfEnabled(p, true)) return true;
finishPasswordLogin(p, true);
if (matchTemp) {
plugin.getLoggedIn().add(name);
plugin.getDb().setLoggedIn(
name, true);
plugin.getDb().setField(name,
"last_login_time",
System.currentTimeMillis());
plugin.getDb().setField(name,
"last_online_check",
System.currentTimeMillis());
plugin.restoreInventory(p);
plugin.recordIPLogin(p);
plugin.giveMenuSnowball(p);
plugin.getNeedsPasswordChange()
.add(name);
p.sendMessage(plugin.getConfig2()
.msg("login_success"));
p.sendMessage(
"§c§l[警告] §f您使用的是临时密码,请尽快修改密码!");
p.sendMessage(
"§7用法: /sdf1_login pw");
activateCY(p, name);
return true;
}
// ★第54批:密码不匹配 → 先同步账号数据(拉回PHP侧凭证入库为主密码),
// 15秒/人限流;同步完成后主线程自动重校验(以Java本地login.db为准),仍未过才计失败次数
if (maybeRetryAfterWebSync(p, pwd)) return true;
// ★ 密码错误,记录风控
int remaining = plugin.getRiskControl()
.recordFailAttempt(p);
if (remaining < 0) {
// 已被封禁(triggerBan内部已踢出)
return true;
}
p.sendMessage(plugin.getConfig2()
.msg("login_failed"));
if (remaining > 0) {
p.sendMessage("§c§l[风控] §f剩余 §e"
+ remaining + " §f次尝试机会");
}
} catch (Exception e) {
plugin.getLogger().severe(
"[Sdf1_login] handleLogin异常: "
@@ -251,148 +213,6 @@ public class LoginManager {
}
/**
* IP风控「密码 + 2FA」顺序两关的第一步。
* 密码正确只记录进度:<b>不加入 loggedIn、不恢复背包</b>,必须等第二步 /2fa code 通过才收口。
*
* @return true = 该玩家处于双验证流程,本轮 /login 到此为止
*/
private boolean markDualStep1(Player p, boolean tempPassword) {
TwoFactorManager twofa = plugin.getTwofa();
String name = p.getName();
if (twofa == null || !twofa.isDualVerify(p)) return false;
twofa.onDualPasswordPassed(p, tempPassword);
// 密码这一步确实对了 → 重置「密码错误次数」风控(不代表已登录,仍不解冻)
plugin.getRiskControl().onLoginSuccess(name);
p.sendMessage("§a§l[双重验证] §a第一步密码验证通过(尚未解冻)");
p.sendMessage("§7第二步: 执行 §f/2fa code <动态码|恢复代码>");
p.sendMessage("§c两步全部通过后才会解冻并恢复背包");
return true;
}
/**
* ★第48批#249:已绑定 2FA(twofa_enabled=1)的玩家,密码通过后不直接放行,
* 转入「密码 + 2FA」双验证第二步(等 /2fa code)。
* 仅在该玩家当前不在双验证流程时生效(IP风控已 mark 的走 markDualStep1)。
*
* @return true = 已进入双验证流程,本轮 /login 到此为止
*/
private boolean requireTwoFaIfEnabled(Player p, boolean tempPassword) {
TwoFactorManager twofa = plugin.getTwofa();
String name = p.getName();
if (twofa == null) return false;
if (twofa.isDualVerify(p)) return false; // IP风控路径已处理
if (!plugin.getDb().userExists(name)) return false;
if (!twofa.isEnabled(name)) return false; // 未绑定2FA:维持原单步登录
// 密码这一步确实对了 → 建立双验证状态并记录进度(不解冻、不恢复背包)
twofa.markDualVerify(p, plugin.getPlayerIP(p));
twofa.onDualPasswordPassed(p, tempPassword);
// 重置「密码错误次数」风控(密码对了,但仍未完成登录)
plugin.getRiskControl().onLoginSuccess(name);
p.sendMessage("§a§l[双重验证] §a第一步密码验证通过(尚未解冻)");
p.sendMessage("§7第二步: 执行 §f/2fa code <动态码|恢复代码>");
p.sendMessage("§c两步全部通过后才会解冻并恢复背包");
return true;
}
/**
* ★第54批:密码校验失败时先同步账号数据(拉回PHP侧凭证入库)再自动重试一次。
* 15秒/人限流;重试仍失败走正常风控计数。
*
* @return true = 本轮 /login 已交给异步对账流程处理(调用方直接 return)
*/
private boolean maybeRetryAfterWebSync(Player p, String pwd) {
if (plugin.webManager == null) return false;
String name = p.getName();
if (pwSyncRetrying.contains(name)) return false; // 重试轮失败:不再触发
long now = System.currentTimeMillis();
Long last = pwSyncRetryAt.get(name);
if (last != null && now - last < 15000L) return false; // 15秒/人限流
pwSyncRetryAt.put(name, now);
pwSyncRetrying.add(name);
p.sendMessage("§e§l[登录] §e正在同步账号数据…");
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
plugin.webManager.pushWebLoginCredentials(); // 含 alignGate 拉回
} catch (Throwable t) {
plugin.getLogger().warning("[登录] 对账重试同步异常: " + t.getMessage());
}
Bukkit.getScheduler().runTask(plugin, () -> {
try {
Player online = Bukkit.getPlayerExact(name);
if (online == null || !online.isOnline()) return;
// 主线程重新走一次完整登录校验(含2FA/风控前置)
handleLogin(online, new String[]{pwd});
} finally {
pwSyncRetrying.remove(name);
}
});
});
return true;
}
/**
* 密码登录成功的统一收口:解冻 + 恢复背包 + 记录登录信息。
* 调用点:/login 主密码、/login 临时密码、IP风控双验证第二步通过后。
*/
public void finishPasswordLogin(Player p, boolean tempPassword) {
String name = p.getName();
// ★ 登录成功,重置风控
plugin.getRiskControl().onLoginSuccess(name);
plugin.getLoggedIn().add(name);
// ★ 记录Java手动登录:5分钟内重连可直接放行(检查点1)
if (plugin.webManager != null) {
plugin.webManager.recordJavaLogin(name, plugin.getPlayerIP(p));
// ★ 第57批续3:/login 成功后推送 login_verified=1 给 PHP(统一收口)
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
plugin.webManager.pushLoginVerified(name);
});
}
plugin.getDb().setLoggedIn(name, true);
if (!tempPassword) {
// 主密码路径保留原有的重复写入(行为与历史版本一致)
plugin.getDb().setLoggedIn(name, true);
}
plugin.getDb().setField(name, "last_login_time",
System.currentTimeMillis());
plugin.getDb().setField(name, "last_online_check",
System.currentTimeMillis());
// ★ 立即同步在线状态到PHP(异步,避免阻塞主线程)
if (!tempPassword && plugin.webManager != null) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
plugin.webManager.syncOnlinePlayers();
} catch (Exception e) {
plugin.getLogger().warning("[Web通信] 异步syncOnlinePlayers异常: " + e.getMessage());
}
});
}
// 登录成功关闭飞行
p.setAllowFlight(false);
p.setFlying(false);
// 只在有有效备份时恢复
// ★ 二十二批:DB 读挪异步线程,菜单雪球延后到恢复完成回调
plugin.restoreInventory(p,
() -> plugin.giveMenuSnowball(p));
plugin.recordIPLogin(p);
if (tempPassword) {
// ★ 确保这行存在
plugin.getNeedsPasswordChange().add(name);
}
p.sendMessage(plugin.getConfig2().msg("login_success"));
if (tempPassword) {
p.sendMessage("§c§l[警告] §f您使用的是临时密码,请尽快修改密码!");
p.sendMessage("§7用法: /sdf1_login pw");
}
activateCY(p, name);
// ★ 登录后恢复区域效果
Sdf1_login.AreaProtection areaProt =
plugin.getAreaProtection();
if (areaProt != null) {
areaProt.onPlayerJoin(p);
}
}
public void handleReset(Player p) {
String name = p.getName();
String emailAddr = (String)
File diff suppressed because it is too large Load Diff
@@ -1,136 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* 主线程卡顿看门狗(第十五批,2026-10-14)。
*
* <p>背景:生产服 2026-10-14 14:52:08~14:52:29 主线程静默 21 秒
* (玩家在「我的信息」GUI 做自定义菜单图标交换期间),全程无 ERROR、
* 只有 SSL 断路器 WARN —— 日志里没有任何栈信息能定位卡在哪一帧。
* 本看门狗用于下次复现时直接抓出现场。
*
* <p>机制:
* <ol>
* <li>主线程每 tick 心跳(同步定时任务,主线程一卡心跳就停走);</li>
* <li>独立 daemon 线程每 1 秒检查心跳年龄,≥5 秒 → 立刻把主线程栈
* (深度 120 帧)打进日志,标签 {@code [主线程看门狗]};</li>
* <li>持续卡顿每 10 秒补一次栈(观察卡点是否在变);</li>
* <li>恢复后补一条「恢复」日志,带总卡顿时长;</li>
* <li>若看门狗自己 sleep 都睡了 3 倍以上时长 → JVM/主机级停顿,
* 单独记一条(此时单线程栈已无意义)。</li>
* </ol>
*
* <p>生命周期:daemon 线程 + {@code while (plugin.isEnabled())} 自退出,
* onDisable 后心跳任务被调度器取消 → 1 秒内自然结束,无需手动 stop。
*/
public final class MainThreadWatchdog implements Runnable {
/** 心跳超过这个年龄视为主线程卡顿 */
private static final long STALL_MS = 5000L;
/** 检查间隔 */
private static final long CHECK_MS = 1000L;
/** 持续卡顿时补栈间隔 */
private static final long REDUMP_MS = 10000L;
/** 抓栈深度 */
private static final int DEPTH = 120;
private final JavaPlugin plugin;
private volatile long heartbeat;
private volatile boolean stalled;
private volatile long stallStartAt;
private volatile long lastDumpAt;
public MainThreadWatchdog(JavaPlugin plugin) {
this.plugin = plugin;
}
/** 在 onEnable 里调用一次即可。 */
public void start() {
heartbeat = System.currentTimeMillis();
// 主线程心跳:每 tick 刷一次;主线程被卡住时它自然停走
Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
heartbeat = System.currentTimeMillis();
}
}, 1L, 1L);
Thread t = new Thread(this, "sdf1-main-watchdog");
t.setDaemon(true);
t.start();
plugin.getLogger().info("[主线程看门狗] 已启动(主线程卡顿≥"
+ (STALL_MS / 1000) + " 秒自动抓栈打日志)");
}
@Override
public void run() {
while (plugin.isEnabled()) {
long sleepBegin = System.nanoTime();
try {
Thread.sleep(CHECK_MS);
} catch (InterruptedException ie) {
return;
}
long sleptMs = (System.nanoTime() - sleepBegin) / 1000000L;
if (sleptMs > CHECK_MS * 3) {
// 连看门狗自己都被冻住 → JVM/GC/主机级停顿,栈已无意义
plugin.getLogger().warning("[主线程看门狗] ★ 全线程停顿约 "
+ sleptMs + "ms(JVM/主机级,非单点死锁)");
}
if (!plugin.isEnabled()) return;
long now = System.currentTimeMillis();
long age = now - heartbeat;
if (age >= STALL_MS) {
if (!stalled) {
stalled = true;
stallStartAt = now;
lastDumpAt = now;
dumpMainThread(age, true);
} else if (now - lastDumpAt >= REDUMP_MS) {
lastDumpAt = now;
dumpMainThread(age, false);
}
} else if (stalled) {
stalled = false;
plugin.getLogger().warning("[主线程看门狗] ✓ 主线程已恢复,本次卡顿共 "
+ (now - stallStartAt) + "ms");
}
}
}
private void dumpMainThread(long ageMs, boolean first) {
plugin.getLogger().warning("[主线程看门狗] ★ 主线程已 " + ageMs
+ "ms 未推进!"
+ (first ? "首次抓栈(卡点看最上面几帧):" : "补栈:"));
try {
Thread main = null;
for (Thread t : Thread.getAllStackTraces().keySet()) {
if ("Server thread".equals(t.getName())) {
main = t;
break;
}
}
if (main == null) {
plugin.getLogger().warning(" (没找到 Server thread)");
return;
}
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
ThreadInfo ti = mx.getThreadInfo(main.getId(), DEPTH);
if (ti == null) {
plugin.getLogger().warning(" (拿不到主线程 ThreadInfo)");
return;
}
plugin.getLogger().warning(" 主线程状态: " + ti.getThreadState());
for (StackTraceElement el : ti.getStackTrace()) {
plugin.getLogger().warning(" at " + el);
}
} catch (Throwable t) {
plugin.getLogger().warning(" 抓栈失败: " + t);
}
}
}
@@ -1,962 +0,0 @@
package Sdf1_login;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 维护模式(白名单)管理器
*
* 配置文件:plugins/Sdf1_login/白名单.txt,分两个段落:
* [控制段] 启用 / 开始时间 / 结束时间 / 时长 / 消息 等键值对
* [白名单段] 每行一个玩家名(也可用逗号分隔多个)
*
* 特性:
* - 24 小时硬封顶:无论怎么配,单次维护窗口最长 24 小时,到点自动结束
* - 多格式时间:10位秒级时间戳 / 13位毫秒 / yyyy-MM-dd HH:mm / 2026年9月28日14时30分 / 只写 HH:mm(今天)
* - 未写时长与结束时间时默认 24 小时
* - 消息支持 & 与 § 颜色码、整段 JSON 文本组件、\n 与 &lt;br&gt; 换行
* - 变量:username / 用户名、starttime / 开始时间、endtime / 结束时间
* - 玩家登录(异步预登录)、加入、退出时热重载配置,改完文件即生效,无需重启
* - 拦截发生在异步预登录阶段,不给未授权客户端发送任何世界/区块数据包
* - 独立于 MC 自带白名单,互不影响
*/
public class MaintenanceManager implements Listener {
/** 24小时硬封顶 */
private static final long MAX_WINDOW_MS = 24L * 60L * 60L * 1000L;
/** 未配置时长/结束时间时的默认窗口 */
private static final long DEFAULT_WINDOW_MS = MAX_WINDOW_MS;
private static final String DEFAULT_MESSAGE =
"&c&l[服务器维护] &7服务器正在维护中,请稍后再试&7(结束时间: &e{结束时间}&7)";
private static final Pattern NUM_PAT = Pattern.compile("\\d+");
/** 时长单位正则:单位部分匹配「字母 + 汉字区(一~龥)」,例:10秒 / 5分 / 2小时 */
private static final Pattern DUR_PAT = Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*([a-zA-Z一-龥]*)");
private static final Pattern AMP_COLOR_PAT = Pattern.compile("&([0-9a-fk-orA-FK-OR])");
private final Main plugin;
private final File file;
/** 解析互斥:异步登录线程与主线程(join/quit)都可能触发热重载 */
private final Object lock = new Object();
private volatile long lastMtime = -1L;
private volatile boolean enabled = false;
private volatile long windowStart = 0L;
private volatile long windowEnd = 0L;
private volatile boolean opBypass = true;
private volatile String rawMessage = DEFAULT_MESSAGE;
private volatile Set<String> whitelistLower = Collections.emptySet();
/** 未显式写「开始时间」时记住本轮起点,避免热重载把窗口反复清零 */
private long implicitStart = 0L;
/** 到期日志只打一次 */
private volatile boolean expiryLogged = false;
/** OP 查询缓存(异步线程里只查一次) */
private final ConcurrentHashMap<String, Boolean> opCache = new ConcurrentHashMap<>();
public MaintenanceManager(Main plugin) {
this.plugin = plugin;
this.file = new File(plugin.getDataFolder(), "白名单.txt");
try {
Files.createDirectories(plugin.getDataFolder().toPath());
} catch (IOException e) {
plugin.getLogger().warning("[维护模式] 创建数据目录失败: " + e.getMessage());
}
if (!file.exists()) {
writeDefaultFile();
}
reload(true);
}
// ==================== 对外接口 ====================
/** 维护窗口是否正在生效 */
public boolean isActive() {
if (!enabled) return false;
long now = System.currentTimeMillis();
return now >= windowStart && now < windowEnd;
}
/** 玩家是否在白名单内(大小写不敏感) */
public boolean isWhitelisted(String name) {
if (name == null || name.isEmpty()) return false;
return whitelistLower.contains(name.toLowerCase(Locale.ROOT));
}
public long getWindowStart() {
return windowStart;
}
public long getWindowEnd() {
return windowEnd;
}
public Set<String> getWhitelist() {
return whitelistLower;
}
// ==================== 配置文件 ====================
private void writeDefaultFile() {
String tpl = String.join("\n",
"# =========================================================",
"# 维护模式(白名单)配置文件",
"# 修改保存后无需重启:玩家尝试登录 / 加入 / 退出时自动热加载",
"#",
"# [控制段] 用「键 = 值」写服务器开关、时间与提示语",
"# [白名单段] 严格一行一个玩家名(一行只写一个,不支持逗号/空格分隔)",
"# (标题行漏写也能兜底收录,但请尽量保留 [白名单] 标题)",
"#",
"# 可用键:",
"# 启用 = true / false",
"# 开始时间 = 时间戳 / 2026-09-28 20:00 / 2026年9月28日20时00分(留空=立即开始)",
"# 结束时间 = 同上(留空则按时长或默认24小时计算)",
"# 时长 = 24h / 12小时 / 90分钟(单次维护最长 24 小时,硬封顶)",
"# OP可绕过 = true / false(OP 是否可以绕过维护直接进服)",
"# 消息 = 支持 &a§a 颜色码、整段 JSON(对象 {...} 或数组 [...])、\\n 与 <br> 换行",
"# 可用变量 {username} {starttime} {endtime}(带花括号,JSON 内同样生效)",
"# =========================================================",
"",
"# ===== 控制段 =====",
"启用 = false",
"开始时间 =",
"结束时间 =",
"时长 = 24h",
"OP可绕过 = true",
"消息 = " + DEFAULT_MESSAGE,
"",
"# ===== 白名单段 =====",
"[白名单]",
"");
try {
Files.write(file.toPath(), tpl.getBytes(StandardCharsets.UTF_8));
plugin.getLogger().info("[维护模式] 已生成默认配置: " + file.getAbsolutePath());
} catch (IOException e) {
plugin.getLogger().warning("[维护模式] 写入默认配置失败: " + e.getMessage());
}
}
/** 玩家登录/加入/退出时调用:文件变了就重新解析 */
public void reloadIfChanged() {
if (!file.exists()) return;
long m;
try {
m = file.lastModified();
} catch (Exception e) {
return;
}
if (m == lastMtime) return;
reload(true);
}
private void reload(boolean force) {
synchronized (lock) {
long m;
try {
m = file.lastModified();
} catch (Exception e) {
return;
}
if (!force && m == lastMtime) return;
String text;
try {
text = decode(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
plugin.getLogger().warning("[维护模式] 读取配置失败: " + e.getMessage());
return;
}
// 行扫描抽成 static parseConfig(含段标题丢失兜底 / 条目清洗),便于单测
ParsedConfig pc = parseConfig(text, plugin.getLogger());
Map<String, String> ctl = pc.ctl;
Set<String> wl = pc.wl;
boolean wasActive = isActive();
boolean wasEnabled = this.enabled;
String enRaw = pick(ctl,
"启用", "开启", "开关", "维护", "enable", "enabled", "maintenance", "on");
boolean en = toBool(enRaw, false);
Long st = parseTime(pick(ctl, "开始时间", "开始", "起始时间", "start", "starttime", "begintime"));
Long enT = parseTime(pick(ctl, "结束时间", "结束", "截止时间", "end", "endtime"));
Long dur = parseDuration(pick(ctl, "时长", "持续时间", "持续", "duration", "hours", "小时"));
String opRaw = pick(ctl, "OP可绕过", "op可绕过", "OP绕过", "管理员绕过",
"opbypass", "op_bypass", "op", "bypass");
boolean op = toBool(opRaw, true);
if (enRaw != null && !isBoolWord(enRaw)) {
plugin.getLogger().warning("[维护模式] 「启用」的值不是可识别的布尔词: ["
+ enRaw + "],按 false 处理(请写 true / false)");
}
if (opRaw != null && !isBoolWord(opRaw)) {
plugin.getLogger().warning("[维护模式] 「OP可绕过」的值不是可识别的布尔词: ["
+ opRaw + "],按 false 处理(请写 true / false)");
}
String msg = pick(ctl, "消息", "提示", "维护消息", "踢出消息", "message", "msg", "kickmessage");
if (msg == null || msg.isEmpty()) msg = DEFAULT_MESSAGE;
long now = System.currentTimeMillis();
if (st == null) {
// 没写开始时间:沿用上一轮未过期的起点,否则从现在开始
if (implicitStart > 0L && implicitStart + MAX_WINDOW_MS > now) {
st = implicitStart;
} else {
st = now;
}
}
implicitStart = st;
long end;
if (enT != null) {
end = enT;
} else if (dur != null) {
end = st + dur;
} else {
end = st + DEFAULT_WINDOW_MS;
}
// ★ 24小时硬封顶
if (end > st + MAX_WINDOW_MS) end = st + MAX_WINDOW_MS;
if (end < st) end = st;
this.enabled = en;
this.windowStart = st;
this.windowEnd = end;
this.opBypass = op;
this.rawMessage = msg;
Set<String> lowered = new LinkedHashSet<>();
for (String n : wl) lowered.add(n.toLowerCase(Locale.ROOT));
this.whitelistLower = Collections.unmodifiableSet(lowered);
this.lastMtime = m;
if (wasEnabled && !en) {
this.implicitStart = 0L; // 手动关掉后,下次开启重新计时
}
this.expiryLogged = false;
this.opCache.clear();
boolean nowActive = isActive();
if (nowActive && !wasActive) {
plugin.getLogger().info("[维护模式] ★ 维护已开启,白名单 " + whitelistLower.size()
+ " 人,窗口 " + fmt(windowStart) + " ~ " + fmt(windowEnd));
} else if (nowActive) {
plugin.getLogger().info("[维护模式] 配置已热重载,白名单 " + whitelistLower.size()
+ " 人,窗口 " + fmt(windowStart) + " ~ " + fmt(windowEnd));
} else if (wasActive) {
plugin.getLogger().info("[维护模式] 维护已结束");
}
// ★ 直接把读到的条目与控制段键打出来,线上「配了却进不去」时一眼能对账
if (nowActive && !whitelistLower.isEmpty()) {
plugin.getLogger().info("[维护模式] 白名单条目: [" + summarize(whitelistLower) + "]");
}
if (nowActive && whitelistLower.isEmpty()) {
plugin.getLogger().warning("[维护模式] ⚠ 维护已开启但白名单为 0 人!段标题[白名单]识别="
+ pc.sawWhiteHeader
+ (opBypass ? ",OP 仍可绕过" : ",且 OP 不可绕过:所有玩家都会被拦在外面")
+ ";控制段读到的键: " + ctl.keySet() + ",请检查 [白名单] 段标题与条目写法");
}
}
}
// ==================== 登录拦截 ====================
@EventHandler(priority = EventPriority.LOWEST)
public void onPreLogin(AsyncPlayerPreLoginEvent e) {
// 登录阶段热重载:改完文件直接重连即可生效
try {
reloadIfChanged();
} catch (Throwable t) {
// 配置读取异常不能影响正常登录
}
if (!isActive()) {
// 到期后只提示一次
if (enabled && !expiryLogged && System.currentTimeMillis() >= windowEnd) {
expiryLogged = true;
plugin.getLogger().info("[维护模式] 维护窗口已到期(" + fmt(windowEnd) + "),自动结束");
}
return;
}
String name = e.getName();
if (isWhitelisted(name)) return;
if (opBypass && isOp(name)) {
plugin.getLogger().info("[维护模式] 放行OP: " + name);
return;
}
// ★ 无感化拦截:在异步预登录阶段直接断开,客户端只看到自定义提示,
// 服务端不会为他分配世界/区块,也不产生多余的网络往返
e.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, buildMessage(name));
plugin.getLogger().info("[维护模式] 已拦截未在白名单的玩家: " + name
+ "(当前白名单 " + whitelistLower.size() + " 人)");
}
@EventHandler(priority = EventPriority.MONITOR)
public void onJoin(PlayerJoinEvent e) {
try {
reloadIfChanged();
} catch (Throwable ignored) {
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent e) {
try {
reloadIfChanged();
} catch (Throwable ignored) {
}
}
// ==================== 提示消息 ====================
private Component buildMessage(String playerName) {
String msg = this.rawMessage;
long s = this.windowStart;
long e = this.windowEnd;
msg = replaceVar(msg, new String[]{"username", "用户名", "用户", "player", "玩家名",
"玩家", "name", "昵称"}, playerName);
msg = replaceVar(msg, new String[]{"starttime", "start_time", "开始时间",
"起始时间", "start"}, fmt(s));
msg = replaceVar(msg, new String[]{"endtime", "end_time", "结束时间",
"截止时间", "end"}, fmt(e));
return format(msg);
}
// ==================== 占位符定界符 ====================
/**
* 占位符可用的定界符对:中英文小括号、中括号、花括号,外加 %…% 与 &lt;…&gt;。
* 例:{username} [username] (username) 【用户】 (用户) {username} [username]
* 「玩家名」 『开始时间』 %endtime% &lt;结束时间&gt;
* JSON 模式会跳过花括号 {} 这一对——JSON 对象结构本身就是花括号,避免不必要的冲突。
*/
private static final String[][] PLACEHOLDER_DELIMS = {
{"{", "}"},
{"[", "]"},
{"(", ")"},
{"【", "】"},
{"(", ")"},
{"{", "}"},
{"[", "]"},
{"「", "」"},
{"『", "』"},
{"%", "%"},
{"<", ">"}
};
/** 是否 Legacy 色码字符(0-9a-fk-or,大小写不敏感,含 hex 的 x) */
private static boolean isLegacyCodeChar(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|| "kKlLoOmMnNrRxX".indexOf(c) >= 0;
}
/**
* 防御性剥离:去掉首尾空白与 Legacy 色码(&amp;c / §c / &amp;x&amp;R&amp;R&amp;R&amp;R&amp;R&amp;R)。
* headDeco(可为 null)收集头部被剥离的色码原串,JSON 解析成功后回贴到组件上;
* 尾部色码只剥离不收集——它后面已无文本,应用它没有意义。
* 这层剥离专门解决「&amp;c&amp;l 包着 JSON → 判不出 JSON → 原样吐源码给玩家」的冲突。
*/
private static String stripDecoration(String s, StringBuilder headDeco) {
if (s == null) return "";
int b = 0, e = s.length();
while (b < e) {
char c = s.charAt(b);
if (Character.isWhitespace(c)) {
b++;
continue;
}
if ((c == '&' || c == '§') && b + 1 < e && isLegacyCodeChar(s.charAt(b + 1))) {
if (headDeco != null) headDeco.append(c).append(s.charAt(b + 1));
b += 2;
continue;
}
break;
}
while (e > b) {
char last = s.charAt(e - 1);
if (Character.isWhitespace(last)) {
e--;
continue;
}
if (e - 2 >= b && (s.charAt(e - 2) == '&' || s.charAt(e - 2) == '§')
&& isLegacyCodeChar(last)) {
e -= 2;
continue;
}
break;
}
return s.substring(b, e);
}
/** Legacy 色码字符 → Adventure 命名色(0-9a-f),未知字符返回 null */
private static NamedTextColor legacyColor(char c) {
switch (c) {
case '0': return NamedTextColor.BLACK;
case '1': return NamedTextColor.DARK_BLUE;
case '2': return NamedTextColor.DARK_GREEN;
case '3': return NamedTextColor.DARK_AQUA;
case '4': return NamedTextColor.DARK_RED;
case '5': return NamedTextColor.DARK_PURPLE;
case '6': return NamedTextColor.GOLD;
case '7': return NamedTextColor.GRAY;
case '8': return NamedTextColor.DARK_GRAY;
case '9': return NamedTextColor.BLUE;
case 'a': return NamedTextColor.GREEN;
case 'b': return NamedTextColor.AQUA;
case 'c': return NamedTextColor.RED;
case 'd': return NamedTextColor.LIGHT_PURPLE;
case 'e': return NamedTextColor.YELLOW;
case 'f': return NamedTextColor.WHITE;
default: return null;
}
}
/**
* 把剥离出来的前置色码(&amp;c&amp;l / §c§l / &amp;x&amp;R…)贴回解析好的组件:
* 包一层空组件承载,色码只是「默认样式」,JSON 片段里显式写了颜色/样式的仍然优先。
*/
private static Component applyDecoration(Component c, String deco) {
if (c == null) return Component.empty();
if (deco == null || deco.isEmpty()) return c;
Component out = Component.empty();
for (int i = 0; i + 1 < deco.length(); i++) {
char sep = deco.charAt(i);
if (sep != '&' && sep != '§') continue;
char code = Character.toLowerCase(deco.charAt(i + 1));
if (code == 'x') {
// 六位十六进制:&x&R&R&R&R&R&R(成对色码,只吃 hex 数字)
StringBuilder hex = new StringBuilder();
int j = i + 2;
while (j + 1 < deco.length()
&& (deco.charAt(j) == '&' || deco.charAt(j) == '§')
&& isLegacyCodeChar(deco.charAt(j + 1))) {
char h = Character.toLowerCase(deco.charAt(j + 1));
if (h < '0' || (h > '9' && h < 'a') || h > 'f') break;
hex.append(h);
j += 2;
}
if (hex.length() == 6) {
TextColor col = TextColor.fromHexString("#" + hex);
if (col != null) out = out.color(col);
i = j - 2;
}
continue;
}
if ((code >= '0' && code <= '9') || (code >= 'a' && code <= 'f')) {
NamedTextColor col = legacyColor(code);
if (col != null) out = out.color(col);
} else if (code == 'l') {
out = out.decorate(TextDecoration.BOLD);
} else if (code == 'o') {
out = out.decorate(TextDecoration.ITALIC);
} else if (code == 'n') {
out = out.decorate(TextDecoration.UNDERLINED);
} else if (code == 'm') {
out = out.decorate(TextDecoration.STRIKETHROUGH);
} else if (code == 'k') {
out = out.decorate(TextDecoration.OBFUSCATED);
} else if (code == 'r') {
out = out.color(null)
.decoration(TextDecoration.BOLD, TextDecoration.State.FALSE)
.decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE)
.decoration(TextDecoration.UNDERLINED, TextDecoration.State.FALSE)
.decoration(TextDecoration.STRIKETHROUGH, TextDecoration.State.FALSE)
.decoration(TextDecoration.OBFUSCATED, TextDecoration.State.FALSE);
}
}
return out.append(c);
}
/** 解析 JSON 文本组件;失败返回 null(不抛异常) */
private static Component tryParseJson(String json) {
try {
return GsonComponentSerializer.gson().deserialize(json);
} catch (Throwable t) {
return null;
}
}
/**
* 「像 JSON 但没闭合」的防御判定:以 { 或 [ 开头,且含引号后跟冒号的键值特征。
* 普通文本([公告] 他说你好)不含该特征,挡在外面,不会被误修。
*/
private static boolean looksRepairableJson(String s) {
if (s == null || s.length() < 2) return false;
char f = s.charAt(0);
return (f == '{' || f == '[') && s.indexOf("\":") >= 0;
}
/**
* 尽力修补残缺 JSON:引号数为奇数则补一个闭合引号,再按括号栈补齐右括号。
* 只在原解析失败后调用;修不好就返回原串(调用方退回纯文本渲染)。
*/
private static String repairJson(String s) {
String out = s;
int quotes = 0;
for (int i = 0; i < out.length(); i++) {
if (out.charAt(i) == '"') quotes++;
}
if (quotes % 2 == 1) out = out + '"';
StringBuilder stack = new StringBuilder();
boolean inStr = false;
for (int i = 0; i < out.length(); i++) {
char c = out.charAt(i);
if (c == '"' && (i == 0 || out.charAt(i - 1) != '\\')) inStr = !inStr;
if (inStr) continue;
if (c == '{') stack.append('}');
else if (c == '[') stack.append(']');
else if (c == '}' || c == ']') {
if (stack.length() > 0 && stack.charAt(stack.length() - 1) == c) {
stack.deleteCharAt(stack.length() - 1);
}
}
}
for (int i = stack.length() - 1; i >= 0; i--) out = out + stack.charAt(i);
return out;
}
/**
* 占位符替换,定界符见 PLACEHOLDER_DELIMS(中英文小/中/大括号、%…%、&lt;…&gt;)。
* JSON 消息(含 &amp;c&amp;l 包着 JSON 的情形):跳过花括号 {}、不做裸子串替换——
* 花括号是 JSON 对象结构本身,裸替换会吃掉正文里的 end/start/player 等英文词
* ("end soon" -> "2026-09-28 10:00 soon")。JSON 消息里请用 [username]、(用户)、%username% 等形式。
* 普通 &amp;c 文本:全部定界符 + 裸替换都生效({username}、username 均可)。
* 「标签+定界符」混合写法(开始时间[starttime]):只替换定界符占位符、保留标签文字,
* 避免标签被裸替换二次吃掉、渲染成双份时间。
*/
private static String replaceVar(String msg, String[] keys, String value) {
if (msg == null || msg.isEmpty()) return msg;
String v = value == null ? "" : value;
boolean jsonMode = looksLikeJson(msg);
// 「标签+定界符」混合写法防御:如「开始时间[starttime],结束时间:{endtime}」。
// 只要本组任一 key 已以定界符形式出现,就说明用户写的是「标签文字 + 占位符」,
// 此时整组跳过裸子串替换、保留 开始时间/结束时间 这类标签原文;
// 否则标签会被二次替换成时间,渲染成「时间 时间」双份连排。
boolean delimHit = false;
for (String k : keys) {
for (String[] d : PLACEHOLDER_DELIMS) {
if (jsonMode && d[0].equals("{")) continue;
if (msg.contains(d[0] + k + d[1])) {
delimHit = true;
break;
}
}
if (delimHit) break;
}
for (String k : keys) {
for (String[] d : PLACEHOLDER_DELIMS) {
if (jsonMode && d[0].equals("{")) continue; // JSON 跳过花括号,避免与 JSON 结构冲突
msg = msg.replace(d[0] + k + d[1], v);
}
if (!jsonMode && !delimHit) msg = msg.replace(k, v);
}
return msg;
}
/**
* 整段是否为 JSON 文本组件:形如 {...} 或 [...],且含双引号。
* 先剥离首尾色码与空白再判定——&amp;c&amp;l 包着 JSON 也认得出来(防御层)。
* 「含双引号」用于把 [玩家名]、[公告] 这类普通文本挡在 JSON 分支之外——
* Gson 默认宽松解析会把 [玩家名] 当字符串数组吃掉,导致正文被吞。
*/
private static boolean looksLikeJson(String s) {
if (s == null) return false;
String t = stripDecoration(s, null);
int n = t.length();
if (n < 2 || t.indexOf('"') < 0) return false;
char f = t.charAt(0);
char l = t.charAt(n - 1);
return (f == '{' && l == '}') || (f == '[' && l == ']');
}
/** JSON 内的 &lt;br&gt; 变体(<br> <br/> <br /> </br>,大小写不敏感) */
private static final Pattern BR_IN_JSON_PAT = Pattern.compile("(?i)</?br\\s*/?>");
/**
* 把 JSON 文本里的字面 &lt;br&gt; 换成 JSON 转义换行(反斜杠 + n 两字符)。
* 必须是两字符序列:真实换行在 JSON 字符串里非法,写进去整段就解析失败了。
*/
private static String replaceBrInJson(String json) {
return BR_IN_JSON_PAT.matcher(json).replaceAll("\\\\n");
}
/**
* 消息格式化:
* 0) 防御层:剥掉首尾色码/空白再判定 JSON;残缺 JSON 尽力修补——
* 绝不把 JSON 源码原样吐给玩家(剥掉的色码如 &amp;c&amp;l 作为默认样式贴回结果)
* 1) 整段是 JSON(对象 {...} 或顶层数组 [...],后者是 tellraw 常见写法)
* → 按文本组件解析(支持 text/color/extra 等);字面 &lt;br&gt; 会先换成 JSON 转义换行
* 2) 否则处理 &lt;br&gt; 与字面 \n 换行、&amp; 颜色码与 § 颜色码
*/
private static Component format(String msg) {
if (msg == null) msg = "";
// 防御层:先剥掉包在外面的 Legacy 色码(&c&l / §c§l 等)再判定,
// 否则「&c&l 包着 JSON」首字符是 & → 判不出 JSON → JSON 源码原样吐给玩家。
StringBuilder headDeco = new StringBuilder();
String core = stripDecoration(msg.trim(), headDeco);
if (looksLikeJson(core) || looksRepairableJson(core)) {
// ★ JSON 字符串里的字面 <br>/<br/> 同样要变成换行,否则标签会原样显示给玩家。
// Gson 只认 JSON 转义(反斜杠 + n),所以替换成两字符序列,而不是真实换行
// (真实换行在 JSON 字符串里是非法字符,会让整段解析失败退回纯文本)。
Component parsed = tryParseJson(replaceBrInJson(core));
if (parsed == null) {
// 残缺 JSON(缺引号/右括号)→ 尽力补齐再试一次,同样是为了不原样吐源码
String fixed = repairJson(core);
if (!fixed.equals(core)) parsed = tryParseJson(replaceBrInJson(fixed));
}
if (parsed != null) return applyDecoration(parsed, headDeco.toString());
}
String s = msg;
s = s.replace("<br/>", "\n").replace("<br />", "\n").replace("<br>", "\n");
s = s.replace("</br>", "\n").replace("<BR>", "\n").replace("<Br>", "\n");
s = s.replace("\\n", "\n");
s = AMP_COLOR_PAT.matcher(s).replaceAll("§$1");
String[] lines = s.split("\n", -1);
Component out = Component.empty();
for (int i = 0; i < lines.length; i++) {
if (i > 0) out = out.append(Component.newline());
out = out.append(LegacyComponentSerializer.legacySection().deserialize(lines[i]));
}
return out;
}
private static String fmt(long ms) {
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(ms));
} catch (Exception e) {
return String.valueOf(ms);
}
}
// ==================== 工具 ====================
private boolean isOp(String name) {
Boolean cached = opCache.get(name);
if (cached != null) return cached;
boolean r = false;
try {
OfflinePlayer p = Bukkit.getOfflinePlayer(name);
r = p.isOp();
} catch (Throwable t) {
r = false;
}
opCache.put(name, r);
return r;
}
/** 段落头:[白名单] / 【白名单】 / 白名单 / ===== 白名单段 ===== / 玩家白名单 / [WHITELIST](含 = 的行一律不是段落头) */
private static boolean isWhitelistHeader(String line) {
String s = line.trim();
if (s.isEmpty()) return false;
// ★ 注释形式的段标题也算:用户常把「[白名单]」行删掉,只留下「# ===== 白名单段 =====」这条注释。
// 先剥掉 # /// 注释前缀再判;键值对类注释(含 =)仍被下面的硬门槛挡住,不会误判成段落头。
while (s.startsWith("#") || s.startsWith("//")) {
s = s.substring(s.startsWith("//") ? 2 : 1).trim();
}
if (s.isEmpty()) return false;
// ★ 硬门槛:先剥掉首尾装饰符号(=====、----、::: 等),再看中间是否还剩「=」。
// 剩下的 = 说明这是控制段的键值对(如「挂机白名单 = xxx」),绝不是段落头;
// 只有装饰等号的 =====白名单段===== 剥完就干净了,不会被误杀。
// 没有这道门槛时,控制键一旦被误判成段落头,后续所有行都滑进白名单段,
// 「启用 = true」就读不到 → 维护开关直接失效。
String body = s.replaceAll("^[=\\-_::·*#\\s]+|[=\\-_::·*#\\s]+$", "");
if (body.indexOf('=') >= 0) return false;
// 剥离各类括号与装饰符号(含全角【】〔〕「」『』()),只留标题正文
String stripped = s.replaceAll("[\\[\\]【】〔〕「」『』()()\\-=_::·*#\\s]+", "");
String low = stripped.toLowerCase(Locale.ROOT);
// 精确匹配常见写法;再兜底 endsWith 兼容「玩家白名单」「ALLOWLIST」这类变体标题
//(有了上面的 = 门槛,endsWith 已经不会再吞掉控制段键值对)
return low.equals("白名单") || low.equals("白名单段") || low.equals("白名单列表")
|| low.equals("允许名单") || low.equals("whitelist") || low.equals("allowlist")
|| low.endsWith("白名单") || low.endsWith("whitelist") || low.endsWith("allowlist");
}
// ==================== 配置文本解析(static,便于单测) ====================
/** parseConfig 的结果:控制段键值对 + 白名单条目 + 是否见过 [白名单] 段标题 */
static final class ParsedConfig {
final Map<String, String> ctl;
final Set<String> wl;
final boolean sawWhiteHeader;
ParsedConfig(Map<String, String> ctl, Set<String> wl, boolean sawWhiteHeader) {
this.ctl = ctl;
this.wl = wl;
this.sawWhiteHeader = sawWhiteHeader;
}
}
/**
* 解析配置文本。三层兜底,防止管理员把自己关在门外:
* 1) 段标题判断在注释跳过之前——「# ===== 白名单段 =====」这种注释形式的标题也认
* 2) 段外的无键值行(既没有 = 也没有 :)按玩家名收录——标题行被删时靠它救
* 3) 条目先清洗零宽字符 / 行内注释 / 列表前缀再收录,避免肉眼看着对却匹配不上
*/
static ParsedConfig parseConfig(String text, Logger log) {
Map<String, String> ctl = new LinkedHashMap<>();
Set<String> wl = new LinkedHashSet<>();
boolean inWhite = false;
boolean sawHeader = false;
for (String rawLine : text.split("\n")) {
String line = rawLine.trim();
if (line.isEmpty()) continue;
if (isWhitelistHeader(line)) {
inWhite = true;
sawHeader = true;
continue;
}
if (line.startsWith("#") || line.startsWith("//")) continue;
if (inWhite) {
addWhitelistEntry(wl, line, log, null);
} else {
int eq = line.indexOf('=');
if (eq < 0) eq = line.indexOf(':');
if (eq < 0) {
addWhitelistEntry(wl, line, log,
"该行不在 [白名单] 段内也不是键值对,已按玩家名兜底收录");
continue;
}
String k = normKey(line.substring(0, eq));
if (k.isEmpty()) continue;
ctl.put(k, line.substring(eq + 1).trim());
}
}
if (!sawHeader && !wl.isEmpty()) {
warn(log, "未识别到 [白名单] 段标题,已按「无键值=玩家名」兜底收录 "
+ wl.size() + " 个条目");
}
return new ParsedConfig(ctl, wl, sawHeader);
}
/** 清洗并收录一条白名单条目(note 为附加告警说明,可为 null) */
private static void addWhitelistEntry(Set<String> wl, String raw, Logger log, String note) {
String s = stripInvisible(raw);
if (!s.equals(raw)) {
warn(log, "白名单条目含不可见字符(零宽/全角空格/不间断空格),已清洗: ["
+ raw + "] -> [" + s + "]");
}
int c = indexOfInlineComment(s);
if (c >= 0) {
warn(log, "白名单条目的行内注释已忽略: " + s.substring(c).trim());
s = s.substring(0, c).trim();
}
// 列表装饰前缀:- > * · •(合法 MC 名不会以这些字符开头)
String noDecor = s.replaceFirst("^[-*>·•]\\s+", "");
if (!noDecor.equals(s)) {
warn(log, "白名单条目前缀符号已忽略: [" + s + "] -> [" + noDecor + "]");
s = noDecor;
}
s = s.trim();
if (s.isEmpty()) return;
if (note != null) warn(log, note + ": " + raw);
// 仍坚持「一行一个玩家名」:整行收录,但格式不规范必须能被看见
if (s.indexOf(',') >= 0 || s.indexOf(',') >= 0 || s.indexOf('、') >= 0
|| s.indexOf(';') >= 0 || s.indexOf(';') >= 0 || s.indexOf(' ') >= 0
|| s.indexOf(UnicodeChars.IDEOGRAPHIC_SPACE) >= 0 || s.indexOf('\t') >= 0) {
warn(log, "白名单条目不符合「一行一个玩家名」,已按整行收录: " + s);
}
wl.add(s);
}
/** 去掉肉眼看不见却会让匹配失败的字符:零宽/BOM/不间断空格/全角空格 */
private static String stripInvisible(String s) {
if (s == null) return null;
return s.replaceAll(UnicodeChars.INVISIBLE_STRIP_CLASS, "");
}
/** 行内注释起点(# / # / //),返回 -1 表示没有 */
private static int indexOfInlineComment(String s) {
int h = s.indexOf('#');
if (h < 0) h = s.indexOf('#');
if (h < 0) h = s.indexOf("//");
return h <= 0 ? -1 : h;
}
private static void warn(Logger log, String msg) {
if (log != null) log.warning("[维护模式] " + msg);
}
/** 布尔词识别(与 toBool 口径一致),用于把 flase / ture 这类拼写错误提示出来 */
private static boolean isBoolWord(String v) {
if (v == null) return false;
String s = v.trim().toLowerCase(Locale.ROOT);
if (s.isEmpty()) return false;
return s.equals("true") || s.equals("yes") || s.equals("y") || s.equals("on")
|| s.equals("1") || s.equals("是") || s.equals("开") || s.equals("开启") || s.equals("启用")
|| s.equals("false") || s.equals("no") || s.equals("n") || s.equals("off")
|| s.equals("0") || s.equals("否") || s.equals("关") || s.equals("关闭") || s.equals("停用");
}
/** 白名单条目摘要(最多 20 个),日志里直接对账用 */
private static String summarize(Set<String> names) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (String n : names) {
if (i == 20) {
sb.append(", …共").append(names.size()).append("人");
return sb.toString();
}
if (i++ > 0) sb.append(", ");
sb.append(n);
}
return sb.toString();
}
private static String normKey(String k) {
if (k == null) return "";
return k.trim().toLowerCase(Locale.ROOT).replace(" ", "").replace("_", "").replace(" ", "");
}
private static String pick(Map<String, String> ctl, String... keys) {
for (String k : keys) {
String v = ctl.get(normKey(k));
if (v != null && !v.trim().isEmpty()) return v.trim();
}
return null;
}
private static boolean toBool(String v, boolean def) {
if (v == null) return def;
String s = v.trim().toLowerCase(Locale.ROOT);
if (s.isEmpty()) return def;
return s.equals("true") || s.equals("yes") || s.equals("y") || s.equals("on")
|| s.equals("1") || s.equals("是") || s.equals("开") || s.equals("开启") || s.equals("启用");
}
/**
* 时间解析,支持:
* - 10位秒级时间戳 / 13位毫秒时间戳
* - 2026-09-28 20:00 / 2026/9/28 20:00:33 / 2026.09.28
* - 2026年9月28日20时30分 / 2026年9月28日 20:30
* - 只写 20:00(今天该时刻)
* 解析失败返回 null
*/
static Long parseTime(String raw) {
if (raw == null) return null;
String s = raw.trim().replace("\"", "");
if (s.isEmpty()) return null;
if (s.matches("\\d{10}")) return Long.parseLong(s) * 1000L;
if (s.matches("\\d{13}")) return Long.parseLong(s);
List<Long> n = new ArrayList<>();
Matcher m = NUM_PAT.matcher(s);
while (m.find()) {
try {
n.add(Long.parseLong(m.group()));
} catch (Exception ignore) {
}
}
if (n.isEmpty()) return null;
String first = String.valueOf(n.get(0));
if (first.length() == 10) return n.get(0) * 1000L;
if (first.length() == 13) return n.get(0);
if (n.size() == 2 && n.get(0) <= 23 && n.get(1) <= 59) {
LocalDateTime now = LocalDateTime.now();
return now.withHour(n.get(0).intValue()).withMinute(n.get(1).intValue())
.withSecond(0).withNano(0)
.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
if (n.size() < 3) return null;
int y = n.get(0).intValue();
int mo = n.get(1).intValue();
int d = n.get(2).intValue();
int h = n.size() > 3 ? n.get(3).intValue() : 0;
int mi = n.size() > 4 ? n.get(4).intValue() : 0;
int se = n.size() > 5 ? n.get(5).intValue() : 0;
if (y < 1970 || y > 2100 || mo < 1 || mo > 12 || d < 1 || d > 31
|| h > 23 || mi > 59 || se > 59) {
return null;
}
try {
return LocalDateTime.of(y, mo, d, h, mi, se)
.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
} catch (Exception e) {
return null;
}
}
/** 时长解析:24 / 24h / 12小时 / 90分钟 / 2天,默认单位小时 */
static Long parseDuration(String raw) {
if (raw == null) return null;
String s = raw.trim().toLowerCase(Locale.ROOT);
if (s.isEmpty()) return null;
Matcher m = DUR_PAT.matcher(s);
if (!m.find()) return null;
double v;
try {
v = Double.parseDouble(m.group(1));
} catch (Exception e) {
return null;
}
String unit = m.group(2) == null ? "" : m.group(2);
long ms;
if (unit.contains("毫秒")) ms = 1L;
else if (unit.startsWith("s") || unit.contains("秒")) ms = 1000L;
else if (unit.startsWith("m") || unit.contains("分")) ms = 60_000L;
else if (unit.startsWith("d") || unit.contains("天")) ms = 86_400_000L;
else ms = 3_600_000L;
long r = (long) (v * ms);
return r <= 0 ? null : r;
}
/** 优先按 UTF-8 严格解码,失败则按 GBK(Windows 记事本默认编码) */
private static String decode(byte[] bytes) {
if (bytes == null || bytes.length == 0) return "";
try {
CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
dec.decode(ByteBuffer.wrap(bytes));
return new String(bytes, StandardCharsets.UTF_8);
} catch (CharacterCodingException e) {
try {
return new String(bytes, Charset.forName("GBK"));
} catch (Exception e2) {
return new String(bytes, StandardCharsets.UTF_8);
}
}
}
}
@@ -1,355 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import java.net.URI;
import java.net.URLEncoder;
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.*;
import java.util.concurrent.*;
/**
* 多源在线翻译工具 —— 将MC英文材料名翻译为中文。
* 优先使用国内接口(有道/简心),失败后降级到Google。
* 结果缓存避免重复请求。
*/
public class MaterialTranslator {
private static final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();
private static final ExecutorService executor = Executors.newFixedThreadPool(2);
private static final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.build();
// 翻译源优先级:国内接口优先
private static final List<TranslationSource> SOURCES = Arrays.asList(
TranslationSource.YOUDAO,
TranslationSource.JIANXIN,
TranslationSource.GOOGLE
);
/**
* 翻译源枚举
*/
private enum TranslationSource {
YOUDAO("有道翻译"),
JIANXIN("简心翻译"),
GOOGLE("Google翻译");
final String name;
TranslationSource(String name) {
this.name = name;
}
}
/**
* 将材料名(如 GRASS_BLOCK)转为可读英文(Grass Block)
*/
public static String toReadable(String materialName) {
if (materialName == null || materialName.isEmpty()) return "";
return Arrays.stream(materialName.split("_"))
.map(w -> w.substring(0, 1).toUpperCase() + w.substring(1).toLowerCase())
.reduce((a, b) -> a + " " + b)
.orElse(materialName);
}
/**
* 同步翻译单个材料名(有缓存则直接返回)。
* 优先走 MC 官方 zh_cn.json 翻译,查不到才走机翻。
*/
public static String translate(String materialName) {
if (materialName == null || materialName.isEmpty()) return "";
String key = materialName.toUpperCase();
// 缓存命中
if (cache.containsKey(key)) {
return cache.get(key);
}
// 1. 官方翻译(基于原始 Material 名 GRASS_BLOCK → block.minecraft.grass_block)
String official = OfficialTranslations.lookUp(materialName);
if (official != null && !official.isEmpty()) {
cache.put(key, official);
return official;
}
// 2. 机翻兜底
String readable = toReadable(key);
String zh = translateWithFallback(readable);
if (zh != null && !zh.isEmpty()) {
cache.put(key, zh);
return zh;
}
return readable; // fallback 可读英文
}
/**
* 批量异步翻译,返回 future map
*/
public static CompletableFuture<Map<String, String>> translateBatch(Collection<String> materials) {
Set<String> unique = new LinkedHashSet<>();
for (String m : materials) {
if (m != null && !m.isEmpty() && !cache.containsKey(m.toUpperCase())) {
unique.add(m);
}
}
if (unique.isEmpty()) {
Map<String, String> result = new HashMap<>();
for (String m : materials) {
if (m != null) result.put(m, cache.getOrDefault(m.toUpperCase(), toReadable(m)));
}
return CompletableFuture.completedFuture(result);
}
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (String m : unique) {
futures.add(CompletableFuture.runAsync(() -> translate(m), executor));
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> {
Map<String, String> result = new HashMap<>();
for (String m : materials) {
if (m != null) {
result.put(m, cache.getOrDefault(m.toUpperCase(), toReadable(m)));
}
}
return result;
});
}
/**
* 多源翻译,按优先级尝试,失败自动降级
*/
private static String translateWithFallback(String text) {
for (TranslationSource source : SOURCES) {
try {
String result = null;
switch (source) {
case YOUDAO:
result = translateViaYoudao(text);
break;
case JIANXIN:
result = translateViaJianxin(text);
break;
case GOOGLE:
result = translateViaGoogle(text);
break;
}
if (result != null && !result.isEmpty()) {
return result;
}
} catch (Exception e) {
Bukkit.getLogger().warning("[翻译] 机翻 " + source.name + " 异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
return null;
}
// ==================== 翻译源实现 ====================
/**
* 有道翻译API
* URL: https://v.api.aa1.cn/api/api-fanyi-yd/index.php
* 参数: msg=翻译内容, type=1(中→英) / 2(英→中)
*/
private static String translateViaYoudao(String text) {
try {
String encoded = URLEncoder.encode(text, StandardCharsets.UTF_8);
// type=2 表示英→中
String url = "https://v.api.aa1.cn/api/api-fanyi-yd/index.php?msg=" + encoded + "&type=2";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("User-Agent", "Mozilla/5.0")
.timeout(Duration.ofSeconds(3))
.GET()
.build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() == 200) {
// 返回: {"type":"中英互译","desc":"中文翻译英文","text":"翻译结果"}
return parseJsonField(resp.body(), "text");
}
} catch (Exception e) {
// 静默降级
}
return null;
}
/**
* 简心翻译API
* URL: https://api.qvqa.cn/api/fanyi
* 参数: text=翻译内容, source=en, target=zh
*/
private static String translateViaJianxin(String text) {
try {
String encoded = URLEncoder.encode(text, StandardCharsets.UTF_8);
String url = "https://api.qvqa.cn/api/fanyi?text=" + encoded + "&source=en&target=zh";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("User-Agent", "Mozilla/5.0")
.timeout(Duration.ofSeconds(3))
.GET()
.build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() == 200) {
// 返回: {"code":200,"message":"OK","data":{"sourceText":"...","targetText":"翻译结果",...}}
return parseNestedJsonField(resp.body(), "data", "targetText");
}
} catch (Exception e) {
// 静默降级
}
return null;
}
/**
* Google Translate 免费接口
*/
private static String translateViaGoogle(String text) {
try {
String encoded = URLEncoder.encode(text, StandardCharsets.UTF_8);
String url = "https://clients5.google.com/translate_a/single"
+ "?client=gtx&sl=en&tl=zh-CN&dt=t&q=" + encoded;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("User-Agent", "Mozilla/5.0")
.timeout(Duration.ofSeconds(3))
.GET()
.build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() == 200) {
// 响应格式: [["翻译结果","原文",...],...]
String body = resp.body();
int firstQuote = body.indexOf("[[\"");
if (firstQuote >= 0) {
int endQuote = body.indexOf("\"", firstQuote + 3);
if (endQuote > firstQuote) {
return body.substring(firstQuote + 3, endQuote);
}
}
}
} catch (Exception e) {
// 静默降级
}
return null;
}
// ==================== JSON解析工具 ====================
/**
* 简单JSON字段解析(单层)
* 从 {"key":"value"} 中提取 value
*/
private static String parseJsonField(String json, String field) {
try {
String pattern = "\"" + field + "\"";
int idx = json.indexOf(pattern);
if (idx < 0) return null;
// 找到冒号后的引号
int colon = json.indexOf(':', idx + pattern.length());
if (colon < 0) return null;
int quoteStart = json.indexOf('"', colon + 1);
if (quoteStart < 0) return null;
int quoteEnd = json.indexOf('"', quoteStart + 1);
if (quoteEnd < 0) return null;
return json.substring(quoteStart + 1, quoteEnd);
} catch (Exception e) {
return null;
}
}
/**
* 嵌套JSON字段解析
* 从 {"outer":{"inner":"value"}} 中提取 value
*/
private static String parseNestedJsonField(String json, String outerField, String innerField) {
try {
// 找到外层对象
String outerPattern = "\"" + outerField + "\"";
int outerIdx = json.indexOf(outerPattern);
if (outerIdx < 0) return null;
// 找到外层对象的开始大括号
int braceStart = json.indexOf('{', outerIdx);
if (braceStart < 0) return null;
// 从外层对象内部解析内层字段
int depth = 1;
int i = braceStart + 1;
while (i < json.length() && depth > 0) {
char c = json.charAt(i);
if (c == '{') depth++;
else if (c == '}') depth--;
i++;
}
String innerJson = json.substring(braceStart, i);
return parseJsonField(innerJson, innerField);
} catch (Exception e) {
return null;
}
}
/**
* 清理缓存(可选)
*/
public static void clearCache() {
cache.clear();
chatCache.clear();
}
// ==================== 聊天整句机翻(28批新增) ====================
/** 聊天机翻独立缓存(与材料名缓存隔离),上限保护防内存膨胀 */
private static final ConcurrentHashMap<String, String> chatCache = new ConcurrentHashMap<>();
private static final int CHAT_CACHE_MAX = 500;
/**
* 聊天整句机翻(英→中)。复用 translateWithFallback 的
* YOUDAO→JIANXIN→GOOGLE 降级链(与领地系统同一套 API 流程)。
* 结果独立缓存(上限500条,满则整体清空重来),不污染材料名缓存。
* 同步阻塞 HTTP(每源 3s 超时),调用方必须放在异步线程执行。
* 返回 null 表示翻译失败或译文无意义(如与原文相同)。
*/
public static String translateChatText(String text) {
if (text == null) return null;
String key = text.trim();
if (key.isEmpty()) return null;
String hit = chatCache.get(key);
if (hit != null) return hit;
String zh = translateWithFallback(key);
if (zh != null && !zh.isEmpty() && !zh.equals(key)) {
if (chatCache.size() >= CHAT_CACHE_MAX) chatCache.clear();
chatCache.put(key, zh);
return zh;
}
return null;
}
/**
* 获取当前使用的翻译源信息(调试用)
*/
public static String getSourceInfo() {
StringBuilder sb = new StringBuilder("翻译源优先级: ");
for (int i = 0; i < SOURCES.size(); i++) {
TranslationSource src = SOURCES.get(i);
sb.append(i + 1).append(".").append(src.name);
if (i < SOURCES.size() - 1) sb.append(" > ");
}
return sb.toString();
}
}
@@ -1,152 +0,0 @@
package Sdf1_login;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
public class MenuIconManager {
private final Main plugin;
private final NamespacedKey iconKey;
public MenuIconManager(Main plugin) {
this.plugin = plugin;
this.iconKey = new NamespacedKey(
plugin, "custom_menu_icon");
}
// ========== GUIManager 调用的方法 ==========
/**
* Base64 → ItemStack
* 对应 GUIManager 中的
* plugin.getMenuIconMgr().deserializeItem(...)
*/
public ItemStack deserializeItem(String b64) {
if (b64 == null || b64.isEmpty())
return null;
try {
byte[] data =
Base64.getDecoder().decode(b64);
ByteArrayInputStream bais =
new ByteArrayInputStream(data);
BukkitObjectInputStream is =
new BukkitObjectInputStream(bais);
Object obj = is.readObject();
is.close();
if (obj instanceof ItemStack)
return (ItemStack) obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* ItemStack → Base64
* 对应 GUIManager 中的
* plugin.getMenuIconMgr().serializeItem(...)
*/
public String serializeItem(ItemStack item) {
if (item == null) return null;
try {
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
BukkitObjectOutputStream os =
new BukkitObjectOutputStream(baos);
os.writeObject(item);
os.close();
return Base64.getEncoder()
.encodeToString(
baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 给物品打上菜单图标标记
* 对应 GUIManager 中的
* plugin.getMenuIconMgr().ensureMenuIconTag(...)
*/
public void ensureMenuIconTag(ItemStack item) {
if (item == null) return;
ItemMeta meta = item.getItemMeta();
if (meta == null) return;
meta.getPersistentDataContainer().set(
iconKey,
PersistentDataType.STRING,
"menu");
item.setItemMeta(meta);
}
/**
* 获取图标Key
* 对应 GUIManager 中的
* plugin.getMenuIconMgr().getIconKey()
*/
public NamespacedKey getIconKey() {
return iconKey;
}
// ========== LoginManager / Main 调用的方法 ==========
/**
* 获取玩家自定义图标物品
* 有返回物品,无返回null
*/
public ItemStack getIcon(Player player) {
String b64 = plugin.getDb()
.getMenuIcon(player.getName());
if (b64 == null || b64.isEmpty())
return null;
ItemStack item = deserializeItem(b64);
if (item == null) return null;
ensureMenuIconTag(item);
return item;
}
/**
* 保存图标到DB
*/
public void saveIcon(Player player,
ItemStack item) {
String b64 = serializeItem(item);
if (b64 != null) {
plugin.getDb().saveMenuIcon(
player.getName(), b64,
item.getType().name());
}
}
/**
* 删除图标
*/
public void removeIcon(Player player) {
plugin.getDb().deleteMenuIcon(
player.getName());
}
/**
* 检查物品是否是自定义菜单图标
*/
public boolean isCustomMenuIcon(
ItemStack item) {
if (item == null) return false;
ItemMeta meta = item.getItemMeta();
if (meta == null) return false;
return meta.getPersistentDataContainer()
.has(iconKey,
PersistentDataType.STRING);
}
}
-470
View File
@@ -1,470 +0,0 @@
package Sdf1_login;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.nio.file.Files;
public class MenuManager implements Listener {
private final Main plugin;
private final List<MenuItem> items =
new ArrayList<>();
private final Set<String> chatWait =
ConcurrentHashMap.newKeySet();
private final Map<String, String> chatField =
new ConcurrentHashMap<>();
private final Map<String, Integer> chatIdx =
new ConcurrentHashMap<>();
// ===== 菜单项 =====
public static class MenuItem {
public String title = "新菜单项";
public String command = "";
public String permType = "玩家";
public Integer slot = null;
public ItemStack icon;
public MenuItem() {
icon = randomIcon();
}
public MenuItem(String t,
String c, String p) {
title = t;
command = c;
permType = p;
icon = randomIcon();
}
static ItemStack randomIcon() {
Material[] pool = {
Material.COMPASS,
Material.ENDER_PEARL,
Material.DIAMOND,
Material.GOLD_INGOT,
Material.EMERALD,
Material.NETHER_STAR,
Material.BEACON,
Material.ENCHANTING_TABLE,
Material.CHEST,
Material.FIREWORK_ROCKET,
Material.BOOK,
Material.ELYTRA,
Material.TOTEM_OF_UNDYING
};
Material m = pool[
(int) (Math.random()
* pool.length)];
ItemStack it =
new ItemStack(m);
ItemMeta im = it.getItemMeta();
im.setDisplayName("§e默认图标");
it.setItemMeta(im);
return it;
}
}
public MenuManager(Main plugin) {
this.plugin = plugin;
}
public List<MenuItem> getItems() {
return items;
}
// ===== 读取菜单.txt(主菜单唯一来源) =====
public void loadMenu() {
items.clear();
// 优先菜单.txt,备选menu.txt
File f = new File(
plugin.getDataFolder(),
"菜单.txt");
if (!f.exists()) {
File alt = new File(
plugin.getDataFolder(),
"menu.txt");
if (alt.exists()) {
f = alt;
} else {
createDefault(f);
}
}
parseFile(f);
plugin.getLogger().info(
"[Menu] 加载 " + items.size()
+ " 个菜单项 (源: "
+ f.getName() + ")");
}
private void parseFile(File f) {
plugin.getLogger().info("[Menu] ===== 扫描 =====");
plugin.getLogger().info("[Menu] 路径: "
+ f.getAbsolutePath());
plugin.getLogger().info("[Menu] 大小: "
+ f.length());
try {
List<String> lines = Files.readAllLines(
f.toPath(), StandardCharsets.UTF_8);
plugin.getLogger().info("[Menu] 总行数: "
+ lines.size());
boolean inBlock = false;
boolean inHtml = false;
StringBuilder buf = new StringBuilder();
boolean inItem = false;
int parsed = 0;
for (int lineNum = 1;
lineNum <= lines.size();
lineNum++) {
String raw = lines.get(lineNum - 1);
String l = raw.trim();
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": 原文[" + l.length()
+ "字符] " + l);
// ===== 第1优先:跨行块注释 =====
if (inBlock) {
if (l.contains("*/")) {
inBlock = false;
l = l.substring(
l.indexOf("*/") + 2)
.trim();
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": 块注释结束");
} else {
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": [块注释中]");
continue;
}
}
// ===== 第2优先:跨行HTML注释 =====
if (inHtml) {
if (l.contains("-->")) {
inHtml = false;
l = l.substring(
l.indexOf("-->") + 3)
.trim();
} else {
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": [HTML注释中]");
continue;
}
}
// ===== 第3优先:整行注释(最高裁决) =====
// 以 # 或 // 开头的行,直接跳过
// 不管后面包含什么 /* <!-- 等
if (l.startsWith("#")
|| l.startsWith("//")) {
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": [整行注释,跳过]");
continue;
}
// ===== 第4优先:块注释开始 =====
if (l.contains("/*")) {
l = l.substring(0, l.indexOf("/*"))
.trim();
inBlock = true;
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": 进入/*块注释"
+ " 剩余[" + l + "]");
if (l.isEmpty()) {
continue;
}
}
// ===== 第5优先:HTML注释开始 =====
if (l.contains("<!--")) {
l = l.substring(0,
l.indexOf("<!--")).trim();
inHtml = true;
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": 进入<!--注释");
if (l.isEmpty()) {
continue;
}
}
// ===== 第6优先:行内注释 =====
int hashPos = l.indexOf("#");
int slashPos = l.indexOf("//");
if (hashPos >= 0) {
l = l.substring(0, hashPos).trim();
}
if (slashPos >= 0) {
if (hashPos < 0
|| slashPos < hashPos) {
l = l.substring(0, slashPos)
.trim();
}
}
if (l.isEmpty()) {
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": 空");
continue;
}
plugin.getLogger().info(
"[Menu] L" + lineNum
+ ": [保留] " + l);
if (l.equals("{")) {
inItem = true;
buf.setLength(0);
plugin.getLogger().info(
"[Menu] === 块开始 ===");
continue;
}
if (l.equals("}")) {
if (inItem) {
plugin.getLogger().info(
"[Menu] === 块结束 ===");
parseBlock(buf.toString());
parsed++;
plugin.getLogger().info(
"[Menu] 当前菜单项: "
+ items.size());
}
inItem = false;
continue;
}
if (inItem) {
buf.append(l).append("\n");
}
}
plugin.getLogger().info(
"[Menu] ===== 完毕 =====");
plugin.getLogger().info(
"[Menu] 块数: " + parsed);
plugin.getLogger().info(
"[Menu] 菜单项: "
+ items.size());
} catch (Exception e) {
plugin.getLogger().warning(
"[Menu] 异常: "
+ e.getMessage());
}
}
private void parseBlock(String block) {
String title = "";
String cmd = "";
String perm = "玩家";
String iconMat = "";
int slotNum = -1;
for (String line : block.split("\n")) {
line = line.trim();
if (line.isEmpty()) continue;
String v = "";
int idx = line.indexOf(":");
if (idx < 0) idx = line.indexOf(":");
if (idx >= 0) {
v = line.substring(idx + 1).trim();
if (v.startsWith("\"")
&& v.endsWith("\"")
&& v.length() >= 2) {
v = v.substring(1, v.length() - 1);
}
}
if (line.startsWith("标题")) {
title = v;
} else if (line.startsWith("指令")) {
cmd = v;
if (!cmd.isEmpty()
&& !cmd.startsWith("/")) {
cmd = "/" + cmd;
}
} else if (line.startsWith("权限")) {
perm = v;
} else if (line.startsWith("图标")) {
iconMat = v;
} else if (line.startsWith("格子")) {
try {
int s = Integer.parseInt(v);
if (s >= 1 && s <= 54) {
slotNum = s;
}
} catch (NumberFormatException ignored) {
}
}
}
if (title.isEmpty()) return;
MenuItem mi = new MenuItem(title, cmd, perm);
if (slotNum >= 1 && slotNum <= 54) {
mi.slot = slotNum;
}
if (!iconMat.isEmpty()) {
try {
String matName = iconMat
.replace("minecraft:", "")
.replace("bukkit:", "")
.trim().toUpperCase();
Material m =
Material.valueOf(matName);
mi.icon = new ItemStack(m);
ItemMeta im =
mi.icon.getItemMeta();
im.setDisplayName(
"§e" + title);
mi.icon.setItemMeta(im);
} catch (Exception e) {
plugin.getLogger().warning(
"[Menu] 无法解析: "
+ iconMat);
}
}
items.add(mi);
}
private void createDefault(File f) {
try (PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(f),
StandardCharsets
.UTF_8))) {
pw.println("# 服务器菜单");
pw.println("# {}定义菜单项");
pw.println("# 支持"
+ " # // /* */ <!-- -->");
pw.println();
pw.println("{");
pw.println(" 标题:主城传送");
pw.println(" 指令:/spawn");
pw.println(" 权限类型:玩家");
pw.println(" 图标:COMPASS");
pw.println("}");
pw.println();
pw.println("{");
pw.println(" 标题:随机传送");
pw.println(" 指令:/rtp");
pw.println(" 权限类型:玩家");
pw.println(" 图标:ENDER_PEARL");
pw.println("}");
} catch (Exception ignored) {
}
}
// ===== 保存 =====
public void saveMenu() {
// 保存到加载源文件
File f = new File(
plugin.getDataFolder(),
"菜单.txt");
if (!f.exists()) {
File alt = new File(
plugin.getDataFolder(),
"menu.txt");
if (alt.exists()) f = alt;
}
try (PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(f),
StandardCharsets.UTF_8))) {
pw.println("# 服务器菜单");
pw.println();
for (MenuItem mi : items) {
pw.println("{");
pw.println(" 标题:"
+ mi.title);
pw.println(" 指令:"
+ mi.command);
pw.println(" 权限类型:"
+ mi.permType);
// ★ 保存实际材质名 ★
pw.println(" 图标:"
+ mi.icon.getType().name());
pw.println("}");
pw.println();
}
} catch (Exception e) {
plugin.getLogger().warning(
"[Menu] 保存失败: "
+ e.getMessage());
}
}
// ===== 聊天编辑 =====
public boolean isEditing(String name) {
return chatWait.contains(name);
}
public void editTitle(
Player p, int idx) {
chatIdx.put(p.getName(), idx);
chatWait.add(p.getName());
chatField.put(p.getName(), "title");
p.closeInventory();
p.sendMessage("§e请输入菜单标题:");
}
public void editCommand(
Player p, int idx) {
chatIdx.put(p.getName(), idx);
chatWait.add(p.getName());
chatField.put(p.getName(), "command");
p.closeInventory();
p.sendMessage("§e请输入指令"
+ "(自动补全/):");
}
public void onChat(Player p, String input) {
String name = p.getName();
if (!chatWait.remove(name)) return;
String field = chatField.remove(name);
Integer idx = chatIdx.get(name);
if (idx == null || idx >= items.size()) return;
MenuItem mi = items.get(idx);
if ("title".equals(field)) {
mi.title = input;
p.sendMessage("§a标题: " + input);
} else if ("command".equals(field)) {
if (!input.startsWith("/"))
input = "/" + input;
mi.command = input;
p.sendMessage("§a指令: " + input);
}
Bukkit.getScheduler().runTask(plugin, () ->
plugin.gui.openEditor(p, idx));
}
}
@@ -1,245 +0,0 @@
package Sdf1_login;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.bukkit.Bukkit;
import java.io.File;
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.nio.file.Files;
import java.time.Duration;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
/**
* MC 官方中文翻译加载器。<br>
* <br>
* 工作流程优先级:<br>
* 1. 本地缓存 (plugins/Sdf1_login/zh_cn.json) —— 同步加载,开机即用<br>
* 2. Mojang API —— 异步下载最新版,写缓存并刷入内存<br>
* 3. 全部失败 —— 返回 null,调用者走机翻兜底<br>
* <br>
* zh_cn.json 键示例:<br>
* {@code block.minecraft.grass_block → "草方块"}<br>
* {@code item.minecraft.diamond_sword → "钻石剑"}<br>
* <br>
* 查找策略:直接 key → block.minecraft.* → item.minecraft.*
*/
public class OfficialTranslations {
private static final ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
private static final Gson gson = new Gson();
/** 反向索引(中文→英文键),懒构建;loadFromJson 后置 null 触发重建 */
private static volatile Map<String, java.util.List<String>> reverseIndex;
// ---------- 对外 API ----------
/**
* 初始化(在 onEnable 调用)。<br>
* 纯同步:先读本地缓存 &rarr; 没有则从 Mojang API 下载并写缓存。<br>
* 缓存文件由部署脚本随 JAR 一起上传,确保服务器不直连 Mojang 也能加载。
*/
public static void init(Main plugin) {
File cacheFile = new File(plugin.getDataFolder(), "zh_cn.json");
// 1. 本地缓存 —— 同步加载
if (cacheFile.isFile()) {
try {
String content = Files.readString(cacheFile.toPath(), StandardCharsets.UTF_8);
loadFromJson(content);
plugin.getLogger().info("[官方翻译] 已加载本地缓存 zh_cn.json(" + map.size() + " 条)");
return; // 缓存命中,完毕
} catch (Exception e) {
plugin.getLogger().warning("[官方翻译] 本地缓存损坏: " + e.getMessage());
}
}
// 2. 无缓存或损坏 → 同步从 Mojang API 下载
plugin.getLogger().info("[官方翻译] 本地缓存不存在/损坏,从 Mojang API 同步下载...");
try {
String version = getMinecraftVersion();
if (version == null) throw new RuntimeException("无法获取服务器版本号");
String json = downloadFromMojang(version);
if (json == null) throw new RuntimeException("下载返回空");
Files.writeString(cacheFile.toPath(), json, StandardCharsets.UTF_8);
loadFromJson(json);
plugin.getLogger().info("[官方翻译] Mojang 下载成功(" + map.size() + " 条),已缓存至 " + cacheFile.getName());
} catch (Exception e) {
plugin.getLogger().warning("[官方翻译] 同步下载失败: " + e.getMessage() + ",走机翻兜底");
plugin.getLogger().log(Level.FINE, "[官方翻译] 同步下载详情", e);
}
}
/**
* 查找官方翻译。<br>
* 传入原始 Material 名(如 {@code GRASS_BLOCK}),自动尝试多种 key 模式。
*
* @param materialName 原始 Material 名(大小写无关)
* @return 中文翻译,或 null(未命中)
*/
public static String lookUp(String materialName) {
if (materialName == null || materialName.isEmpty()) return null;
String lower = materialName.toLowerCase(Locale.ROOT);
// 1. 精确匹配(部分 key 可直接用)
String val = map.get(lower);
if (val != null) return val;
// 2. block.minecraft.<name>
val = map.get("block.minecraft." + lower);
if (val != null) return val;
// 3. item.minecraft.<name>
val = map.get("item.minecraft." + lower);
if (val != null) return val;
return null; // 未命中 -> 调用者走机翻兜底
}
/**
* 反向索引:中文名 → 英文键列表(如 「钻石剑」→ ["diamond_sword"])。<br>
* 仅收录 item.minecraft.* / block.minecraft.* 条目;同名时 item 优先(先扫 item 再扫 block)。<br>
* 懒构建 + volatile,zh_cn.json 重新 load 后失效重建。
*/
public static Map<String, java.util.List<String>> reverseMap() {
Map<String, java.util.List<String>> idx = reverseIndex;
if (idx != null) return idx;
synchronized (OfficialTranslations.class) {
if (reverseIndex != null) return reverseIndex;
Map<String, java.util.List<String>> built = new java.util.HashMap<>();
for (String prefix : new String[]{"item.minecraft.", "block.minecraft."}) {
for (Map.Entry<String, String> e : map.entrySet()) {
if (!e.getKey().startsWith(prefix)) continue;
String zh = e.getValue();
if (zh == null || zh.isEmpty()) continue;
String mat = e.getKey().substring(prefix.length());
java.util.List<String> list = built.computeIfAbsent(zh,
k -> new java.util.ArrayList<>(2));
if (!list.contains(mat)) list.add(mat);
}
}
reverseIndex = built;
return built;
}
}
/** 当前加载的条目数(调试用) */
public static int size() {
return map.size();
}
/** 是否已完成至少一次加载(缓存或下载) */
public static boolean isLoaded() {
return !map.isEmpty();
}
// ---------- 内部 ----------
/** 解析 zh_cn.json 字符串灌入内存 */
static void loadFromJson(String json) {
JsonObject obj = gson.fromJson(json, JsonObject.class);
if (obj == null) return;
map.clear();
for (Map.Entry<String, com.google.gson.JsonElement> entry : obj.entrySet()) {
map.put(entry.getKey(), entry.getValue().getAsString());
}
reverseIndex = null; // 失效反向索引,下次访问重建
}
/** 从 Mojang API 拉取 zh_cn.json(完整链:manifest → version → asset index → object) */
static String downloadFromMojang(String version) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
// Step 1: Version manifest
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://launchermeta.mojang.com/mc/game/version_manifest.json"))
.timeout(Duration.ofSeconds(10))
.header("User-Agent", "Sdf1Login/1.0")
.GET()
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) return null;
JsonObject manifest = gson.fromJson(resp.body(), JsonObject.class);
// 在 versions 数组中找目标版本
String versionUrl = null;
JsonArray versions = manifest.getAsJsonArray("versions");
if (versions != null) {
for (int i = 0; i < versions.size(); i++) {
JsonObject v = versions.get(i).getAsJsonObject();
if (version.equals(v.get("id").getAsString())) {
versionUrl = v.get("url").getAsString();
break;
}
}
}
if (versionUrl == null) return null;
// Step 2: Version JSON (获取 assetIndex url)
req = HttpRequest.newBuilder()
.uri(URI.create(versionUrl))
.timeout(Duration.ofSeconds(10))
.header("User-Agent", "Sdf1Login/1.0")
.GET()
.build();
resp = client.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) return null;
JsonObject versionJson = gson.fromJson(resp.body(), JsonObject.class);
JsonObject assetIndex = versionJson.getAsJsonObject("assetIndex");
if (assetIndex == null) return null;
String assetIndexUrl = assetIndex.get("url").getAsString();
// Step 3: Asset index (定位 zh_cn.json 的 hash)
req = HttpRequest.newBuilder()
.uri(URI.create(assetIndexUrl))
.timeout(Duration.ofSeconds(10))
.header("User-Agent", "Sdf1Login/1.0")
.GET()
.build();
resp = client.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) return null;
JsonObject assets = gson.fromJson(resp.body(), JsonObject.class);
JsonObject objects = assets.getAsJsonObject("objects");
if (objects == null) return null;
JsonObject langEntry = objects.getAsJsonObject("minecraft/lang/zh_cn.json");
if (langEntry == null) return null;
String hash = langEntry.get("hash").getAsString();
if (hash == null || hash.length() < 2) return null;
// Step 4: 下载 zh_cn.json
String langUrl = "https://resources.download.minecraft.net/" + hash.substring(0, 2) + "/" + hash;
req = HttpRequest.newBuilder()
.uri(URI.create(langUrl))
.timeout(Duration.ofSeconds(15))
.header("User-Agent", "Sdf1Login/1.0")
.GET()
.build();
resp = client.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() == 200) {
return resp.body();
}
return null;
}
/** 从 Bukkit API 获取纯版本号,如 "1.21.4" */
private static String getMinecraftVersion() {
String ver = Bukkit.getBukkitVersion();
if (ver == null) return null;
int dash = ver.indexOf('-');
return dash > 0 ? ver.substring(0, dash) : ver;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+72 -77
View File
@@ -1,77 +1,72 @@
package Sdf1_login;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
public class PasswordUtils {
private static final SecureRandom RANDOM =
new SecureRandom();
public static String generateSalt() {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
return Base64.getEncoder().encodeToString(salt);
}
public static String hash(String password, String salt) {
try {
MessageDigest md =
MessageDigest.getInstance("SHA-256");
// 清理非 Base64 字符,防止数据库中转义字符导致解析错误
String cleanSalt = salt.replaceAll("[^A-Za-z0-9+/=]", "");
if (cleanSalt.isEmpty()) {
throw new IllegalArgumentException("Invalid salt: " + salt);
}
md.update(Base64.getDecoder().decode(cleanSalt));
byte[] hash =
md.digest(password.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(hash);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean validate(String password) {
if (password == null) return false;
if (password.length() < 6 || password.length() > 20)
return false;
boolean hasUpper = false;
boolean hasLower = false;
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isUpperCase(c)) hasUpper = true;
if (Character.isLowerCase(c)) hasLower = true;
if (Character.isDigit(c)) hasDigit = true;
}
return hasUpper && hasLower && hasDigit;
}
public static String generateTempPassword() {
String chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder(8);
for (int i = 0; i < 8; i++) {
sb.append(chars.charAt(
RANDOM.nextInt(chars.length())));
}
return sb.toString();
}
public static String generateInviteCode() {
String chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < 6; i++) {
sb.append(chars.charAt(
RANDOM.nextInt(chars.length())));
}
return sb.toString();
}
public static String generateVerifyCode() {
int code = 100000 + RANDOM.nextInt(900000);
return String.valueOf(code);
}
}
package Sdf1_login;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
public class PasswordUtils {
private static final SecureRandom RANDOM =
new SecureRandom();
public static String generateSalt() {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
return Base64.getEncoder().encodeToString(salt);
}
public static String hash(String password, String salt) {
try {
MessageDigest md =
MessageDigest.getInstance("SHA-256");
md.update(Base64.getDecoder().decode(salt));
byte[] hash =
md.digest(password.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(hash);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean validate(String password) {
if (password == null) return false;
if (password.length() < 6 || password.length() > 20)
return false;
boolean hasUpper = false;
boolean hasLower = false;
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isUpperCase(c)) hasUpper = true;
if (Character.isLowerCase(c)) hasLower = true;
if (Character.isDigit(c)) hasDigit = true;
}
return hasUpper && hasLower && hasDigit;
}
public static String generateTempPassword() {
String chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder(8);
for (int i = 0; i < 8; i++) {
sb.append(chars.charAt(
RANDOM.nextInt(chars.length())));
}
return sb.toString();
}
public static String generateInviteCode() {
String chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < 6; i++) {
sb.append(chars.charAt(
RANDOM.nextInt(chars.length())));
}
return sb.toString();
}
public static String generateVerifyCode() {
int code = 100000 + RANDOM.nextInt(900000);
return String.valueOf(code);
}
}
+1 -4
View File
@@ -12,11 +12,8 @@ public class PlayerStorage {
Logger logger) {
this.logger = logger;
File dbFile = new File(
new File(dataFolder,
"任务面板"),
dataFolder,
"quest_data.db");
dbFile.getParentFile()
.mkdirs();
try {
Class.forName(
"org.sqlite.JDBC");
+374 -375
View File
@@ -1,375 +1,374 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Method;
import java.util.*;
public class PointsManager {
private final Main plugin;
private Object cyInstance = null;
private Method cyActivationMethod = null;
private Method cyGetShopItemsMethod = null;
private final List<Map<String, Object>> cyItems =
new ArrayList<>();
public PointsManager(Main plugin) {
this.plugin = plugin;
discoverCY();
}
private void discoverCY() {
try {
org.bukkit.plugin.Plugin p = Bukkit
.getPluginManager()
.getPlugin("CY_beibao");
if (p != null && p.isEnabled()) {
cyInstance = p;
cyGetShopItemsMethod = p.getClass()
.getMethod("onSdf1GetShopItems");
cyActivationMethod = p.getClass()
.getMethod("onSdf1Activation",
String.class,
int.class, int.class);
plugin.getLogger().info(
"[Sdf1_login] CY_beibao 联控已连接");
}
} catch (Exception ignored) {
}
}
private void refreshCYItems() {
cyItems.clear();
if (cyInstance == null
|| cyGetShopItemsMethod == null) return;
try {
Object result =
cyGetShopItemsMethod.invoke(cyInstance);
if (result == null) return;
String data = result.toString();
if (data.isEmpty()) return;
String[] items = data.split(";");
for (String itemStr : items) {
String[] p = itemStr.split("\\|");
if (p.length < 8) continue;
Map<String, Object> item =
new LinkedHashMap<>();
item.put("id", p[0]);
item.put("name", p[1]);
item.put("days",
Integer.parseInt(p[2]));
item.put("slots",
Integer.parseInt(p[3]));
item.put("price",
Integer.parseInt(p[4]));
item.put("stock",
Integer.parseInt(p[5]));
item.put("icon", p[6]);
item.put("lifetime",
"1".equals(p[7]));
cyItems.add(item);
}
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] 拉取CY商品失败: "
+ e.getMessage());
}
}
private void activateCY(String name,
int slots, int days) {
try {
if (cyInstance == null
|| cyActivationMethod == null) return;
cyActivationMethod.invoke(
cyInstance, name, slots, days);
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] CY激活失败: "
+ e.getMessage());
}
}
public int getPoints(String name) {
return ((Number) plugin.getDb()
.getField(name, "points")).intValue();
}
public Inventory createShopGUI(Player p) {
int points = getPoints(p.getName());
Inventory inv = Bukkit.createInventory(
null, 54,
"§d§l积分商城 | 当前积分: " + points);
fillBg(inv);
inv.setItem(10, mkItem(Material.EMERALD,
"§a游戏币充值",
"§7消耗积分兑换游戏币",
"§7100积分 = $1000",
"",
"§e点击兑换"));
inv.setItem(12, mkItem(Material.ENDER_CHEST,
"§b背包空间",
"§7消耗积分兑换背包格子",
"§750积分 = 9格永久空间",
"",
"§e点击兑换"));
inv.setItem(14, mkItem(Material.EXPERIENCE_BOTTLE,
"§e经验瓶",
"§7消耗积分兑换经验",
"§720积分 = 10级经验",
"",
"§e点击兑换"));
if (cyInstance != null) {
inv.setItem(31, mkItem(Material.CHEST,
"§6背包商城",
"§7来自CY_beibao的商品",
"",
"§e点击查看"));
}
inv.setItem(49, mkItem(Material.ARROW, "§7返回"));
return inv;
}
public Inventory createCYShopGUI(Player p) {
refreshCYItems();
int points = getPoints(p.getName());
int size = Math.max(54,
((cyItems.size() / 9) + 1) * 9);
if (size > 54) size = 54;
Inventory inv = Bukkit.createInventory(
null, size,
"§d§lCY背包商城 | 当前积分: " + points);
fillBg(inv);
for (int i = 0; i < cyItems.size()
&& i < 45; i++) {
Map<String, Object> item = cyItems.get(i);
String name = (String) item.get("name");
int price = ((Number) item.get("price"))
.intValue();
int stock = ((Number) item.get("stock"))
.intValue();
int days = ((Number) item.get("days"))
.intValue();
int slots = ((Number) item.get("slots"))
.intValue();
boolean lifetime = (boolean) item
.get("lifetime");
List<String> lore = new ArrayList<>();
lore.add("§7价格: §e" + price + " 积分");
if (lifetime) {
lore.add("§7格子: §e终身 +" + slots);
} else {
lore.add("§7格子: §e+" + slots);
lore.add("§7时间: §e" + days + "天");
}
if (stock == 0) {
lore.add("§7库存: §a无限");
} else if (stock == -1) {
lore.add("§7库存: §c已下架");
} else {
lore.add("§7库存: §e" + stock);
}
lore.add("");
if (points >= price && stock != -1) {
lore.add("§e点击购买");
} else if (stock == -1) {
lore.add("§c已下架");
} else {
lore.add("§c积分不足");
}
inv.setItem(i, mkItem(Material.CHEST,
"§a" + name,
lore.toArray(new String[0])));
}
inv.setItem(size - 1,
mkItem(Material.ARROW, "§7返回"));
return inv;
}
public void addItem(String name,
int price, String cmd2) {
// 追加到商品配置文件
File file = new File(
plugin.getDataFolder(),
"ShopItems.txt");
try {
java.io.FileWriter fw =
new java.io.FileWriter(file, true);
fw.write(name + ":" + price
+ ":" + cmd2 + "\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeItem(int index) {
File file = new File(
plugin.getDataFolder(),
"ShopItems.txt");
try {
java.util.List<String> lines =
new java.util.ArrayList<>();
java.io.BufferedReader br =
new java.io.BufferedReader(
new java.io.FileReader(
file));
String line;
int i = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()
|| line.startsWith("#")) {
lines.add(line);
continue;
}
if (i != index) {
lines.add(line);
}
i++;
}
br.close();
java.io.PrintWriter pw =
new java.io.PrintWriter(file);
for (String l : lines) pw.println(l);
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void handleClick(Player p, int slot) {
int points = getPoints(p.getName());
switch (slot) {
case 10:
if (points >= 100) {
BondManager bm = plugin.getBonds();
if (bm != null) {
int before = bm.getBonds(p.getName());
bm.addBonds(p.getName(), 1000, "points_exchange", "", "积分商店", "积分兑换债券");
int after = bm.getBonds(p.getName());
plugin.getDb().deductPoints(p.getName(), 100);
p.sendMessage(plugin.getConfig2().msg("points_purchase_success")
.replace("{count}", "100"));
p.sendMessage("§a[积分] §f债券: §e" + before + " → §a" + after);
} else {
p.sendMessage("§c债券系统不可用");
}
} else {
p.sendMessage(plugin.getConfig2().msg("points_insufficient")
.replace("{points}", String.valueOf(points)));
}
break;
case 12:
if (points >= 50) {
plugin.getDb().deductPoints(
p.getName(), 50);
activateCY(p.getName(), 9, 0);
p.sendMessage(plugin.getConfig2()
.msg("points_purchase_success")
.replace("{count}", "50"));
} else {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
}
break;
case 14:
if (points >= 20) {
plugin.getDb().deductPoints(
p.getName(), 20);
p.setLevel(p.getLevel() + 10);
p.sendMessage(plugin.getConfig2()
.msg("points_purchase_success")
.replace("{count}", "20"));
} else {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
}
break;
case 31:
if (cyInstance != null) {
p.openInventory(
createCYShopGUI(p));
}
break;
}
}
public void handleCYClick(Player p, int slot) {
if (slot < 0 || slot >= cyItems.size()
|| slot >= 45) return;
Map<String, Object> item = cyItems.get(slot);
int price = ((Number) item.get("price"))
.intValue();
int stock = ((Number) item.get("stock"))
.intValue();
int days = ((Number) item.get("days"))
.intValue();
int slots = ((Number) item.get("slots"))
.intValue();
boolean lifetime = (boolean) item
.get("lifetime");
if (stock == -1) {
p.sendMessage("§c该商品已下架");
return;
}
int points = getPoints(p.getName());
if (points < price) {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
return;
}
plugin.getDb().deductPoints(p.getName(), price);
int actDays = lifetime ? 0 : days;
activateCY(p.getName(), slots, actDays);
String tl = lifetime
? "终身" : (days + "天");
p.sendMessage("§a购买成功!获得 "
+ tl + " +" + slots + "格 背包空间");
}
private void fillBg(Inventory inv) {
ItemStack gl = mkItem(
Material.GRAY_STAINED_GLASS_PANE, " ");
for (int i = 0; i < inv.getSize(); i++)
inv.setItem(i, gl);
}
private ItemStack mkItem(Material mat, String name,
String... lore) {
ItemStack it = new ItemStack(mat);
ItemMeta im = it.getItemMeta();
if (im != null) {
im.setDisplayName(name);
if (lore.length > 0)
im.setLore(Arrays.asList(lore));
it.setItemMeta(im);
}
return it;
}
}
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Method;
import java.util.*;
public class PointsManager {
private final Main plugin;
private Object cyInstance = null;
private Method cyActivationMethod = null;
private Method cyGetShopItemsMethod = null;
private final List<Map<String, Object>> cyItems =
new ArrayList<>();
public PointsManager(Main plugin) {
this.plugin = plugin;
discoverCY();
}
private void discoverCY() {
try {
org.bukkit.plugin.Plugin p = Bukkit
.getPluginManager()
.getPlugin("CY_beibao");
if (p != null && p.isEnabled()) {
cyInstance = p;
cyGetShopItemsMethod = p.getClass()
.getMethod("onSdf1GetShopItems");
cyActivationMethod = p.getClass()
.getMethod("onSdf1Activation",
String.class,
int.class, int.class);
plugin.getLogger().info(
"[Sdf1_login] CY_beibao 联控已连接");
}
} catch (Exception ignored) {
}
}
private void refreshCYItems() {
cyItems.clear();
if (cyInstance == null
|| cyGetShopItemsMethod == null) return;
try {
Object result =
cyGetShopItemsMethod.invoke(cyInstance);
if (result == null) return;
String data = result.toString();
if (data.isEmpty()) return;
String[] items = data.split(";");
for (String itemStr : items) {
String[] p = itemStr.split("\\|");
if (p.length < 8) continue;
Map<String, Object> item =
new LinkedHashMap<>();
item.put("id", p[0]);
item.put("name", p[1]);
item.put("days",
Integer.parseInt(p[2]));
item.put("slots",
Integer.parseInt(p[3]));
item.put("price",
Integer.parseInt(p[4]));
item.put("stock",
Integer.parseInt(p[5]));
item.put("icon", p[6]);
item.put("lifetime",
"1".equals(p[7]));
cyItems.add(item);
}
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] 拉取CY商品失败: "
+ e.getMessage());
}
}
private void activateCY(String name,
int slots, int days) {
try {
if (cyInstance == null
|| cyActivationMethod == null) return;
cyActivationMethod.invoke(
cyInstance, name, slots, days);
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] CY激活失败: "
+ e.getMessage());
}
}
public int getPoints(String name) {
return ((Number) plugin.getDb()
.getField(name, "points")).intValue();
}
public Inventory createShopGUI(Player p) {
int points = getPoints(p.getName());
Inventory inv = Bukkit.createInventory(
null, 54,
"§d§l积分商城 | 当前积分: " + points);
fillBg(inv);
inv.setItem(10, mkItem(Material.EMERALD,
"§a游戏币充值",
"§7消耗积分兑换游戏币",
"§7100积分 = $1000",
"",
"§e点击兑换"));
inv.setItem(12, mkItem(Material.ENDER_CHEST,
"§b背包空间",
"§7消耗积分兑换背包格子",
"§750积分 = 9格永久空间",
"",
"§e点击兑换"));
inv.setItem(14, mkItem(Material.EXPERIENCE_BOTTLE,
"§e经验瓶",
"§7消耗积分兑换经验",
"§720积分 = 10级经验",
"",
"§e点击兑换"));
if (cyInstance != null) {
inv.setItem(31, mkItem(Material.CHEST,
"§6背包商城",
"§7来自CY_beibao的商品",
"",
"§e点击查看"));
}
inv.setItem(49, mkItem(Material.ARROW, "§7返回"));
return inv;
}
public Inventory createCYShopGUI(Player p) {
refreshCYItems();
int points = getPoints(p.getName());
int size = Math.max(54,
((cyItems.size() / 9) + 1) * 9);
if (size > 54) size = 54;
Inventory inv = Bukkit.createInventory(
null, size,
"§d§lCY背包商城 | 当前积分: " + points);
fillBg(inv);
for (int i = 0; i < cyItems.size()
&& i < 45; i++) {
Map<String, Object> item = cyItems.get(i);
String name = (String) item.get("name");
int price = ((Number) item.get("price"))
.intValue();
int stock = ((Number) item.get("stock"))
.intValue();
int days = ((Number) item.get("days"))
.intValue();
int slots = ((Number) item.get("slots"))
.intValue();
boolean lifetime = (boolean) item
.get("lifetime");
List<String> lore = new ArrayList<>();
lore.add("§7价格: §e" + price + " 积分");
if (lifetime) {
lore.add("§7格子: §e终身 +" + slots);
} else {
lore.add("§7格子: §e+" + slots);
lore.add("§7时间: §e" + days + "天");
}
if (stock == 0) {
lore.add("§7库存: §a无限");
} else if (stock == -1) {
lore.add("§7库存: §c已下架");
} else {
lore.add("§7库存: §e" + stock);
}
lore.add("");
if (points >= price && stock != -1) {
lore.add("§e点击购买");
} else if (stock == -1) {
lore.add("§c已下架");
} else {
lore.add("§c积分不足");
}
inv.setItem(i, mkItem(Material.CHEST,
"§a" + name,
lore.toArray(new String[0])));
}
inv.setItem(size - 1,
mkItem(Material.ARROW, "§7返回"));
return inv;
}
public void addItem(String name,
int price, String cmd2) {
// 追加到商品配置文件
File file = new File(
plugin.getDataFolder(),
"ShopItems.txt");
try {
java.io.FileWriter fw =
new java.io.FileWriter(file, true);
fw.write(name + ":" + price
+ ":" + cmd2 + "\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeItem(int index) {
File file = new File(
plugin.getDataFolder(),
"ShopItems.txt");
try {
java.util.List<String> lines =
new java.util.ArrayList<>();
java.io.BufferedReader br =
new java.io.BufferedReader(
new java.io.FileReader(
file));
String line;
int i = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()
|| line.startsWith("#")) {
lines.add(line);
continue;
}
if (i != index) {
lines.add(line);
}
i++;
}
br.close();
java.io.PrintWriter pw =
new java.io.PrintWriter(file);
for (String l : lines) pw.println(l);
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void handleClick(Player p, int slot) {
int points = getPoints(p.getName());
switch (slot) {
case 10:
if (points >= 100) {
plugin.getDb().deductPoints(
p.getName(), 100);
if (plugin.getEconomy() != null) {
plugin.getEconomy()
.depositPlayer(p, 1000);
}
p.sendMessage(plugin.getConfig2()
.msg("points_purchase_success")
.replace("{count}", "100"));
} else {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
}
break;
case 12:
if (points >= 50) {
plugin.getDb().deductPoints(
p.getName(), 50);
activateCY(p.getName(), 9, 0);
p.sendMessage(plugin.getConfig2()
.msg("points_purchase_success")
.replace("{count}", "50"));
} else {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
}
break;
case 14:
if (points >= 20) {
plugin.getDb().deductPoints(
p.getName(), 20);
p.setLevel(p.getLevel() + 10);
p.sendMessage(plugin.getConfig2()
.msg("points_purchase_success")
.replace("{count}", "20"));
} else {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
}
break;
case 31:
if (cyInstance != null) {
p.openInventory(
createCYShopGUI(p));
}
break;
}
}
public void handleCYClick(Player p, int slot) {
if (slot < 0 || slot >= cyItems.size()
|| slot >= 45) return;
Map<String, Object> item = cyItems.get(slot);
int price = ((Number) item.get("price"))
.intValue();
int stock = ((Number) item.get("stock"))
.intValue();
int days = ((Number) item.get("days"))
.intValue();
int slots = ((Number) item.get("slots"))
.intValue();
boolean lifetime = (boolean) item
.get("lifetime");
if (stock == -1) {
p.sendMessage("§c该商品已下架");
return;
}
int points = getPoints(p.getName());
if (points < price) {
p.sendMessage(plugin.getConfig2()
.msg("points_insufficient")
.replace("{points}",
String.valueOf(points)));
return;
}
plugin.getDb().deductPoints(p.getName(), price);
int actDays = lifetime ? 0 : days;
activateCY(p.getName(), slots, actDays);
String tl = lifetime
? "终身" : (days + "天");
p.sendMessage("§a购买成功!获得 "
+ tl + " +" + slots + "格 背包空间");
}
private void fillBg(Inventory inv) {
ItemStack gl = mkItem(
Material.GRAY_STAINED_GLASS_PANE, " ");
for (int i = 0; i < inv.getSize(); i++)
inv.setItem(i, gl);
}
private ItemStack mkItem(Material mat, String name,
String... lore) {
ItemStack it = new ItemStack(mat);
ItemMeta im = it.getItemMeta();
if (im != null) {
im.setDisplayName(name);
if (lore.length > 0)
im.setLore(Arrays.asList(lore));
it.setItemMeta(im);
}
return it;
}
}
+98 -167
View File
@@ -7,201 +7,132 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
public class QuestStorage {
private volatile Connection conn;
private final String dbPath;
private final Plugin plugin;
private final Object connLock = new Object();
private Connection conn;
public QuestStorage(File dataFolder, Plugin plugin) {
this.plugin = plugin;
String path = "";
public QuestStorage(File dataFolder) {
try {
Class.forName("org.sqlite.JDBC");
File dbFile = new File(
new File(dataFolder, "任务面板"),
dataFolder,
"quest_data.db");
dbFile.getParentFile().mkdirs();
path = dbFile.getPath();
conn = DriverManager.getConnection(
"jdbc:sqlite:"
+ dbFile.getPath());
initTable();
} catch (Exception e) {
e.printStackTrace();
}
dbPath = path;
conn = openConnection();
if (conn != null) {
initTable();
}
}
private Connection openConnection() {
String url = "jdbc:sqlite:" + dbPath
+ "?journal_mode=WAL"
+ "&synchronous=NORMAL"
+ "&busy_timeout=5000";
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
private void initTable()
throws SQLException {
Statement stmt =
conn.createStatement();
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS "
+ "quest_conditions ("
+ "player TEXT NOT NULL, "
+ "condition_key TEXT NOT NULL, "
+ "value TEXT DEFAULT '1', "
+ "timestamp INTEGER, "
+ "PRIMARY KEY "
+ "(player, condition_key))");
stmt.close();
}
/**
* 轻量级连接检查 — 仅检查本地状态,不执行SQL
* 避免 isValid() 在主线程上阻塞
* 标记条件已完成(value = "1")
*/
private void ensureConnection() {
try {
if (conn != null && !conn.isClosed()) {
return;
}
} catch (SQLException ignored) {}
synchronized (connLock) {
try { if (conn != null) conn.close(); }
catch (Exception ignored) {}
conn = openConnection();
}
}
private void initTable() {
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS quest_conditions ("
+ "player TEXT NOT NULL, "
+ "condition_key TEXT NOT NULL, "
+ "value TEXT DEFAULT '1', "
+ "timestamp INTEGER, "
+ "PRIMARY KEY (player, condition_key))");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void setCondition(String player, String condition) {
setConditionRaw(player, condition, "1");
}
/**
* 异步写入 — 不阻塞主线程
* 使用 Bukkit 异步调度,在独立线程中执行 SQLite 写操作
*/
public void setConditionRaw(String player,
String condition, String value) {
final String sql =
"INSERT OR REPLACE INTO quest_conditions "
+ "(player, condition_key, value, timestamp) "
+ "VALUES (?, ?, ?, ?)";
final long ts = System.currentTimeMillis();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
writeSync(sql, player, condition, value, ts);
});
}
/**
* 在异步线程中执行写入,带重试
*/
private void writeSync(String sql, String player,
String condKey, String value, long timestamp) {
synchronized (connLock) {
for (int attempt = 0; attempt < 5; attempt++) {
try {
ensureConnection();
if (conn == null) return;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, player);
ps.setString(2, condKey);
ps.setString(3, value);
ps.setLong(4, timestamp);
ps.executeUpdate();
ps.close();
return;
} catch (SQLException e) {
String msg = e.getMessage();
if (msg != null && (msg.contains("SQLITE_BUSY")
|| msg.contains("database is locked"))) {
try {
Thread.sleep(200 + attempt * 200);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
} else {
e.printStackTrace();
return;
}
}
}
}
}
/**
* 同步读取(主线程)
* WAL 模式下读操作不阻塞写,可安全在主线程执行
*/
public Object getCondition(String player,
public void setCondition(
String player,
String condition) {
synchronized (connLock) {
for (int attempt = 0; attempt < 3; attempt++) {
try {
ensureConnection();
if (conn == null) return null;
PreparedStatement ps = conn.prepareStatement(
"SELECT value FROM quest_conditions "
setConditionRaw(
player, condition, "1");
}
/**
* 写入任意值(计数器等)
*/
public void setConditionRaw(
String player,
String condition,
String value) {
try {
PreparedStatement ps =
conn.prepareStatement(
"INSERT OR REPLACE "
+ "INTO "
+ "quest_conditions "
+ "(player, "
+ "condition_key, "
+ "value, timestamp) "
+ "VALUES "
+ "(?, ?, ?, ?)");
ps.setString(1, player);
ps.setString(2, condition);
ps.setString(3, value);
ps.setLong(4,
System.currentTimeMillis());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询条件值
*/
public Object getCondition(
String player,
String condition) {
try {
PreparedStatement ps =
conn.prepareStatement(
"SELECT value FROM "
+ "quest_conditions "
+ "WHERE player = ? "
+ "AND condition_key = ?");
ps.setString(1, player);
ps.setString(2, condition);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String val = rs.getString("value");
rs.close();
ps.close();
try {
if (val.contains("."))
return Double.parseDouble(val);
return Long.parseLong(val);
} catch (NumberFormatException e) {
return val;
}
}
rs.close();
ps.close();
return null;
} catch (SQLException e) {
String msg = e.getMessage();
if (msg != null && (msg.contains("SQLITE_BUSY")
|| msg.contains("database is locked"))) {
try {
Thread.sleep(100 + attempt * 100);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return null;
}
} else {
e.printStackTrace();
return null;
+ "AND "
+ "condition_key = ?");
ps.setString(1, player);
ps.setString(2, condition);
ResultSet rs =
ps.executeQuery();
if (rs.next()) {
String val =
rs.getString("value");
rs.close();
ps.close();
// 尝试解析为数字
try {
if (val.contains(".")) {
return Double.parseDouble(
val);
}
return Long.parseLong(val);
} catch (NumberFormatException e) {
return val;
}
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void close() {
synchronized (connLock) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
try {
if (conn != null
&& !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
File diff suppressed because it is too large Load Diff
-260
View File
@@ -1,260 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 快速返回系统 (/back)
* - 每分钟记录一次在线玩家的坐标
* - /back 命令传送玩家到最近的一个记录坐标
*/
public class QuickBack implements Listener, CommandExecutor, TabCompleter {
private final Main plugin;
// 内存缓存: player_name → Location (每分钟刷新)
private final Map<String, Location> lastKnownLocations = new ConcurrentHashMap<>();
// 冷却: player_name → next_available_time
private final Map<String, Long> cooldowns = new ConcurrentHashMap<>();
// ★ 定时器引用(用于 shutdown 时取消)
private BukkitTask scheduleTask = null;
private static final long COOLDOWN_MS = 10 * 1000; // 10秒冷却
public QuickBack(Main plugin) {
this.plugin = plugin;
loadAllFromDB();
// 每分钟记录所有在线玩家的坐标
scheduleTask = new BukkitRunnable() {
@Override
public void run() {
for (Player p : Bukkit.getOnlinePlayers()) {
recordLocation(p);
}
}
}.runTaskTimer(plugin, 1200L, 1200L);
}
// ==================== 事件监听 ====================
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
// 移动超过8格时才记录(减少数据库写入压力)
Location from = event.getFrom();
Location to = event.getTo();
if (to == null || from.getWorld() != to.getWorld()) return;
double distance = from.distance(to);
if (distance < 8.0) return;
recordLocation(event.getPlayer());
}
// ==================== 命令处理 ====================
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("§c此命令仅限玩家使用");
return true;
}
Player player = (Player) sender;
// 检查冷却
Long nextAvailable = cooldowns.get(player.getName());
if (nextAvailable != null && System.currentTimeMillis() < nextAvailable) {
long remaining = (nextAvailable - System.currentTimeMillis()) / 1000;
player.sendMessage("§c快速返回冷却中,请等待 §e" + remaining + " §c秒");
return true;
}
// 获取最近的已知位置
Location loc = getLastKnownLocation(player);
if (loc == null) {
player.sendMessage("§c没有找到可返回的位置记录");
return true;
}
// 传送
if (loc.getWorld() == null) {
player.sendMessage("§c位置世界信息无效");
return true;
}
// ★ 禁止/back传送至PVP测试世界
String worldName = loc.getWorld().getName();
if (worldName != null && worldName.startsWith("pvp_test_")) {
player.sendMessage("§c§l[快速返回] §c无法返回PVP测试世界,请使用 /pvp test 进入测试场选装");
return true;
}
Location dest = loc.clone().add(0.5, 0, 0.5); // 对齐格子中心
player.teleport(dest);
// 设置冷却
cooldowns.put(player.getName(), System.currentTimeMillis() + COOLDOWN_MS);
player.sendMessage("§a§l[快速返回] §f已传送到最近记录点");
return true;
}
// ==================== 位置记录 ====================
private void recordLocation(Player player) {
Location loc = player.getLocation();
lastKnownLocations.put(player.getName(), loc);
// ★ 读坐标/更新内存缓存留主线程;写库是阻塞 DB 操作 -> 异步
final String name = player.getName();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
saveToDB(name, loc);
} catch (Throwable t) {
plugin.getLogger().warning("[快捷返回] 坐标落库失败 (" + name + "): " + t.getMessage());
}
});
}
public Location getLastKnownLocation(Player player) {
// 优先从内存获取
Location loc = lastKnownLocations.get(player.getName());
if (loc != null && loc.getWorld() != null) {
return loc;
}
// 从数据库获取
return loadFromDB(player.getName());
}
// ==================== 数据库操作 ====================
private void loadAllFromDB() {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return;
PreparedStatement ps = conn.prepareStatement(
"SELECT player_name, world, x, y, z FROM quick_back_records");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String playerName = rs.getString("player_name");
Location loc = new Location(
Bukkit.getWorld(rs.getString("world")),
rs.getDouble("x"),
rs.getDouble("y"),
rs.getDouble("z")
);
lastKnownLocations.put(playerName, loc);
}
rs.close();
ps.close();
} catch (SQLException e) {
// 表可能不存在
}
}
private void saveToDB(String playerName, Location loc) {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return;
PreparedStatement ps = conn.prepareStatement(
"INSERT OR REPLACE INTO quick_back_records (player_name, world, x, y, z) VALUES (?, ?, ?, ?, ?)");
ps.setString(1, playerName);
ps.setString(2, loc.getWorld() != null ? loc.getWorld().getName() : "world");
ps.setDouble(3, loc.getX());
ps.setDouble(4, loc.getY());
ps.setDouble(5, loc.getZ());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
// 忽略
}
}
private Location loadFromDB(String playerName) {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return null;
PreparedStatement ps = conn.prepareStatement(
"SELECT world, x, y, z FROM quick_back_records WHERE player_name=? LIMIT 1");
ps.setString(1, playerName);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Location loc = new Location(
Bukkit.getWorld(rs.getString("world")),
rs.getDouble("x"),
rs.getDouble("y"),
rs.getDouble("z")
);
rs.close();
ps.close();
return loc;
}
rs.close();
ps.close();
} catch (SQLException e) {
// 忽略
}
return null;
}
// ==================== Tab补全 ====================
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return new ArrayList<>();
}
// ==================== 初始化 ====================
public void initTable() {
try {
java.sql.Connection conn = plugin.getDb().getConnection();
if (conn == null) return;
java.sql.Statement st = conn.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS quick_back_records ("
+ "player_name TEXT PRIMARY KEY, "
+ "world TEXT, "
+ "x REAL, y REAL, z REAL)");
st.close();
} catch (SQLException e) {
plugin.getLogger().warning("[快速返回] 建表失败: " + e.getMessage());
}
}
// ==================== 关闭 ====================
public void shutdown() {
if (scheduleTask != null) {
scheduleTask.cancel();
}
lastKnownLocations.clear();
cooldowns.clear();
}
}
@@ -4,141 +4,115 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player
.PlayerResourcePackStatusEvent;
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent
.ConcurrentHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
public class RadioDownloadListener
implements Listener {
private final Logger log;
private final Main plugin;
private final java.util.logging.Logger log;
private final ConcurrentHashMap<UUID, Integer>
failCount = new ConcurrentHashMap<>();
private final ConcurrentHashMap<UUID, Boolean>
blocked = new ConcurrentHashMap<>();
private static final int MAX_FAILED = 3;
private final Map<UUID, Integer> retryCount =
new ConcurrentHashMap<>();
private static final int MAX_RETRY = 2;
public RadioDownloadListener(Main plugin) {
this.plugin = plugin;
this.log = plugin.getLogger();
}
public void onPlayerQuit(UUID uuid) {
failCount.remove(uuid);
blocked.remove(uuid);
}
@EventHandler
public void onStatus(
PlayerResourcePackStatusEvent e) {
Player p = e.getPlayer();
UUID uuid = p.getUniqueId();
String status =
e.getStatus().name();
String status = e.getStatus().name();
log.info("[Radio] === 资源包状态 ===");
log.info("[Radio] 玩家: "
+ p.getName());
log.info("[Radio] UUID: " + uuid);
log.info("[Radio] 状态: "
+ status);
log.info("[Radio] 原始状态枚举: "
+ e.getStatus().getClass()
.getSimpleName()
+ "."
+ e.getStatus().name());
if (blocked.containsKey(uuid)) {
log.info("[Radio] 已熔断,跳过: "
+ p.getName());
return;
}
log.info("[Radio] " + p.getName()
+ " status: " + status);
switch (status) {
case "SUCCESS":
log.info("[Radio] "
+ p.getName()
+ " ✓ 资源包加载成功");
failCount.remove(uuid);
blocked.remove(uuid);
break;
case "ACCEPTED":
log.info("[Radio] "
+ p.getName()
+ " 客户端已接受,"
+ "等待下载...");
break;
case "DECLINED":
log.warning("[Radio] "
+ p.getName()
+ " ✗ 拒绝了资源包");
/* log.warning("[Radio] "
+ "可能原因: "
+ "1.客户端设置禁用资源包"
+ " 2.已缓存拒绝记录"
+ " 3.SSL证书不匹配");*/
handleFailure(p, uuid);
case "DOWNLOADED":
break;
case "SUCCESS":
log.info("[Radio] " + p.getName()
+ " 资源包加载成功");
retryCount.remove(uuid);
break;
case "FAILED_DOWNLOAD":
log.warning("[Radio] "
+ p.getName()
+ " ✗ 下载失败");
/* log.warning("[Radio] "
+ "可能原因: "
+ "1.URL无法访问"
+ " 2.SSL证书错误"
+ " 3.网络超时"
+ " 4.文件不存在(404)");*/
handleFailure(p, uuid);
handleRetry(p, uuid);
break;
case "DECLINED":
log.info("[Radio] " + p.getName()
+ " 拒绝下载");
p.sendMessage(
"§e[Radio] §f你拒绝了资源包");
retryCount.remove(uuid);
break;
case "DISCARDED":
log.warning("[Radio] " + p.getName()
+ " DISCARDED");
p.sendMessage(
"§c[Radio] §f资源包下载失败"
+ ",可能原因:");
p.sendMessage(
"§71. CDN/防火墙拦截");
p.sendMessage(
"§72. SSL证书问题");
retryCount.remove(uuid);
break;
case "INVALID_URL":
log.warning("[Radio] " + p.getName()
+ " URL无效");
retryCount.remove(uuid);
break;
default:
log.info("[Radio] "
+ p.getName()
+ " 未知状态: "
+ status);
log.info("[Radio] " + p.getName()
+ " 未知: " + status);
break;
}
}
private void handleFailure(Player p, UUID uuid) {
int failNum = failCount.getOrDefault(uuid, 0) + 1;
failCount.put(uuid, failNum);
private void handleRetry(Player p, UUID uuid) {
int count = retryCount
.getOrDefault(uuid, 0) + 1;
retryCount.put(uuid, count);
log.warning("[Radio] " + p.getName()
+ " 失败次数: " + failNum + "/" + MAX_FAILED);
+ " 下载失败 (" + count
+ "/" + MAX_RETRY + ")");
if (failNum >= MAX_FAILED) {
blocked.put(uuid, true);
log.severe("[Radio] " + p.getName()
+ " 已达最大失败次数,停止重试,"
+ "玩家继续留在服务器");
// 不踢出,只记录熔断,玩家正常游玩
p.sendMessage("§e§l[Radio] 资源包加载失败"
+ ",已取消下载资源包,部分画面音频可能出现问题"
+ "\n§d§l若想继续下载,请退出重进。若持续失败,请上报管理员");
return;
if (count <= MAX_RETRY) {
p.sendMessage(
"§e[Radio] §f下载失败,重试中... ("
+ count + "/" + MAX_RETRY + ")");
Bukkit.getScheduler().runTaskLater(
plugin,
() -> {
if (p.isOnline()
&& plugin.radio != null) {
plugin.radio
.sendResourcePack(p);
}
}, 60L);
} else {
p.sendMessage(
"§c[Radio] §f资源包加载失败,"
+ "部分音乐无法播放");
retryCount.remove(uuid);
}
// 打了包没测试
p.sendMessage("§e§l[Radio] 下载失败,"
+ "重试... (" + failNum + "/" + MAX_FAILED + ")");
// 5秒后重试
Bukkit.getScheduler()
.runTaskLater(plugin, () -> {
if (p.isOnline() && plugin.radio != null) {
plugin.radio.sendResourcePack(p);
}
}, 100L);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,62 +0,0 @@
package Sdf1_login;
import org.bukkit.Material;
import java.util.UUID;
public class RefundRecord {
public final UUID playerUUID;
public final String playerName;
public final String itemId;
public final String itemName;
public final Material material;
public final Material shulkerMaterial;
public int amount;
public int totalPaid;
public final long timestamp;
// 普通购买
public RefundRecord(UUID uuid, String name,
String itemId, String itemName,
Material material, int amount,
int totalPaid, long timestamp) {
this.playerUUID = uuid;
this.playerName = name;
this.itemId = itemId;
this.itemName = itemName;
this.material = material;
this.shulkerMaterial = null;
this.amount = amount;
this.totalPaid = totalPaid;
this.timestamp = timestamp;
}
// 盒装购买
public RefundRecord(UUID uuid, String name,
String itemId, String itemName,
Material material,
Material shulkerMat,
int amount, int totalPaid,
long timestamp) {
this.playerUUID = uuid;
this.playerName = name;
this.itemId = itemId;
this.itemName = itemName;
this.material = material;
this.shulkerMaterial = shulkerMat;
this.amount = amount;
this.totalPaid = totalPaid;
this.timestamp = timestamp;
}
public boolean isExpired() {
return System.currentTimeMillis()
- timestamp > 300000L;
}
public int getSecondsLeft() {
long left = 300000L
- (System.currentTimeMillis()
- timestamp);
return (int) Math.max(0, left / 1000);
}
}
+248 -271
View File
@@ -1,271 +1,248 @@
package Sdf1_login;
import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
/**
* 风控管理器:密码错误阈值封禁 + 报警邮件
*
* 功能1:密码错误达到阈值 → 自动封禁账号N分钟 + 推送报警邮件
* 功能2:封禁期间拒绝所有登录尝试
*/
public class RiskControlManager {
private final Main plugin;
// 每个玩家名 -> 连续失败次数
private final Map<String, Integer> failAttempts =
new ConcurrentHashMap<>();
// 每个玩家名 -> 封禁到期时间戳(毫秒)
private final Map<String, Long> banUntil =
new ConcurrentHashMap<>();
public RiskControlManager(Main plugin) {
this.plugin = plugin;
}
/**
* 获取当前密码错误阈值(从配置读取)
*/
private int getMaxFailAttempts() {
return plugin.getConfig2().passwordFailThreshold;
}
/**
* 获取封禁时长(毫秒)(从配置读取)
*/
private long getBanDurationMs() {
return (long) plugin.getConfig2().passwordBanDuration * 1000L;
}
// ==================== 封禁检查 ====================
/**
* 检查玩家是否已被封禁
* @return true=已被封禁(应拒绝登录)
*/
public boolean isBanned(String playerName) {
Long until = banUntil.get(playerName);
if (until == null) return false;
if (System.currentTimeMillis() < until) {
return true; // 仍在封禁期内
}
// 封禁已过期,自动解除
banUntil.remove(playerName);
failAttempts.remove(playerName);
return false;
}
/**
* 获取玩家剩余封禁时间(秒),0=未封禁
*/
public int getBanRemainingSeconds(String playerName) {
Long until = banUntil.get(playerName);
if (until == null) return 0;
long remaining = until - System.currentTimeMillis();
if (remaining <= 0) {
banUntil.remove(playerName);
failAttempts.remove(playerName);
return 0;
}
return (int) (remaining / 1000) + 1; // 向上取整
}
// ==================== 失败记录 ====================
/**
* 记录一次失败的登录尝试,判断是否触发封禁
*
* @param player 登录失败的玩家
* @return 剩余尝试次数(-1=已被封禁)
*/
public int recordFailAttempt(Player player) {
String name = player.getName();
int maxAttempts = getMaxFailAttempts();
// 已被封禁,直接返回
if (isBanned(name)) {
return -1;
}
int current = failAttempts
.getOrDefault(name, 0) + 1;
failAttempts.put(name, current);
int remaining = Math.max(0, maxAttempts - current);
// 达到阈值 → 触发封禁
if (current >= maxAttempts) {
triggerBan(player);
}
return remaining;
}
/**
* 触发封禁:Bukkit真实封禁 + 记录时间 + 发邮件 + 踢出
* 双层封禁:Bukkit ban阻止连接加入,内存计时器到期自动解封
*/
private void triggerBan(Player player) {
String name = player.getName();
long durationMs = getBanDurationMs();
long until = System.currentTimeMillis() + durationMs;
banUntil.put(name, until);
String ip = plugin.getPlayerIP(player);
int banMinutes = (int) (durationMs / 60000);
plugin.getLogger().warning(
"[风控] 玩家 " + name
+ " 密码错误达到阈值("
+ getMaxFailAttempts() + "次)"
+ ",封禁 " + banMinutes + " 分钟");
// ★ 真实封禁:调用Bukkit BanList API阻止玩家重新加入服务器
String banReason = "§c§l[安全风控] 密码连续错误"
+ getMaxFailAttempts() + "次,"
+ "账号临时封禁" + banMinutes + "分钟";
try {
// 使用 BanList API 设置带过期时间的封禁
Date expiry = new Date(System.currentTimeMillis() + durationMs);
Bukkit.getBanList(BanList.Type.NAME).addBan(
name, banReason, expiry, "[Sdf1_login] 风控");
plugin.getLogger().info(
"[风控] 已通过Bukkit BanList封禁玩家 "
+ name + " (" + banMinutes + "分钟,到期: " + expiry + ")");
} catch (Exception e) {
plugin.getLogger().warning(
"[风控] BanList封禁失败: " + e.getMessage());
}
// 踢出玩家(无论BanList是否成功,立即踢出)
player.kickPlayer(banReason);
// 异步发送报警邮件
sendBanAlertEmail(name, ip, banMinutes);
}
/**
* 发送封禁报警邮件到玩家绑定的邮箱
* 未绑定邮箱则跳过
*/
private void sendBanAlertEmail(String playerName,
String ip, int banMinutes) {
String emailAddr = (String) plugin.getDb()
.getField(playerName, "email");
if (emailAddr == null || emailAddr.isEmpty()) {
plugin.getLogger().info(
"[风控] 玩家 " + playerName
+ " 未绑定邮箱,跳过报警邮件");
return;
}
String subject =
"[安全警告] 您的账号已被临时封禁";
String body = "尊敬的玩家 " + playerName + ":\n\n"
+ "您的账号在 "
+ new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss")
.format(new java.util.Date())
+ " 因密码连续错误 "
+ getMaxFailAttempts() + " 次"
+ ",已被自动封禁 " + banMinutes + " 分钟。\n\n"
+ "来源IP: " + (ip != null ? ip : "未知") + "\n"
+ "封禁到期: "
+ new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss")
.format(new java.util.Date(
System.currentTimeMillis()
+ (long) banMinutes * 60000L))
+ "\n\n"
+ "如果这是您本人操作,请等待封禁到期后重试。\n"
+ "如果非本人操作,建议您立即修改密码"
+ "(使用 /sdf1_login pw)。\n\n"
+ "--Sdf1_login 安全系统";
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
plugin.getEmail().sendBody(
emailAddr, subject, body);
plugin.getLogger().info(
"[风控] 封禁报警邮件已发送到 "
+ emailAddr);
} catch (Exception e) {
plugin.getLogger().warning(
"[风控] 报警邮件发送失败: "
+ e.getMessage());
}
});
}
// ==================== 成功重置 ====================
/**
* 登录成功后重置风控状态
*/
public void onLoginSuccess(String playerName) {
failAttempts.remove(playerName);
banUntil.remove(playerName);
}
// ==================== 清理 ====================
/**
* 清理过期的封禁记录(可由定时任务调用)
* 同步解除过期玩家的Bukkit封禁
*/
public void cleanup() {
long now = System.currentTimeMillis();
// 收集过期的玩家名
List<String> expired = new ArrayList<>();
banUntil.entrySet().removeIf(e -> {
if (e.getValue() < now) {
expired.add(e.getKey());
return true;
}
return false;
});
// 同步解除Bukkit封禁
for (String name : expired) {
try {
Bukkit.getBanList(BanList.Type.NAME)
.pardon(name);
plugin.getLogger().info(
"[风控] 封禁到期,已解除Bukkit封禁: "
+ name);
} catch (Exception ignored) {}
failAttempts.remove(name);
}
}
/**
* 获取所有封禁记录(调试/管理用)
*/
public Map<String, Long> getAllBans() {
return Collections.unmodifiableMap(banUntil);
}
/**
* 获取所有失败尝试记录(调试用)
*/
public Map<String, Integer> getAllFailAttempts() {
return Collections.unmodifiableMap(failAttempts);
}
/**
* 手动解除某玩家的封禁(管理员用)
*/
public void unban(String playerName) {
banUntil.remove(playerName);
failAttempts.remove(playerName);
// 同步解除Bukkit封禁
try {
Bukkit.getBanList(BanList.Type.NAME)
.pardon(playerName);
plugin.getLogger().info("[风控] 已解除Bukkit封禁: "
+ playerName);
} catch (Exception ignored) {}
}
/**
* 清除所有风控数据(管理员调试用)
*/
public void clearAll() {
failAttempts.clear();
banUntil.clear();
}
}
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 风控管理器:检测异常登录行为,记录尝试次数,触发安全报警
*/
public class RiskControlManager {
private final Main plugin;
// 每个玩家名 -> 连续失败次数
private final Map<String, Integer> failAttempts =
new ConcurrentHashMap<>();
// 每个IP -> 关联的可疑玩家列表
private final Map<String, Set<String>> ipSuspicious =
new ConcurrentHashMap<>();
// 每个玩家 -> 上次验证时间(用于冷却)
private final Map<String, Long> verifyCooldown =
new ConcurrentHashMap<>();
// 配置项
private static final int MAX_FAIL_ATTEMPTS = 5;
private static final int MAX_ACCOUNTS_PER_IP = 5;
private static final long COOLDOWN_MS = 60000L;
public RiskControlManager(Main plugin) {
this.plugin = plugin;
}
/**
* 记录一次失败的登录尝试
*
* @param playerName 玩家名
* @return 剩余尝试次数
*/
public int recordFailAttempt(String playerName) {
int current = failAttempts
.getOrDefault(playerName, 0) + 1;
failAttempts.put(playerName, current);
return Math.max(0, MAX_FAIL_ATTEMPTS - current);
}
/**
* 重置指定玩家的失败计数(登录成功时调用)
*/
public void resetFailAttempts(String playerName) {
failAttempts.remove(playerName);
}
/**
* 获取指定玩家的失败次数
*/
public int getFailAttempts(String playerName) {
return failAttempts
.getOrDefault(playerName, 0);
}
/**
* 判断玩家是否已被锁定(失败次数达到上限)
*/
public boolean isLocked(String playerName) {
return failAttempts
.getOrDefault(playerName, 0)
>= MAX_FAIL_ATTEMPTS;
}
/**
* 检查IP是否达到注册上限
* 直接查数据库,不依赖 DatabaseManager 的方法
*/
public boolean canRegisterFromIP(String ip) {
if (ip == null || ip.isEmpty()) return true;
try {
java.sql.Connection conn =
plugin.getDb().getDb();
if (conn == null) return true;
java.sql.PreparedStatement ps =
conn.prepareStatement(
"SELECT COUNT(*) FROM users "
+ "WHERE ip_address = ?");
ps.setString(1, ip);
java.sql.ResultSet rs = ps.executeQuery();
int count = 0;
if (rs.next()) count = rs.getInt(1);
rs.close();
ps.close();
return count < 5;
} catch (Exception e) {
e.printStackTrace();
return true;
}
}
/**
* 记录IP关联的可疑行为
*/
public void recordSuspiciousIP(String ip,
String playerName) {
if (ip == null || ip.isEmpty()) return;
ipSuspicious
.computeIfAbsent(ip,
k -> ConcurrentHashMap.newKeySet())
.add(playerName);
}
/**
* 获取某IP关联的所有可疑玩家
*/
public Set<String> getSuspiciousAccounts(String ip) {
return ipSuspicious
.getOrDefault(ip, Collections.emptySet());
}
/**
* 检查是否在验证冷却期内
*/
public boolean isOnCooldown(String playerName) {
Long last = verifyCooldown.get(playerName);
if (last == null) return false;
return System.currentTimeMillis() - last
< COOLDOWN_MS;
}
/**
* 设置验证冷却时间
*/
public void setCooldown(String playerName) {
verifyCooldown.put(playerName,
System.currentTimeMillis());
}
/**
* 当检测到可疑登录时触发报警
* - 全服广播
* - 有邮箱则发邮件
* - 记录到数据库
*/
public void triggerAlert(Player player,
String suspiciousIP) {
String name = player.getName();
// 记录到数据库
plugin.getDb().recordSecurityAlert(
name, suspiciousIP);
// 记录IP可疑行为
recordSuspiciousIP(suspiciousIP, name);
// 全服广播
String serverMsg = "§c§l[安全警告] §e" + name
+ " §f的账号疑似遭到 §c" + suspiciousIP
+ " §f的盗号尝试, 请各位玩家注意账号安全!";
Bukkit.broadcastMessage(serverMsg);
// 有邮箱则发邮件
String emailAddr = (String) plugin.getDb()
.getField(name, "email");
if (emailAddr != null
&& !emailAddr.isEmpty()) {
String subject =
"[安全警告] 您的账号疑似遭到盗号尝试";
String body = "尊敬的玩家 " + name
+ ":\n\n"
+ "您的账号在 "
+ new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss")
.format(new java.util.Date())
+ " 疑似遭到 IP: " + suspiciousIP
+ " 的盗号尝试。\n\n"
+ "建议您:\n"
+ "1. 立即修改密码"
+ "(使用 /sdf1_login pw)\n"
+ "2. 如非本人操作,"
+ "请联系管理员处理\n\n"
+ "--Sdf1_login 安全系统";
plugin.getEmail().sendTempPassword(
emailAddr, name, body);
}
}
/**
* 处理登录失败时的风控逻辑
*
* @param player 玩家
* @param suspiciousIP 可疑来源IP
* @return true=已被锁定(应踢出), false=仍可继续尝试
*/
public boolean handleLoginFailure(Player player,
String suspiciousIP) {
String name = player.getName();
int remaining = recordFailAttempt(name);
if (remaining <= 0) {
// 达到上限,触发报警
triggerAlert(player, suspiciousIP);
player.kickPlayer(
"§c§l[风控] §f登录失败次数过多,"
+ " 账号已被临时锁定, 请联系管理员");
return true;
}
// 未达上限,提示剩余次数
player.sendMessage(
"§c§l[风控] §f密码错误! "
+ "剩余" + remaining + "次机会");
return false;
}
/**
* 登录成功后重置风控状态
*/
public void onLoginSuccess(String playerName) {
resetFailAttempts(playerName);
}
/**
* 清理过期的冷却记录(可由定时任务调用)
*/
public void cleanup() {
long now = System.currentTimeMillis();
verifyCooldown.entrySet().removeIf(
e -> now - e.getValue() > COOLDOWN_MS * 10);
}
/**
* 获取所有玩家的失败尝试记录(调试用)
*/
public Map<String, Integer> getAllFailAttempts() {
return Collections.unmodifiableMap(failAttempts);
}
/**
* 清除所有风控数据(管理员调试用)
*/
public void clearAll() {
failAttempts.clear();
ipSuspicious.clear();
verifyCooldown.clear();
}
}
@@ -1,170 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class SalesStatsManager {
private final Main plugin;
private final Map<String, Integer> sessionSales =
new ConcurrentHashMap<>();
private int sessionRevenue = 0;
private int sessionOrders = 0;
private int sessionItems = 0;
private int sessionRefunds = 0;
private int sessionRefundAmount = 0;
private long sessionStart = System.currentTimeMillis();
// 状态
private boolean waitingForEmpty = false;
private boolean hasReported = false;
private BukkitRunnable waitTask = null;
public SalesStatsManager(Main plugin) {
this.plugin = plugin;
startMonitor();
}
// ★ 每10秒检测一次
private void startMonitor() {
new BukkitRunnable() {
@Override
public void run() {
int online = Bukkit.getOnlinePlayers().size();
if (online > 0) {
// 有玩家在线 → 重置等待状态
if (waitingForEmpty) {
// 刚有人进来了,清除已汇报标记
// 下次没人时会重新汇报
}
waitingForEmpty = false;
hasReported = false;
cancelWaitTask();
} else if (!waitingForEmpty && !hasReported) {
// 没人了,且还没汇报过 → 开始1分钟倒计时
waitingForEmpty = true;
startWaitCountdown();
}
}
}.runTaskTimer(plugin, 200L, 200L);
}
// ★ 1分钟等待
private void startWaitCountdown() {
cancelWaitTask();
waitTask = new BukkitRunnable() {
@Override
public void run() {
int online = Bukkit.getOnlinePlayers().size();
if (online > 0) {
// 等待期间有人进来 → 取消,等下次没人
waitingForEmpty = false;
hasReported = false;
waitTask = null;
cancel();
return;
}
// 1分钟没人 → 汇报一次
if (!hasReported) {
hasReported = true;
report();
}
waitingForEmpty = false;
waitTask = null;
cancel();
}
};
waitTask.runTaskLater(plugin, 1200L); // 60秒
}
private void cancelWaitTask() {
if (waitTask != null) {
waitTask.cancel();
waitTask = null;
}
}
// ===== 记录 =====
public void recordSale(String itemName, int price) {
sessionSales.merge(itemName, 1, Integer::sum);
sessionRevenue += price;
sessionOrders++;
sessionItems++;
}
public void recordRefund(int amount) {
sessionRefunds++;
sessionRefundAmount += amount;
}
// ===== 汇报 =====
public void report() {
if (sessionItems == 0 && sessionRefunds == 0) {
// plugin.getLogger().info("[Sales] 无数据,跳过");
return;
}
long minutes =
(System.currentTimeMillis() - sessionStart)
/ 60000;
if (minutes < 1) minutes = 1;
StringBuilder sb = new StringBuilder();
sb.append("§6§l========== 销量汇总 ==========");
sb.append("\n§7时长: §f").append(minutes).append("分钟");
sb.append("\n§7订单: §f").append(sessionOrders).append("笔");
sb.append("\n§7商品: §f").append(sessionItems).append("件");
sb.append("\n§7成交额: §6").append(sessionRevenue).append("枚");
sb.append("\n§7退款: §c").append(sessionRefunds)
.append("次(§c").append(sessionRefundAmount)
.append("枚§7)");
sb.append("\n§6§l------------------------------");
if (!sessionSales.isEmpty()) {
sb.append("\n§7销量排行:");
List<Map.Entry<String, Integer>> sorted =
new ArrayList<>(sessionSales.entrySet());
sorted.sort((a, b) ->
b.getValue() - a.getValue());
int rank = 1;
for (Map.Entry<String, Integer> e : sorted) {
if (rank > 10) break;
sb.append("\n§e").append(rank).append(". ")
.append(e.getKey())
.append(" §7x").append(e.getValue());
rank++;
}
}
sb.append("\n§6§l==============================");
String msg = sb.toString();
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.isOp()) {
for (String line : msg.split("\n"))
p.sendMessage(line);
}
}
plugin.getLogger().info("[Sales] 汇报完成");
resetSession();
}
public void resetSession() {
sessionSales.clear();
sessionRevenue = 0;
sessionOrders = 0;
sessionItems = 0;
sessionRefunds = 0;
sessionRefundAmount = 0;
sessionStart = System.currentTimeMillis();
}
}
@@ -1,32 +0,0 @@
package Sdf1_login;
import java.util.ArrayList;
import java.util.List;
public class ShopCategory {
private final String name;
private final String fileName;
private final List<ShopItem> items;
public ShopCategory(String name, String fileName) {
this.name = name;
this.fileName = fileName;
this.items = new ArrayList<>();
}
public String getName() { return name; }
public String getFileName() { return fileName; }
public List<ShopItem> getItems() { return items; }
public ShopItem getItem(String id) {
for (ShopItem item : items) {
if (item.getId().equalsIgnoreCase(id))
return item;
}
return null;
}
public void addItem(ShopItem item) {
items.add(item);
}
}
-51
View File
@@ -1,51 +0,0 @@
package Sdf1_login;
import org.bukkit.Material;
public class ShopItem {
private final String id;
private final String displayName;
private final Material material;
private int buyPrice;
private int sellPrice;
private int stock;
private int hourlySales;
private int totalSales;
public ShopItem(String id, String displayName,
Material material, int buyPrice,
int sellPrice, int stock,
int hourlySales, int totalSales) {
this.id = id;
this.displayName = displayName;
this.material = material;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
this.stock = stock;
this.hourlySales = hourlySales;
this.totalSales = totalSales;
}
public int getEffectiveSellPrice() {
if (sellPrice <= 0) return 0;
return sellPrice;
}
public String getId() { return id; }
public String getDisplayName() { return displayName; }
public Material getMaterial() { return material; }
public int getBuyPrice() { return buyPrice; }
public int getSellPrice() { return sellPrice; }
public int getStock() { return stock; }
public int getHourlySales() { return hourlySales; }
public int getTotalSales() { return totalSales; }
public void setStock(int s) { this.stock = s; }
public void setHourlySales(int s) { this.hourlySales = s; }
public void setTotalSales(int s) { this.totalSales = s; }
public void setBuyPrice(int p) { this.buyPrice = p; }
public void setSellPrice(int p) { this.sellPrice = p; }
public void addSales(int n) {
this.hourlySales += n;
this.totalSales += n;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+119 -153
View File
@@ -163,7 +163,7 @@ public class TicketManager {
"§7类型: §f" + type,
"§7状态: " + stxt(status),
"§7提交者: §f" + requester,
"§7奖励: §e" + reward + " 债券"));
"§7奖励: §e" + reward + " 积分"));
g.setItem(12, mk(Material.BOOK,
"§7详细描述",
@@ -242,13 +242,6 @@ public class TicketManager {
"§a标记完结",
"§7确认工单处理完成"));
}
// ★ 服务商上报完结后:管理员确认完结
if ("completed".equals(status)) {
g.setItem(19, mk(Material.LIME_DYE,
"§a确认完结",
"§7确认服务商处理完成",
"§7输入评分1-5"));
}
// 驳回(非已关闭/已完结状态)
if (!"closed".equals(status)
&& !"resolved".equals(status)
@@ -417,7 +410,7 @@ public class TicketManager {
"§a§l[工单] §f创建成功!"
+ " #§e" + id
+ " 奖励: §e"
+ price + "债券");
+ price + "积分");
}
notifyAdmins(p.getName(), id);
} else {
@@ -704,11 +697,6 @@ public class TicketManager {
"§e§l===================");
}
/**
* ★ 由异步定时器调用(Main.startTicketAutoProcess)。
* DB 查询/写回留在当前(异步)线程;
* 取玩家 / 发消息 / 备份背包 / 踢人 一律经 sync() 回主线程。
*/
public void autoProcessCompleted() {
long timeoutMs = 10 * 60 * 1000L;
@@ -742,26 +730,25 @@ public class TicketManager {
.getUnconfirmedCompleted(
timeoutMs);
for (Map<String, Object> t : list) {
final int id = nv(t, "id");
int id = nv(t, "id");
plugin.getDb().confirmTicket(id, 3);
final String req = sv(t, "requester");
final String asg = sv(t, "assigned_to");
sync(() -> {
Player rp = Bukkit.getPlayer(req);
if (rp != null && rp.isOnline())
rp.sendMessage(
Player rp = Bukkit.getPlayer(
sv(t, "requester"));
if (rp != null && rp.isOnline())
rp.sendMessage(
"§e§l[工单] §f工单 #"
+ id + " 已自动完结");
String assigned =
sv(t, "assigned_to");
if (!assigned.isEmpty()) {
Player pp =
Bukkit.getPlayer(assigned);
if (pp != null && pp.isOnline())
pp.sendMessage(
"§e§l[工单] §f工单 #"
+ id + " 已自动完结");
if (!asg.isEmpty()) {
Player pp =
Bukkit.getPlayer(asg);
if (pp != null && pp.isOnline())
pp.sendMessage(
"§e§l[工单] §f工单 #"
+ id
+ " 已自动完结");
}
});
+ id
+ " 已自动完结");
}
settleTicket(id);
}
@@ -771,16 +758,14 @@ public class TicketManager {
.getRepliedStaleTickets(
timeoutMs);
for (Map<String, Object> t : stale) {
final int id = nv(t, "id");
int id = nv(t, "id");
plugin.getDb().confirmTicket(id, 3);
final String req = sv(t, "requester");
sync(() -> {
Player rp = Bukkit.getPlayer(req);
if (rp != null && rp.isOnline())
rp.sendMessage(
"§e§l[工单] §f工单 #"
+ id + " 超时自动完结");
});
Player rp = Bukkit.getPlayer(
sv(t, "requester"));
if (rp != null && rp.isOnline())
rp.sendMessage(
"§e§l[工单] §f工单 #"
+ id + " 超时自动完结");
settleTicket(id);
}
}
@@ -1032,18 +1017,23 @@ public class TicketManager {
// 管理员:标记完结(已回复状态)
if (adm(p) && "replied".equals(st)
&& asg.equals("admin")) {
Map<String, Object> tk =
plugin.getDb().getTicket(id);
String tkType = sv(tk, "type");
if (TYPE_DELETE.equals(tkType)) {
approveDeleteTicket(p, id);
// 管理员:标记完结(已回复状态)
if (adm(p) && "replied".equals(st)
&& asg.equals("admin")) {
Map<String, Object> tk =
plugin.getDb().getTicket(id);
String tkType = sv(tk, "type");
if (TYPE_DELETE.equals(tkType)) {
approveDeleteTicket(p, id);
return true;
}
plugin.getDb().completeTicket(id);
p.sendMessage("§a工单 #" + id
+ " 已标记完结");
openDetail(p, id);
return true;
}
plugin.getDb().completeTicket(id);
p.sendMessage("§a工单 #" + id
+ " 已标记完结");
openDetail(p, id);
return true;
}
// 服务商:抢单
if (plugin.getDb()
@@ -1054,19 +1044,6 @@ public class TicketManager {
openDetail(p, id);
return true;
}
// ★ 管理员:确认服务商完结(输入评分)
if (adm(p) && "completed".equals(st)) {
p.closeInventory();
plugin.getChatInput()
.getState(p).type =
ChatInputManager.InputType
.TICKET_SCORE;
plugin.getChatInput()
.getState(p).ticketId = id;
p.sendMessage(
"§e输入评分1-5:");
return true;
}
// 服务商:标记完结
if (plugin.getDb()
.isServiceProvider(p.getName())
@@ -1274,73 +1251,72 @@ public class TicketManager {
// ========== 私有 ==========
/**
* 把 Bukkit 操作切回主线程执行。
* 已在主线程时立即执行(保持原调用方的同步语义)。
* 供异步定时器路径(autoProcessCompleted / settleTicket / processDeleteAccount)使用。
*/
private void sync(Runnable r) {
if (Bukkit.isPrimaryThread()) r.run();
else Bukkit.getScheduler().runTask(plugin, r);
}
private void settleTicket(int tid) {
Map<String, Object> t =
plugin.getDb().getTicket(tid);
if (t == null) return;
final String requester =
String requester =
sv(t, "requester");
final String assigned =
String assigned =
sv(t, "assigned_to");
int reward = nv(t, "reward_amount");
int score = nv(t, "score");
ConfigManager cfg =
plugin.getConfig2();
// ★ 提交者获得工单奖励(债券)
if (reward > 0) {
plugin.getBonds().addBonds(
requester, reward,
BondManager.TX_TICKET_REWARD, "",
"System", "工单 #" + tid + " 奖励");
sync(() -> {
Player rp = Bukkit.getPlayer(
requester);
if (rp != null && rp.isOnline()) {
rp.sendMessage(
"§e§l[工单] §f获得 "
+ reward
+ " 债券奖励");
}
});
}
// ★ 服务商获得债券奖励
if (!assigned.isEmpty()) {
int bondReward = (int) (score
* cfg.providerPointsPerScore);
if (bondReward > 0) {
plugin.getBonds().addBonds(
assigned, bondReward,
BondManager.TX_TICKET_SERVICE, "",
"System", "工单 #" + tid
+ " 服务奖励(评分"
+ score + ")");
plugin.getDb().addPoints(
requester, reward);
Player rp = Bukkit.getPlayer(
requester);
if (rp != null && rp.isOnline()) {
rp.sendMessage(
"§e§l[工单] §f获得 "
+ reward
+ " 积分奖励");
}
final int br = bondReward;
sync(() -> {
Player pp =
Bukkit.getPlayer(assigned);
if (pp != null && pp.isOnline()) {
pp.sendMessage(
"§a§l[工单] §f工单 #"
+ tid
+ " 确认完结");
if (br > 0)
pp.sendMessage("§7债券: §e"
+ br + " 枚");
}
if (!assigned.isEmpty()) {
int pts = (int) (score
* cfg.providerPointsPerScore);
if (pts > 0) {
plugin.getDb().addPoints(
assigned, pts);
}
double money =
cfg.baseEconomyReward
+ score
* cfg.providerEconomyPerScore;
boolean ok = false;
try {
if (plugin.getEconomy() != null) {
OfflinePlayer op =
Bukkit.getOfflinePlayer(
assigned);
plugin.getEconomy()
.depositPlayer(
op, money);
ok = true;
}
});
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] 经济失败: "
+ e.getMessage());
}
Player pp =
Bukkit.getPlayer(assigned);
if (pp != null && pp.isOnline()) {
pp.sendMessage(
"§a§l[工单] §f工单 #"
+ tid
+ " 确认完结");
if (pts > 0)
pp.sendMessage("§7积分: §e"
+ pts);
if (ok)
pp.sendMessage("§7经济: §a$"
+ String.format(
"%.0f", money));
}
}
}
@@ -1428,46 +1404,36 @@ public class TicketManager {
*/
public void processDeleteAccount(int tid,
Map<String, Object> t) {
final String requester = sv(t, "requester");
String requester = sv(t, "requester");
plugin.getDb().updateTicketStatus(
tid, "resolved");
plugin.getDb().updateTicketField(tid,
"admin_confirmed", 1);
// ★ 备份背包 / 发消息 / 踢人 必须主线程
sync(() -> {
Player target =
Bukkit.getPlayerExact(requester);
if (target != null && target.isOnline()) {
plugin.backupInventory(target);
target.sendMessage(
"§a§l[工单] §f您的删号请求已通过");
target.sendMessage(
"§7物品已备份,下次登录可取回");
target.kickPlayer(
"§a删号成功,物品已备份。\n"
+ "请等待5分钟后重新注册取回物品。");
} else {
// 离线:仅标记,不操作数据库
plugin.getLogger().info(
"[Sdf1_login] " + requester
+ " 删号工单已通过,等待上线执行");
}
});
// 延迟执行删号(DB 写 -> 异步,不占主线程)
Player target =
Bukkit.getPlayer(requester);
if (target != null && target.isOnline()) {
plugin.backupInventory(target);
target.sendMessage(
"§a§l[工单] §f您的删号请求已通过");
target.sendMessage(
"§7物品已备份,下次登录可取回");
target.kickPlayer(
"§a删号成功,物品已备份。\n"
+ "请等待5分钟后重新注册取回物品。");
} else {
// 离线:仅标记,不操作数据库
plugin.getLogger().info(
"[Sdf1_login] " + requester
+ " 删号工单已通过,等待上线执行");
}
// 延迟执行删号
final String name = requester;
Bukkit.getScheduler().runTaskLaterAsynchronously(
Bukkit.getScheduler().runTaskLater(
plugin, () -> {
int deleted =
plugin.getDb().deleteUser(name);
if (deleted > 0) {
plugin.getLogger().info(
"[Sdf1_login] " + name
+ " 删号工单已执行");
} else {
plugin.getLogger().warning(
"[Sdf1_login] " + name
+ " 删号工单未执行(精准匹配下账号不存在,未误删)");
}
plugin.getDb().deleteUser(name);
plugin.getLogger().info(
"[Sdf1_login] " + name
+ " 删号工单已执行");
}, 100L);
}
@@ -1593,7 +1559,7 @@ public class TicketManager {
lore.add("§7提交者: §f"
+ requester);
lore.add("§7奖励: §e" + reward
+ " 债券");
+ " 积分");
lore.add("");
lore.add("§7点击查看详情");
im.setLore(lore);
@@ -1,186 +0,0 @@
package Sdf1_login;
import java.io.File;
import java.sql.*;
/**
* 交易记录数据库(2026-10-11 新增)。
*
* <p>独立 db(交易记录/shop_trades.db),专门存放三类数据:
* <ul>
* <li>{@code normal_shop_orders} —— 正常商店的交易订单(直购 + 购物车结账)</li>
* <li>{@code secondhand_orders} —— 二手商店的交易订单(含手续费与实际到手)</li>
* <li>{@code player_selling_prefs}—— 玩家的出售偏好(奸商模式=买方出 / 正常模式=卖方出)</li>
* </ul>
*
* <p>铁律:db 文件创建即指向子目录,绝不人工移动/改名(WAL 三件套同进同退)。
*/
public class TradeLogManager {
private final Main plugin;
private Connection db;
private boolean ready = false;
public TradeLogManager(Main plugin) {
this.plugin = plugin;
init();
}
private synchronized void init() {
try {
Class.forName("org.sqlite.JDBC");
// ★ 创建即归位到子目录(2026-10-11 db 铁律:路径直接指向目标目录)
File dir = new File(plugin.getDataFolder(), "交易记录");
dir.mkdirs();
File dbFile = new File(dir, "shop_trades.db");
db = DriverManager.getConnection(
"jdbc:sqlite:" + dbFile.getAbsolutePath());
try (Statement st = db.createStatement()) {
st.execute("PRAGMA journal_mode=WAL");
st.execute("CREATE TABLE IF NOT EXISTS normal_shop_orders ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "buyer TEXT NOT NULL,"
+ "item_name TEXT NOT NULL,"
+ "amount INTEGER NOT NULL,"
+ "unit_price INTEGER NOT NULL,"
+ "total_bonds INTEGER NOT NULL,"
+ "discount_pct INTEGER DEFAULT 0,"
+ "source TEXT DEFAULT 'direct',"
+ "created_at INTEGER NOT NULL)");
st.execute("CREATE TABLE IF NOT EXISTS secondhand_orders ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "listing_id INTEGER NOT NULL,"
+ "buyer TEXT NOT NULL,"
+ "seller TEXT NOT NULL,"
+ "item_name TEXT NOT NULL,"
+ "amount INTEGER NOT NULL,"
+ "price INTEGER NOT NULL,"
+ "fee INTEGER DEFAULT 0,"
+ "fee_mode TEXT DEFAULT 'SELLER',"
+ "buyer_paid INTEGER NOT NULL,"
+ "seller_received INTEGER NOT NULL,"
+ "created_at INTEGER NOT NULL)");
st.execute("CREATE TABLE IF NOT EXISTS player_selling_prefs ("
+ "player_name TEXT PRIMARY KEY,"
+ "fee_mode TEXT NOT NULL,"
+ "updated_at INTEGER NOT NULL)");
}
ready = true;
plugin.getLogger().info("[交易记录] shop_trades.db 初始化完成: "
+ dbFile.getAbsolutePath());
} catch (Exception e) {
ready = false;
plugin.getLogger().warning("[交易记录] 初始化失败: " + e.getMessage());
}
}
// ==================== 正常商店订单 ====================
/**
* 记录一笔正常商店交易订单。
*
* @param source direct=直购 / cart=购物车结账
*/
public void recordNormalOrder(String buyer, String itemName, int amount,
int unitPrice, int totalBonds,
int discountPct, String source) {
if (!ready) return;
try (PreparedStatement ps = db.prepareStatement(
"INSERT INTO normal_shop_orders "
+ "(buyer, item_name, amount, unit_price, total_bonds, "
+ "discount_pct, source, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
ps.setString(1, nvl(buyer));
ps.setString(2, nvl(itemName));
ps.setInt(3, amount);
ps.setInt(4, unitPrice);
ps.setInt(5, totalBonds);
ps.setInt(6, discountPct);
ps.setString(7, nvl(source));
ps.setLong(8, System.currentTimeMillis());
ps.executeUpdate();
} catch (Exception e) {
plugin.getLogger().warning("[交易记录] 正常订单写入失败: " + e.getMessage());
}
}
// ==================== 二手商店订单 ====================
/**
* 记录一笔二手交易订单(含手续费与双方实际金额)。
*
* @param feeMode BUYER=奸商模式(买方承担手续费)/ SELLER=正常模式(卖方承担)
*/
public void recordSecondHandOrder(long listingId, String buyer, String seller,
String itemName, int amount, int price,
int fee, String feeMode,
int buyerPaid, int sellerReceived) {
if (!ready) return;
try (PreparedStatement ps = db.prepareStatement(
"INSERT INTO secondhand_orders "
+ "(listing_id, buyer, seller, item_name, amount, price, "
+ "fee, fee_mode, buyer_paid, seller_received, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
ps.setLong(1, listingId);
ps.setString(2, nvl(buyer));
ps.setString(3, nvl(seller));
ps.setString(4, nvl(itemName));
ps.setInt(5, amount);
ps.setInt(6, price);
ps.setInt(7, fee);
ps.setString(8, nvl(feeMode));
ps.setInt(9, buyerPaid);
ps.setInt(10, sellerReceived);
ps.setLong(11, System.currentTimeMillis());
ps.executeUpdate();
} catch (Exception e) {
plugin.getLogger().warning("[交易记录] 二手订单写入失败: " + e.getMessage());
}
}
// ==================== 玩家出售偏好 ====================
/** 取玩家出售偏好;无记录返回 null(由调用方回退全局配置)。 */
public String getSellingPref(String player) {
if (!ready || player == null) return null;
try (PreparedStatement ps = db.prepareStatement(
"SELECT fee_mode FROM player_selling_prefs WHERE player_name = ?")) {
ps.setString(1, player);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) return rs.getString(1);
}
} catch (Exception e) {
plugin.getLogger().warning("[交易记录] 读取偏好失败: " + e.getMessage());
}
return null;
}
/** 写入/覆盖玩家出售偏好(BUYER=奸商模式 / SELLER=正常模式)。 */
public void setSellingPref(String player, String feeMode) {
if (!ready || player == null || feeMode == null) return;
try (PreparedStatement ps = db.prepareStatement(
"INSERT OR REPLACE INTO player_selling_prefs "
+ "(player_name, fee_mode, updated_at) VALUES (?, ?, ?)")) {
ps.setString(1, player);
ps.setString(2, feeMode);
ps.setLong(3, System.currentTimeMillis());
ps.executeUpdate();
} catch (Exception e) {
plugin.getLogger().warning("[交易记录] 写入偏好失败: " + e.getMessage());
}
}
private static String nvl(String s) {
return s == null ? "" : s;
}
public synchronized void close() {
try {
if (db != null) db.close();
} catch (Exception ignored) {
}
}
}
@@ -1,116 +0,0 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Sdf1_game寻宝系统桥接类
* 用于Sdf1_login调用Sdf1_game的clearPlayerAllClaims方法
*/
public class TreasureBridge {
private Object treasureManager;
private Method clearPlayerAllClaimsMethod;
private boolean hooked = false;
/**
* 桥接Sdf1_game插件
* @return 是否桥接成功
*/
public boolean hook() {
Plugin sdf1_game = Bukkit.getPluginManager()
.getPlugin("Sdf1_game");
if (sdf1_game == null || !sdf1_game.isEnabled()) {
return false;
}
try {
// 获取Sdf1_game的Main实例
Object mainInstance = sdf1_game;
// 获取TreasureManager实例
treasureManager = findTreasureManager(mainInstance);
if (treasureManager == null) {
return false;
}
// 获取clearPlayerAllClaims方法
clearPlayerAllClaimsMethod = treasureManager.getClass()
.getMethod("clearPlayerAllClaims", String.class);
hooked = true;
return true;
} catch (Exception e) {
return false;
}
}
/**
* 清空指定玩家的所有领取记录
* @param playerName 玩家名
* @return 清除的记录数量,失败返回-1
*/
public int clearPlayerAllClaims(String playerName) {
if (!isHooked()) return -1;
try {
int result = (int) clearPlayerAllClaimsMethod.invoke(
treasureManager, playerName);
return result;
} catch (Exception e) {
return -1;
}
}
/**
* 查找TreasureManager实例
* @param mainInstance Sdf1_game的Main实例
* @return TreasureManager实例
*/
private Object findTreasureManager(Object mainInstance) {
Class<?> c = mainInstance.getClass();
// 策略1: getTreasureManager() 方法
try {
Method m = c.getMethod("getTreasureManager");
Object r = m.invoke(mainInstance);
if (r != null) return r;
} catch (Exception ignored) {
}
// 策略2: treasureManager 字段
try {
Field f = c.getDeclaredField("treasureManager");
f.setAccessible(true);
Object r = f.get(mainInstance);
if (r != null) return r;
} catch (Exception ignored) {
}
// 策略3: 遍历字段按类型名查找
try {
for (Field f : c.getDeclaredFields()) {
if (f.getType().getSimpleName()
.equals("TreasureManager")) {
f.setAccessible(true);
Object r = f.get(mainInstance);
if (r != null) return r;
}
}
} catch (Exception ignored) {
}
return null;
}
/**
* 是否已桥接
* @return 桥接状态
*/
public boolean isHooked() {
return hooked;
}
}
File diff suppressed because it is too large Load Diff
-240
View File
@@ -1,240 +0,0 @@
package Sdf1_login;
/**
* Unicode 特殊字符常量表。
*
* <p>背景:项目里原先大量使用 Unicode 转义字面量(写成 U+XXXX 形式),
* 读代码的人必须逐个心算码位才能看懂(例如 U+00A7 其实是 MC 颜色码 §)。
* 尤其不可见字符(零宽空格、BOM、全角空格…)直接写成字面量后
* 在编辑器里根本"看不见",反而更难排查。</p>
*
* <p>因此本类把两类字符分开处理:</p>
* <ul>
* <li><b>可见字符</b>(§、:、全角数字、汉字等)→ 直接在业务代码里写字面量,
* 一眼可读;</li>
* <li><b>不可见字符</b>(零宽空格、BOM、全角空格、U+0001 分隔符等)→
* 统一引用本类的具名常量,既可读又不会因"看不见"而误判。</li>
* </ul>
*
* <p>注意:正则表达式字符串里的 Unicode 转义属于<b>正则层</b>转义
* (Java 字符串里存的是字面反斜杠+u,由正则引擎在运行期解释),
* 改写会改变正则语义。本项目已把正则层里<b>可见</b>的转义全部改写成
* 真实字符或本类的具名常量;<b>不可见</b>的转义则通过本类常量参与拼接。</p>
*/
public final class UnicodeChars {
private UnicodeChars() {
}
// ==================== 不可见字符(必须用具名常量) ====================
/** U+0001 SOH —— SnManager 与 PHP 命令执行结果之间的分隔符 */
public static final char SEPARATOR = '\u0001';
/** U+00A0 不间断空格(NO-BREAK SPACE) */
public static final char NBSP = '\u00A0';
/** U+00AD 软连字符(SOFT HYPHEN) */
public static final char SOFT_HYPHEN = '\u00AD';
/** U+2000 EN QUAD —— Unicode 各种空格区起点 */
public static final char SPACE_U2000 = '\u2000';
/** U+200A HAIR SPACE —— Unicode 各种空格区终点 */
public static final char SPACE_U200A = '\u200A';
/** U+200B 零宽空格(ZERO WIDTH SPACE) */
public static final char ZERO_WIDTH_SPACE = '\u200B';
/** U+200C 零宽非连接符(ZERO WIDTH NON-JOINER) */
public static final char ZERO_WIDTH_NON_JOINER = '\u200C';
/** U+200D 零宽连接符(ZERO WIDTH JOINER) */
public static final char ZERO_WIDTH_JOINER = '\u200D';
/** U+200E 从左至右标记(LTR MARK) */
public static final char LTR_MARK = '\u200E';
/** U+200F 从右至左标记(RTL MARK) */
public static final char RTL_MARK = '\u200F';
/** U+2028 行分隔符(LINE SEPARATOR) */
public static final char LINE_SEPARATOR = '\u2028';
/** U+2029 段分隔符(PARAGRAPH SEPARATOR) */
public static final char PARAGRAPH_SEPARATOR = '\u2029';
/** U+2060 字连接符(WORD JOINER) */
public static final char WORD_JOINER = '\u2060';
/** U+3000 表意空格(IDEOGRAPHIC SPACE,即"全角空格") */
public static final char IDEOGRAPHIC_SPACE = '\u3000';
/** U+FEFF 零宽不换行空格 / BOM(ZERO WIDTH NO-BREAK SPACE) */
public static final char BOM = '\uFEFF';
// ==================== 区间常量(不可见/边界判定用) ====================
/** CJK 基本汉字区起点 U+4E00(一) */
public static final char CJK_START = '一';
/** CJK 基本汉字区终点 U+9FFF */
public static final char CJK_END = '鿿';
/** CJK 兼容汉字常用终点 U+9FA5(龥) */
public static final char CJK_COMPAT_END = '龥';
/** CJK 扩展 A 区起点 U+3400(㐀) */
public static final char CJK_EXT_A_START = '㐀';
/** CJK 扩展 A 区终点 U+4DBF(䶿) */
public static final char CJK_EXT_A_END = '䶿';
/** 全角 ASCII 起点 U+FF01(!) */
public static final char FULLWIDTH_START = '!';
/** 全角 ASCII 终点 U+FF5E(~) */
public static final char FULLWIDTH_END = '~';
/** 全角数字 0 U+FF10 */
public static final char FULLWIDTH_ZERO = '0';
/** 全角数字 9 U+FF19 */
public static final char FULLWIDTH_NINE = '9';
/** 全角大写 A U+FF21 */
public static final char FULLWIDTH_A_UPPER = 'A';
/** 全角大写 Z U+FF3A */
public static final char FULLWIDTH_Z_UPPER = 'Z';
/** 全角小写 a U+FF41 */
public static final char FULLWIDTH_A_LOWER = 'a';
/** 全角小写 z U+FF5A */
public static final char FULLWIDTH_Z_LOWER = 'z';
/** 全角左括号 U+FF08 */
public static final char FULLWIDTH_LPAREN = '(';
/** 全角右括号 U+FF09 */
public static final char FULLWIDTH_RPAREN = ')';
/** 全角井号 U+FF03 */
public static final char FULLWIDTH_HASH = '#';
/** 全角逗号 U+FF0C */
public static final char FULLWIDTH_COMMA = ',';
/** 全角分号 U+FF1B */
public static final char FULLWIDTH_SEMICOLON = ';';
/** 全角冒号 U+FF1A */
public static final char FULLWIDTH_COLON = ':';
/** 全角句点 U+FF0E */
public static final char FULLWIDTH_STOP = '.';
/** 全角波浪号 U+FF5E */
public static final char FULLWIDTH_TILDE = '~';
/** 半角片假名中点 U+FF65 */
public static final char HALFWIDTH_KATAKANA_MIDDLE_DOT = '・';
/** 小型句点 U+FE52 */
public static final char SMALL_FULL_STOP = '﹒';
/** 二点引导符 U+2025 */
public static final char TWO_DOT_LEADER = '‥';
/** 水平省略号 U+2026 */
public static final char HORIZONTAL_ELLIPSIS = '…';
/** 中点 U+00B7 */
public static final char MIDDLE_DOT = '·';
/** 项目符号 U+2022 */
public static final char BULLET = '•';
/** 表意句点 U+3002 */
public static final char IDEOGRAPHIC_STOP = '。';
/** 表意逗号 U+3001 */
public static final char IDEOGRAPHIC_COMMA = '、';
/** 表意数字零 U+3007(〇) */
public static final char IDEOGRAPHIC_ZERO = '〇';
/** 左黑 lenticular 方括号 U+3010(【) */
public static final char LEFT_BLACK_LENTICULAR = '【';
/** 右黑 lenticular 方括号 U+3011(】) */
public static final char RIGHT_BLACK_LENTICULAR = '】';
/** 左 tortoise shell 括号 U+3014(〔) */
public static final char LEFT_TORTOISE_SHELL = '〔';
/** 右 tortoise shell 括号 U+3015(〕) */
public static final char RIGHT_TORTOISE_SHELL = '〕';
/** 左直角引号 U+300C(「) */
public static final char LEFT_CORNER_BRACKET = '「';
/** 右直角引号 U+300D」(」) */
public static final char RIGHT_CORNER_BRACKET = '」';
/** 左白直角引号 U+300E(『) */
public static final char LEFT_WHITE_CORNER_BRACKET = '『';
/** 右白直角引号 U+300F(』) */
public static final char RIGHT_WHITE_CORNER_BRACKET = '』';
// ==================== 常用字符串常量 ====================
/** MC 颜色码前缀 § */
public static final String COLOR_SIGN = "§";
/** 全角冒号 ":" */
public static final String WIDE_COLON = ":";
// ==================== 字符串版(用于拼接场景) ====================
// 注意:char 常量参与字符串拼接时若两侧都是 char 会被当成数值加法,
// 因此需要拼接的不可见字符一律用这里的 String 版常量。
/** U+FEFF BOM 的字符串版 */
public static final String BOM_TEXT = "\uFEFF";
/** U+0001 分隔符的字符串版 */
public static final String SEPARATOR_TEXT = "\u0001";
/** U+3000 全角空格的字符串版 */
public static final String IDEOGRAPHIC_SPACE_TEXT = "\u3000";
/**
* 零宽/不可见字符集合(聊天变形 URL 归一前剔除用)。
* 含:零宽空格、零宽非连接、零宽连接、字连接符、BOM、软连字符。
*/
public static final String INVISIBLE_CHARS = "\u200B\u200C\u200D\u2060\uFEFF\u00AD";
/** U+200B 零宽空格的字符串版 */
public static final String ZERO_WIDTH_SPACE_TEXT = "\u200B";
/** U+200D 零宽连接符的字符串版 */
public static final String ZERO_WIDTH_JOINER_TEXT = "\u200D";
/** U+2060 字连接符的字符串版 */
public static final String WORD_JOINER_TEXT = "\u2060";
/** U+00A0 不间断空格的字符串版 */
public static final String NBSP_TEXT = "\u00A0";
/**
* 需要剔除的不可见字符(正则字符类形式,净化玩家输入用)。
* 含:零宽空格~零宽连接(区间)、字连接符、BOM、不间断空格、全角空格。
* <p>这里用具名常量拼接,而不是转义写法——这样源码里能直接看出
* 每个字符的用途,读代码的人不必去心算码位。</p>
*/
public static final String INVISIBLE_STRIP_CLASS =
"[" + ZERO_WIDTH_SPACE_TEXT + "-" + ZERO_WIDTH_JOINER_TEXT
+ WORD_JOINER_TEXT + BOM_TEXT + NBSP_TEXT + IDEOGRAPHIC_SPACE_TEXT + "]";
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+158 -102
View File
@@ -1,102 +1,158 @@
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.function.Consumer;
/**
* 玩家正版/离线身份验证管理器
*
* 核心逻辑:在离线模式(online-mode=false)服务器中,所有玩家UUID都是离线格式,
* 无法通过UUID区分正版/盗版。因此:
* - UUID非离线格式 → 服务器在线模式,正版玩家 → autoLogin
* - UUID离线格式 → 一律视为非正版,需手动登录或OAuth验证
* - 正版玩家通过 /mslogin OAuth验证后,由Main.addVerifiedPremiumPlayer()标记,
* 在onJoin检查点0直接autoLogin,不经过此验证器
*/
public class VerificationManager {
private final Main plugin;
public VerificationManager(Main plugin) {
this.plugin = plugin;
}
public boolean isBedrockPlayer(Player p) {
String uuid = p.getUniqueId().toString();
return uuid.contains("f851ba4")
|| uuid.startsWith("00000000-0000-0000");
}
public boolean isOnlineMode() {
return Bukkit.getServer().getOnlineMode();
}
/**
* 异步验证玩家身份
* 注意:此方法仅用于判断UUID格式,不执行自动登录
* 自动登录由onJoin中的检查点0/1/2控制
*/
public void verifyPremiumAsync(Player player,
Consumer<Boolean> callback) {
Thread t = new Thread(() -> doVerify(player, callback),
"Sdf1_login-PremiumVerify");
t.setDaemon(true);
t.start();
}
private void doVerify(Player player,
Consumer<Boolean> callback) {
String name = player.getName();
String uuid = player.getUniqueId().toString();
plugin.getLogger().info(
"[Sdf1_login] ====== 验证开始 ======");
plugin.getLogger().info(
"[Sdf1_login] 玩家: " + name);
plugin.getLogger().info(
"[Sdf1_login] 当前UUID: " + uuid);
try {
java.util.UUID offlineUuid = java.util.UUID.nameUUIDFromBytes(
("OfflinePlayer:" + name)
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
boolean isOfflineUuid =
player.getUniqueId().equals(offlineUuid);
plugin.getLogger().info(
"[Sdf1_login] 离线UUID: " + offlineUuid);
plugin.getLogger().info(
"[Sdf1_login] UUID匹配离线格式: "
+ isOfflineUuid);
if (!isOfflineUuid) {
// UUID不是离线格式 → 服务器在线模式的正版玩家
plugin.getLogger().info(
"[Sdf1_login] 结论: 正版玩家(非离线UUID)");
plugin.getLogger().info(
"[Sdf1_login] ====== 验证结束 ======");
callback.accept(true);
return;
}
// ★ 离线UUID → 无法通过UUID区分正版/盗版,一律视为非正版
// 正版玩家需通过 /mslogin OAuth验证 或 /login 手动登录
plugin.getLogger().info(
"[Sdf1_login] 结论: 离线UUID玩家,需手动登录");
plugin.getLogger().info(
"[Sdf1_login] (正版玩家请使用 /mslogin 或 /正版 命令验证)");
plugin.getLogger().info(
"[Sdf1_login] ====== 验证结束 ======");
callback.accept(false);
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] 验证异常: "
+ e.getMessage());
callback.accept(false);
}
}
}
package Sdf1_login;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.function.Consumer;
public class VerificationManager {
private final Main plugin;
public VerificationManager(Main plugin) {
this.plugin = plugin;
}
public boolean isBedrockPlayer(Player p) {
String uuid = p.getUniqueId().toString();
return uuid.contains("f851ba4")
|| uuid.startsWith("00000000-0000-0000");
}
public boolean isOnlineMode() {
return Bukkit.getServer().getOnlineMode();
}
public void verifyPremiumAsync(Player player,
Consumer<Boolean> callback) {
Thread t = new Thread(() -> doVerify(player, callback),
"Sdf1_login-PremiumVerify");
t.setDaemon(true);
t.start();
}
private void doVerify(Player player,
Consumer<Boolean> callback) {
String name = player.getName();
String uuid = player.getUniqueId().toString();
plugin.getLogger().info(
"[Sdf1_login] ====== 验证开始 ======");
plugin.getLogger().info(
"[Sdf1_login] 玩家: " + name);
plugin.getLogger().info(
"[Sdf1_login] 当前UUID: " + uuid);
try {
UUID offlineUuid = UUID.nameUUIDFromBytes(
("OfflinePlayer:" + name)
.getBytes(StandardCharsets.UTF_8));
String offlineStr = offlineUuid.toString();
plugin.getLogger().info(
"[Sdf1_login] 离线UUID: " + offlineStr);
boolean isOfflineUuid =
player.getUniqueId().equals(offlineUuid);
plugin.getLogger().info(
"[Sdf1_login] UUID匹配离线格式: "
+ isOfflineUuid);
if (!isOfflineUuid) {
plugin.getLogger().info(
"[Sdf1_login] 结论: 正版玩家");
plugin.getLogger().info(
"[Sdf1_login] ====== 验证结束 ======");
callback.accept(true);
return;
}
plugin.getLogger().info(
"[Sdf1_login] UUID为离线格式,"
+ "查询Mojang API...");
UUID mojangUuid = fetchMojangUuid(name);
if (mojangUuid != null) {
plugin.getLogger().info(
"[Sdf1_login] Mojang返回UUID: "
+ mojangUuid);
plugin.getLogger().info(
"[Sdf1_login] 结论: 盗版客户端"
+ "使用了正版名字");
} else {
plugin.getLogger().info(
"[Sdf1_login] Mojang无此名字");
plugin.getLogger().info(
"[Sdf1_login] 结论: 纯离线玩家");
}
plugin.getLogger().info(
"[Sdf1_login] ====== 验证结束 ======");
callback.accept(false);
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] 验证异常: "
+ e.getMessage());
callback.accept(false);
}
}
private UUID fetchMojangUuid(String name) {
HttpURLConnection conn = null;
try {
URL url = new URL(
"https://api.mojang.com/users/profiles/minecraft/"
+ name);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
plugin.getLogger().info(
"[Sdf1_login] Mojang API响应: " + code);
if (code == 200) {
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
conn.getInputStream(),
StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String json = sb.toString();
String uuidStr = json.replaceAll(
".*\"id\"\\s*:\\s*\"([^\"]+)\".*",
"$1");
plugin.getLogger().info(
"[Sdf1_login] Mojang原始UUID: "
+ uuidStr);
String formatted = uuidStr.replaceFirst(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5");
return UUID.fromString(formatted);
}
} catch (Exception e) {
plugin.getLogger().warning(
"[Sdf1_login] Mojang查询异常: "
+ e.getMessage());
} finally {
if (conn != null) conn.disconnect();
}
return null;
}
}
File diff suppressed because it is too large Load Diff

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