Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
254700cb79 |
@@ -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 ==="
|
||||
|
||||
@@ -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
-84
@@ -39,91 +39,8 @@ 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
|
||||
Generated
+3
-1
@@ -8,5 +8,7 @@
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="26" project-jdk-type="JavaSDK" />
|
||||
<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
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -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/>.
|
||||
@@ -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,19 @@
|
||||
</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 +55,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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -95,24 +95,11 @@ public class AccountRequestManager {
|
||||
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";
|
||||
plugin.getDb().deleteUser(req.target);
|
||||
pendingByPlayer.remove(req.requester);
|
||||
// 清背包+传送出生点+踢出(★ getPlayerExact:避免误伤大小写不同的在线玩家)
|
||||
Player target = Bukkit.getPlayerExact(req.target);
|
||||
// 清背包+传送出生点+踢出
|
||||
Player target = Bukkit.getPlayer(req.target);
|
||||
if (target != null && target.isOnline()) {
|
||||
target.getInventory().clear();
|
||||
target.getInventory().setArmorContents(new org.bukkit.inventory.ItemStack[4]);
|
||||
|
||||
@@ -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
+3775
-14377
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);
|
||||
}
|
||||
}
|
||||
@@ -11,26 +11,6 @@ public class BondManager {
|
||||
private final Main plugin;
|
||||
private Connection db;
|
||||
|
||||
// ===== 交易监听器 =====
|
||||
public interface TransactionListener {
|
||||
void onTransaction(String playerName, String type, int amount, String targetPlayer);
|
||||
}
|
||||
private final List<TransactionListener> transactionListeners = new ArrayList<>();
|
||||
|
||||
public void addTransactionListener(TransactionListener listener) {
|
||||
transactionListeners.add(listener);
|
||||
}
|
||||
|
||||
private void fireTransactionEvent(String playerName, String type, int amount, String targetPlayer) {
|
||||
for (TransactionListener listener : transactionListeners) {
|
||||
try {
|
||||
listener.onTransaction(playerName, type, amount, targetPlayer);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 交易类型常量 =====
|
||||
public static final String TX_ADMIN_GIVE = "admin_give";
|
||||
public static final String TX_ADMIN_DEDUCT = "admin_deduct";
|
||||
@@ -41,8 +21,6 @@ public class BondManager {
|
||||
public static final String TX_DAILY_SIGN = "daily_sign";
|
||||
public static final String TX_FREEZE = "freeze";
|
||||
public static final String TX_UNFREEZE = "unfreeze";
|
||||
public static final String TX_TICKET_REWARD = "ticket_reward";
|
||||
public static final String TX_TICKET_SERVICE = "ticket_service";
|
||||
|
||||
|
||||
public static final int MAX_WATER_DAYS = 14;
|
||||
@@ -53,85 +31,23 @@ public class BondManager {
|
||||
initDB();
|
||||
}
|
||||
|
||||
// ===== 信誉积分债券交易限额(★ 第63批) =====
|
||||
|
||||
/** 交易型类型(买卖全算限额),非交易型(管理员/系统)不受限 */
|
||||
private static boolean isTradeType(String type) {
|
||||
return TX_TRANSFER_OUT.equals(type)
|
||||
|| TX_TRANSFER_IN.equals(type)
|
||||
|| TX_SHOP_BUY.equals(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询玩家本小时债券交易累计总额(买入+卖出全算)
|
||||
*/
|
||||
private int getHourlyBondTradeTotal(String player) {
|
||||
try {
|
||||
long oneHourAgo = System.currentTimeMillis() - 3600_000L;
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT COALESCE(SUM(amount), 0) as total FROM bond_transaction "
|
||||
+ "WHERE player_name=? AND time > ?");
|
||||
ps.setString(1, player);
|
||||
ps.setLong(2, oneHourAgo);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
int total = 0;
|
||||
if (rs.next()) total = rs.getInt("total");
|
||||
rs.close(); ps.close();
|
||||
return total;
|
||||
} catch (SQLException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第63批:检查玩家债券交易是否超限
|
||||
* @return true=允许交易,false=超限被拒
|
||||
*/
|
||||
private boolean checkBondTradeLimit(String player, int amount) {
|
||||
// 管理员操作不受限
|
||||
if (plugin.getCreditManager() == null) return true;
|
||||
double limit = plugin.getCreditManager().getBondTradeLimit(player);
|
||||
if (limit <= 0) return true; // 无限制
|
||||
// 获取倍数(>80分 → 1.2倍)
|
||||
double multiplier = plugin.getCreditManager().getBondTradeMultiplier(player);
|
||||
double effectiveLimit = limit * multiplier;
|
||||
int currentTotal = getHourlyBondTradeTotal(player);
|
||||
if (currentTotal + amount > effectiveLimit) {
|
||||
return false; // 超限
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第十批(2026-10-12):暴露 bond.db 连接。
|
||||
* bond_transaction 在 bond.db(财务债券/),不在 login.db——
|
||||
* 跨库查询必须走这里(CommissionManager 日上限/翻倍统计、
|
||||
* InviteManager 存量绑定时间回填均依赖)。
|
||||
*/
|
||||
public Connection getConnection() {
|
||||
return db;
|
||||
}
|
||||
|
||||
// ======================== 数据库初始化 ========================
|
||||
|
||||
private void initDB() {
|
||||
try {
|
||||
Class.forName("org.sqlite.JDBC");
|
||||
File dbFile = new File(
|
||||
new File(plugin.getDataFolder(), "财务债券"),
|
||||
"bond.db");
|
||||
dbFile.getParentFile().mkdirs();
|
||||
plugin.getDataFolder(), "bond.db");
|
||||
db = DriverManager.getConnection(
|
||||
"jdbc:sqlite:" + dbFile.getAbsolutePath());
|
||||
Statement st = db.createStatement();
|
||||
st.execute("PRAGMA journal_mode=WAL");
|
||||
|
||||
// 债券余额(含冻结状态 + 冻结到期时间)
|
||||
// 债券余额(含冻结状态)
|
||||
st.execute("CREATE TABLE IF NOT EXISTS bonds ("
|
||||
+ "player_name TEXT PRIMARY KEY,"
|
||||
+ "amount INTEGER DEFAULT 0,"
|
||||
+ "status TEXT DEFAULT 'normal',"
|
||||
+ "freeze_until INTEGER DEFAULT 0)");
|
||||
+ "status TEXT DEFAULT 'normal')");
|
||||
|
||||
// 兼容旧表
|
||||
try {
|
||||
@@ -139,12 +55,6 @@ public class BondManager {
|
||||
+ "ADD COLUMN status "
|
||||
+ "TEXT DEFAULT 'normal'");
|
||||
} catch (SQLException ignored) {}
|
||||
// ★ 2026-10-04:冻结到期时间(Unix 毫秒,0=永久冻结)
|
||||
try {
|
||||
st.execute("ALTER TABLE bonds "
|
||||
+ "ADD COLUMN freeze_until "
|
||||
+ "INTEGER DEFAULT 0");
|
||||
} catch (SQLException ignored) {}
|
||||
|
||||
// 旧流水(保留兼容)
|
||||
st.execute("CREATE TABLE IF NOT EXISTS bond_log ("
|
||||
@@ -190,111 +100,47 @@ public class BondManager {
|
||||
|
||||
// ======================== 账户状态 ========================
|
||||
|
||||
/**
|
||||
* 账户是否处于冻结状态。
|
||||
*
|
||||
* <p>★ 2026-10-04 支持临时冻结:status='frozen' 且
|
||||
* {@code freeze_until>0} 时,到期自动解冻并回写 status='normal';
|
||||
* {@code freeze_until=0} 表示永久冻结。
|
||||
*/
|
||||
public boolean isFrozen(String player) {
|
||||
boolean frozen = false;
|
||||
long until = 0L;
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT status, freeze_until FROM bonds "
|
||||
"SELECT status FROM bonds "
|
||||
+ "WHERE player_name=?");
|
||||
ps.setString(1, player);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
frozen = "frozen".equals(rs.getString("status"));
|
||||
until = rs.getLong("freeze_until");
|
||||
String s = rs.getString("status");
|
||||
rs.close(); ps.close();
|
||||
return "frozen".equals(s);
|
||||
}
|
||||
rs.close(); ps.close();
|
||||
} catch (SQLException ignored) {
|
||||
return false;
|
||||
}
|
||||
if (!frozen) return false;
|
||||
if (until > 0L && until <= System.currentTimeMillis()) {
|
||||
unfreezeAccount(player); // 临时冻结到期 -> 自动解冻
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 冻结到期时间(Unix 毫秒);0=永久冻结;-1=未冻结 */
|
||||
public long getFreezeUntil(String player) {
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT status, freeze_until FROM bonds "
|
||||
+ "WHERE player_name=?");
|
||||
ps.setString(1, player);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
long until = -1L;
|
||||
if (rs.next()) {
|
||||
if (!"frozen".equals(rs.getString("status"))) {
|
||||
rs.close(); ps.close();
|
||||
return -1L;
|
||||
}
|
||||
until = rs.getLong("freeze_until");
|
||||
}
|
||||
rs.close(); ps.close();
|
||||
if (until > 0L && until <= System.currentTimeMillis()) {
|
||||
unfreezeAccount(player);
|
||||
return -1L;
|
||||
}
|
||||
return until;
|
||||
} catch (SQLException ignored) {
|
||||
return -1L;
|
||||
}
|
||||
} catch (SQLException ignored) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getAccountStatus(String player) {
|
||||
String s = "normal";
|
||||
long until = 0L;
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT status, freeze_until FROM bonds "
|
||||
"SELECT status FROM bonds "
|
||||
+ "WHERE player_name=?");
|
||||
ps.setString(1, player);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
s = rs.getString("status");
|
||||
until = rs.getLong("freeze_until");
|
||||
if (s == null) s = "normal";
|
||||
String s = rs.getString("status");
|
||||
rs.close(); ps.close();
|
||||
return s != null ? s : "normal";
|
||||
}
|
||||
rs.close(); ps.close();
|
||||
} catch (SQLException ignored) {
|
||||
return "normal";
|
||||
}
|
||||
if ("frozen".equals(s)
|
||||
&& until > 0L
|
||||
&& until <= System.currentTimeMillis()) {
|
||||
unfreezeAccount(player); // 到期自动解冻
|
||||
return "normal";
|
||||
}
|
||||
return s;
|
||||
} catch (SQLException ignored) {}
|
||||
return "normal";
|
||||
}
|
||||
|
||||
/** 永久冻结 */
|
||||
public void freezeAccount(String player) {
|
||||
freezeAccount(player, 0L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 冻结账户(★ 2026-10-04 支持到期时间)。
|
||||
*
|
||||
* @param expireMs Unix 毫秒到期时间;{@code <=0} 表示永久冻结
|
||||
*/
|
||||
public void freezeAccount(String player, long expireMs) {
|
||||
ensureAccount(player);
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"UPDATE bonds SET status='frozen', "
|
||||
+ "freeze_until=? "
|
||||
"UPDATE bonds SET status='frozen' "
|
||||
+ "WHERE player_name=?");
|
||||
ps.setLong(1, expireMs > 0L ? expireMs : 0L);
|
||||
ps.setString(2, player);
|
||||
ps.setString(1, player);
|
||||
ps.executeUpdate(); ps.close();
|
||||
} catch (SQLException e) { e.printStackTrace(); }
|
||||
}
|
||||
@@ -303,8 +149,7 @@ public class BondManager {
|
||||
ensureAccount(player);
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"UPDATE bonds SET status='normal', "
|
||||
+ "freeze_until=0 "
|
||||
"UPDATE bonds SET status='normal' "
|
||||
+ "WHERE player_name=?");
|
||||
ps.setString(1, player);
|
||||
ps.executeUpdate(); ps.close();
|
||||
@@ -369,14 +214,6 @@ public class BondManager {
|
||||
String operator,
|
||||
String reason) {
|
||||
if (isFrozen(player)) return -1;
|
||||
// ★ 第63批:交易型操作检查债券限额
|
||||
if (isTradeType(type) && !checkBondTradeLimit(player, Math.abs(amount))) {
|
||||
Player p = org.bukkit.Bukkit.getPlayerExact(player);
|
||||
if (p != null) {
|
||||
p.sendMessage("§c§l[信誉积分] §c债券交易超限,本小时交易额已达上限");
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
return addBondsInternal(player, amount,
|
||||
type, targetPlayer, operator, reason);
|
||||
}
|
||||
@@ -438,8 +275,7 @@ public class BondManager {
|
||||
logTransaction(player, type, amount,
|
||||
targetPlayer, operator, reason,
|
||||
before, after);
|
||||
// 记录扣除流水,use positive amount, UI uses type to determine sign
|
||||
logLegacy(player, amount);
|
||||
logLegacy(player, -amount);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -522,8 +358,6 @@ public class BondManager {
|
||||
ps.setLong(9, System.currentTimeMillis());
|
||||
ps.executeUpdate();
|
||||
ps.close();
|
||||
// 触发交易监听器
|
||||
fireTransactionEvent(player, type, amount, targetPlayer);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -532,46 +366,13 @@ public class BondManager {
|
||||
|
||||
// ======================== 扣除债券 ========================
|
||||
|
||||
/** 完整版:含冻结检查 + 信誉积分限额 + 流水记录 */
|
||||
/** 完整版:含冻结检查 + 流水记录 */
|
||||
public boolean deductBonds(String player, int amount,
|
||||
String type,
|
||||
String targetPlayer,
|
||||
String operator,
|
||||
String reason) {
|
||||
if (isFrozen(player)) return false;
|
||||
// ★ 第63批:交易型操作检查债券限额
|
||||
if (isTradeType(type) && !checkBondTradeLimit(player, Math.abs(amount))) {
|
||||
Player p = org.bukkit.Bukkit.getPlayerExact(player);
|
||||
if (p != null) {
|
||||
p.sendMessage("§c§l[信誉积分] §c债券交易超限,本小时交易额已达上限");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return deductBondsInternal(player, amount,
|
||||
type, targetPlayer, operator, reason);
|
||||
}
|
||||
|
||||
// ===== 冻结豁免通道(★ 2026-10-04 冻结规则定案) =====
|
||||
// 冻结期间「仅允许 PHP 后端动账 + 管理员手动 give/remove」,
|
||||
// 玩家主动消费(商城/领地/商店)与他人转账一律被上面的
|
||||
// isFrozen 拦掉;只有走下面两个豁免方法的调用方才能动账。
|
||||
|
||||
/** 管理员/PHP 后台加款:冻结期也放行(只记流水,不查冻结) */
|
||||
public int addBondsAdmin(String player, int amount,
|
||||
String type,
|
||||
String targetPlayer,
|
||||
String operator,
|
||||
String reason) {
|
||||
return addBondsInternal(player, amount,
|
||||
type, targetPlayer, operator, reason);
|
||||
}
|
||||
|
||||
/** 管理员/PHP 后台扣款:冻结期也放行(管理员手动 remove) */
|
||||
public boolean deductBondsAdmin(String player, int amount,
|
||||
String type,
|
||||
String targetPlayer,
|
||||
String operator,
|
||||
String reason) {
|
||||
return deductBondsInternal(player, amount,
|
||||
type, targetPlayer, operator, reason);
|
||||
}
|
||||
@@ -893,221 +694,4 @@ public class BondManager {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 获取玩家最近1小时出售总额 =====
|
||||
public int getTodaySellTotal(String player) {
|
||||
return getSellTotalInWindow(player, System.currentTimeMillis() - 3600000L);
|
||||
}
|
||||
|
||||
private int getSellTotalInWindow(String player, long since) {
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT COALESCE(SUM(amount), 0) FROM bond_transaction "
|
||||
+ "WHERE player_name=? AND type='shop_sell' AND time >= ?");
|
||||
ps.setString(1, player);
|
||||
ps.setLong(2, since);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
int total = 0;
|
||||
if (rs.next()) {
|
||||
total = rs.getInt(1);
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
return total;
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取玩家最近1小时出售窗口中最早交易的时间戳。
|
||||
* 返回0表示窗口内无交易。
|
||||
*/
|
||||
public long getEarliestSellTimeInWindow(String player) {
|
||||
long since = System.currentTimeMillis() - 3600000L;
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT MIN(time) FROM bond_transaction "
|
||||
+ "WHERE player_name=? AND type='shop_sell' AND time >= ?");
|
||||
ps.setString(1, player);
|
||||
ps.setLong(2, since);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
long earliest = 0;
|
||||
if (rs.next()) {
|
||||
earliest = rs.getLong(1);
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
return earliest;
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 交易流水总笔数(用于开服与PHP对账)
|
||||
*/
|
||||
public long getTxCount() {
|
||||
try {
|
||||
Statement st = db.createStatement();
|
||||
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM bond_transaction");
|
||||
long n = rs.next() ? rs.getLong(1) : 0L;
|
||||
rs.close(); st.close();
|
||||
return n;
|
||||
} catch (SQLException e) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 交易流水最大序列号(bond_transaction.id 自增主键,即对账用的「交易序列号」)
|
||||
*/
|
||||
public long getMaxTxId() {
|
||||
try {
|
||||
Statement st = db.createStatement();
|
||||
ResultSet rs = st.executeQuery("SELECT COALESCE(MAX(id), 0) FROM bond_transaction");
|
||||
long n = rs.next() ? rs.getLong(1) : 0L;
|
||||
rs.close(); st.close();
|
||||
return n;
|
||||
} catch (SQLException e) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定时间之后的所有交易记录(用于Web同步)
|
||||
*/
|
||||
public List<Map<String, Object>> getTransactionsAfterTime(long afterTime) {
|
||||
List<Map<String, Object>> transactions = new ArrayList<>();
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT id, player_name, type, amount, target_player, operator, reason, balance_before, balance_after, time "
|
||||
+ "FROM bond_transaction WHERE time > ? ORDER BY time ASC");
|
||||
ps.setLong(1, afterTime);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
while (rs.next()) {
|
||||
Map<String, Object> tx = new LinkedHashMap<>();
|
||||
tx.put("id", rs.getInt("id"));
|
||||
tx.put("player_name", rs.getString("player_name"));
|
||||
tx.put("type", rs.getString("type"));
|
||||
tx.put("amount", rs.getInt("amount"));
|
||||
tx.put("target_player", rs.getString("target_player"));
|
||||
tx.put("operator", rs.getString("operator"));
|
||||
tx.put("reason", rs.getString("reason"));
|
||||
tx.put("balance_before", rs.getInt("balance_before"));
|
||||
tx.put("balance_after", rs.getInt("balance_after"));
|
||||
tx.put("time", rs.getLong("time"));
|
||||
transactions.add(tx);
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return transactions;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ★ 周期对账:水位线之后「还没推给 PHP」的笔数(只 COUNT,不拉行)。
|
||||
* 用来区分 PHP 的缺口是「正常的待推增量」还是「运行期被清空的历史」。
|
||||
*
|
||||
* @return 待推笔数;本地查不出来时返回 -1,调用方跳过本轮判定
|
||||
*/
|
||||
public long countTransactionsAfterTime(long afterTime) {
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"SELECT COUNT(*) FROM bond_transaction WHERE time > ?");
|
||||
ps.setLong(1, afterTime);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
long n = rs.next() ? rs.getLong(1) : 0L;
|
||||
rs.close();
|
||||
ps.close();
|
||||
return n;
|
||||
} catch (SQLException e) {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ★ 阶段E 多退少补:本机全部流水序列号(开服与 PHP 双向点验用)
|
||||
*/
|
||||
public List<Long> getAllTxIds() {
|
||||
List<Long> ids = new ArrayList<>();
|
||||
try {
|
||||
Statement st = db.createStatement();
|
||||
ResultSet rs = st.executeQuery(
|
||||
"SELECT id FROM bond_transaction ORDER BY id ASC");
|
||||
while (rs.next()) ids.add(rs.getLong(1));
|
||||
rs.close();
|
||||
st.close();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ★ 阶段E 多退少补:把「PHP 有、本机没有」的流水收回本地。
|
||||
* 只补流水记录(INSERT OR IGNORE 指定主键):
|
||||
* 不改余额、不触发交易事件、不发货,纯对账补记录。
|
||||
* PHP 的 tx_time 是秒级、本地 time 是毫秒 → 超过 1e12 视为毫秒,否则乘 1000。
|
||||
*
|
||||
* @param rows PHP pull_tx 返回的交易数组
|
||||
* @return 实际新写入的笔数
|
||||
*/
|
||||
public int importTransactionsFromWeb(List<Map<String, Object>> rows) {
|
||||
if (rows == null || rows.isEmpty()) return 0;
|
||||
int imported = 0;
|
||||
try {
|
||||
PreparedStatement ps = db.prepareStatement(
|
||||
"INSERT OR IGNORE INTO bond_transaction "
|
||||
+ "(id, player_name, type, amount,"
|
||||
+ " target_player, operator,"
|
||||
+ " reason, balance_before,"
|
||||
+ " balance_after, time)"
|
||||
+ " VALUES (?,?,?,?,?,?,?,?,?,?)");
|
||||
for (Map<String, Object> row : rows) {
|
||||
Object idv = row.get("id");
|
||||
if (!(idv instanceof Number)) continue;
|
||||
long txId = ((Number) idv).longValue();
|
||||
if (txId <= 0) continue;
|
||||
|
||||
long time = 0L;
|
||||
Object tv = row.get("time");
|
||||
if (tv instanceof Number) {
|
||||
time = ((Number) tv).longValue();
|
||||
if (time > 0 && time < 1000000000000L) time *= 1000L;
|
||||
}
|
||||
|
||||
ps.setLong(1, txId);
|
||||
ps.setString(2, row.get("player_name") == null ? ""
|
||||
: String.valueOf(row.get("player_name")));
|
||||
ps.setString(3, row.get("type") == null ? ""
|
||||
: String.valueOf(row.get("type")));
|
||||
ps.setInt(4, row.get("amount") instanceof Number
|
||||
? ((Number) row.get("amount")).intValue() : 0);
|
||||
ps.setString(5, row.get("target_player") == null ? ""
|
||||
: String.valueOf(row.get("target_player")));
|
||||
ps.setString(6, row.get("operator") == null ? ""
|
||||
: String.valueOf(row.get("operator")));
|
||||
ps.setString(7, row.get("reason") == null ? ""
|
||||
: String.valueOf(row.get("reason")));
|
||||
ps.setInt(8, row.get("balance_before") instanceof Number
|
||||
? ((Number) row.get("balance_before")).intValue() : 0);
|
||||
ps.setInt(9, row.get("balance_after") instanceof Number
|
||||
? ((Number) row.get("balance_after")).intValue() : 0);
|
||||
ps.setLong(10, time);
|
||||
imported += ps.executeUpdate();
|
||||
}
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,6 @@ public class BondPrinter {
|
||||
TYPE_NAMES.put("daily_sign", "签到奖励");
|
||||
TYPE_NAMES.put("freeze", "冻结");
|
||||
TYPE_NAMES.put("unfreeze", "解冻");
|
||||
TYPE_NAMES.put("ticket_reward", "工单奖励");
|
||||
TYPE_NAMES.put("ticket_service", "工单服务奖励");
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -25,9 +25,7 @@ public class CDKManager {
|
||||
try {
|
||||
Class.forName("org.sqlite.JDBC");
|
||||
File dbFile = new File(
|
||||
new File(plugin.getDataFolder(), "财务债券"),
|
||||
"bond.db");
|
||||
dbFile.getParentFile().mkdirs();
|
||||
plugin.getDataFolder(), "bond.db");
|
||||
db = DriverManager.getConnection(
|
||||
"jdbc:sqlite:" + dbFile.getAbsolutePath());
|
||||
Statement st = db.createStatement();
|
||||
@@ -57,17 +55,6 @@ public class CDKManager {
|
||||
*/
|
||||
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=?");
|
||||
@@ -177,35 +164,64 @@ public class CDKManager {
|
||||
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[经济操作] 功能已移除,请使用债券系统");
|
||||
net.milkbowl.vault.economy.Economy econ
|
||||
= null;
|
||||
try {
|
||||
var reg = plugin.getServer()
|
||||
.getServicesManager()
|
||||
.getRegistration(
|
||||
net.milkbowl.vault
|
||||
.economy
|
||||
.Economy.class);
|
||||
if (reg != null)
|
||||
econ = reg.getProvider();
|
||||
} catch (Exception ignored) {}
|
||||
if (econ == null) {
|
||||
admin.sendMessage("§c经济系统不可用");
|
||||
return;
|
||||
}
|
||||
if (!msg.startsWith("+")
|
||||
&& !msg.startsWith("-")) {
|
||||
admin.sendMessage("§c格式: §a+100"
|
||||
+ " §7或 §c-50");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String numStr =
|
||||
msg.substring(1).trim();
|
||||
double amount =
|
||||
Double.parseDouble(numStr);
|
||||
if (amount <= 0) {
|
||||
admin.sendMessage("§c金额必须>0");
|
||||
return;
|
||||
}
|
||||
if (msg.startsWith("-")) {
|
||||
Player tp = plugin.getServer()
|
||||
.getPlayerExact(target);
|
||||
if (tp == null) {
|
||||
admin.sendMessage("§c" + target
|
||||
+ " 不在线");
|
||||
return;
|
||||
}
|
||||
if (!econ.has(tp, amount)) {
|
||||
admin.sendMessage("§c余额不足");
|
||||
return;
|
||||
}
|
||||
econ.withdrawPlayer(tp, amount);
|
||||
admin.sendMessage("§a扣款成功");
|
||||
} else {
|
||||
econ.depositPlayer(target, amount);
|
||||
admin.sendMessage("§a到账成功");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
admin.sendMessage("§c格式错误");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleBondInput(Player admin,
|
||||
@@ -265,41 +281,6 @@ public class CDKManager {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,
|
||||
@@ -91,9 +90,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 +100,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 +147,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 +164,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 +354,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账号已被删除");
|
||||
@@ -640,18 +597,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 +608,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;
|
||||
}
|
||||
|
||||
@@ -57,20 +57,17 @@ public class CheckInManager {
|
||||
long diff = todayD.getTime()
|
||||
- lastD.getTime();
|
||||
if (diff > 86400000L * 2) {
|
||||
// 间隔超过2天,重置连续天数
|
||||
streak = 1;
|
||||
streak = 0;
|
||||
} else if (diff > 86400000L) {
|
||||
// 间隔1-2天(连续签到),天数+1
|
||||
streak++;
|
||||
}
|
||||
// 间隔<=1天(同一天),不改变连续天数
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
} else {
|
||||
// 首次签到
|
||||
streak = 1;
|
||||
}
|
||||
|
||||
if (streak == 0) streak = 1;
|
||||
else streak++;
|
||||
|
||||
double multi = 1.0;
|
||||
if (streak >= 21) multi = 1.5;
|
||||
else if (streak >= 14) multi = 1.3;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 >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 >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
@@ -67,7 +67,9 @@ public class CypayCommand
|
||||
+ " 余额: §a" + bonds);
|
||||
sender.sendMessage(
|
||||
"§e§l[债券] §f状态: "
|
||||
+ freezeText(name));
|
||||
+ ("frozen".equals(status)
|
||||
? "§c冻结中"
|
||||
: "§a正常"));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -93,10 +95,8 @@ public class CypayCommand
|
||||
return true;
|
||||
}*/
|
||||
|
||||
// ===== /cypay freeze <玩家> [时长] =====
|
||||
// ★ 2026-10-04 改版:时长可选,硬编封顶 30 天,
|
||||
// 不传时长 = 永久冻结;支持 1分钟/壹分钟/one min/时间戳
|
||||
if (args.length >= 2
|
||||
// ===== /cypay freeze =====
|
||||
if (args.length == 2
|
||||
&& "freeze".equalsIgnoreCase(
|
||||
args[0])) {
|
||||
if (!hasAdminPerm(sender)) {
|
||||
@@ -104,57 +104,20 @@ public class CypayCommand
|
||||
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);
|
||||
if (plugin.getBonds().isFrozen(target)) {
|
||||
sender.sendMessage("§c" + target
|
||||
+ " 已处于冻结状态");
|
||||
return true;
|
||||
}
|
||||
plugin.getBonds().freezeAccount(target, until);
|
||||
plugin.getBonds().freezeAccount(target);
|
||||
sender.sendMessage("§a已冻结 " + target
|
||||
+ " 的债券账户(" + durNote + ")");
|
||||
+ " 的债券账户");
|
||||
Player tp = plugin.getServer()
|
||||
.getPlayerExact(target);
|
||||
if (tp != null)
|
||||
tp.sendMessage(
|
||||
"§c§l[系统] 你的债券账户已被管理员冻结"
|
||||
+ (until <= 0L ? ""
|
||||
: ",到期时间: "
|
||||
+ DurationParser
|
||||
.formatExpire(until)));
|
||||
"§c§l[系统] 你的债券账户"
|
||||
+ "已被管理员冻结");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -219,7 +182,9 @@ public class CypayCommand
|
||||
+ plugin.getBonds()
|
||||
.getBonds(target)
|
||||
+ " §f状态: "
|
||||
+ freezeText(target));
|
||||
+ (plugin.getBonds()
|
||||
.isFrozen(target)
|
||||
? "§c冻结" : "§a正常"));
|
||||
|
||||
if (txs.isEmpty()) {
|
||||
sender.sendMessage("§7 (暂无记录)");
|
||||
@@ -276,7 +241,7 @@ public class CypayCommand
|
||||
}
|
||||
|
||||
// ===== /cypay give/remove =====
|
||||
if (args.length >= 3 && args.length <= 4) {
|
||||
if (args.length == 3) {
|
||||
String action = args[0].toLowerCase();
|
||||
if ("give".equals(action)
|
||||
|| "remove".equals(action)) {
|
||||
@@ -303,19 +268,12 @@ public class CypayCommand
|
||||
sender instanceof Player
|
||||
? sender.getName()
|
||||
: "Console";
|
||||
// 自定义理由(可选)
|
||||
String reason = args.length == 4
|
||||
? args[3]
|
||||
: ("give".equals(action)
|
||||
? "管理员发放"
|
||||
: "管理员扣除");
|
||||
|
||||
if ("give".equals(action)) {
|
||||
// ★ 冻结期豁免:管理员手动 give 允许动账
|
||||
plugin.getBonds().addBondsAdmin(
|
||||
plugin.getBonds().addBonds(
|
||||
target, amount,
|
||||
txType, "",
|
||||
opName, reason);
|
||||
opName, "管理员发放");
|
||||
sender.sendMessage(
|
||||
"§a已给 " + target
|
||||
+ " " + amount
|
||||
@@ -328,14 +286,12 @@ public class CypayCommand
|
||||
+ amount
|
||||
+ " 债券");
|
||||
} else {
|
||||
// ★ 冻结期豁免:管理员手动 remove
|
||||
// 允许动账(deductBondsAdmin 不查冻结)
|
||||
if (plugin.getBonds()
|
||||
.deductBondsAdmin(target,
|
||||
.deductBonds(target,
|
||||
amount,
|
||||
txType, "",
|
||||
opName,
|
||||
reason)) {
|
||||
"管理员扣除")) {
|
||||
sender.sendMessage(
|
||||
"§a已扣除 " + target
|
||||
+ " " + amount
|
||||
@@ -353,7 +309,8 @@ public class CypayCommand
|
||||
} else {
|
||||
sender.sendMessage(
|
||||
"§c" + target
|
||||
+ " 债券不足");
|
||||
+ " 债券不足"
|
||||
+ "或账户冻结");
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
@@ -430,7 +387,10 @@ public class CypayCommand
|
||||
+ bonds);
|
||||
sender.sendMessage(
|
||||
"§e§l[债券] §f状态: "
|
||||
+ freezeText(target));
|
||||
+ ("frozen".equals(
|
||||
status)
|
||||
? "§c冻结中"
|
||||
: "§a正常"));
|
||||
} else {
|
||||
int bonds = plugin.getBonds()
|
||||
.getBonds(
|
||||
@@ -446,19 +406,6 @@ public class CypayCommand
|
||||
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(
|
||||
@@ -530,14 +477,13 @@ public class CypayCommand
|
||||
"§e/cypay <玩家> <金额> §7- 转账");
|
||||
if (hasAdminPerm(sender)) {
|
||||
sender.sendMessage(
|
||||
"§e/cypay give <玩家> <金额> [理由] §7- 给债券");
|
||||
"§e/cypay give <玩家> <金额> §7- 给债券");
|
||||
sender.sendMessage(
|
||||
"§e/cypay remove <玩家> <金额> [理由] §7- 扣债券");
|
||||
"§e/cypay remove <玩家> <金额> §7- 扣债券");
|
||||
sender.sendMessage(
|
||||
"§e/cypay import <文件> §7- 导入CDK");
|
||||
sender.sendMessage(
|
||||
"§e/cypay freeze <玩家> [时长] §7- 冻结"
|
||||
+ "(不填=永久,封顶30天)");
|
||||
"§e/cypay freeze <玩家> §7- 冻结");
|
||||
sender.sendMessage(
|
||||
"§e/cypay unfreeze <玩家> §7- 解冻");
|
||||
sender.sendMessage(
|
||||
@@ -607,15 +553,6 @@ public class CypayCommand
|
||||
|
||||
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");
|
||||
@@ -635,19 +572,6 @@ public class CypayCommand
|
||||
}
|
||||
}
|
||||
|
||||
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
@@ -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));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,30 +221,16 @@ 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(
|
||||
@@ -769,8 +287,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) {
|
||||
@@ -904,7 +425,7 @@ public class GarbageManager implements Listener {
|
||||
"§7已是最后一页"));
|
||||
}
|
||||
|
||||
// 52 格:返回主菜单
|
||||
// 52 格:返回
|
||||
g.setItem(52, mk(Material.ARROW,
|
||||
"§7返回",
|
||||
"§7返回主菜单"));
|
||||
@@ -998,38 +519,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 +564,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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,6 @@ public class IPGroupManager {
|
||||
return can;
|
||||
}
|
||||
|
||||
public int getMaxAccounts() {
|
||||
return maxAccounts;
|
||||
}
|
||||
|
||||
public int getAccountCount(String ip) {
|
||||
if (ip == null || ip.isEmpty()) return 0;
|
||||
return queryAccountsByIP(ip).size();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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- 查看该处今日记录");
|
||||
}
|
||||
}
|
||||
@@ -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,14 +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);
|
||||
@@ -94,16 +79,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 +100,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;
|
||||
}
|
||||
|
||||
@@ -168,16 +139,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 +161,55 @@ 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().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);
|
||||
p.setAllowFlight(false);
|
||||
p.setFlying(false);
|
||||
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 +222,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)
|
||||
|
||||
+5498
-11834
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 与 <br> 换行
|
||||
* - 变量: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);
|
||||
}
|
||||
|
||||
// ==================== 占位符定界符 ====================
|
||||
|
||||
/**
|
||||
* 占位符可用的定界符对:中英文小括号、中括号、花括号,外加 %…% 与 <…>。
|
||||
* 例:{username} [username] (username) 【用户】 (用户) {username} [username]
|
||||
* 「玩家名」 『开始时间』 %endtime% <结束时间>
|
||||
* 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 色码(&c / §c / &x&R&R&R&R&R&R)。
|
||||
* headDeco(可为 null)收集头部被剥离的色码原串,JSON 解析成功后回贴到组件上;
|
||||
* 尾部色码只剥离不收集——它后面已无文本,应用它没有意义。
|
||||
* 这层剥离专门解决「&c&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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把剥离出来的前置色码(&c&l / §c§l / &x&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(中英文小/中/大括号、%…%、<…>)。
|
||||
* JSON 消息(含 &c&l 包着 JSON 的情形):跳过花括号 {}、不做裸子串替换——
|
||||
* 花括号是 JSON 对象结构本身,裸替换会吃掉正文里的 end/start/player 等英文词
|
||||
* ("end soon" -> "2026-09-28 10:00 soon")。JSON 消息里请用 [username]、(用户)、%username% 等形式。
|
||||
* 普通 &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 文本组件:形如 {...} 或 [...],且含双引号。
|
||||
* 先剥离首尾色码与空白再判定——&c&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 内的 <br> 变体(<br> <br/> <br /> </br>,大小写不敏感) */
|
||||
private static final Pattern BR_IN_JSON_PAT = Pattern.compile("(?i)</?br\\s*/?>");
|
||||
|
||||
/**
|
||||
* 把 JSON 文本里的字面 <br> 换成 JSON 转义换行(反斜杠 + n 两字符)。
|
||||
* 必须是两字符序列:真实换行在 JSON 字符串里非法,写进去整段就解析失败了。
|
||||
*/
|
||||
private static String replaceBrInJson(String json) {
|
||||
return BR_IN_JSON_PAT.matcher(json).replaceAll("\\\\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息格式化:
|
||||
* 0) 防御层:剥掉首尾色码/空白再判定 JSON;残缺 JSON 尽力修补——
|
||||
* 绝不把 JSON 源码原样吐给玩家(剥掉的色码如 &c&l 作为默认样式贴回结果)
|
||||
* 1) 整段是 JSON(对象 {...} 或顶层数组 [...],后者是 tellraw 常见写法)
|
||||
* → 按文本组件解析(支持 text/color/extra 等);字面 <br> 会先换成 JSON 转义换行
|
||||
* 2) 否则处理 <br> 与字面 \n 换行、& 颜色码与 § 颜色码
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -83,29 +83,18 @@ public class MenuManager implements Listener {
|
||||
return items;
|
||||
}
|
||||
|
||||
// ===== 读取菜单.txt(主菜单唯一来源) =====
|
||||
// ===== 读取菜单.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);
|
||||
}
|
||||
}
|
||||
if (!f.exists()) createDefault(f);
|
||||
parseFile(f);
|
||||
plugin.getLogger().info(
|
||||
"[Menu] 加载 " + items.size()
|
||||
+ " 个菜单项 (源: "
|
||||
+ f.getName() + ")");
|
||||
"[Menu] 加载 "
|
||||
+ items.size()
|
||||
+ " 个菜单项");
|
||||
}
|
||||
|
||||
private void parseFile(File f) {
|
||||
@@ -383,16 +372,9 @@ public class MenuManager implements Listener {
|
||||
|
||||
// ===== 保存 =====
|
||||
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),
|
||||
|
||||
@@ -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>
|
||||
* 纯同步:先读本地缓存 → 没有则从 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
@@ -77,21 +77,10 @@ public class OrderManager implements Listener {
|
||||
public static class OrderItem {
|
||||
public String name; public String mat;
|
||||
public int originalPrice; public int finalPrice; public int qty;
|
||||
public String nbt; // 物品NBT快照(Base64 of ItemStack.serializeAsBytes),退款时用于精确匹配含NBT商品;null/空=无NBT或旧数据
|
||||
public OrderItem(String n,String m,int op,int fp,int q){
|
||||
name=n;mat=m;originalPrice=op;finalPrice=fp;qty=q;nbt=null;}
|
||||
public OrderItem(String n,String m,int op,int fp,int q,String nbtB64){
|
||||
name=n;mat=m;originalPrice=op;finalPrice=fp;qty=q;nbt=nbtB64;}
|
||||
name=n;mat=m;originalPrice=op;finalPrice=fp;qty=q;}
|
||||
public int subtotal(){return finalPrice*qty;}
|
||||
public int originalSubtotal(){return originalPrice*qty;}
|
||||
/** 还原下单时的真实物品(含NBT),用于退款时精确匹配;无快照或还原失败返回null */
|
||||
public org.bukkit.inventory.ItemStack toTemplateStack() {
|
||||
if (nbt == null || nbt.isEmpty()) return null;
|
||||
try {
|
||||
byte[] b = java.util.Base64.getDecoder().decode(nbt);
|
||||
return org.bukkit.inventory.ItemStack.deserializeBytes(b);
|
||||
} catch (Exception e) { return null; }
|
||||
}
|
||||
}
|
||||
public static class OrderRecord {
|
||||
public long orderId; public UUID uuid; public String player;
|
||||
@@ -395,31 +384,13 @@ public class OrderManager implements Listener {
|
||||
int c = 0; for (ItemStack is : p.getInventory().getContents()) if (is != null && is.getType() == m) c += is.getAmount();
|
||||
return c;
|
||||
}
|
||||
/** 精确按材质+ItemMeta(NBT)计数,用于含NBT商品(如附魔书)退款校验 */
|
||||
private int countSimilarItems(Player p, org.bukkit.inventory.ItemStack tmpl) {
|
||||
if (tmpl == null) return 0;
|
||||
int c = 0; for (ItemStack is : p.getInventory().getContents()) if (is != null && is.isSimilar(tmpl)) c += is.getAmount();
|
||||
return c;
|
||||
}
|
||||
private int countShulkers(Player p, String matName) {
|
||||
Material m = Material.matchMaterial(matName); if (m == null) return 0;
|
||||
int c = 0; for (ItemStack is : p.getInventory().getContents()) if (is != null && is.getType() == m) c += is.getAmount();
|
||||
return c;
|
||||
}
|
||||
/**
|
||||
* 收走订单物品:优先按记录中的NBT快照精确匹配(材质+ItemMeta一致),
|
||||
* 确保含NBT商品(附魔书等)既退钱又收回正确的实物,而非"仅退款"。
|
||||
* 无快照(旧订单/普通物品)则按材质兜底。
|
||||
*/
|
||||
private void removeItems(Player p, OrderItem it) {
|
||||
org.bukkit.inventory.ItemStack tmpl = it.toTemplateStack();
|
||||
if (tmpl != null) {
|
||||
tmpl.setAmount(it.qty);
|
||||
p.getInventory().removeItem(tmpl); // removeItem 按 isSimilar 匹配,精确收走含NBT实物
|
||||
} else {
|
||||
Material m = Material.matchMaterial(it.mat);
|
||||
if (m != null) p.getInventory().removeItem(new ItemStack(m, it.qty));
|
||||
}
|
||||
private void removeItems(Player p, String matName, int amt) {
|
||||
Material m = Material.matchMaterial(matName); if (m != null) p.getInventory().removeItem(new ItemStack(m, amt));
|
||||
}
|
||||
private boolean removeOneShulker(Player p,
|
||||
String materialName) {
|
||||
@@ -477,10 +448,9 @@ public class OrderManager implements Listener {
|
||||
}
|
||||
return "§c对应的潜影盒已不在背包中";
|
||||
} else {
|
||||
// ★ 散装:检测物品数量(含NBT商品按材质+ItemMeta精确校验,必须"有货且有正确NBT")
|
||||
// ★ 散装:检测物品数量
|
||||
for (OrderItem it : r.items) {
|
||||
org.bukkit.inventory.ItemStack tmpl = it.toTemplateStack();
|
||||
int have = (tmpl != null) ? countSimilarItems(p, tmpl) : countDirectItems(p, it.mat);
|
||||
int have = countDirectItems(p, it.mat);
|
||||
if (have < it.qty)
|
||||
return "§c" + it.name + "不足(有"
|
||||
+ have + "/" + it.qty + ")";
|
||||
@@ -715,7 +685,7 @@ public class OrderManager implements Listener {
|
||||
}
|
||||
} else {
|
||||
for (OrderItem it : r.items)
|
||||
removeItems(p, it);
|
||||
removeItems(p, it.mat, it.qty);
|
||||
}
|
||||
// 退钱
|
||||
plugin.getBonds().addBonds(
|
||||
@@ -851,38 +821,13 @@ public class OrderManager implements Listener {
|
||||
p.sendMessage("§e输入退款百分比(1-100): #" + r.orderId + " 实付" + r.totalPaid + "枚");
|
||||
}
|
||||
} else {
|
||||
if (r.status == 0) {
|
||||
// ★ 管理员全额退款:同步收回物品(玩家在线时),避免"只退钱不退货"
|
||||
Player target = Bukkit.getPlayer(r.uuid);
|
||||
if (target != null && target.isOnline()) {
|
||||
String pt = r.packType != null ? r.packType : "none";
|
||||
boolean isShulker = pt.equals("custom")
|
||||
|| pt.equals("default") || pt.equals("shulker");
|
||||
if (isShulker) {
|
||||
for (int i = 0; i < 36; i++) {
|
||||
ItemStack is = target.getInventory().getItem(i);
|
||||
if (is == null) continue;
|
||||
if (!is.getType().name().contains("SHULKER")) continue;
|
||||
ItemMeta im = is.getItemMeta();
|
||||
boolean tagged = false;
|
||||
if (im != null && im.getLore() != null) {
|
||||
for (String line : im.getLore()) {
|
||||
if (line.equals("§8#" + r.orderId)) { tagged = true; break; }
|
||||
}
|
||||
}
|
||||
if (tagged) { target.getInventory().clear(i); break; }
|
||||
}
|
||||
} else {
|
||||
for (OrderItem it : r.items) removeItems(target, it);
|
||||
}
|
||||
}
|
||||
if (r.status == 0 || r.status == 1) {
|
||||
plugin.getBonds().addBonds(r.player, r.totalPaid);
|
||||
r.status = 2;
|
||||
r.refundedAmount = r.totalPaid;
|
||||
r.refundType = "auto_return";
|
||||
saveOrders();
|
||||
p.sendMessage("§a全额退款(含退货) §e" + r.player + " §6" + r.totalPaid + "枚");
|
||||
notifyPlayer(r.uuid, "§a[订单] 退款退货成功,§6" + r.totalPaid + "枚已退还");
|
||||
p.sendMessage("§a全额退款 §e" + r.player + " §6" + r.totalPaid + "枚");
|
||||
notifyPlayer(r.uuid, "§a退款 §6" + r.totalPaid + "枚");
|
||||
openAdminOrders(p, tu, page);
|
||||
}
|
||||
}
|
||||
@@ -987,7 +932,7 @@ public class OrderManager implements Listener {
|
||||
Player target = Bukkit.getPlayer(r.uuid);
|
||||
if (target != null && target.isOnline()) {
|
||||
for (OrderItem it : r.items)
|
||||
removeItems(target, it);
|
||||
removeItems(target, it.mat, it.qty);
|
||||
}
|
||||
plugin.getBonds().addBonds(r.player, r.totalPaid);
|
||||
r.status = 2;
|
||||
@@ -1092,7 +1037,7 @@ public class OrderManager implements Listener {
|
||||
}
|
||||
} else {
|
||||
for (OrderItem it : r.items)
|
||||
removeItems(p, it);
|
||||
removeItems(p, it.mat, it.qty);
|
||||
}
|
||||
|
||||
plugin.getBonds().addBonds(r.player, r.totalPaid);
|
||||
@@ -1335,27 +1280,15 @@ public class OrderManager implements Listener {
|
||||
case "packFee": cur.packFee = Integer.parseInt(v); break; case "packType": cur.packType = v; break; case "packColor": cur.packColor = v; break;
|
||||
case "status": cur.status = Integer.parseInt(v); break; case "refundedAmount": cur.refundedAmount = Integer.parseInt(v); break;
|
||||
case "printTime": cur.printTime = Long.parseLong(v); break; case "refundType": cur.refundType = v; break;
|
||||
case "item": String[] pp = v.split("\\|"); if (pp.length >= 5) { OrderItem oi = new OrderItem(pp[0], pp[1], Integer.parseInt(pp[2]), Integer.parseInt(pp[3]), Integer.parseInt(pp[4])); if (pp.length >= 6) oi.nbt = pp[5]; cur.items.add(oi); } break; }
|
||||
case "item": String[] pp = v.split("\\|"); if (pp.length >= 5) cur.items.add(new OrderItem(pp[0], pp[1], Integer.parseInt(pp[2]), Integer.parseInt(pp[3]), Integer.parseInt(pp[4]))); break; }
|
||||
} else if (line.isEmpty() && cur != null && cur.uuid != null) { orders.add(cur); cur = null; }
|
||||
} if (cur != null && cur.uuid != null) orders.add(cur); br.close();
|
||||
} catch (Exception e) { plugin.getLogger().warning("[Order]加载失败: " + e.getMessage()); }
|
||||
}
|
||||
/** 写盘互斥锁:与 orders 锁分离,避免持 orders 锁做文件 IO(异步清理写盘时主线程 add 会被卡) */
|
||||
private final Object saveLock = new Object();
|
||||
|
||||
private void saveOrders() {
|
||||
// ★ 先在 orders 锁内取快照(极快),再持 saveLock 写盘
|
||||
// ① 主线程 recordOrder 的 add 不会被慢速写盘阻塞
|
||||
// ② 主线程与异步清理任务不会同时写 orders.dat 互相截断
|
||||
final List<OrderRecord> snap;
|
||||
synchronized (orders) { snap = new ArrayList<>(orders); }
|
||||
synchronized (saveLock) { saveOrdersTo(snap); }
|
||||
}
|
||||
|
||||
private void saveOrdersTo(List<OrderRecord> snap) {
|
||||
File f = new File(plugin.getDataFolder(), "orders.dat");
|
||||
try { PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8));
|
||||
{ for (OrderRecord r : snap) { pw.println("==");
|
||||
synchronized (orders) { for (OrderRecord r : orders) { pw.println("==");
|
||||
pw.println("id=" + r.orderId); pw.println("uuid=" + r.uuid); pw.println("player=" + r.player);
|
||||
pw.println("totalOriginal=" + r.totalOriginal); pw.println("totalPaid=" + r.totalPaid);
|
||||
pw.println("discount=" + r.discount); pw.println("discountType=" + nn(r.discountType));
|
||||
@@ -1363,13 +1296,11 @@ public class OrderManager implements Listener {
|
||||
pw.println("packType=" + nn(r.packType)); pw.println("packColor=" + nn(r.packColor));
|
||||
pw.println("status=" + r.status); pw.println("refundedAmount=" + r.refundedAmount);
|
||||
pw.println("printTime=" + r.printTime); pw.println("refundType=" + nn(r.refundType));
|
||||
for (OrderItem it : r.items) pw.println("item=" + it.name + "|" + it.mat + "|" + it.originalPrice + "|" + it.finalPrice + "|" + it.qty + "|" + (it.nbt == null ? "" : it.nbt));
|
||||
for (OrderItem it : r.items) pw.println("item=" + it.name + "|" + it.mat + "|" + it.originalPrice + "|" + it.finalPrice + "|" + it.qty);
|
||||
} } pw.flush(); pw.close();
|
||||
} catch (Exception e) { plugin.getLogger().warning("[Order]保存失败: " + e.getMessage()); }
|
||||
}
|
||||
// ★ 过期清理 = 遍历 + 全量落盘(文件 IO)→ 异步定时器;
|
||||
// removeIf 在 orders 锁内完成即释放,写盘走 saveLock,不长期占着 orders 锁
|
||||
private void startCleanupTask() { new BukkitRunnable() { public void run() { boolean changed; synchronized (orders) { changed = orders.removeIf(OrderManager.this::isExpired); } if (changed) saveOrders(); } }.runTaskTimerAsynchronously(plugin, 36000L, 36000L); }
|
||||
private void startCleanupTask() { new BukkitRunnable() { public void run() { synchronized (orders) { if (orders.removeIf(OrderManager.this::isExpired)) saveOrders(); } } }.runTaskTimer(plugin, 36000L, 36000L); }
|
||||
/**
|
||||
* 将小票书塞入潜影盒
|
||||
*/
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -108,9 +108,8 @@ public class PVPManager implements Listener {
|
||||
Class.forName(
|
||||
"org.sqlite.JDBC");
|
||||
File dbFile = new File(
|
||||
new File(plugin.getDataFolder(), "pvp"),
|
||||
plugin.getDataFolder(),
|
||||
"pvp.db");
|
||||
dbFile.getParentFile().mkdirs();
|
||||
pvpDb = DriverManager.getConnection(
|
||||
"jdbc:sqlite:"
|
||||
+ dbFile.getAbsolutePath());
|
||||
@@ -417,16 +416,6 @@ public class PVPManager implements Listener {
|
||||
return regions.keySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第35批:玩家当前是否在某个 PVP 区域内。
|
||||
* 公告计分板据此避让 —— PVP 区域/竞技场内的侧边栏归 PVP 模块管,
|
||||
* 玩家离开 PVP 区域后由公告板接管回去。
|
||||
*/
|
||||
public boolean isInPVPRegion(String playerName) {
|
||||
if (playerName == null) return false;
|
||||
return inRegion.get(playerName) != null;
|
||||
}
|
||||
|
||||
// ===== 加载 =====
|
||||
|
||||
private void loadRegions() {
|
||||
@@ -496,32 +485,10 @@ public class PVPManager implements Listener {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (has) return;
|
||||
// ★ SN 管控:1人同种类仅限1个
|
||||
if (plugin.getSnManager() != null
|
||||
&& plugin.getSnManager().isBlocked(
|
||||
p, SnManager.TYPE_PVP)) {
|
||||
long cdMin = plugin.getSnManager().cooldownMinutesLeft(p.getName());
|
||||
if (cdMin > 0) {
|
||||
p.sendMessage("§c[PVP] 注销冷静期未结束,还剩约 " + cdMin + " 分钟,期间无法申领新设备");
|
||||
} else {
|
||||
p.sendMessage("§c[PVP] 你已有PVP圈地棒的有效登记,"
|
||||
+ "旧SN未注销前不能重新申领");
|
||||
}
|
||||
return;
|
||||
if (!has) {
|
||||
p.getInventory()
|
||||
.addItem(createTool());
|
||||
}
|
||||
ItemStack tool = createTool();
|
||||
if (plugin.getSnManager() != null) {
|
||||
String sn = plugin.getSnManager().applySn(
|
||||
p, SnManager.TYPE_PVP, "PVP圈地棒");
|
||||
if (sn == null) {
|
||||
p.sendMessage("§c[PVP] 申领被SN系统拒绝");
|
||||
return;
|
||||
}
|
||||
plugin.getSnManager().writeSn(
|
||||
tool, sn, SnManager.TYPE_PVP);
|
||||
}
|
||||
p.getInventory().addItem(tool);
|
||||
}
|
||||
|
||||
// ===== 边框粒子 =====
|
||||
@@ -746,10 +713,8 @@ public class PVPManager implements Listener {
|
||||
instanceof Player)) return;
|
||||
Player victim =
|
||||
(Player) event.getEntity();
|
||||
org.bukkit.entity.Entity kc =
|
||||
event.getDamageSource().getCausingEntity();
|
||||
Player killer =
|
||||
(kc instanceof Player) ? (Player) kc : null;
|
||||
victim.getKiller();
|
||||
if (killer == null) return;
|
||||
if (killer.equals(victim)) return;
|
||||
|
||||
@@ -1027,14 +992,6 @@ public class PVPManager implements Listener {
|
||||
|
||||
private void removeScoreboard(
|
||||
Player p) {
|
||||
// ★ 第35批:PVP 区域结束后把侧边栏还给公告板
|
||||
// (原实现塞一个空计分板,玩家看到空白侧边栏)
|
||||
// force=true:此时 inRegion 已移除,强制归还公告板
|
||||
if (plugin.getAnnouncementBoard() != null) {
|
||||
plugin.getAnnouncementBoard()
|
||||
.applyTo(p, true);
|
||||
return;
|
||||
}
|
||||
ScoreboardManager mgr =
|
||||
Bukkit.getScoreboardManager();
|
||||
p.setScoreboard(
|
||||
@@ -1117,15 +1074,8 @@ public class PVPManager implements Listener {
|
||||
public boolean onCommand(Player p,
|
||||
String[] args) {
|
||||
if (args.length == 0) {
|
||||
showStats(p, p.getName());
|
||||
// ★ 同时展示竞技场总战绩
|
||||
showArenaTotalStats(p, p.getName());
|
||||
return true;
|
||||
}
|
||||
// ★ 数字参数 → 查询指定会话编号的竞技场战绩
|
||||
if (args.length == 1 && args[0].matches("\\d+")) {
|
||||
showArenaSessionStats(p, p.getName(), Integer.parseInt(args[0]));
|
||||
return true;
|
||||
return showStats(p,
|
||||
p.getName());
|
||||
}
|
||||
switch (args[0].toLowerCase()) {
|
||||
case "create":
|
||||
@@ -1162,48 +1112,9 @@ public class PVPManager implements Listener {
|
||||
case "tempban":
|
||||
return handleTempBan(
|
||||
p, args);
|
||||
case "join":
|
||||
case "arena":
|
||||
// ★ /pvp join see → 直接进入观赛(默认幽灵形态)
|
||||
if (args.length >= 2 && args[1].equalsIgnoreCase("see")) {
|
||||
plugin.getPVPArenaManager().handleSeeCommand(p, "enter");
|
||||
return true;
|
||||
}
|
||||
plugin.getPVPArenaManager().joinArena(p);
|
||||
return true;
|
||||
case "equip":
|
||||
case "adjust":
|
||||
if (!plugin.getPVPArenaManager().isInPVPArena(p.getName())) {
|
||||
p.sendMessage("§c你不在PVP竞技场中");
|
||||
return true;
|
||||
}
|
||||
plugin.getPVPArenaManager().openEquipmentSelection(p);
|
||||
return true;
|
||||
case "see":
|
||||
// PVP观赛:/pvp see=在裁判⇄幽灵两种观赛形态间切换(仅PVP世界,绝不切回无保护的普通玩家)
|
||||
plugin.getPVPArenaManager().handleSeeCommand(p);
|
||||
return true;
|
||||
case "leave":
|
||||
case "exit":
|
||||
// ★ /pvp leave see → 彻底退出观赛:恢复身份并重新触发选装、补发PVP装备
|
||||
if (args.length >= 2 && args[1].equalsIgnoreCase("see")) {
|
||||
plugin.getPVPArenaManager().handleSeeCommand(p, "exit");
|
||||
return true;
|
||||
}
|
||||
plugin.leavePVP(p);
|
||||
return true;
|
||||
default:
|
||||
showStats(p, p.getName());
|
||||
p.sendMessage("§7——— PVP指令 ———");
|
||||
p.sendMessage("§e/pvp join §7进入PVP竞技场");
|
||||
p.sendMessage("§e/pvp equip §7调整装备(食物/盾牌/弓弩)");
|
||||
p.sendMessage("§e/pvp see §7观赛:切换裁判⇄幽灵形态(仅PVP世界)");
|
||||
p.sendMessage("§e/pvp join see §7加入观赛:进入幽灵形态");
|
||||
p.sendMessage("§e/pvp leave see §7退出观赛:重新选装并补发PVP装备");
|
||||
p.sendMessage("§e/pvp leave §7离开PVP竞技场");
|
||||
p.sendMessage("§e/pvp stats [玩家] §7查看战绩");
|
||||
p.sendMessage("§e/pvp list §7查看PVP区域列表");
|
||||
return true;
|
||||
return showStats(p,
|
||||
p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1424,28 +1335,9 @@ public class PVPManager implements Listener {
|
||||
if (region == null) {
|
||||
p.sendMessage("§6§l" + target
|
||||
+ " 的PVP战绩:");
|
||||
|
||||
// ★ PVP世界战绩(从PvPArenaManager获取)
|
||||
int pvpWorldKills = 0;
|
||||
int pvpWorldDeaths = 0;
|
||||
if (plugin.getPVPArenaManager() != null) {
|
||||
Map<String, Integer> wk = plugin.getPVPArenaManager().getPVPWorldKills();
|
||||
Map<String, Integer> wd = plugin.getPVPArenaManager().getPVPWorldDeaths();
|
||||
pvpWorldKills = wk.getOrDefault(target, 0);
|
||||
pvpWorldDeaths = wd.getOrDefault(target, 0);
|
||||
}
|
||||
if (pvpWorldKills > 0 || pvpWorldDeaths > 0) {
|
||||
double pvpKd = pvpWorldDeaths > 0
|
||||
? (double) pvpWorldKills / pvpWorldDeaths : pvpWorldKills;
|
||||
p.sendMessage("§e- §fPVP世界 §a击杀:" + pvpWorldKills
|
||||
+ " §c死亡:" + pvpWorldDeaths
|
||||
+ " §eKD:" + String.format("%.2f", pvpKd));
|
||||
}
|
||||
|
||||
// PVP区域战绩
|
||||
List<Map<String, Object>> all =
|
||||
getAllRegions();
|
||||
boolean has = pvpWorldKills > 0 || pvpWorldDeaths > 0;
|
||||
boolean has = false;
|
||||
for (Map<String, Object> row :
|
||||
all) {
|
||||
String rn = (String) row
|
||||
@@ -1463,21 +1355,6 @@ public class PVPManager implements Listener {
|
||||
has = true;
|
||||
}
|
||||
}
|
||||
// ★ 总计
|
||||
int totalKills = pvpWorldKills;
|
||||
int totalDeaths = pvpWorldDeaths;
|
||||
for (Map<String, Object> row : all) {
|
||||
String rn = (String) row.get("name");
|
||||
totalKills += getKills(target, rn);
|
||||
totalDeaths += getDeaths(target, rn);
|
||||
}
|
||||
if (totalKills > 0 || totalDeaths > 0) {
|
||||
double totalKd = totalDeaths > 0
|
||||
? (double) totalKills / totalDeaths : totalKills;
|
||||
p.sendMessage("§6§l- §f总计 §a击杀:" + totalKills
|
||||
+ " §c死亡:" + totalDeaths
|
||||
+ " §eKD:" + String.format("%.2f", totalKd));
|
||||
}
|
||||
if (!has)
|
||||
p.sendMessage(
|
||||
"§7暂无记录");
|
||||
@@ -1500,43 +1377,4 @@ public class PVPManager implements Listener {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ★ 展示PVP竞技场总战绩
|
||||
private void showArenaTotalStats(Player p, String target) {
|
||||
org.bukkit.OfflinePlayer off = Bukkit.getOfflinePlayer(target);
|
||||
String uuid = off.getUniqueId().toString();
|
||||
Map<String, Object> stats = plugin.getPVPArenaManager().getTotalArenaStats(uuid);
|
||||
int kills = (int) stats.get("kills");
|
||||
int deaths = (int) stats.get("deaths");
|
||||
if (kills == 0 && deaths == 0) return;
|
||||
double kd = deaths > 0 ? (double) kills / deaths : kills;
|
||||
p.sendMessage("§6§l[PVP竞技场] " + target);
|
||||
p.sendMessage(" §a击杀: " + kills + " §c死亡: " + deaths + " §eKD: " + String.format("%.2f", kd));
|
||||
}
|
||||
|
||||
// ★ 展示指定会话编号的竞技场战绩
|
||||
private void showArenaSessionStats(Player p, String target, int sessionNumber) {
|
||||
org.bukkit.OfflinePlayer off = Bukkit.getOfflinePlayer(target);
|
||||
String uuid = off.getUniqueId().toString();
|
||||
// 先查会话信息(含3天有效期检查)
|
||||
Map<String, Object> session = plugin.getPVPArenaManager().getArenaSessionByNumber(sessionNumber);
|
||||
if (session == null) {
|
||||
p.sendMessage("§c未找到编号 " + sessionNumber + " 的竞技场记录,或已超出3天查询范围");
|
||||
return;
|
||||
}
|
||||
long createdAt = (Long) session.get("created_at");
|
||||
long threeDaysMs = 3L * 24 * 60 * 60 * 1000;
|
||||
if (System.currentTimeMillis() - createdAt > threeDaysMs) {
|
||||
p.sendMessage("§c该记录已超出3天查询范围,不再支持查询");
|
||||
return;
|
||||
}
|
||||
int dbSessionId = (int) session.get("id");
|
||||
Map<String, Object> stats = plugin.getPVPArenaManager().getArenaSessionStats(uuid, dbSessionId);
|
||||
int kills = (int) stats.get("kills");
|
||||
int deaths = (int) stats.get("deaths");
|
||||
String worldName = (String) session.get("world_name");
|
||||
String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(createdAt));
|
||||
p.sendMessage("§6§l[PVP竞技场#" + sessionNumber + "] " + target + " §7(" + dateStr + " " + worldName + ")");
|
||||
p.sendMessage(" §a击杀: " + kills + " §c死亡: " + deaths + " §eKD: " + String.format("%.2f", deaths > 0 ? (double) kills / deaths : kills));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,12 +19,7 @@ public class PasswordUtils {
|
||||
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));
|
||||
md.update(Base64.getDecoder().decode(salt));
|
||||
byte[] hash =
|
||||
md.digest(password.getBytes("UTF-8"));
|
||||
return Base64.getEncoder().encodeToString(hash);
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -259,21 +259,20 @@ public class PointsManager {
|
||||
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债券系统不可用");
|
||||
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)));
|
||||
p.sendMessage(plugin.getConfig2()
|
||||
.msg("points_insufficient")
|
||||
.replace("{points}",
|
||||
String.valueOf(points)));
|
||||
}
|
||||
break;
|
||||
case 12:
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,8 @@ import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Registry;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.generator.structure.Structure;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
// 如果 Bonds 在 Sdf1_login 包下:
|
||||
@@ -40,8 +35,6 @@ public class QuestTracker {
|
||||
checkInRecords = new ArrayList<>();
|
||||
private final Map<String, String>
|
||||
lastCheckInPos = new HashMap<>();
|
||||
private static boolean loggedStructureRegistry
|
||||
= false;
|
||||
|
||||
public void recordCheckIn(
|
||||
String player,
|
||||
@@ -87,19 +80,11 @@ public class QuestTracker {
|
||||
public QuestTracker(Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.storage = new QuestStorage(
|
||||
plugin.getDataFolder(), plugin);
|
||||
plugin.getDataFolder());
|
||||
|
||||
loadAllQuests();
|
||||
}
|
||||
|
||||
// ========== 重载任务配置 ==========
|
||||
public void reload() {
|
||||
questCache.clear();
|
||||
loadAllQuests();
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 任务配置已重载");
|
||||
}
|
||||
|
||||
public void debugPlayer(String player) {
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] === "
|
||||
@@ -236,27 +221,14 @@ public class QuestTracker {
|
||||
"下界", "末地"
|
||||
};
|
||||
|
||||
// ===== 结构映射(PaperMC 1.21.4 实际结构 key)=====
|
||||
// ===== 结构映射 =====
|
||||
private static final Map<String, String>
|
||||
STRUCTURE_CATEGORY =
|
||||
new HashMap<>();
|
||||
static {
|
||||
// 主世界结构
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:village_plains",
|
||||
"村庄");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:village_desert",
|
||||
"村庄");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:village_savanna",
|
||||
"村庄");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:village_snowy",
|
||||
"村庄");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:village_taiga",
|
||||
"村庄");
|
||||
"minecraft:village", "村庄");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:desert_pyramid",
|
||||
"沙漠");
|
||||
@@ -271,39 +243,24 @@ public class QuestTracker {
|
||||
"minecraft:mansion", "森林");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:pillager_outpost",
|
||||
"掠夺者前哨站");
|
||||
"平原");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:mineshaft", "地下");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:mineshaft_mesa",
|
||||
"地下");
|
||||
// 要塞是独立的探索结构(通往末地的传送门所在地)
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:stronghold",
|
||||
"末地要塞");
|
||||
// 远古城市是结构,应分类为"远古城市"而非"地下"
|
||||
"minecraft:stronghold", "地下");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ancient_city",
|
||||
"远古城市");
|
||||
"地下");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:trail_ruins",
|
||||
"远古遗迹");
|
||||
"平原");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:trial_chambers",
|
||||
"试炼密室");
|
||||
"地下");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:monument", "海洋");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ocean_ruin_cold",
|
||||
"海洋");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ocean_ruin_warm",
|
||||
"海洋");
|
||||
"minecraft:ocean_ruin", "海洋");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:shipwreck", "海洋");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:shipwreck_beached",
|
||||
"海洋");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:buried_treasure",
|
||||
"海洋");
|
||||
@@ -311,23 +268,14 @@ public class QuestTracker {
|
||||
"minecraft:ruined_portal",
|
||||
"平原");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ruined_portal_desert",
|
||||
"沙漠");
|
||||
"minecraft:fossil", "平原");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ruined_portal_jungle",
|
||||
"森林");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ruined_portal_mountain",
|
||||
"山地");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ruined_portal_ocean",
|
||||
"海洋");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ruined_portal_swamp",
|
||||
"沼泽");
|
||||
"minecraft:ancient_city",
|
||||
"地下");
|
||||
// 下界结构
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:fortress", "下界");
|
||||
"minecraft:nether_fortress",
|
||||
"下界");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:bastion_remnant",
|
||||
"下界");
|
||||
@@ -335,11 +283,8 @@ public class QuestTracker {
|
||||
"minecraft:nether_fossil",
|
||||
"下界");
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:ruined_portal_nether",
|
||||
"minecraft:basalt_pillars",
|
||||
"下界");
|
||||
// 末地结构
|
||||
STRUCTURE_CATEGORY.put(
|
||||
"minecraft:end_city", "末地");
|
||||
}
|
||||
|
||||
// 所有群系分类的条件关键词映射
|
||||
@@ -367,40 +312,6 @@ public class QuestTracker {
|
||||
CATEGORY_KEYWORDS.put("沙滩", "石岸");
|
||||
CATEGORY_KEYWORDS.put("海岸", "石岸");
|
||||
|
||||
// ===== 结构名称关键词映射 =====
|
||||
// 主世界结构
|
||||
CATEGORY_KEYWORDS.put("村庄", "村庄");
|
||||
CATEGORY_KEYWORDS.put("沙漠神殿", "沙漠");
|
||||
CATEGORY_KEYWORDS.put("丛林神庙", "森林");
|
||||
CATEGORY_KEYWORDS.put("沼泽小屋", "沼泽");
|
||||
CATEGORY_KEYWORDS.put("雪屋", "雪原");
|
||||
CATEGORY_KEYWORDS.put("林地府邸", "森林");
|
||||
CATEGORY_KEYWORDS.put("掠夺者前哨站", "平原");
|
||||
CATEGORY_KEYWORDS.put("废弃矿井", "地下");
|
||||
CATEGORY_KEYWORDS.put("要塞", "末地要塞");
|
||||
CATEGORY_KEYWORDS.put("末地要塞", "末地要塞");
|
||||
CATEGORY_KEYWORDS.put("远古城市", "远古城市");
|
||||
CATEGORY_KEYWORDS.put("古迹废墟", "地下");
|
||||
CATEGORY_KEYWORDS.put("试炼密室", "地下");
|
||||
CATEGORY_KEYWORDS.put("海底废墟", "海洋");
|
||||
CATEGORY_KEYWORDS.put("沉船", "海洋");
|
||||
CATEGORY_KEYWORDS.put("埋藏的宝箱", "海洋");
|
||||
CATEGORY_KEYWORDS.put("废弃传送门", "主世界");
|
||||
CATEGORY_KEYWORDS.put("化石", "主世界");
|
||||
|
||||
// 下界结构
|
||||
CATEGORY_KEYWORDS.put("下界要塞", "下界");
|
||||
CATEGORY_KEYWORDS.put("猪灵堡垒", "下界");
|
||||
CATEGORY_KEYWORDS.put("玄武岩结构", "下界");
|
||||
|
||||
// 末地结构
|
||||
CATEGORY_KEYWORDS.put("末地城", "末地");
|
||||
CATEGORY_KEYWORDS.put("末地船", "末地");
|
||||
|
||||
// 下界相关别名
|
||||
CATEGORY_KEYWORDS.put("地狱要塞", "下界");
|
||||
CATEGORY_KEYWORDS.put("下界堡垒", "下界");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -456,223 +367,6 @@ public class QuestTracker {
|
||||
return "主世界";
|
||||
}
|
||||
|
||||
// ========== 结构检测 ==========
|
||||
|
||||
/**
|
||||
* 检测指定位置是否存在自然生成的结构
|
||||
* 返回结构分类(如"村庄"、"沙漠"等),未找到返回null
|
||||
* 使用 PaperMC World.hasStructureAt() + Registry.STRUCTURE API
|
||||
*/
|
||||
private String detectStructureAt(
|
||||
String worldName, double x,
|
||||
double y, double z) {
|
||||
try {
|
||||
World w = Bukkit.getWorld(worldName);
|
||||
if (w == null) {
|
||||
plugin.getLogger().warning(
|
||||
"[QuestTracker] 结构检测: 世界 '"
|
||||
+ worldName + "' 不存在");
|
||||
return null;
|
||||
}
|
||||
|
||||
int bx = (int) Math.floor(x);
|
||||
int by = (int) Math.floor(y);
|
||||
int bz = (int) Math.floor(z);
|
||||
|
||||
// 首次调用时打印所有注册表结构键
|
||||
if (!loggedStructureRegistry) {
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] === 结构注册表诊断 ===");
|
||||
int count = 0;
|
||||
for (Structure s : Registry.STRUCTURE) {
|
||||
NamespacedKey key =
|
||||
Registry.STRUCTURE.getKey(s);
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 注册表结构 #"
|
||||
+ count + ": " + key);
|
||||
count++;
|
||||
}
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 注册表共 "
|
||||
+ count + " 个结构");
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] === 诊断结束 ===");
|
||||
loggedStructureRegistry = true;
|
||||
}
|
||||
|
||||
// 第1步: 精确位置检查
|
||||
io.papermc.paper.math.Position exactPos =
|
||||
io.papermc.paper.math.Position.block(
|
||||
bx, by, bz);
|
||||
for (Structure structure : Registry.STRUCTURE) {
|
||||
boolean hasAt =
|
||||
w.hasStructureAt(exactPos, structure);
|
||||
if (hasAt) {
|
||||
NamespacedKey key =
|
||||
Registry.STRUCTURE
|
||||
.getKey(structure);
|
||||
String keyStr = (key != null)
|
||||
? key.toString() : "unknown";
|
||||
String cat =
|
||||
STRUCTURE_CATEGORY.get(keyStr);
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 结构匹配(精确): "
|
||||
+ keyStr + " -> category="
|
||||
+ (cat != null
|
||||
? cat : "未映射"));
|
||||
if (cat != null) return cat;
|
||||
}
|
||||
}
|
||||
|
||||
// 第2步: Y轴偏移检查 (-5 到 +10)
|
||||
for (int dy = -5; dy <= 10; dy++) {
|
||||
if (dy == 0) continue;
|
||||
int testY = by + dy;
|
||||
io.papermc.paper.math.Position testPos =
|
||||
io.papermc.paper.math.Position.block(
|
||||
bx, testY, bz);
|
||||
for (Structure structure
|
||||
: Registry.STRUCTURE) {
|
||||
boolean hasAt = w.hasStructureAt(
|
||||
testPos, structure);
|
||||
if (hasAt) {
|
||||
NamespacedKey key =
|
||||
Registry.STRUCTURE
|
||||
.getKey(structure);
|
||||
String keyStr = (key != null)
|
||||
? key.toString() : "unknown";
|
||||
String cat =
|
||||
STRUCTURE_CATEGORY
|
||||
.get(keyStr);
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 结构匹配(Y偏移"
|
||||
+ dy + "): "
|
||||
+ keyStr
|
||||
+ " -> category="
|
||||
+ (cat != null
|
||||
? cat : "未映射"));
|
||||
if (cat != null) return cat;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 第3步: 水平偏移检查 (±1格)
|
||||
for (int dx = -1; dx <= 1; dx++) {
|
||||
for (int dz = -1; dz <= 1; dz++) {
|
||||
if (dx == 0 && dz == 0) continue;
|
||||
io.papermc.paper.math.Position offsetPos =
|
||||
io.papermc.paper.math.Position
|
||||
.block(bx + dx, by,
|
||||
bz + dz);
|
||||
for (Structure structure
|
||||
: Registry.STRUCTURE) {
|
||||
boolean hasAt = w.hasStructureAt(
|
||||
offsetPos, structure);
|
||||
if (hasAt) {
|
||||
NamespacedKey key =
|
||||
Registry.STRUCTURE
|
||||
.getKey(
|
||||
structure);
|
||||
String keyStr = (key != null)
|
||||
? key.toString()
|
||||
: "unknown";
|
||||
String cat =
|
||||
STRUCTURE_CATEGORY
|
||||
.get(keyStr);
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 结构匹配(偏移"
|
||||
+ dx + ","
|
||||
+ dz + "): "
|
||||
+ keyStr
|
||||
+ " -> category="
|
||||
+ (cat != null
|
||||
? cat
|
||||
: "未映射"));
|
||||
if (cat != null) return cat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 所有位置检查完毕, "
|
||||
+ "未匹配任何结构 (pos="
|
||||
+ bx + "," + by + "," + bz
|
||||
+ ")");
|
||||
} catch (Exception ex) {
|
||||
plugin.getLogger().warning(
|
||||
"[QuestTracker] 结构检测异常: "
|
||||
+ ex.getClass().getSimpleName()
|
||||
+ ": " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将结构中文名映射到对应的大类
|
||||
* 用于匹配任务条件中的结构名
|
||||
*/
|
||||
private String mapStructureCategory(
|
||||
String structureName) {
|
||||
if (structureName == null) return "";
|
||||
|
||||
// 主世界结构
|
||||
if (structureName.contains("村庄"))
|
||||
return "村庄";
|
||||
if (structureName.contains("沙漠神殿"))
|
||||
return "沙漠";
|
||||
if (structureName.contains("丛林神庙") || structureName.contains("丛林神殿"))
|
||||
return "森林";
|
||||
if (structureName.contains("沼泽小屋"))
|
||||
return "沼泽";
|
||||
if (structureName.contains("雪屋") || structureName.contains("冰屋"))
|
||||
return "雪原";
|
||||
if (structureName.contains("林地府邸"))
|
||||
return "森林";
|
||||
if (structureName.contains("掠夺者前哨站"))
|
||||
return "掠夺者前哨站";
|
||||
if (structureName.contains("废弃矿井") || structureName.contains("恶地废弃矿井"))
|
||||
return "地下";
|
||||
// 要塞是独立的探索结构
|
||||
if (structureName.contains("要塞"))
|
||||
return "末地要塞";
|
||||
// 远古城市是结构,应分类为"远古城市"
|
||||
if (structureName.contains("远古城市"))
|
||||
return "远古城市";
|
||||
if (structureName.contains("远古遗迹") || structureName.contains("古迹废墟"))
|
||||
return "远古遗迹";
|
||||
if (structureName.contains("试炼密室"))
|
||||
return "试炼密室";
|
||||
if (structureName.contains("海底神殿") || structureName.contains("海洋神殿"))
|
||||
return "海洋";
|
||||
if (structureName.contains("海底废墟") || structureName.contains("冻洋废墟") || structureName.contains("暖洋废墟"))
|
||||
return "海洋";
|
||||
if (structureName.contains("沉船"))
|
||||
return "海洋";
|
||||
if (structureName.contains("埋藏的宝箱") || structureName.contains("埋藏的宝藏"))
|
||||
return "海洋";
|
||||
if (structureName.contains("废弃传送门"))
|
||||
return "平原";
|
||||
if (structureName.contains("化石"))
|
||||
return "主世界";
|
||||
|
||||
// 下界结构
|
||||
if (structureName.contains("下界要塞"))
|
||||
return "下界";
|
||||
if (structureName.contains("猪灵堡垒") || structureName.contains("堡垒遗迹"))
|
||||
return "下界";
|
||||
if (structureName.contains("玄武岩结构") || structureName.contains("下界化石"))
|
||||
return "下界";
|
||||
|
||||
// 末地结构
|
||||
if (structureName.contains("末地城"))
|
||||
return "末地";
|
||||
if (structureName.contains("末地船"))
|
||||
return "末地";
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
// ========== 解析为区块 ==========
|
||||
@@ -1213,6 +907,15 @@ public class QuestTracker {
|
||||
}
|
||||
|
||||
Main main = (Main) plugin;
|
||||
// ★ 读取配置:economy = Vault,bonds = 债券(默认)
|
||||
boolean useEconomy = "economy".equalsIgnoreCase(
|
||||
main.getConfigMgr().rewardChannel);
|
||||
|
||||
// Vault 经济引用(仅 useEconomy 时使用)
|
||||
net.milkbowl.vault.economy.Economy econ = null;
|
||||
if (useEconomy) {
|
||||
econ = main.getEconomy();
|
||||
}
|
||||
|
||||
int sentCount = 0;
|
||||
|
||||
@@ -1238,17 +941,53 @@ public class QuestTracker {
|
||||
// 尝试识别经济金额
|
||||
double amt = extractEconomyAmount(part);
|
||||
if (amt > 0) {
|
||||
// Economy已移除,全部转为债券发放
|
||||
// —— 债券 ——
|
||||
int bondAmt = (int) Math.round(amt);
|
||||
BondManager bonds = main.getBonds();
|
||||
if (bonds != null) {
|
||||
int before = bonds.getBonds(player.getName());
|
||||
bonds.addBonds(player.getName(), bondAmt, "quest_reward", qf.displayName, "任务系统", "任务奖励:" + qf.displayName);
|
||||
int after = bonds.getBonds(player.getName());
|
||||
player.sendMessage("§a§l[任务奖励] §f" + part + " §7(债券: §e" + before + " §7→ §a" + after + "§7)");
|
||||
// ★ 根据配置分发
|
||||
if (useEconomy && econ != null) {
|
||||
// —— Vault 经济 ——
|
||||
double before =
|
||||
econ.getBalance(player);
|
||||
econ.depositPlayer(player, amt);
|
||||
double after =
|
||||
econ.getBalance(player);
|
||||
player.sendMessage(
|
||||
"§a§l[任务奖励] §f" + part
|
||||
+ " §7(余额: §e"
|
||||
+ String.format("%.2f", before)
|
||||
+ " §7→ §a"
|
||||
+ String.format("%.2f", after)
|
||||
+ "§7)");
|
||||
if (plugin instanceof Main) {
|
||||
((Main) plugin).getCommission()
|
||||
.payCommission(
|
||||
player.getName(), amt);
|
||||
}
|
||||
} else {
|
||||
player.sendMessage("§c债券系统不可用");
|
||||
// —— 债券(默认) ——
|
||||
int bondAmt =
|
||||
(int) Math.round(amt);
|
||||
BondManager bonds = main.getBonds();
|
||||
if (bonds != null) {
|
||||
int before = bonds.getBonds(
|
||||
player.getName());
|
||||
bonds.addBonds(
|
||||
player.getName(),
|
||||
bondAmt,
|
||||
"quest_reward",
|
||||
qf.displayName,
|
||||
"任务系统",
|
||||
"任务奖励:" + qf.displayName);
|
||||
int after = bonds.getBonds(
|
||||
player.getName());
|
||||
player.sendMessage(
|
||||
"§a§l[任务奖励] §f" + part
|
||||
+ " §7(债券: §e"
|
||||
+ before
|
||||
+ " §7→ §a"
|
||||
+ after + "§7)");
|
||||
} else {
|
||||
player.sendMessage(
|
||||
"§c债券系统不可用");
|
||||
}
|
||||
}
|
||||
sentCount++;
|
||||
continue;
|
||||
@@ -1929,24 +1668,6 @@ public class QuestTracker {
|
||||
+ total + "/1";
|
||||
}
|
||||
|
||||
// 打卡结构条件:打卡X个结构名 → 显示进度
|
||||
if (key.contains("打卡")
|
||||
&& !key.contains("群系")
|
||||
&& !key.contains("风景")) {
|
||||
String target = extractBiome(key);
|
||||
if (!target.isEmpty()) {
|
||||
int needed = parseNumberFromText(key);
|
||||
if (needed <= 0) needed = 1;
|
||||
int cur = getCounter(player,
|
||||
"biomecat_" + target);
|
||||
boolean done = cur >= needed;
|
||||
return (done ? "§a" : "§7")
|
||||
+ "打卡 " + target + ": §e"
|
||||
+ Math.min(cur, needed)
|
||||
+ "/" + needed;
|
||||
}
|
||||
}
|
||||
|
||||
if (key.contains("完成")
|
||||
&& key.contains("阶段")) {
|
||||
boolean done = checkStageDependency(
|
||||
@@ -2018,19 +1739,11 @@ public class QuestTracker {
|
||||
Object val =
|
||||
getDb().getField(
|
||||
player,
|
||||
"login_streak");
|
||||
if (val == null || (val instanceof Number && ((Number) val).intValue() == 0)) {
|
||||
// 兼容旧数据:如果没有login_streak则读取checkin_streak
|
||||
val = getDb().getField(
|
||||
player,
|
||||
"checkin_streak");
|
||||
}
|
||||
"checkin_streak");
|
||||
int streak = val instanceof Number
|
||||
? ((Number) val).intValue()
|
||||
: 0;
|
||||
boolean done = streak >= needed;
|
||||
return (done ? "§a" : "§7")
|
||||
+ "连续登录: §e"
|
||||
return "§7连续登录: §e"
|
||||
+ streak + "/" + needed + "天";
|
||||
}
|
||||
|
||||
@@ -2174,12 +1887,7 @@ public class QuestTracker {
|
||||
if (needed <= 0) needed = 1;
|
||||
int streak = getIntField(
|
||||
player,
|
||||
"login_streak");
|
||||
if (streak == 0) {
|
||||
streak = getIntField(
|
||||
player,
|
||||
"checkin_streak");
|
||||
}
|
||||
"checkin_streak");
|
||||
if (streak == 0) {
|
||||
streak = getIntField(
|
||||
player, "streak");
|
||||
@@ -2189,9 +1897,7 @@ public class QuestTracker {
|
||||
player,
|
||||
"total_checkin_days");
|
||||
}
|
||||
boolean done = streak >= needed;
|
||||
return (done ? "§a" : "§7")
|
||||
+ "近7天登录: §e"
|
||||
return "§7近7天登录: §e"
|
||||
+ streak + "/"
|
||||
+ needed + "天";
|
||||
}
|
||||
@@ -2473,57 +2179,22 @@ public class QuestTracker {
|
||||
String category =
|
||||
mapBiomeCategory(
|
||||
rawBiomeKey, worldName);
|
||||
|
||||
// ===== 结构检测优先于Y轴"地下"判断 =====
|
||||
// 要塞等结构可生成在任何主世界群系下,不应固定为"地下"
|
||||
// 使用 PaperMC API 检测玩家所在位置的结构
|
||||
String structureCat = null;
|
||||
// 结构检测(覆盖纯生物群系分类)
|
||||
// 地下检测:Y低于表面则归类为地下
|
||||
// 覆盖废弃矿井/试炼密室/要塞/远古城市等
|
||||
try {
|
||||
structureCat = detectStructureAt(
|
||||
worldName, x, y, z);
|
||||
} catch (Exception ignored) {}
|
||||
|
||||
if (structureCat != null
|
||||
&& !structureCat.isEmpty()
|
||||
&& !"地下".equals(structureCat)) {
|
||||
// 结构检测成功且非"地下"类,结构分类优先
|
||||
category = structureCat;
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 结构覆盖: "
|
||||
+ category
|
||||
+ " (结构: "
|
||||
+ structureCat + ")");
|
||||
} else {
|
||||
// 未检测到有效结构,使用Y轴检测判定地下
|
||||
// 地下检测:Y低于表面则归类为地下
|
||||
try {
|
||||
org.bukkit.World uw =
|
||||
Bukkit.getWorld(worldName);
|
||||
if (uw != null) {
|
||||
int surfaceY = uw
|
||||
.getHighestBlockYAt(
|
||||
(int) Math.floor(x),
|
||||
(int) Math.floor(z));
|
||||
if (y < surfaceY - 8) {
|
||||
category = "地下";
|
||||
}
|
||||
org.bukkit.World uw =
|
||||
Bukkit.getWorld(worldName);
|
||||
if (uw != null) {
|
||||
int surfaceY = uw
|
||||
.getHighestBlockYAt(
|
||||
(int) Math.floor(x),
|
||||
(int) Math.floor(z));
|
||||
if (y < surfaceY - 8) {
|
||||
category = "地下";
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
if (structureCat != null
|
||||
&& !structureCat.isEmpty()) {
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 结构"
|
||||
+ structureCat
|
||||
+ " 使用Y轴判定");
|
||||
} else {
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 未检测到结构: world="
|
||||
+ worldName + ", pos="
|
||||
+ String.format(
|
||||
"%.0f,%.0f,%.0f",
|
||||
x, y, z));
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
|
||||
|
||||
// 记录总打卡
|
||||
@@ -2532,11 +2203,10 @@ public class QuestTracker {
|
||||
setCounter(player, "biome_ALL",
|
||||
allCur + 1);
|
||||
|
||||
// 记录分类打卡(群系,排除结构避免重复计数)
|
||||
// 记录分类打卡
|
||||
if (!category.isEmpty()
|
||||
&& !"主世界".equals(category)
|
||||
&& (structureCat == null
|
||||
|| !category.equals(structureCat))) {
|
||||
&& !"主世界"
|
||||
.equals(category)) {
|
||||
String catKey =
|
||||
"biomecat_" + category;
|
||||
int catCur = getCounter(
|
||||
@@ -2545,17 +2215,6 @@ public class QuestTracker {
|
||||
catCur + 1);
|
||||
}
|
||||
|
||||
// 记录结构打卡(结构单独计数)
|
||||
if (structureCat != null
|
||||
&& !structureCat.isEmpty()) {
|
||||
String structKey =
|
||||
"biomecat_" + structureCat;
|
||||
int structCur = getCounter(
|
||||
player, structKey);
|
||||
setCounter(player, structKey,
|
||||
structCur + 1);
|
||||
}
|
||||
|
||||
// 记录具体群系
|
||||
String bioKey =
|
||||
"biome_" + rawBiomeKey;
|
||||
@@ -2585,61 +2244,12 @@ public class QuestTracker {
|
||||
String condKey =
|
||||
stripOptional(cond);
|
||||
if (!condKey
|
||||
.contains("打卡"))
|
||||
continue;
|
||||
// 支持群系和结构两种打卡条件
|
||||
boolean isBiomeCond =
|
||||
condKey.contains("群系")
|
||||
|| condKey
|
||||
.contains("风景点");
|
||||
boolean isStructureCond =
|
||||
condKey.contains("结构")
|
||||
|| condKey
|
||||
.contains("村庄")
|
||||
|| condKey
|
||||
.contains("神殿")
|
||||
|| condKey
|
||||
.contains("神庙")
|
||||
|| condKey
|
||||
.contains("小屋")
|
||||
|| condKey
|
||||
.contains("雪屋")
|
||||
|| condKey
|
||||
.contains("府邸")
|
||||
|| condKey
|
||||
.contains("前哨站")
|
||||
|| condKey
|
||||
.contains("矿井")
|
||||
|| condKey
|
||||
.contains("要塞")
|
||||
|| condKey
|
||||
.contains("城市")
|
||||
|| condKey
|
||||
.contains("废墟")
|
||||
|| condKey
|
||||
.contains("密室")
|
||||
|| condKey
|
||||
.contains("沉船")
|
||||
|| condKey
|
||||
.contains("宝箱")
|
||||
|| condKey
|
||||
.contains("传送门")
|
||||
|| condKey
|
||||
.contains("化石")
|
||||
|| condKey
|
||||
.contains("堡垒");
|
||||
if (!isBiomeCond
|
||||
&& !isStructureCond)
|
||||
.contains("打卡")
|
||||
|| !condKey
|
||||
.contains("群系"))
|
||||
continue;
|
||||
String target =
|
||||
extractBiome(condKey);
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] 条件匹配: condKey=\""
|
||||
+ condKey + "\", target=\""
|
||||
+ target + "\", category=\""
|
||||
+ category + "\", isBiomeCond="
|
||||
+ isBiomeCond + ", isStructureCond="
|
||||
+ isStructureCond);
|
||||
boolean hit = false;
|
||||
if ("ALL".equals(target)
|
||||
|| "风景点"
|
||||
@@ -2686,7 +2296,6 @@ public class QuestTracker {
|
||||
// ===== 获取群系和分类 =====
|
||||
String biome = "minecraft:plains";
|
||||
String category = "平原";
|
||||
String structureCat = null;
|
||||
try {
|
||||
org.bukkit.World w =
|
||||
Bukkit.getWorld(worldName);
|
||||
@@ -2703,29 +2312,12 @@ public class QuestTracker {
|
||||
category = mapBiomeCategory(
|
||||
biome, worldName);
|
||||
|
||||
// ===== 结构检测优先于Y轴"地下"判断 =====
|
||||
structureCat =
|
||||
detectStructureAt(
|
||||
worldName, x, y, z);
|
||||
plugin.getLogger().info(
|
||||
"[QuestTracker] checkInAtPosition 结构检测: "
|
||||
+ structureCat + " at "
|
||||
+ String.format("%.0f,%.0f,%.0f", x, y, z));
|
||||
|
||||
if (structureCat != null
|
||||
&& !structureCat.isEmpty()
|
||||
&& !"地下".equals(structureCat)) {
|
||||
// 结构检测成功且非"地下"类,结构分类优先
|
||||
category = structureCat;
|
||||
} else {
|
||||
// 未检测到有效结构,使用Y轴检测判定地下
|
||||
int surfaceY = w
|
||||
.getHighestBlockYAt(
|
||||
(int) Math.floor(x),
|
||||
(int) Math.floor(z));
|
||||
if (y < surfaceY - 8) {
|
||||
category = "地下";
|
||||
}
|
||||
int surfaceY = w
|
||||
.getHighestBlockYAt(
|
||||
(int) Math.floor(x),
|
||||
(int) Math.floor(z));
|
||||
if (y < surfaceY - 8) {
|
||||
category = "地下";
|
||||
}
|
||||
|
||||
if ("下界".equals(category)
|
||||
@@ -2770,9 +2362,6 @@ public class QuestTracker {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("§a打卡成功!群系: §e")
|
||||
.append(category);
|
||||
if (structureCat != null && !structureCat.isEmpty()) {
|
||||
sb.append("\n§a结构: §e").append(structureCat);
|
||||
}
|
||||
if (!matched.isEmpty()) {
|
||||
sb.append("\n§a完成任务条件:");
|
||||
for (String m : matched) {
|
||||
@@ -3027,19 +2616,9 @@ public class QuestTracker {
|
||||
* "打卡任意海洋群系" → "海洋"
|
||||
* "打卡任意群系" → "ALL"
|
||||
* "打卡任意风景点" → ""
|
||||
* "打卡村庄" → "村庄"
|
||||
* "打卡沙漠神殿" → "沙漠"
|
||||
*/
|
||||
private String extractBiome(String text) {
|
||||
if (text == null) return "";
|
||||
|
||||
// 优先匹配结构名称(更具体)
|
||||
String structureResult =
|
||||
mapStructureCategory(text);
|
||||
if (!structureResult.isEmpty()) {
|
||||
return structureResult;
|
||||
}
|
||||
|
||||
// 逐个匹配分类关键词
|
||||
for (Map.Entry<String, String> en
|
||||
: CATEGORY_KEYWORDS.entrySet()) {
|
||||
@@ -3187,43 +2766,22 @@ public class QuestTracker {
|
||||
|
||||
if (key.contains("打卡")
|
||||
&& (key.contains("群系")
|
||||
|| key.contains("风景点")
|
||||
|| key.contains("结构")
|
||||
|| key.contains("村庄")
|
||||
|| key.contains("神殿")
|
||||
|| key.contains("神庙")
|
||||
|| key.contains("小屋")
|
||||
|| key.contains("雪屋")
|
||||
|| key.contains("府邸")
|
||||
|| key.contains("前哨站")
|
||||
|| key.contains("矿井")
|
||||
|| key.contains("要塞")
|
||||
|| key.contains("城市")
|
||||
|| key.contains("废墟")
|
||||
|| key.contains("密室")
|
||||
|| key.contains("废墟")
|
||||
|| key.contains("沉船")
|
||||
|| key.contains("宝箱")
|
||||
|| key.contains("传送门")
|
||||
|| key.contains("化石")
|
||||
|| key.contains("堡垒"))) {
|
||||
|| key.contains("风景点"))) {
|
||||
String biome =
|
||||
extractBiome(key);
|
||||
int needed = parseNumberFromText(key);
|
||||
if (needed <= 0) needed = 1;
|
||||
if ("ALL".equals(biome)) {
|
||||
int total = getCounter(
|
||||
player, "biome_ALL");
|
||||
return total >= needed;
|
||||
return total >= 1;
|
||||
}
|
||||
if (!biome.isEmpty()) {
|
||||
int catCount = getCounter(
|
||||
player,
|
||||
"biomecat_" + biome);
|
||||
return catCount >= needed;
|
||||
return catCount >= 1;
|
||||
}
|
||||
return getCounter(
|
||||
player, "biome_ALL") >= needed;
|
||||
player, "biome_ALL") >= 1;
|
||||
}
|
||||
|
||||
if (key.contains("完成")
|
||||
@@ -3283,12 +2841,7 @@ public class QuestTracker {
|
||||
Object val =
|
||||
getDb().getField(
|
||||
player,
|
||||
"login_streak");
|
||||
if (val == null || (val instanceof Number && ((Number) val).intValue() == 0)) {
|
||||
val = getDb().getField(
|
||||
player,
|
||||
"checkin_streak");
|
||||
}
|
||||
"checkin_streak");
|
||||
int streak = val instanceof Number
|
||||
? ((Number) val).intValue()
|
||||
: 0;
|
||||
@@ -3377,12 +2930,7 @@ public class QuestTracker {
|
||||
if (needed <= 0) needed = 1;
|
||||
int streak = getIntField(
|
||||
player,
|
||||
"login_streak");
|
||||
if (streak == 0) {
|
||||
streak = getIntField(
|
||||
player,
|
||||
"checkin_streak");
|
||||
}
|
||||
"checkin_streak");
|
||||
if (streak == 0) {
|
||||
streak = getIntField(
|
||||
player, "streak");
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -80,11 +80,11 @@ public class RadioDownloadListener
|
||||
log.warning("[Radio] "
|
||||
+ p.getName()
|
||||
+ " ✗ 拒绝了资源包");
|
||||
/* log.warning("[Radio] "
|
||||
log.warning("[Radio] "
|
||||
+ "可能原因: "
|
||||
+ "1.客户端设置禁用资源包"
|
||||
+ " 2.已缓存拒绝记录"
|
||||
+ " 3.SSL证书不匹配");*/
|
||||
+ " 3.SSL证书不匹配");
|
||||
handleFailure(p, uuid);
|
||||
break;
|
||||
|
||||
@@ -92,12 +92,12 @@ public class RadioDownloadListener
|
||||
log.warning("[Radio] "
|
||||
+ p.getName()
|
||||
+ " ✗ 下载失败");
|
||||
/* log.warning("[Radio] "
|
||||
log.warning("[Radio] "
|
||||
+ "可能原因: "
|
||||
+ "1.URL无法访问"
|
||||
+ " 2.SSL证书错误"
|
||||
+ " 3.网络超时"
|
||||
+ " 4.文件不存在(404)");*/
|
||||
+ " 4.文件不存在(404)");
|
||||
handleFailure(p, uuid);
|
||||
break;
|
||||
|
||||
@@ -124,8 +124,9 @@ public class RadioDownloadListener
|
||||
+ "玩家继续留在服务器");
|
||||
// 不踢出,只记录熔断,玩家正常游玩
|
||||
p.sendMessage("§e§l[Radio] 资源包加载失败"
|
||||
+ ",已取消下载资源包,部分画面音频可能出现问题"
|
||||
+ "\n§d§l若想继续下载,请退出重进。若持续失败,请上报管理员");
|
||||
+ ",跳过资源包,部分画面、音频可能出现问题"
|
||||
+ "\n§d§l若想继续下载,请退出重进" +
|
||||
"\n§b§l若持续失败,请重启客户端");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
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 {
|
||||
|
||||
@@ -22,250 +17,232 @@ public class RiskControlManager {
|
||||
private final Map<String, Integer> failAttempts =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
// 每个玩家名 -> 封禁到期时间戳(毫秒)
|
||||
private final Map<String, Long> banUntil =
|
||||
// 每个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 剩余尝试次数
|
||||
*/
|
||||
private int getMaxFailAttempts() {
|
||||
return plugin.getConfig2().passwordFailThreshold;
|
||||
public int recordFailAttempt(String playerName) {
|
||||
int current = failAttempts
|
||||
.getOrDefault(playerName, 0) + 1;
|
||||
failAttempts.put(playerName, current);
|
||||
return Math.max(0, MAX_FAIL_ATTEMPTS - current);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取封禁时长(毫秒)(从配置读取)
|
||||
* 重置指定玩家的失败计数(登录成功时调用)
|
||||
*/
|
||||
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);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取玩家剩余封禁时间(秒),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);
|
||||
resetFailAttempts(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);
|
||||
}
|
||||
verifyCooldown.entrySet().removeIf(
|
||||
e -> now - e.getValue() > COOLDOWN_MS * 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有封禁记录(调试/管理用)
|
||||
*/
|
||||
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();
|
||||
ipSuspicious.clear();
|
||||
verifyCooldown.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@ public class ShopItem {
|
||||
private final String id;
|
||||
private final String displayName;
|
||||
private final Material material;
|
||||
private int buyPrice;
|
||||
private int sellPrice;
|
||||
private final int buyPrice;
|
||||
private final 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,
|
||||
@@ -42,8 +43,6 @@ public class ShopItem {
|
||||
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
@@ -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
@@ -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
@@ -3,18 +3,14 @@ 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;
|
||||
|
||||
/**
|
||||
* 玩家正版/离线身份验证管理器
|
||||
*
|
||||
* 核心逻辑:在离线模式(online-mode=false)服务器中,所有玩家UUID都是离线格式,
|
||||
* 无法通过UUID区分正版/盗版。因此:
|
||||
* - UUID非离线格式 → 服务器在线模式,正版玩家 → autoLogin
|
||||
* - UUID离线格式 → 一律视为非正版,需手动登录或OAuth验证
|
||||
* - 正版玩家通过 /mslogin OAuth验证后,由Main.addVerifiedPremiumPlayer()标记,
|
||||
* 在onJoin检查点0直接autoLogin,不经过此验证器
|
||||
*/
|
||||
public class VerificationManager {
|
||||
|
||||
private final Main plugin;
|
||||
@@ -33,11 +29,6 @@ public class VerificationManager {
|
||||
return Bukkit.getServer().getOnlineMode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步验证玩家身份
|
||||
* 注意:此方法仅用于判断UUID格式,不执行自动登录
|
||||
* 自动登录由onJoin中的检查点0/1/2控制
|
||||
*/
|
||||
public void verifyPremiumAsync(Player player,
|
||||
Consumer<Boolean> callback) {
|
||||
Thread t = new Thread(() -> doVerify(player, callback),
|
||||
@@ -59,35 +50,49 @@ public class VerificationManager {
|
||||
"[Sdf1_login] 当前UUID: " + uuid);
|
||||
|
||||
try {
|
||||
java.util.UUID offlineUuid = java.util.UUID.nameUUIDFromBytes(
|
||||
UUID offlineUuid = UUID.nameUUIDFromBytes(
|
||||
("OfflinePlayer:" + name)
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
.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: " + offlineUuid);
|
||||
plugin.getLogger().info(
|
||||
"[Sdf1_login] UUID匹配离线格式: "
|
||||
+ isOfflineUuid);
|
||||
|
||||
if (!isOfflineUuid) {
|
||||
// UUID不是离线格式 → 服务器在线模式的正版玩家
|
||||
plugin.getLogger().info(
|
||||
"[Sdf1_login] 结论: 正版玩家(非离线UUID)");
|
||||
"[Sdf1_login] 结论: 正版玩家");
|
||||
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 或 /正版 命令验证)");
|
||||
"[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);
|
||||
@@ -99,4 +104,55 @@ public class VerificationManager {
|
||||
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
@@ -10,7 +10,7 @@ import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
public class WelcomeManager {
|
||||
//
|
||||
|
||||
private final Main plugin;
|
||||
private final Random random = new Random();
|
||||
private final List<String> registerMsgs =
|
||||
@@ -41,7 +41,7 @@ public class WelcomeManager {
|
||||
String section = "";
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
if (line.startsWith(UnicodeChars.BOM_TEXT))
|
||||
if (line.startsWith("\uFEFF"))
|
||||
line = line.substring(1);
|
||||
String t = line.trim();
|
||||
if (t.isEmpty()
|
||||
@@ -135,7 +135,7 @@ public class WelcomeManager {
|
||||
}
|
||||
|
||||
private String colorize(String msg) {
|
||||
return msg.replace("&", "§");
|
||||
return msg.replace("&", "\u00a7");
|
||||
}
|
||||
|
||||
private void writeDefault(File f) {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
{
|
||||
"OP白名单": "服务器的好管家",
|
||||
"为什么要OP白名单": {
|
||||
"根因有几点": {
|
||||
"第一点": "已有OP乱给权限防不住",
|
||||
"第二点": "有人利用服务器漏洞拿到OP权限",
|
||||
"第三点": "不信任OP",
|
||||
"第四点": "想临时给某个玩家一个op,原生不支持。必须到期手动/deop user"
|
||||
}
|
||||
},
|
||||
"我们做了什么": {
|
||||
"第一层": "临时授权,允许你给OP设置到期时间,到期自动撤销",
|
||||
"第二层": "接管原生OP名单,不在白名单的一律撤销+报警"
|
||||
},
|
||||
"你需要做什么": [
|
||||
"共3步",
|
||||
"第一步:安装sdf1_login插件",
|
||||
"第二步改这个文件",
|
||||
"第三步按参考格式或后台指令添加授权",
|
||||
"第四步:玩家自动获得授权,整点自动生效(手动改本文件时,会在15、30、45、0秒的整点自动增量热重载)"
|
||||
],
|
||||
"----": "----",
|
||||
"启用状态": true,
|
||||
"无固定期限授权列表": [],
|
||||
"有固定期限授权列表": {},
|
||||
"非法持有报警信息": "§8[§cOP白名单§8] §f{user} §7不持有授权却持有 OP,已于 §f{time} §7自动撤销 §8| §8[OPWL] §f{user} §7held OP illegally, revoked at §f{time}",
|
||||
"默认时长": "24h",
|
||||
"时长支持格式": [
|
||||
"可以是中文口语:一个小时",
|
||||
"可以是英文one hour",
|
||||
"可以是标准写法:24H",
|
||||
"格式很宽松,只要是标准json字符串格式就行。至于你怎么写,插件会解析"
|
||||
],
|
||||
"报警模板变量": {
|
||||
"{user}": "非法持有的玩家名(也认 player / 用户 / 玩家 / username)",
|
||||
"{time}": "发现时间(也认 时间 / date / 日期)",
|
||||
"写法": "大小写不敏感,中英文变量名都支持;& 颜色码可用,渲染后自动转成§"
|
||||
},
|
||||
"接管说明": [
|
||||
"本插件【接管原生OP名单】:插件首次加载时,会把当前所有原生OP自动导入「无固定期限授权列表」并写回本文件。",
|
||||
"之后:任何持有OP但不在白名单的玩家(不在永久表/ 临时已过期 / 时长无法解析),一律自动撤销OP并按「非法持有报警信息」报警。",
|
||||
"所以以后新增OP请用 /opwl add <玩家>,别用原版 /op;否则会被15秒内的巡检撤掉。",
|
||||
"白名单全部写在本文件里(单文件),没有子目录也没有附属名单文件。"
|
||||
],
|
||||
"以下是模板文件": {
|
||||
"# 启用状态": true,
|
||||
"# 无固定期限授权列表": [
|
||||
"user1",
|
||||
"user2"
|
||||
],
|
||||
"# 有固定期限授权列表": {
|
||||
"user1": "2026-10-06 23:00",
|
||||
"user2": "1小时",
|
||||
"user3": "two hour"
|
||||
},
|
||||
"# 非法持有报警信息": "支持 {user} 与 {time} 变量,中英文写法都认;留空则用内置默认文案",
|
||||
"# 默认时长": "24小时"
|
||||
},
|
||||
"为什么这次选择json": {
|
||||
"根因依旧2点": {
|
||||
"1": "防止非专业人士修改本文件",
|
||||
"2": "使用专业格式,让小白试探着劝退(一旦解析失败,所有玩家OP全部卸载)"
|
||||
}
|
||||
},
|
||||
"指令参数": {
|
||||
"opwl": "帮助菜单",
|
||||
"opwl add user": "添加user用户为无固定期限用户",
|
||||
"opwl addtime user": "按默认时长添加临时授权用户",
|
||||
"opwl addtime user 1h": "给user用户价1小时授权",
|
||||
"opwl removetime user 1h": "给user用户扣1小时授权",
|
||||
"opwl remove user": "移除user的授权",
|
||||
"opwl list user": "获取user的授权状态",
|
||||
"opwl list": "列出OP白名单",
|
||||
"opwl reload": "重载OP白名单",
|
||||
"温馨提示": "opwl命令仅限控台执行,普通用户无权",
|
||||
"加授权完全无感": "因为用户本身没有op时,被授权后,插件立即给予OP并记录授权状态。删除也是。不需要先添加用户在添加授权。"
|
||||
},
|
||||
"安全升级": [
|
||||
"本文件即是配置文件也是说明书。这就意味着,你可以把其它混淆内容一起打包进本json文件,只要保留配置项。其它的你随便删改",
|
||||
"编辑本文件时,如果担心改坏了,直接联网找一个在线json解析器,把本文件扔上去。json的写法是双引号包裹内容,一对双引号就是一个键值对。用花括号做嵌套式。就像本文件的解释说明字段一样"
|
||||
]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
## ----配置区开始----
|
||||
|
||||
| 名字 | 功能说明 | 参数值 |
|
||||
| --- | --- | --- |
|
||||
| 轮播最低间隔 | 最短是多少秒一次(建议阈值60,太低很吵) | 60 |
|
||||
| 轮播最大间隔 | 最长多少秒一次(建议阈值300以内,太长起不到效果) | 180 |
|
||||
| 播报模式 | 是由远到近(即从第一个封禁的玩家开始报到最后一个),还是又近到远(从最新一个被封禁的玩家播报到第一个被封禁的玩家)。此项填0或最大最小间隔都为0表示关闭播报 | 由近到远 |
|
||||
| 播报起点 | 插件安装之前的封禁(历史封禁)不播报。填插件安装日期如2026-08-01,0或留空=自动(取插件数据目录创建时间) | 0 |
|
||||
|
||||
```json
|
||||
{
|
||||
"最小间隔":"",
|
||||
"最大间隔":"",
|
||||
"播报模式":true,
|
||||
"播报起点":"",
|
||||
"解释说明":{
|
||||
"播报模式":"true表示开启播报又近到远,false表示开启播报由远到近。0为关闭",
|
||||
"最小间隔":"最短是多少秒一次(建议阈值60,太低很吵)",
|
||||
"最大间隔":"最长多少秒一次(建议阈值300以内,太长起不到效果)",
|
||||
"播报起点":"插件安装之前的封禁不播报,填如2026-08-01;0或留空=自动"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ----配置区域结束----
|
||||
|
||||
## 功能说明
|
||||
- 此功能为服务器打造一个不可拆解的耻辱台,展示所有被封禁的玩家。json代码块的参数值和md表格是2选1,你可以删了表格,留json则表示用json作为配置值,也可以删了json用表格。小白用户推荐使用md,因为最简单,专业人员推荐使用json,因为最清晰,没有注释(注释是另起一行,不在配置块)。<br>
|
||||
- 同时兼容.json直接作为配置文件
|
||||
@@ -1,30 +0,0 @@
|
||||
### ----配置区域开始----
|
||||
|
||||
| 玩家名字 | 拉黑时长 | 理由 |
|
||||
| --- | --- | --- |
|
||||
|
||||
### ----配置区域结束
|
||||
|
||||
## 软折磨黑名单配置
|
||||
|
||||
功能说明:<br>
|
||||
此功能为软折磨,用于折磨违反规则的玩家。通过`/addblack user time(可选) msg(可选)`添加违规玩家或直接编辑本文件即可。被拉黑的玩家不能消费债券、不能登录PHP后端、不能创建领地,不能成为他人领地的授权玩家。不能破坏、放置方块,不能打开任何容器、不能拾取任何物品、不能与村民交易,没有背包(清空前备份,自动备份跳过该玩家)。能说话但,会被系统加上"---我是罪人user"的签名
|
||||
|
||||
## 示例配置:
|
||||
| 玩家名字 | 拉黑时长 | 理由 |
|
||||
| --- | --- | --- |
|
||||
| steve | 终身 | 违反服务器规则 |
|
||||
| Dream | 2026-10-20 14:30 | 随意殴打他人 |
|
||||
|
||||
## 指令集
|
||||
|
||||
| 前缀 | 参数1 | 参数2 | 参数3 |
|
||||
| --- | --- | ---| --- |
|
||||
| /addblack | user | time | msg |
|
||||
| /removeblack | user | 空 | 空 |
|
||||
| /addblack | steve | 2026-10-20 10:00 | 违反服务器规则 |
|
||||
| /addblack | Dream | 0 | 空 |
|
||||
| /removeblack | Notch | 空 | 空 |
|
||||
|
||||
- 备注:0表示永久拉黑,填入日期+时间则表示遵循到期时间。填入日期则表示以当天23:59:59为界限。填相对时长(30分 / 2小时 / 3天 / 1周)= 从拉黑那一刻起算,到期自动解除并自动恢复背包与权限<br>
|
||||
- 生效规则: 定时,每分钟的第0秒、5秒、10秒...以此类推、55秒定时增量重载,删了5秒后立即恢复背包和各项权限,加了5秒后立即生效
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"开关": true,
|
||||
"是否合并两个箱子": 1,
|
||||
"解释说明": {
|
||||
"开关": "开启状态下,将自动接管手持精准采集斧头的、被授权「容器管理」权限的领地在拆箱动作;关闭则拆箱完全交还原版散落",
|
||||
"是否合并两个箱子": "即2秒内连续拆箱时,是否将两个箱子的物品合二为一个打包箱(不看塞满,只看时间窗口达标即合并)",
|
||||
"热重载": "玩家每次拆箱时增量热重载:文件 mtime+size 没变就不重新解析,变化才按新值生效",
|
||||
"支持参数": "同时支持填 true 为开 / false 为关;数字 0 为关 / 1 为开"
|
||||
}
|
||||
}
|
||||
@@ -1,458 +0,0 @@
|
||||
# 非法域名后缀列表
|
||||
# 每行一个后缀,支持以 * 开头表示匹配所有子域名
|
||||
# 修改此文件后无需重启,插件会在每次检测时重新加载
|
||||
# 默认包含常见非法注册域名后缀
|
||||
|
||||
com
|
||||
cn
|
||||
net
|
||||
org
|
||||
io
|
||||
xyz
|
||||
top
|
||||
club
|
||||
site
|
||||
online
|
||||
store
|
||||
tech
|
||||
info
|
||||
biz
|
||||
ru
|
||||
tk
|
||||
ml
|
||||
ga
|
||||
cf
|
||||
cc
|
||||
ws
|
||||
tv
|
||||
link
|
||||
click
|
||||
date
|
||||
vip
|
||||
party
|
||||
fun
|
||||
zone
|
||||
space
|
||||
name
|
||||
pro
|
||||
aero
|
||||
coop
|
||||
museum
|
||||
jobs
|
||||
travel
|
||||
asia
|
||||
cat
|
||||
edu
|
||||
gov
|
||||
int
|
||||
mil
|
||||
ac
|
||||
ad
|
||||
ae
|
||||
af
|
||||
ag
|
||||
ai
|
||||
al
|
||||
am
|
||||
ao
|
||||
aq
|
||||
ar
|
||||
as
|
||||
at
|
||||
au
|
||||
aw
|
||||
ax
|
||||
az
|
||||
ba
|
||||
bb
|
||||
bd
|
||||
be
|
||||
bf
|
||||
bg
|
||||
bh
|
||||
bi
|
||||
bj
|
||||
bm
|
||||
bn
|
||||
bo
|
||||
br
|
||||
bs
|
||||
bt
|
||||
bw
|
||||
by
|
||||
bz
|
||||
ca
|
||||
cd
|
||||
cg
|
||||
ch
|
||||
ci
|
||||
ck
|
||||
cl
|
||||
cm
|
||||
cr
|
||||
cu
|
||||
cv
|
||||
cy
|
||||
cz
|
||||
de
|
||||
dj
|
||||
dk
|
||||
dm
|
||||
do
|
||||
dz
|
||||
ec
|
||||
ee
|
||||
eg
|
||||
er
|
||||
es
|
||||
et
|
||||
eu
|
||||
fi
|
||||
fj
|
||||
fk
|
||||
fm
|
||||
fo
|
||||
fr
|
||||
gd
|
||||
ge
|
||||
gf
|
||||
gg
|
||||
gh
|
||||
gi
|
||||
gl
|
||||
gm
|
||||
gn
|
||||
gp
|
||||
gq
|
||||
gr
|
||||
gs
|
||||
gt
|
||||
gu
|
||||
gw
|
||||
gy
|
||||
hk
|
||||
hn
|
||||
hr
|
||||
ht
|
||||
hu
|
||||
id
|
||||
ie
|
||||
il
|
||||
im
|
||||
in
|
||||
iq
|
||||
ir
|
||||
is
|
||||
it
|
||||
je
|
||||
jm
|
||||
jo
|
||||
jp
|
||||
ke
|
||||
kg
|
||||
kh
|
||||
ki
|
||||
km
|
||||
kn
|
||||
kp
|
||||
kr
|
||||
kw
|
||||
ky
|
||||
kz
|
||||
la
|
||||
lb
|
||||
lc
|
||||
li
|
||||
lk
|
||||
lr
|
||||
ls
|
||||
lt
|
||||
lu
|
||||
lv
|
||||
ly
|
||||
ma
|
||||
mc
|
||||
md
|
||||
me
|
||||
mg
|
||||
mh
|
||||
mk
|
||||
mm
|
||||
mn
|
||||
mo
|
||||
mp
|
||||
mq
|
||||
mr
|
||||
ms
|
||||
mt
|
||||
mu
|
||||
mv
|
||||
mw
|
||||
mx
|
||||
my
|
||||
mz
|
||||
na
|
||||
nc
|
||||
ne
|
||||
nf
|
||||
ng
|
||||
ni
|
||||
nl
|
||||
no
|
||||
np
|
||||
nr
|
||||
nu
|
||||
nz
|
||||
om
|
||||
pa
|
||||
pe
|
||||
pf
|
||||
pg
|
||||
ph
|
||||
pk
|
||||
pl
|
||||
pm
|
||||
pn
|
||||
pr
|
||||
ps
|
||||
pt
|
||||
pw
|
||||
py
|
||||
qa
|
||||
re
|
||||
ro
|
||||
rs
|
||||
rw
|
||||
sa
|
||||
sb
|
||||
sc
|
||||
sd
|
||||
se
|
||||
sg
|
||||
sh
|
||||
si
|
||||
sk
|
||||
sl
|
||||
sm
|
||||
sn
|
||||
so
|
||||
sr
|
||||
ss
|
||||
st
|
||||
sv
|
||||
sx
|
||||
sy
|
||||
sz
|
||||
tc
|
||||
td
|
||||
tf
|
||||
tg
|
||||
th
|
||||
tj
|
||||
tl
|
||||
tm
|
||||
tn
|
||||
to
|
||||
tt
|
||||
tw
|
||||
tz
|
||||
ug
|
||||
uk
|
||||
um
|
||||
us
|
||||
uy
|
||||
uz
|
||||
va
|
||||
vc
|
||||
ve
|
||||
vg
|
||||
vi
|
||||
vn
|
||||
vu
|
||||
wf
|
||||
ye
|
||||
yt
|
||||
za
|
||||
zm
|
||||
zw
|
||||
ac.uk
|
||||
co.uk
|
||||
org.uk
|
||||
gov.uk
|
||||
edu.au
|
||||
ac.nz
|
||||
co.nz
|
||||
org.nz
|
||||
gov.au
|
||||
co.jp
|
||||
ne.jp
|
||||
or.jp
|
||||
ed.jp
|
||||
ac.jp
|
||||
go.jp
|
||||
co.kr
|
||||
or.kr
|
||||
re.kr
|
||||
go.kr
|
||||
ac.kr
|
||||
ne.kr
|
||||
com.cn
|
||||
net.cn
|
||||
org.cn
|
||||
gov.cn
|
||||
edu.cn
|
||||
ac.cn
|
||||
mil.cn
|
||||
com.hk
|
||||
net.hk
|
||||
org.hk
|
||||
idv.hk
|
||||
com.tw
|
||||
net.tw
|
||||
org.tw
|
||||
gov.tw
|
||||
edu.tw
|
||||
com.sg
|
||||
net.sg
|
||||
org.sg
|
||||
gov.sg
|
||||
edu.sg
|
||||
per.sg
|
||||
com.my
|
||||
net.my
|
||||
org.my
|
||||
gov.my
|
||||
edu.my
|
||||
per.my
|
||||
com.vn
|
||||
net.vn
|
||||
org.vn
|
||||
gov.vn
|
||||
edu.vn
|
||||
ac.vn
|
||||
com.ph
|
||||
net.ph
|
||||
org.ph
|
||||
gov.ph
|
||||
edu.ph
|
||||
com.pk
|
||||
net.pk
|
||||
org.pk
|
||||
gov.pk
|
||||
edu.pk
|
||||
com.bd
|
||||
net.bd
|
||||
org.bd
|
||||
gov.bd
|
||||
edu.bd
|
||||
com.lk
|
||||
net.lk
|
||||
gov.lk
|
||||
ac.lk
|
||||
com.np
|
||||
net.np
|
||||
org.np
|
||||
gov.np
|
||||
com.mm
|
||||
com.kh
|
||||
com.kg
|
||||
com.kz
|
||||
com.ge
|
||||
com.am
|
||||
com.az
|
||||
com.by
|
||||
com.km
|
||||
com.sc
|
||||
co.id
|
||||
web.id
|
||||
co.th
|
||||
or.th
|
||||
ac.th
|
||||
go.th
|
||||
net.th
|
||||
com.mu
|
||||
org.mu
|
||||
co.za
|
||||
org.za
|
||||
web.za
|
||||
com.eg
|
||||
net.eg
|
||||
com.ma
|
||||
net.ma
|
||||
org.ma
|
||||
co.ke
|
||||
or.ke
|
||||
ac.ke
|
||||
co.tz
|
||||
or.tz
|
||||
ac.tz
|
||||
co.ug
|
||||
or.ug
|
||||
com.sn
|
||||
net.sn
|
||||
org.sn
|
||||
co.rw
|
||||
ac.rw
|
||||
com.cm
|
||||
co.bi
|
||||
co.dz
|
||||
com.dj
|
||||
co.so
|
||||
co.tg
|
||||
co.np
|
||||
ac.cy
|
||||
com.cy
|
||||
co.il
|
||||
org.il
|
||||
net.il
|
||||
ac.il
|
||||
gov.il
|
||||
co.ma
|
||||
com.kw
|
||||
net.kw
|
||||
org.kw
|
||||
com.om
|
||||
net.om
|
||||
com.ps
|
||||
com.sy
|
||||
com.jo
|
||||
net.jo
|
||||
com.lb
|
||||
net.lb
|
||||
com.tn
|
||||
com.tj
|
||||
com.tf
|
||||
app
|
||||
dev
|
||||
page
|
||||
shop
|
||||
work
|
||||
website
|
||||
wiki
|
||||
blog
|
||||
live
|
||||
best
|
||||
cool
|
||||
red
|
||||
icu
|
||||
one
|
||||
ltd
|
||||
# ===== 中文域名(真实可注册,按最后一段匹配)=====
|
||||
# ICANN 官方中文 TLD
|
||||
中国
|
||||
网络
|
||||
公司
|
||||
我爱你
|
||||
# .cn 注册局中文通用域名
|
||||
集团
|
||||
商城
|
||||
网店
|
||||
在线
|
||||
游戏
|
||||
网址
|
||||
网站
|
||||
商店
|
||||
企业
|
||||
娱乐
|
||||
移动
|
||||
中文网
|
||||
@@ -1,16 +0,0 @@
|
||||
## ----配置区域开始----
|
||||
|
||||
| 颜色代码 |
|
||||
| --- |
|
||||
| red |
|
||||
| aqua |
|
||||
| |
|
||||
|
||||
## ----配置区域结束----
|
||||
|
||||
## json解码规则说明
|
||||
|
||||
### 一、怎么触发?
|
||||
使用`json`指令触发,或在原版`title、tellraw`产生报错时,插件介入。
|
||||
### 二、颜色代码怎么配置?
|
||||
支持填入`16进制`颜色代码(比如#000000)、或者颜色`英文名`(比如red)、也可以是rgb。比如(R0 G0 B0)
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"对话留档":{
|
||||
"怎么写":"键是提问,值是回答",
|
||||
"谁来写":"每次提问/控场自动写",
|
||||
"请求失败":"响应原文落盘"
|
||||
},
|
||||
"问":"答",
|
||||
"自动":"答"
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
{
|
||||
"人设部分": {
|
||||
"服务器名字": "",
|
||||
"助理名字": "",
|
||||
"写法": "1行1个"
|
||||
},
|
||||
"配置部分": {
|
||||
"1": {
|
||||
"模型配置": {
|
||||
"内置供应商": {
|
||||
"供应商名字": "",
|
||||
"apikey": "",
|
||||
"max_token": "",
|
||||
"可用模型": [],
|
||||
"默认使用": ""
|
||||
},
|
||||
"自定义供应商": {
|
||||
"baseurl": "",
|
||||
"apikey": "",
|
||||
"max_token": "",
|
||||
"可用模型": [],
|
||||
"默认使用": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"2": {
|
||||
"默认上下文长度": "200000",
|
||||
"发言间隔": {
|
||||
"最短": "",
|
||||
"最长": "",
|
||||
"注释": "单位分钟",
|
||||
"自动发言": true
|
||||
},
|
||||
"自动补齐": {
|
||||
"开关": true,
|
||||
"备注": "如果你的厂商"
|
||||
},
|
||||
"互动指标": {
|
||||
"指标": 1,
|
||||
"说明": "指标为在线玩家数量,当在线玩家大于等于指标才会触发自动互动。手动不受此影响。此字段为强制值,若你填写的值≤1,则代码仍按1执行。≥1时以此字段配置值为基准"
|
||||
},
|
||||
"黑名单": [
|
||||
"说明: 一行一个,用双引号包裹。每行末尾加英文逗号,最后一行不加",
|
||||
"命中黑名单时AI直接返回「我无法就此问题,展开讨论和回答」,不告知玩家命中,掐断API请求"
|
||||
]
|
||||
}
|
||||
},
|
||||
"填写规范": {
|
||||
"自定义": {
|
||||
"baseurl": "填写厂家给你的地址,比如https://example.com/v1",
|
||||
"apikey": "填厂家开放平台的key,比如sk-example",
|
||||
"可用模型": "填厂家给的模型名字,比如example",
|
||||
"max_token": "上下文长度,不填则使用默认20万上下文长度",
|
||||
"默认使用": "默认使用哪个模型,此配置仅影响自动模式下,默认发起请求的模型。手动@不受此影响"
|
||||
},
|
||||
"内置供应商": {
|
||||
"供应商名字": "一层一层填,比如mimo/按量计费,deepseek等",
|
||||
"apikey": "填厂家开放平台的key,比如sk-example",
|
||||
"可用模型": "填厂家给的模型名字,比如example",
|
||||
"max_token": "上下文长度,不填则使用默认20万上下文长度",
|
||||
"默认使用": "默认使用哪个模型,此配置仅影响自动模式下,默认发起请求的模型。手动@不受此影响"
|
||||
}
|
||||
},
|
||||
"配置填写示例": {
|
||||
"自定义供应商": {
|
||||
"baseurl": "https://example.com/v1",
|
||||
"apikey": "sk-example",
|
||||
"max_token": "1000000",
|
||||
"可用模型": [
|
||||
"example"
|
||||
]
|
||||
},
|
||||
"内置供应商": {
|
||||
"供应商名字": "mimo/token-plan",
|
||||
"apikey": "sk-example",
|
||||
"可用模型": [
|
||||
"mimo-v2.6-flash",
|
||||
"mimo-v2.6-pro"
|
||||
]
|
||||
},
|
||||
"内置供应商1": {
|
||||
"供应商名字": "deepseek",
|
||||
"apikey": "sk-example",
|
||||
"可用模型": [
|
||||
"deepseek-flash",
|
||||
"deepseek-v4-pro"
|
||||
]
|
||||
},
|
||||
"内置供应商3": {
|
||||
"供应商名字": "讯飞/讯飞星辰maas/标准",
|
||||
"apikey": "sk-example",
|
||||
"可用模型": [
|
||||
"spakr-x2.6",
|
||||
"xopglm5"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
{
|
||||
"openai协议": "内置供应商",
|
||||
"添加方法": [
|
||||
"键值对格式,键是供应商名字,值是请求地址",
|
||||
"如果供应商有区分按量计费、token-plan则用一堆花括号即可。可参考mimo的写法",
|
||||
"如果要备注,就用花括号展开,比如向Agnes、opencode一样",
|
||||
"额外说明:本文件默认会从插件内置的服务器定期拉取更新。"
|
||||
],
|
||||
"国产": {
|
||||
"mimo": {
|
||||
"按量计费": "https://api.xiaomimimo.com/v1",
|
||||
"token-plan": "https://token-plan-cn.xiaomimimo.com/v1",
|
||||
"批量推理": "https://batch-api-cn.xiaomimimo.com/v1"
|
||||
},
|
||||
"deepseek": "https://api.deepseek.com",
|
||||
"kimi": "https://api.moonshot.cn/v1",
|
||||
"智谱GLM": "https://open.bigmodel.cn/api/paas/v4",
|
||||
"通义千问": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"百度AIStudio": "https://aistudio.baidu.com/llm/lmapi/v3",
|
||||
"MiniMax": "https://api.minimax.cn/v1",
|
||||
"阶跃星辰": {
|
||||
"标准": "https://api.stepfun.com/v1",
|
||||
"step-plan": "https://api.stepfun.com/step_plan/v1"
|
||||
},
|
||||
"零一万物": "https://api.lingyiwanwu.com/v1",
|
||||
"百川": "https://api.baichuan-ai.com/v1",
|
||||
"美团": "https://api.longcat.chat/openai",
|
||||
"抖音云(豆包/火山)": "https://ark.cn-beijing.volces.com/api/v3",
|
||||
"讯飞": {
|
||||
"讯飞星火": "https://spark-api-open.xf-yun.com/v1",
|
||||
"讯飞星辰MaaS": {
|
||||
"标准": "https://maas-api.cn-huabei-1.xf-yun.com/v2",
|
||||
"Coding Plan": "https://maas-coding-api.cn-huabei-1.xf-yun.com/v2",
|
||||
"Token Plan": "https://maas-token-api.cn-huabei-1.xf-yun.com/v2"
|
||||
}
|
||||
},
|
||||
"腾讯云": {
|
||||
"Token Plan": "https://api.lkeap.cloud.tencent.com/plan/v3",
|
||||
"Coding Plan": "https://api.lkeap.cloud.tencent.com/coding/v3",
|
||||
"TokenHub(广州)": "https://tokenhub.tencentmaas.com",
|
||||
"TokenHub(新加坡)": "https://tokenhub-intl.tencentmaas.com"
|
||||
},
|
||||
"硅基流动": "https://api.siliconflow.cn/v1",
|
||||
"书生端砚": "https://discovery-api.intern-ai.org.cn/v1"
|
||||
},
|
||||
"非国产": {
|
||||
"OpenAI": "https://api.openai.com/v1",
|
||||
"Claude(Anthropic)": "https://api.anthropic.com/v1/",
|
||||
"推特(xAI Grok)": "https://api.x.ai/v1",
|
||||
"Gemini": "https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
"英伟达": "https://integrate.api.nvidia.com/v1",
|
||||
"agnes": {
|
||||
"国际版": "https://apihub.agnes-ai.com/v1",
|
||||
"中国版": "https://apihub.agnes-ai.cn/v1",
|
||||
"说明": "中国版和国际版互通key,但账号、token-plan不互通"
|
||||
},
|
||||
"opencode": {
|
||||
"zen": "https://opencode.ai/zen/v1",
|
||||
"go": "https://opencode.ai/zen/go/v1",
|
||||
"说明": "opencode zen可以通过9router或其它工具反代opencode cli终端免费使用。但不推荐,额度特别低。作者实测:反代出来跑了50万~100万左右就429限流。"
|
||||
},
|
||||
"OpenRouter": "https://openrouter.ai/api/v1"
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
# 此文件填写的模型将被正是运用请求
|
||||
# 以#开头的表示注释,会被忽略
|
||||
# models=name,这个=就是模型的简称,比如你可以配置deepseek=大肥鱼,后续用户@大肥鱼 xx,就会自动向deepseek的模型发起请求。可以是一个厂家,也可以是单独的模型
|
||||
# 以下是示例配置
|
||||
# 大肥鱼=deepseek-flash
|
||||
# 这里大肥鱼=deepseek-flash,意思是@大肥鱼时,向deepseek-flash模型发起请求,而deepseek-v4-pro不受影响,因为没命中这条规则
|
||||
# 噶啦吗=GLM
|
||||
# 这里噶啦吗=glm,意思是@噶啦吗时,向配置的GLM系列模型发起请求。所有glm系列厂家都会影响,不管是glm5.3、glm5.2等
|
||||
# 不区分大小写
|
||||
|
||||
|
||||
+33
-145
@@ -1,5 +1,5 @@
|
||||
name: Sdf1_login
|
||||
version: 3.30
|
||||
version: 1.0
|
||||
main: Sdf1_login.Main
|
||||
api-version: '1.21'
|
||||
commands:
|
||||
@@ -26,79 +26,61 @@ commands:
|
||||
usage: /玩家信息
|
||||
改密码:
|
||||
description: 修改密码(中文)
|
||||
usage: /改密码 <旧密码> <新密码>
|
||||
usage: /改密码 <旧密码> <新密码> <确认新密码>
|
||||
设置邮箱:
|
||||
description: 设置邮箱(中文)
|
||||
usage: /设置邮箱 <邮箱地址>
|
||||
# 撤销:
|
||||
# description: 撤销操作(中文)
|
||||
# usage: /撤销
|
||||
# 删除:
|
||||
# description: 删除玩家(中文)
|
||||
# usage: /删除 <玩家> <密码>
|
||||
撤销:
|
||||
description: 撤销操作(中文)
|
||||
usage: /撤销
|
||||
删除:
|
||||
description: 删除玩家(中文)
|
||||
usage: /删除 <玩家> <密码>
|
||||
找回密码:
|
||||
description: 找回密码(中文)
|
||||
usage: /找回密码
|
||||
签到:
|
||||
description: 每日签到(中文)
|
||||
usage: /签到
|
||||
#oa:
|
||||
# description: 申请删除账号
|
||||
# usage: /oa [玩家名]
|
||||
# 删除账号:
|
||||
# description: 申请删除账号(中文)
|
||||
# usage: /删除账号 [玩家名]
|
||||
# 通过:
|
||||
# description: 批准OA请求(中文)
|
||||
# usage: /通过 <编号>
|
||||
# 拒绝:
|
||||
# description: 拒绝OA请求(中文)
|
||||
# usage: /拒绝 <编号> [理由]
|
||||
# accept:
|
||||
# description: 批准OA请求
|
||||
# usage: /accept <编号>
|
||||
# deny:
|
||||
# description: 拒绝OA请求
|
||||
# usage: /deny <编号> [理由]
|
||||
#oa:
|
||||
# description: 申请删除账号
|
||||
# usage: /oa [玩家名]
|
||||
删除账号:
|
||||
description: 申请删除账号(中文)
|
||||
usage: /删除账号 [玩家名]
|
||||
通过:
|
||||
description: 批准OA请求(中文)
|
||||
usage: /通过 <编号>
|
||||
拒绝:
|
||||
description: 拒绝OA请求(中文)
|
||||
usage: /拒绝 <编号> [理由]
|
||||
accept:
|
||||
description: 批准OA请求
|
||||
usage: /accept <编号>
|
||||
deny:
|
||||
description: 拒绝OA请求
|
||||
usage: /deny <编号> [理由]
|
||||
email:
|
||||
description: 绑定邮箱
|
||||
usage: /email <邮箱>
|
||||
2fa:
|
||||
description: 二次验证(TOTP)绑定
|
||||
usage: /2fa add|code <6位>|remove <6位>
|
||||
绑定:
|
||||
description: 绑定邮箱(中文)
|
||||
usage: /绑定 <邮箱>
|
||||
绑定邮箱:
|
||||
description: 绑定邮箱
|
||||
usage: /绑定邮箱
|
||||
webbind:
|
||||
description: 网页邮箱绑定批准/拒绝
|
||||
usage: /webbind <approve|reject> <id>
|
||||
chat:
|
||||
description: 聊天过滤管理
|
||||
usage: /chat
|
||||
recycle:
|
||||
description: 打开垃圾回收站
|
||||
usage: /recycle
|
||||
公告板:
|
||||
description: 刷新/查看服务器公告计分板
|
||||
usage: /公告板
|
||||
垃圾清理:
|
||||
description: 手动清理掉落物
|
||||
usage: /垃圾清理
|
||||
垃圾抢救:
|
||||
description: 紧急取消本轮垃圾站清理(物品误投时抢救)
|
||||
usage: /垃圾抢救
|
||||
addblack:
|
||||
description: 拉黑玩家(禁止建领地/破坏/兑换码/网页端,债券冻结,背包备份清空)
|
||||
usage: /addblack <玩家名> [时长] [理由]
|
||||
removeblack:
|
||||
description: 解除拉黑
|
||||
usage: /removeblack <玩家名>
|
||||
# menu:
|
||||
# description: 雪球菜单开关控制
|
||||
# usage: /menu <开/关>
|
||||
menu:
|
||||
description: 雪球菜单开关控制
|
||||
usage: /menu <开/关>
|
||||
pvp :
|
||||
description: PVP榜单
|
||||
usage: /pvp
|
||||
@@ -111,106 +93,12 @@ commands:
|
||||
shop :
|
||||
description: 游戏商人
|
||||
usage: /shop
|
||||
shopbuy :
|
||||
description: 二手交易商店
|
||||
usage: /shopbuy
|
||||
商店:
|
||||
description: 打开商店
|
||||
usage: /商店
|
||||
# testorder:
|
||||
# description: 测试订单中心
|
||||
# usage: /testorder
|
||||
#testorder:
|
||||
# description: 测试订单中心
|
||||
# usage: /testorder
|
||||
protect:
|
||||
description: 区域保护
|
||||
usage: /protect
|
||||
landrec:
|
||||
description: 领地记录系统(回声碎片发放)
|
||||
usage: /landrec give [玩家]
|
||||
传送:
|
||||
description: 传送至领地
|
||||
usage: /传送 <领地名>
|
||||
update:
|
||||
description: 检查所有插件更新(集群控制)
|
||||
usage: /update
|
||||
web:
|
||||
description: 生成Web端登录令牌
|
||||
usage: /web
|
||||
控制台:
|
||||
description: 生成Web端登录令牌(中文版)
|
||||
usage: /控制台
|
||||
mslogin:
|
||||
description: 正版登录(Microsoft OAuth)
|
||||
usage: /mslogin
|
||||
正版:
|
||||
description: 正版登录(中文版)
|
||||
usage: /正版
|
||||
tpa:
|
||||
description: tp传送指令
|
||||
usage: /tpa
|
||||
tpaccept:
|
||||
description: 接受传送
|
||||
usage: /tpaccept
|
||||
tpdeny:
|
||||
description: 拒绝传送
|
||||
usage: /tpdeny
|
||||
tpauto:
|
||||
description: 自动接收传送
|
||||
usage: /tpauto
|
||||
tpacancel:
|
||||
description: 取消传送请求
|
||||
usage: /tpacancel
|
||||
tpaall:
|
||||
description: 请求传送所有人
|
||||
usage: /tpaall
|
||||
tpahere:
|
||||
description: 请求传送ta到自己身边
|
||||
usage: /tpahere
|
||||
sethome:
|
||||
description: 设置一个家
|
||||
usage: /sethome <名称>
|
||||
delhome:
|
||||
description: 删除一个家
|
||||
usage: /delhome <名称>
|
||||
home:
|
||||
description: 传送到家
|
||||
usage: /home [名称]
|
||||
homes:
|
||||
description: 查看所有家
|
||||
usage: /homes
|
||||
group:
|
||||
description: 用户组管理
|
||||
usage: /group <buy|renew|info> [组名]
|
||||
back:
|
||||
description: 快速返回最近记录点
|
||||
usage: /back
|
||||
|
||||
tempban:
|
||||
description: 临时封禁玩家
|
||||
usage: /tempban <玩家名/IP> <时长> [理由]
|
||||
tempbanip:
|
||||
description: 临时封禁IP或玩家
|
||||
usage: /tempbanip <IP/玩家名> <时长> [理由]
|
||||
banip:
|
||||
description: 永久封禁IP或玩家
|
||||
usage: /banip <IP/玩家名> [永久] [理由]
|
||||
whois:
|
||||
description: 查询玩家信息
|
||||
usage: /whois [玩家名]
|
||||
who:
|
||||
description: 查看在线玩家列表
|
||||
usage: /who
|
||||
banget:
|
||||
description: 点名查询封禁(全量,含插件安装前的历史封禁)
|
||||
usage: /banget [user|ip] <玩家名或IP>
|
||||
清空队列:
|
||||
description: 清空DB队列中未回应的web同步任务(管理员)
|
||||
usage: /清空队列
|
||||
cleartake:
|
||||
description: 清空DB队列中未回应的web同步任务(管理员)
|
||||
usage: /cleartake
|
||||
json:
|
||||
description: JSON消息构造器(tellraw/大标题/小标题/actionbar+颜色,需OP以上权限)
|
||||
usage: /json
|
||||
credits:
|
||||
description: 信誉积分管理(上报/审批/记录/规则)
|
||||
usage: /credits [上报|审批|记录|规则] [参数]
|
||||
usage: /protect
|
||||
@@ -1,45 +0,0 @@
|
||||
|
||||
## ----配置区域开始----
|
||||
| 项目 | 解释 | 值 |
|
||||
| :---: | :---: | :---: |
|
||||
| 可上架的商品数量 | 每位普通玩家能上架多少个物品。数值填写为纯数字。用户组另算 | 3 |
|
||||
| 最低售价 | 普通玩家上架物品时,最低能买多少钱,数值填写为纯数字。用户组另算 | 0 |
|
||||
| 手续费 | 二手交易物品的抽成比例,上限10。支持三种写法:小数 `0.05`=5%、`0.005`=5‰;带单位 `5%`、`5‰`。 | 0.05 |
|
||||
| 手续费支付方 | 谁出手续费,买方出即订单加费(奸商模式)或卖方出(到手后的价格已包含完税) | 卖方出 |
|
||||
| 默认管理员面板密码 | 面板后台的验证凭据 | qweasd |
|
||||
| 谁是管理员 | 插件全局tag管理员就填tag,OP则填写OP,指定玩家则填写player+名字 | tag |
|
||||
|
||||
```json
|
||||
{
|
||||
"默认下架理由":"一行一个",
|
||||
"理由列表":[
|
||||
"商品包含违禁品",
|
||||
"商品售价非法",
|
||||
"商品描述与实物不符",
|
||||
"疑似诈骗或诱导交易",
|
||||
"商品利用漏洞复制",
|
||||
"恶意炒作价格",
|
||||
"占位刷屏恶意上架",
|
||||
"违反二手交易规则其他条款"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## ----配置区域结束---
|
||||
|
||||
## 二手交易商店说明书
|
||||
- 什么是二手商店: 二手商店的定位就类似于闲鱼这类二手交易平台。货品挂在平台内,平台平台进行担保<br>
|
||||
- 什么不能卖: sdf1_game宝箱的物品不能卖,本插件的SN物品不能卖<br>
|
||||
- 怎么配置: 只需要改对应的值,比如可上架的商品数量,只要改数字,比如100,1000就行<br>
|
||||
- 手续费怎么算:
|
||||
|
||||
| 交易金额 | 谁出 | 手续费多少钱 | 卖家到手多少钱 | 买家支付多少钱 | 计算公式 |
|
||||
| :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 100债券 | 卖家出 | 5% | 95 | 100 | 100(原价)×5%(0.05)=5(手续费金额),100(原价)-5(手续费)=95(卖家到手) |
|
||||
| 100债券 | 买家出 | 5% | 100 | 105 | 100(原价)×5%(0.05)=5(手续费金额),100(原价)+5(手续费)=105(买家实付金额) |
|
||||
| 100债券 | 卖家出 | 5‰(=0.005) | 99 | 100 | 100(原价)×5‰=0.5,手续费四舍五入=1,100-1=99(卖家到手);千分位适合低抽成场景 |
|
||||
| 100债券 | 买家出 | 5‰ | 100 | 101 | 100(原价)×5‰(手续费)=0.5(4舍5入),100(原价)+1(手续费取整)=101 |
|
||||
|
||||
- 改完多久生效: 自动增量重载,平时安安静静,有人下单了,发布新商品了自动拉起增量重载,有变更就对齐。每个整点(每分钟的第0秒、15秒、30秒、45秒)自动拉起增量热重载,有变更就对齐,没有则跳过<br>
|
||||
- 默认理由最大支持8个,第9号位为返回。<br>
|
||||
- 谁是管理员这一栏填单格式:`player+example`→指定example为管理员,`op`→指定全服OP为管理员,`tag`→指定插件的tag玩家是管理员
|
||||
@@ -1,65 +0,0 @@
|
||||
## ----公告区域开始----
|
||||
```json
|
||||
{
|
||||
"开关状态":true,
|
||||
"翻页时间":15,
|
||||
"1": {
|
||||
"msg": "草原探险服务器欢迎您",
|
||||
"color": "green"
|
||||
},
|
||||
"2": {
|
||||
"msg": "服务器官方群:981954292",
|
||||
"color": "aqua"
|
||||
},
|
||||
"3":{
|
||||
"msg":"最低支持版本:1.21.11",
|
||||
"color":"gold"
|
||||
},
|
||||
"4":{
|
||||
"msg":"最大支持版本:26.x",
|
||||
"color":"#FF55FF"
|
||||
},
|
||||
"5":{
|
||||
"msg":"服务器ip: mc2.ypshidifu.cn",
|
||||
"color":"blue"
|
||||
},
|
||||
"6":{
|
||||
"msg":"端口:30679,Java免输入~"
|
||||
}
|
||||
}
|
||||
```
|
||||
## ----公告区域结束----
|
||||
|
||||
## 公告板使用手册
|
||||
- 插件主导计分板式公告栏,用于记录和公示服务器的基本信息。<br>
|
||||
- 支持填入任意纯文本。<br>
|
||||
- 空白键值自动跳过
|
||||
|
||||
## 公告区参数选项
|
||||
| 键 | 值 | 必填 | 解释 |
|
||||
| --- | --- | --- |--------------------------------------------|
|
||||
| 数字编号 | 花括号 | 必填 | 一条公告的开始 |
|
||||
| msg | 纯文本消息内容 | 必填 | 消息正文 |
|
||||
| color | 颜色英文名或16进制颜色代码,或rgb | 非必填 | 指定颜色,未填写回退MC原版逻辑(继承最近一个color参数,如果都没有就回退白色) |
|
||||
|
||||
## 示例模板
|
||||
|
||||
```json
|
||||
{
|
||||
"1": {
|
||||
"msg": "这是第一条公告",
|
||||
"color": ""
|
||||
},
|
||||
"2": {
|
||||
"msg": "这是第二条公告",
|
||||
"color": "r=0 g=0 b=0"
|
||||
},
|
||||
"3": {
|
||||
"msg": "这是第三条公告",
|
||||
"color": "#000000"
|
||||
},
|
||||
"4": {
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,23 +0,0 @@
|
||||
# 邀好友赢债券活动配置
|
||||
|
||||
## ----配置区开始----
|
||||
| 项目 | 解释 | 值 |
|
||||
| :---: | :---: | :---: |
|
||||
| 邀请人单次奖励 | 邀请人每次成功邀请一位好友后,立即结算获得的债券数量。数值填写为纯数字,单位默认为"个"。适用于"马上邀、马上结账"的场景。 | 10 |
|
||||
| 被邀请人单次奖励 | 被邀请人在注册并首次上线后,立即结算获得的债券数量。数值填写为纯数字,用于吸引新玩家加入。 | 5 |
|
||||
| 单日邀请奖励上限 | 单个邀请人在**一天内**通过邀请好友累计可获得的债券总数上限。达到上限后当日不再发放奖励,次日自动重置。适合控制薅羊毛行为。 | 100 |
|
||||
| 单日邀请翻倍额度 | 拉了多少个人以后,给邀请人的奖励。参数值为:"每邀请X人,奖金翻Y倍" | 每邀请2人,奖金翻1倍 |
|
||||
|
||||
## ----配置区域结束----
|
||||
|
||||
## 邀好友赢债券说明书
|
||||
- 什么是邀好友赢债券:玩家邀请新玩家加入服务器,双方完成任务后分别获得债券奖励,激励玩家拉新。<br>
|
||||
- 三种配置的区别:
|
||||
- **邀请人单次奖励**:每次成功邀请后,邀请人立即获得的债券数,不累积
|
||||
- **被邀请人单次奖励**:被邀请人注册并首次上线后,自己立即获得的债券数
|
||||
- **单日邀请奖励上限**:邀请人一天内累计获得的总奖励上限(仅针对邀请人),达到后当日停止发放,次日重置
|
||||
- 计算公式示例:
|
||||
- 邀请人单次奖励 = 10,单人当天邀请 3 人 → 累计获得 10 × 3 = **30 债券**(未超单日上限)
|
||||
- 邀请人单次奖励 = 10,单人当天邀请 11 人 → 理论应得 10 × 11 = 110,但被单日上限卡住,实际获得 **100 债券**,当日不再发放
|
||||
- 被邀请人单次奖励 = 5,新玩家注册首次上线 → 立即获得 **5 债券**
|
||||
|
||||
+989
@@ -0,0 +1,989 @@
|
||||
Index: .gitattributes
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/.gitattributes b/.gitattributes
|
||||
--- a/.gitattributes (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/.gitattributes (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -1,6 +1,5 @@
|
||||
+*.md text=auto encoding=UTF-8
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
-*.gif binary
|
||||
-*.ico binary
|
||||
-*.bmp binary
|
||||
\ No newline at end of file
|
||||
+*.gif binary
|
||||
\ No newline at end of file
|
||||
Index: src/main/java/Sdf1_login/ConfigManager.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/ConfigManager.java b/src/main/java/Sdf1_login/ConfigManager.java
|
||||
--- a/src/main/java/Sdf1_login/ConfigManager.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/ConfigManager.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -312,6 +312,14 @@
|
||||
requesterPointsReward = parseInt(
|
||||
m.getOrDefault("报单人积分奖励", "10"),
|
||||
10);
|
||||
+ garbageEnabled = Boolean.parseBoolean(
|
||||
+ m.getOrDefault("垃圾站_启用", "true"));
|
||||
+ garbageInterval = parseInt(
|
||||
+ m.getOrDefault("垃圾站_清理间隔秒",
|
||||
+ "300"), 300);
|
||||
+ garbageMaxRounds = parseInt(
|
||||
+ m.getOrDefault("垃圾站_保留轮数",
|
||||
+ "1"), 1);
|
||||
|
||||
|
||||
}
|
||||
@@ -331,12 +339,10 @@
|
||||
L.add("挂机超时秒数=" + afkTimeout);
|
||||
// 垃圾站设置
|
||||
L.add("# ---- 垃圾站 ----");
|
||||
- L.add("垃圾站_启用: "
|
||||
- + garbageEnabled);
|
||||
- L.add("垃圾站_清理间隔秒: "
|
||||
- + garbageInterval);
|
||||
- L.add("垃圾站_保留轮数: "
|
||||
- + garbageMaxRounds);
|
||||
+ L.add("垃圾站_启用=" + garbageEnabled);
|
||||
+ L.add("垃圾站_清理间隔秒=" + garbageInterval);
|
||||
+ L.add("垃圾站_保留轮数=" + garbageMaxRounds);
|
||||
+
|
||||
|
||||
writeLines(file, L);
|
||||
}
|
||||
@@ -364,6 +370,11 @@
|
||||
L.add("基础经济奖励=" + baseEconomyReward);
|
||||
L.add("经济奖励每评分=" + providerEconomyPerScore);
|
||||
L.add("报单人积分奖励=" + requesterPointsReward);
|
||||
+ L.add("# ---- 垃圾站 ----");
|
||||
+ L.add("垃圾站_启用=true");
|
||||
+ L.add("垃圾站_清理间隔秒=300");
|
||||
+ L.add("垃圾站_保留轮数=1");
|
||||
+
|
||||
|
||||
writeLines(f, L);
|
||||
}
|
||||
Index: src/main/java/Sdf1_login/DatabaseManager.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/DatabaseManager.java b/src/main/java/Sdf1_login/DatabaseManager.java
|
||||
--- a/src/main/java/Sdf1_login/DatabaseManager.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/DatabaseManager.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -201,7 +201,18 @@
|
||||
+ "active INTEGER DEFAULT 1,"
|
||||
+ "join_time INTEGER DEFAULT 0"
|
||||
+ ")");
|
||||
-
|
||||
+ // 垃圾回收站物品表
|
||||
+ st.execute("CREATE TABLE IF NOT EXISTS "
|
||||
+ + "items ("
|
||||
+ + "id INTEGER PRIMARY KEY "
|
||||
+ + "AUTOINCREMENT,"
|
||||
+ + "player_name TEXT NOT NULL,"
|
||||
+ + "item_data TEXT DEFAULT '',"
|
||||
+ + "amount INTEGER DEFAULT 1,"
|
||||
+ + "create_time INTEGER DEFAULT 0"
|
||||
+ + ")");
|
||||
+ safeAdd(st, "menu_snowball",
|
||||
+ "INTEGER DEFAULT 1");
|
||||
st.close();
|
||||
logger.info("[Sdf1_login] 数据库初始化完成");
|
||||
} catch (Exception e) {
|
||||
Index: src/main/java/Sdf1_login/GUIManager.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/GUIManager.java b/src/main/java/Sdf1_login/GUIManager.java
|
||||
--- a/src/main/java/Sdf1_login/GUIManager.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/GUIManager.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -489,6 +489,12 @@
|
||||
"§e设置密码"));
|
||||
g.setItem(16, mkItem(Material.BARRIER,
|
||||
"§c删除用户", "§7二次验证删除"));
|
||||
+ // 雪球菜单检测(slot 14)
|
||||
+ g.setItem(14, mkItem(
|
||||
+ Material.SNOWBALL,
|
||||
+ "§e§l雪球菜单",
|
||||
+ "§7点击为该玩家发放菜单雪球"));
|
||||
+
|
||||
g.setItem(22, mkItem(Material.ARROW, "§7返回"));
|
||||
p.openInventory(g);
|
||||
}
|
||||
Index: src/main/java/Sdf1_login/GarbageManager.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/GarbageManager.java b/src/main/java/Sdf1_login/GarbageManager.java
|
||||
--- a/src/main/java/Sdf1_login/GarbageManager.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/GarbageManager.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -231,26 +231,26 @@
|
||||
|
||||
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();
|
||||
- }
|
||||
- }}
|
||||
+ 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 {
|
||||
@@ -381,6 +381,38 @@
|
||||
.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();
|
||||
@@ -431,6 +463,10 @@
|
||||
g.setItem(51, mk(Material.ARROW,
|
||||
"§7已是最后一页"));
|
||||
}
|
||||
+ // 52格:返回按钮
|
||||
+ g.setItem(52, mk(Material.ARROW,
|
||||
+ "§7返回",
|
||||
+ "§7返回主菜单"));
|
||||
|
||||
p.openInventory(g);
|
||||
}
|
||||
@@ -459,6 +495,12 @@
|
||||
openRecyclePage(p, page + 1);
|
||||
return true;
|
||||
}
|
||||
+ // 52:返回
|
||||
+ if (slot == 52) {
|
||||
+ plugin.getGui().openMain(p);
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
// 50/52/53:不处理
|
||||
if (slot >= 49 && slot <= 53)
|
||||
return true;
|
||||
Index: src/main/java/Sdf1_login/GiftManager.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/GiftManager.java b/src/main/java/Sdf1_login/GiftManager.java
|
||||
--- a/src/main/java/Sdf1_login/GiftManager.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/GiftManager.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -155,55 +155,18 @@
|
||||
}
|
||||
|
||||
public boolean canClaim(Player p, int stage) {
|
||||
- Map<String, Object> user = plugin.getDb()
|
||||
- .getUser(p.getName());
|
||||
- if (user.isEmpty()) return false;
|
||||
- int curStage = ((Number) user.getOrDefault(
|
||||
- "gift_stage", 0)).intValue();
|
||||
- if (stage > curStage + 1) return false;
|
||||
- if (stage < 1 || stage > stages.size())
|
||||
- return false;
|
||||
- String claimed = (String) user.getOrDefault(
|
||||
- "gift_claimed", "");
|
||||
- if (claimed.contains("[" + stage + "]"))
|
||||
- return false;
|
||||
-
|
||||
- // debug 绕过:检查 tasks_completed
|
||||
- String completed = (String) user.getOrDefault(
|
||||
- "tasks_completed", "");
|
||||
- if (completed.contains("[" + stage + "]"))
|
||||
- return true;
|
||||
-
|
||||
- // 正常条件检查
|
||||
- long dbTime = ((Number) user.getOrDefault(
|
||||
- "total_online_time", 0L)).longValue();
|
||||
- long sessionTime = 0;
|
||||
- Object lastObj = plugin.getDb().getField(
|
||||
- p.getName(), "last_online_check");
|
||||
- if (lastObj != null && plugin.getLoggedIn()
|
||||
- .contains(p.getName())) {
|
||||
- long last = ((Number) lastObj).longValue();
|
||||
- if (last > 0) {
|
||||
- sessionTime =
|
||||
- System.currentTimeMillis() - last;
|
||||
- }
|
||||
- }
|
||||
- long onlineTime = dbTime + sessionTime;
|
||||
- int broken = ((Number) user.getOrDefault(
|
||||
- "blocks_broken", 0)).intValue();
|
||||
- int placed = ((Number) user.getOrDefault(
|
||||
- "blocks_placed", 0)).intValue();
|
||||
+ String name = p.getName();
|
||||
+ int curStage = ((Number) plugin.getDb()
|
||||
+ .getField(name, "gift_stage"))
|
||||
+ .intValue();
|
||||
+ String claimed = (String) plugin.getDb()
|
||||
+ .getField(name, "gift_claimed");
|
||||
+ if (claimed == null) claimed = "";
|
||||
+ return curStage >= stage
|
||||
+ && !claimed.contains(
|
||||
+ String.valueOf(stage));
|
||||
+ }
|
||||
|
||||
- switch (stage) {
|
||||
- case 1: return true;
|
||||
- case 2: return onlineTime >= 3600000;
|
||||
- case 3: return broken >= 100
|
||||
- && onlineTime >= 86400000L;
|
||||
- case 4: return (broken + placed) >= 300
|
||||
- && onlineTime >= 604800000L;
|
||||
- default: return false;
|
||||
- }
|
||||
- }
|
||||
|
||||
public void claimReward(Player p, int stage) {
|
||||
if (!canClaim(p, stage)) return;
|
||||
Index: src/main/java/Sdf1_login/Main.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/Main.java b/src/main/java/Sdf1_login/Main.java
|
||||
--- a/src/main/java/Sdf1_login/Main.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/Main.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -196,6 +196,8 @@
|
||||
getCommand("sdf1debug").setExecutor(this);
|
||||
if (getCommand("oa") != null)
|
||||
getCommand("oa").setExecutor(this);
|
||||
+ if (getCommand("menu") != null)
|
||||
+ getCommand("menu").setExecutor(this);
|
||||
|
||||
|
||||
getServer().getPluginManager()
|
||||
@@ -1099,6 +1101,9 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
+ if (isFrozen(p)) {
|
||||
+ p.setAllowFlight(true);
|
||||
+ }
|
||||
|
||||
if (!"manual".equals(config.approvalMode)
|
||||
&& !db.userExists(name)) {
|
||||
@@ -1238,36 +1243,82 @@
|
||||
private static final String MENU_SNOWBALL_TAG =
|
||||
"sdf1_menu";
|
||||
|
||||
+ // 雪球菜单
|
||||
public void giveMenuSnowball(Player p) {
|
||||
- // 检查背包里是否已有菜单雪球
|
||||
+ // 检查开关
|
||||
+ Object val = db.getField(
|
||||
+ p.getName(), "menu_snowball");
|
||||
+ if (val != null) {
|
||||
+ int on = val instanceof Number
|
||||
+ ? ((Number) val).intValue()
|
||||
+ : 1;
|
||||
+ if (on == 0) {
|
||||
+ return; // 开关关了,不发放
|
||||
+ }
|
||||
+ }
|
||||
+ // 检查是否已有
|
||||
for (ItemStack it : p.getInventory()
|
||||
.getContents()) {
|
||||
if (isMenuSnowball(it)) {
|
||||
- return; // 已有,不重复发
|
||||
+ return;
|
||||
}
|
||||
}
|
||||
- // 没有则发放
|
||||
+ // 发放
|
||||
ItemStack snow = new ItemStack(
|
||||
Material.SNOWBALL);
|
||||
ItemMeta im = snow.getItemMeta();
|
||||
if (im != null) {
|
||||
im.setDisplayName(
|
||||
"§e§l[菜单] §f右键打开主菜单");
|
||||
- List<String> lore = new ArrayList<>();
|
||||
+ List<String> lore =
|
||||
+ new ArrayList<>();
|
||||
lore.add("§7右键点击打开功能菜单");
|
||||
lore.add("§8" + MENU_SNOWBALL_TAG);
|
||||
im.setLore(lore);
|
||||
snow.setItemMeta(im);
|
||||
}
|
||||
- // 放到最后一个空格,避免覆盖
|
||||
- int emptySlot =
|
||||
- p.getInventory()
|
||||
- .firstEmpty();
|
||||
- if (emptySlot >= 0) {
|
||||
+ int slot = p.getInventory()
|
||||
+ .firstEmpty();
|
||||
+ if (slot >= 0) {
|
||||
+ p.getInventory().setItem(
|
||||
+ slot, snow);
|
||||
+ } else {
|
||||
+ p.getWorld().dropItemNaturally(
|
||||
+ p.getLocation(), snow);
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ /**
|
||||
+ * 手动发放雪球菜单(绕过开关检查)
|
||||
+ */
|
||||
+ public void forceGiveMenuSnowball(
|
||||
+ Player p) {
|
||||
+ // 只检查是否已有
|
||||
+ for (ItemStack it : p.getInventory()
|
||||
+ .getContents()) {
|
||||
+ if (isMenuSnowball(it)) {
|
||||
+ return;
|
||||
+ }
|
||||
+ }
|
||||
+ ItemStack snow = new ItemStack(
|
||||
+ Material.SNOWBALL);
|
||||
+ ItemMeta im = snow.getItemMeta();
|
||||
+ if (im != null) {
|
||||
+ im.setDisplayName(
|
||||
+ "§e§l[菜单] §f右键打开主菜单");
|
||||
+ List<String> lore =
|
||||
+ new ArrayList<>();
|
||||
+ lore.add("§7右键点击打开功能菜单");
|
||||
+ lore.add("§8" + MENU_SNOWBALL_TAG);
|
||||
+ im.setLore(lore);
|
||||
+ snow.setItemMeta(im);
|
||||
+ }
|
||||
+ int slot = p.getInventory()
|
||||
+ .firstEmpty();
|
||||
+ if (slot >= 0) {
|
||||
p.getInventory().setItem(
|
||||
- emptySlot, snow);
|
||||
+ slot, snow);
|
||||
} else {
|
||||
- // 背包满,丢在地上
|
||||
p.getWorld().dropItemNaturally(
|
||||
p.getLocation(), snow);
|
||||
}
|
||||
@@ -1296,21 +1347,24 @@
|
||||
@EventHandler
|
||||
public void onMove(PlayerMoveEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
+ if (!isFrozen(p)) return;
|
||||
+
|
||||
Location from = e.getFrom();
|
||||
Location to = e.getTo();
|
||||
- if (isFrozen(p)) {
|
||||
- if (to != null && (from.getX() != to.getX()
|
||||
- || from.getY() != to.getY()
|
||||
- || from.getZ() != to.getZ())) {
|
||||
- e.setTo(e.getFrom());
|
||||
- }
|
||||
+ if (to == null) return;
|
||||
+
|
||||
+ // 允许转头(无位移)
|
||||
+ if (from.getBlockX() == to.getBlockX()
|
||||
+ && from.getBlockY() == to.getBlockY()
|
||||
+ && from.getBlockZ() == to.getBlockZ()) {
|
||||
return;
|
||||
}
|
||||
- if (to != null && (from.getX() != to.getX()
|
||||
- || from.getY() != to.getY()
|
||||
- || from.getZ() != to.getZ())) {
|
||||
- afk.recordAction(p.getUniqueId());
|
||||
- }
|
||||
+
|
||||
+ // 有位移 → 取消
|
||||
+ e.setCancelled(true);
|
||||
+
|
||||
+ // 防止"服务器未启用飞行"踢出
|
||||
+ p.setAllowFlight(true);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
@@ -1484,7 +1538,8 @@
|
||||
|
||||
|
||||
|
||||
- // ===== Inventory Click =====
|
||||
+ // ===== Inventory Click =====
|
||||
+ // ===== Inventory Click =====
|
||||
@EventHandler
|
||||
public void onInvClick(InventoryClickEvent e) {
|
||||
if (!(e.getWhoClicked() instanceof Player))
|
||||
@@ -1494,12 +1549,41 @@
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
- String title =
|
||||
- e.getView().getTitle();
|
||||
+ String title = e.getView().getTitle();
|
||||
int slot = e.getRawSlot();
|
||||
|
||||
- if (needsPasswordChange.contains(p.getName())
|
||||
- && !title.equals("§6§l任务面板")) {
|
||||
+ // Shift+点击背包物品 → 存入垃圾箱
|
||||
+ if (e.isShiftClick()
|
||||
+ && e.getClickedInventory() != null
|
||||
+ && e.getClickedInventory()
|
||||
+ == p.getInventory()
|
||||
+ && e.getCurrentItem() != null
|
||||
+ && e.getCurrentItem().getType()
|
||||
+ != Material.AIR
|
||||
+ && !isMenuSnowball(
|
||||
+ e.getCurrentItem())
|
||||
+ && title.equals(
|
||||
+ "§6§l垃圾回收站")) {
|
||||
+ e.setCancelled(true);
|
||||
+ ItemStack clicked =
|
||||
+ e.getCurrentItem().clone();
|
||||
+ garbage.saveItem(clicked);
|
||||
+ e.getInventory().setItem(
|
||||
+ e.getSlot(), null);
|
||||
+ Bukkit.getScheduler()
|
||||
+ .runTaskLater(this,
|
||||
+ () -> {
|
||||
+ garbage.openRecyclePage(p,
|
||||
+ garbage.getRecyclePage(
|
||||
+ p.getName()));
|
||||
+ }, 1L);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ if (needsPasswordChange
|
||||
+ .contains(p.getName())
|
||||
+ && !title.equals(
|
||||
+ "§6§l任务面板")) {
|
||||
e.setCancelled(true);
|
||||
p.sendMessage("§c请先修改密码!");
|
||||
return;
|
||||
@@ -1516,12 +1600,15 @@
|
||||
TicketManager.T_TICKET_ADMIN)
|
||||
|| title.equals(
|
||||
TicketManager.T_TICKET_DETAIL)
|
||||
- || title.equals("§d§l服务商面板")
|
||||
- || title.equals("§6§l抢单大厅")
|
||||
+ || title.equals(
|
||||
+ "§d§l服务商面板")
|
||||
+ || title.equals(
|
||||
+ "§6§l抢单大厅")
|
||||
|| title.equals(
|
||||
"§b§l我处理中的工单")) {
|
||||
e.setCancelled(true);
|
||||
- ticket.handleClick(p, title, slot);
|
||||
+ ticket.handleClick(
|
||||
+ p, title, slot);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1539,96 +1626,67 @@
|
||||
|
||||
ItemStack inSlot =
|
||||
e.getInventory().getItem(slot);
|
||||
- ItemStack onCursor = e.getCursor();
|
||||
+ ItemStack cursor = e.getCursor();
|
||||
|
||||
- // 1. 格子里是垃圾站物品 → 取出
|
||||
- if (isTrashDisplayItem(inSlot)) {
|
||||
- e.setCancelled(true);
|
||||
- try {
|
||||
- List<String> lore =
|
||||
- inSlot.getItemMeta()
|
||||
- .getLore();
|
||||
- String numStr =
|
||||
- lore.get(0)
|
||||
- .replace(
|
||||
- "§7ID: #", "")
|
||||
- .trim();
|
||||
- int dbId = Integer
|
||||
- .parseInt(numStr);
|
||||
- // 先从DB删除
|
||||
- if (garbage.removeItem(
|
||||
- dbId)) {
|
||||
- // 再给玩家(去掉ID lore)
|
||||
- ItemStack give =
|
||||
- inSlot.clone();
|
||||
- ItemMeta gm =
|
||||
- give.getItemMeta();
|
||||
- if (gm != null) {
|
||||
- List<String> newLore =
|
||||
- new ArrayList<>();
|
||||
- // 保留原始lore(跳过ID和数量行)
|
||||
- if (lore.size() > 2) {
|
||||
- for (int li = 2;
|
||||
- li < lore
|
||||
- .size();
|
||||
- li++) {
|
||||
- newLore.add(
|
||||
- lore.get(
|
||||
- li));
|
||||
- }
|
||||
- }
|
||||
- gm.setLore(
|
||||
- newLore.isEmpty()
|
||||
- ? null
|
||||
- : newLore);
|
||||
+ // ===== 取出 =====
|
||||
+ if (inSlot != null
|
||||
+ && inSlot.hasItemMeta()
|
||||
+ && inSlot.getItemMeta().hasLore()) {
|
||||
+ List<String> lore =
|
||||
+ inSlot.getItemMeta().getLore();
|
||||
+ if (lore != null && !lore.isEmpty()
|
||||
+ && lore.get(0)
|
||||
+ .startsWith("§7ID: #")) {
|
||||
+ e.setCancelled(true);
|
||||
+ try {
|
||||
+ String numStr = lore.get(0)
|
||||
+ .replace("§7ID: #", "")
|
||||
+ .trim();
|
||||
+ int dbId =
|
||||
+ Integer.parseInt(numStr);
|
||||
+ if (garbage.removeItem(dbId)) {
|
||||
+ ItemStack give =
|
||||
+ inSlot.clone();
|
||||
+ ItemMeta gm =
|
||||
+ give.getItemMeta();
|
||||
+ gm.setLore(null);
|
||||
give.setItemMeta(gm);
|
||||
- }
|
||||
- p.getInventory()
|
||||
- .addItem(give);
|
||||
- // 清空格子
|
||||
- e.getInventory()
|
||||
- .setItem(slot,
|
||||
- null);
|
||||
- }
|
||||
- } catch (Exception ex) {
|
||||
- p.sendMessage("§c取出失败");
|
||||
- }
|
||||
- return;
|
||||
+ p.getInventory()
|
||||
+ .addItem(give);
|
||||
+ e.getInventory()
|
||||
+ .setItem(slot, null);
|
||||
+ }
|
||||
+ } catch (Exception ex) {
|
||||
+ p.sendMessage("§c取出失败");
|
||||
+ }
|
||||
+ return;
|
||||
+ }
|
||||
}
|
||||
|
||||
- // 2. 格子空 + 手上有物品 → 放入
|
||||
- if ((inSlot == null
|
||||
- || inSlot.getType()
|
||||
- == Material.AIR)
|
||||
- && onCursor != null
|
||||
- && onCursor.getType()
|
||||
+ // ===== 光标存入 =====
|
||||
+ if (cursor != null
|
||||
+ && cursor.getType()
|
||||
!= Material.AIR
|
||||
- && !isMenuSnowball(
|
||||
- onCursor)) {
|
||||
- // 不取消!让物品自然进入格子
|
||||
- Bukkit.getScheduler()
|
||||
- .runTaskLater(this,
|
||||
- () -> {
|
||||
- ItemStack after =
|
||||
- e.getInventory()
|
||||
- .getItem(
|
||||
- slot);
|
||||
- if (after != null
|
||||
- && after.getType()
|
||||
- != Material.AIR) {
|
||||
- garbage.saveItem(
|
||||
- after
|
||||
- .clone());
|
||||
- e.getInventory()
|
||||
- .setItem(
|
||||
- slot,
|
||||
- null);
|
||||
- }
|
||||
- }, 1L);
|
||||
+ && !isMenuSnowball(cursor)) {
|
||||
+ ItemStack toSave = cursor.clone();
|
||||
+ getLogger().info(
|
||||
+ "[垃圾站] 存入: "
|
||||
+ + toSave.getType()
|
||||
+ + " x" + toSave.getAmount());
|
||||
+ garbage.saveItem(toSave);
|
||||
+ e.setCancelled(true);
|
||||
+ Bukkit.getScheduler().runTaskLater(
|
||||
+ this, () -> {
|
||||
+ p.getOpenInventory()
|
||||
+ .setCursor(null);
|
||||
+ garbage.openRecyclePage(p,
|
||||
+ garbage.getRecyclePage(
|
||||
+ p.getName()));
|
||||
+ }, 1L);
|
||||
return;
|
||||
}
|
||||
|
||||
- // 3. 其他情况
|
||||
+ // 默认取消
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
@@ -1806,6 +1864,7 @@
|
||||
p.closeInventory();
|
||||
p.sendMessage("§e请输入邀请码:");
|
||||
}
|
||||
+
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1828,6 +1887,7 @@
|
||||
.replace("§e", "")
|
||||
.replace("§a", ""));
|
||||
}
|
||||
+
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1856,7 +1916,18 @@
|
||||
p.closeInventory();
|
||||
p.sendMessage("§e输入" + tgt
|
||||
+ "的临时密码:");
|
||||
- } else if (slot == 16) {
|
||||
+ } else if (slot == 14) {
|
||||
+ Player tp = Bukkit.getPlayer(tgt);
|
||||
+ if (tp != null && tp.isOnline()) {
|
||||
+ forceGiveMenuSnowball(tp);
|
||||
+ p.sendMessage("§a已发放雪球菜单给 "
|
||||
+ + tgt);
|
||||
+ } else {
|
||||
+ p.sendMessage("§c玩家不在线");
|
||||
+ }
|
||||
+
|
||||
+
|
||||
+ } else if (slot == 16) {
|
||||
chatInput.getState(p).type =
|
||||
ChatInputManager.InputType
|
||||
.ADMIN_DELETE_CONFIRM;
|
||||
@@ -1866,8 +1937,11 @@
|
||||
p.sendMessage(config.msg(
|
||||
"admin_delete_confirm"));
|
||||
}
|
||||
+
|
||||
return;
|
||||
+
|
||||
}
|
||||
+
|
||||
|
||||
// 积分商城
|
||||
if (title.startsWith("§d§l积分商城")) {
|
||||
@@ -1958,43 +2032,45 @@
|
||||
|
||||
// 回收站拖拽
|
||||
if (t.equals("§6§l垃圾回收站")) {
|
||||
- for (int rawSlot : e.getRawSlots()) {
|
||||
- if (rawSlot >= 49
|
||||
- && rawSlot <= 53) {
|
||||
+ for (int rawSlot :
|
||||
+ e.getRawSlots()) {
|
||||
+ if (rawSlot >= 49) {
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
- // 0-48:不取消,延迟存DB
|
||||
+ // 0-48允许拖入,不取消
|
||||
+ // 延迟2tick后扫描格子
|
||||
+ final Player fp = p;
|
||||
Bukkit.getScheduler()
|
||||
- .runTaskLater(this, () -> {
|
||||
- for (int rawSlot :
|
||||
- e.getRawSlots()) {
|
||||
- if (rawSlot < 0
|
||||
- || rawSlot >= 49)
|
||||
- continue;
|
||||
- ItemStack item =
|
||||
- e.getInventory()
|
||||
- .getItem(
|
||||
- rawSlot);
|
||||
- if (item != null
|
||||
- && item.getType()
|
||||
- != Material.AIR
|
||||
- && !isMenuSnowball(
|
||||
- item)) {
|
||||
- garbage.saveItem(
|
||||
- item.clone());
|
||||
- e.getInventory()
|
||||
- .setItem(
|
||||
- rawSlot,
|
||||
- null);
|
||||
- }
|
||||
- }
|
||||
- }, 1L);
|
||||
+ .runTaskLater(this,
|
||||
+ () -> {
|
||||
+ Inventory top = fp
|
||||
+ .getOpenInventory()
|
||||
+ .getTopInventory();
|
||||
+ for (int rawSlot :
|
||||
+ e.getRawSlots()) {
|
||||
+ if (rawSlot < 0
|
||||
+ || rawSlot >= 49)
|
||||
+ continue;
|
||||
+ ItemStack item =
|
||||
+ top.getItem(rawSlot);
|
||||
+ if (item != null
|
||||
+ && item.getType()
|
||||
+ != Material.AIR
|
||||
+ && !isMenuSnowball(
|
||||
+ item)) {
|
||||
+ garbage.saveItem(
|
||||
+ item.clone());
|
||||
+ top.setItem(
|
||||
+ rawSlot, null);
|
||||
+ }
|
||||
+ }
|
||||
+ }, 2L);
|
||||
return;
|
||||
}
|
||||
|
||||
-
|
||||
+ //服务商工单系统
|
||||
if (t.equals(TicketManager.T_TICKET_MAIN)
|
||||
|| t.equals(
|
||||
TicketManager.T_TICKET_CREATE)
|
||||
@@ -2050,6 +2126,38 @@
|
||||
+ count + " 个掉落物");
|
||||
return true;
|
||||
}
|
||||
+ // /menu 开关雪球菜单
|
||||
+ if (cmdName.equals("menu")) {
|
||||
+ if (!(sender instanceof Player)) {
|
||||
+ sender.sendMessage(
|
||||
+ "§c仅玩家可用");
|
||||
+ return true;
|
||||
+ }
|
||||
+ Player p2 = (Player) sender;
|
||||
+ if (args.length == 0) {
|
||||
+ p2.sendMessage(
|
||||
+ "§e用法: /menu <开/关>");
|
||||
+ return true;
|
||||
+ }
|
||||
+ String arg = args[0];
|
||||
+ if (arg.equals("开")) {
|
||||
+ db.setField(p2.getName(),
|
||||
+ "menu_snowball", 1);
|
||||
+ p2.sendMessage(
|
||||
+ "§a雪球菜单已开启,"
|
||||
+ + "下次进入将发放");
|
||||
+ } else if (arg.equals("关")) {
|
||||
+ db.setField(p2.getName(),
|
||||
+ "menu_snowball", 0);
|
||||
+ p2.sendMessage(
|
||||
+ "§c雪球菜单已关闭,"
|
||||
+ + "下次进入不再发放");
|
||||
+ } else {
|
||||
+ p2.sendMessage(
|
||||
+ "§e用法: /menu <开/关>");
|
||||
+ }
|
||||
+ return true;
|
||||
+ }
|
||||
|
||||
if (cmdName.equals("reg")
|
||||
|| cmdName.equals("注册")) {
|
||||
@@ -2461,9 +2569,9 @@
|
||||
sender.sendMessage(
|
||||
"§e§l================================");
|
||||
}
|
||||
- }
|
||||
+ }
|
||||
|
||||
- // pw / password
|
||||
+ // pw / password
|
||||
if (sub.equals("pw")
|
||||
|| sub.equals("password")) {
|
||||
if (!(sender instanceof Player)) {
|
||||
@@ -2790,6 +2898,29 @@
|
||||
}
|
||||
return true;
|
||||
}
|
||||
+ // give - 手动发放雪球菜单
|
||||
+ if (sub.equals("give")) {
|
||||
+ if (args.length < 2) {
|
||||
+ sender.sendMessage(
|
||||
+ "§e用法: /sdf1_login give <玩家名>");
|
||||
+ return true;
|
||||
+ }
|
||||
+ Player tp = Bukkit.getPlayer(
|
||||
+ args[1]);
|
||||
+ if (tp == null || !tp.isOnline()) {
|
||||
+ sender.sendMessage(
|
||||
+ "§c玩家不在线: "
|
||||
+ + args[1]);
|
||||
+ return true;
|
||||
+ }
|
||||
+ forceGiveMenuSnowball(tp);
|
||||
+ tp.sendMessage(
|
||||
+ "§a管理员已为您发放菜单雪球");
|
||||
+ sender.sendMessage(
|
||||
+ "§a已发放雪球菜单给 "
|
||||
+ + args[1]);
|
||||
+ return true;
|
||||
+ }
|
||||
|
||||
// shopadd
|
||||
if (sub.equals("shopadd")) {
|
||||
@@ -3052,4 +3183,4 @@
|
||||
return list;
|
||||
}
|
||||
|
||||
-}
|
||||
+}
|
||||
\ No newline at end of file
|
||||
Index: src/main/java/Sdf1_login/TicketManager.java
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/java/Sdf1_login/TicketManager.java b/src/main/java/Sdf1_login/TicketManager.java
|
||||
--- a/src/main/java/Sdf1_login/TicketManager.java (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/java/Sdf1_login/TicketManager.java (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -1014,39 +1014,27 @@
|
||||
openDetail(p, id);
|
||||
return true;
|
||||
}
|
||||
- // 管理员:标记完结(自己在处理)
|
||||
- if (adm(p) && "processing".equals(st)
|
||||
+ // 管理员:标记完结(已回复状态)
|
||||
+ 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;
|
||||
- }
|
||||
- // 管理员:标记完结(已回复状态)
|
||||
- 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;
|
||||
+
|
||||
+ // 管理员:标记完结(已回复状态)
|
||||
+ 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;
|
||||
+ }
|
||||
}
|
||||
-
|
||||
// 服务商:抢单
|
||||
if (plugin.getDb()
|
||||
.isServiceProvider(p.getName())
|
||||
Index: src/main/resources/plugin.yml
|
||||
IDEA additional info:
|
||||
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||
<+>UTF-8
|
||||
===================================================================
|
||||
diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml
|
||||
--- a/src/main/resources/plugin.yml (revision 145b392112786b20534254a7a38d716657c962ab)
|
||||
+++ b/src/main/resources/plugin.yml (revision 87de2e12c81f5a5e04825113e7835aca09e0fd09)
|
||||
@@ -84,3 +84,6 @@
|
||||
垃圾清理:
|
||||
description: 手动清理掉落物
|
||||
usage: /垃圾清理
|
||||
+ menu:
|
||||
+ description: 雪球菜单开关控制
|
||||
+ usage: /menu <开/关>
|
||||
\ No newline at end of file
|
||||
Reference in New Issue
Block a user