Compare commits

...

24 Commits

Author SHA1 Message Date
BRanulf
e5eca44059 qwq 2025-06-23 14:04:22 +08:00
BRanulf
c3e4a1b483 qwq 2025-06-23 14:01:09 +08:00
BRanulf
75bacc1ec7 利用已有api添加新元素 2025-06-09 18:27:05 +08:00
BRanulf
0d9e2db5ee 修bug修bug 2025-06-09 17:34:05 +08:00
BRanulf
eef2bbebad 修bug修bug 2025-06-07 14:48:03 +08:00
BRanulf
a5b4efc36e aaaaaa 2025-06-06 12:52:15 +08:00
BRanulf
62ef19006a markdown 2025-06-05 18:18:00 +08:00
BRanulf
a69adaf749 Merge remote-tracking branch 'origin/master' 2025-06-05 18:17:03 +08:00
BRanulf
7e03e0edfa markdown 2025-06-05 18:16:43 +08:00
Branulf
d3523f2442 更新 README_EN.md 2025-06-05 14:54:28 +08:00
BRanulf
a21701a766 awa 2025-06-05 14:26:33 +08:00
BRanulf
10f52e130e awa 2025-06-05 14:25:26 +08:00
BRanulf
1ffa91a98a awa 2025-06-05 12:04:24 +08:00
BRanulf
23a0518ca7 重命名 2025-06-05 11:08:48 +08:00
BRanulf
4ce44dbecf 不大不小的更新 2025-06-05 09:48:53 +08:00
BRanulf
c58a6a071d 小修改 2025-06-02 13:19:01 +08:00
BRanulf
ad90b6e3f4 小修改 2025-06-02 13:18:16 +08:00
BRanulf
651e7f69f7 小修改 2025-06-02 13:08:59 +08:00
BRanulf
550894e8e4 更新许可证 2025-06-02 13:08:41 +08:00
59333dbd2d 上传文件至 / 2025-06-02 10:56:49 +08:00
d12af686b3 删除 LICENSE.txt 2025-06-02 10:56:16 +08:00
Branulf
64623693e9 更新 README.md 2025-04-22 23:18:06 +08:00
BRanulf
387f1a83de 小更新 2025-04-19 22:29:36 +08:00
BRanulf
ef3f3dd1b8 更新网页和后端 2025-04-19 21:14:45 +08:00
26 changed files with 3701 additions and 1022 deletions

View File

@ -1,15 +1,692 @@
MIT许可证 Copyright (c) 2025 BRanulf
版权所有 (c) 2025 BRanulf This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
上述版权声明和本许可声明应包含在本软件的所有副本或实质性部分中。 You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
ServerPlayerOnlineTracker Copyright (C) 2025 BRanulf
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
本软件按"原样"提供,不提供任何明示或暗示的保证,包括但不限于对适销性、
特定用途适用性和非侵权性的保证。在任何情况下,作者或版权持有人均不对
任何索赔、损害或其他责任负责,无论是在合同、侵权还是其他诉讼中,
由软件或软件的使用或其他交易引起、由软件引起或与之相关的。

View File

@ -1,5 +1,24 @@
# Player_OnlineTime # 一个服务器在线玩家时间以及服务器状态的简单的mod
[English](https://git.branulf.top/Branulf/ServerPlayerOnlineTracker/src/branch/master/README_EN.md)
一个监视服务器玩家在线时间的mod带web服务器目前并不完善 注意本mod并不完善可能会存在些许的bug
### 包含功能:
* 显示/记录服务器在线玩家时间
* 显示服务器状态
* 显示服务器在线玩家列表
* ~~移除游戏中的Herobrine~~
*震惊该mod的AI含量竟高达60%* ### 使用方法:
1. 安装Fabric Loader和Fabric API
2. 将最新版本的mod放入mods文件夹
3. 首次启动服务器自动生成配置文件
4. 修改Web服务器端口(默认60048),语言(目前仅支持zh_cn和en_us),自动保存时间(默认300秒)
5. 如需在外部访问请确保端口已开放
### API获取数据
*(也许可以用于机器人?)*
* 获取服务器在线玩家列表【服务器IP+配置的端口】+`/api/online-players`
* 获取服务器状态【服务器IP+配置的端口】+`/api/server-status`
* 获取服务器在线玩家时间【服务器IP+配置的端口】+`/api/stats`
* 获取服务器在线玩家数量【服务器IP+配置的端口】+`/api/player-count`
* ~~原始数据文件【服务器IP+配置的端口】+`/api/playerdata`~~

24
README_EN.md Normal file
View File

@ -0,0 +1,24 @@
# A simple mod for tracking online player time and server status
[中文简体](https://git.branulf.top/Branulf/ServerPlayerOnlineTracker/src/branch/master/README.md)
Note: This mod is not perfect and may have some bugs.
### Features include:
* Display/record server online player time
* Show server status
* Display a list of online players on the server
* ~~Remove Herobrine from the game~~
### How to use:
1. Install Fabric Loader and Fabric API.
2. Place the latest version of the mod into the mods folder.
3. The configuration file will be generated automatically when starting the server for the first time.
4. Modify the web server port (default 60048), language (currently only supports zh_cn and en_us), and automatic save interval (default 300 seconds).
5. If external access is needed, ensure that the port is open.
### API data retrieval:
*(Maybe can be used for bots?)*
* Get a list of online players on the server: [Server IP + configured port] + `/api/online-players`
* Get server status: [Server IP + configured port] + `/api/server-status`
* Get online player time on the server: [Server IP + configured port] + `/api/stats`
* Get number of online players on the server: [Server IP + configured port] + `/api/player-count`
* ~~Raw data file: [Server IP + configured port] + `/api/playerdata`~~

View File

@ -92,3 +92,5 @@ publishing {
// retrieving dependencies. // retrieving dependencies.
} }
} }

View File

@ -6,9 +6,9 @@ minecraft_version=1.21.4
yarn_mappings=1.21.4+build.8 yarn_mappings=1.21.4+build.8
loader_version=0.16.10 loader_version=0.16.10
# Mod Properties # Mod Properties
mod_version=1.14.514.118 mod_version=1.14.514.141
maven_group=org.example1 maven_group=org.example1
archives_base_name=playerOnlineTimeTrackerMod archives_base_name=ServerPlayerOnlineTracker
# Dependencies # Dependencies
# check this on https://modmuss50.me/fabric.html # check this on https://modmuss50.me/fabric.html
fabric_version=0.119.2+1.21.4 fabric_version=0.119.2+1.21.4

View File

@ -0,0 +1,108 @@
package com.example.playertime;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.fabricmc.loader.api.FabricLoader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
// 这个是gemini写的 (保留原注释但代码已根据需求调整)
public class LocalizationManager {
private final Map<String, String> translations = new HashMap<>();
private final String defaultLanguage = "zh_cn"; // 默认语言代码
public LocalizationManager(String languageCode) {
// 尝试加载用户配置的语言
loadLanguage(languageCode, false);
// 如果配置的语言不是默认语言加载默认语言作为备用
if (!languageCode.equalsIgnoreCase(defaultLanguage)) {
loadLanguage(defaultLanguage, true);
}
// 如果配置的语言和默认语言都没加载成功或者配置的语言文件不完整确保默认语言至少被加载
if (translations.isEmpty() && !languageCode.equalsIgnoreCase(defaultLanguage)) {
PlayerTimeMod.LOGGER.warn("[PlayerTime] 未能加载配置的语言文件({})或默认语言文件({})Mod将使用原始键。", languageCode, defaultLanguage);
} else if (translations.isEmpty() && languageCode.equalsIgnoreCase(defaultLanguage)) {
PlayerTimeMod.LOGGER.warn("[PlayerTime] 未能加载默认语言文件({})Mod将使用原始键。", defaultLanguage);
}
}
private void loadLanguage(String languageCode, boolean isFallback) {
String resourcePath = String.format("assets/playertime/lang/%s.json", languageCode.toLowerCase()); // 确保小写
try {
// 使用 FabricLoader 获取 Mod 资源
InputStream is = FabricLoader.getInstance().getModContainer("playertime")
.flatMap(container -> container.findPath(resourcePath))
.map(path -> {
try {
return path.toUri().toURL().openStream();
} catch (Exception e) {
// 查找路径或打开流失败
return null;
}
})
.orElse(null); // 如果找不到路径或打开失败返回 null
if (is == null) {
if (!isFallback) {
PlayerTimeMod.LOGGER.warn("[PlayerTime] 未找到语言文件: {}", resourcePath);
}
return;
}
try (InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
json.entrySet().forEach(entry -> {
// 如果是加载备用语言只有当主语言没有该键时才添加
// 如果是加载主语言则覆盖备用语言中的同名键
if (!translations.containsKey(entry.getKey()) || !isFallback) {
translations.put(entry.getKey(), entry.getValue().getAsString());
}
});
PlayerTimeMod.LOGGER.info("[PlayerTime] 已加载 {} 语言字符串 ({}): {}", translations.size(), isFallback ? "备用" : "主要", languageCode);
}
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[PlayerTime] 加载语言文件失败 ({}): {}", languageCode, resourcePath, e);
}
}
/**
* 根据键获取本地化字符串如果找不到键返回键本身
* @param key 本地化键
* @return 本地化字符串或原始键
*/
public String getString(String key) {
return translations.getOrDefault(key, key);
}
/**
* 根据键获取本地化字符串并使用参数格式化如果找不到键返回原始键
* @param key 本地化键
* @param args 格式化参数
* @return 格式化后的本地化字符串或原始键
*/
public String getString(String key, Object... args) {
String pattern = getString(key);
try {
// MessageFormat 可以处理 {0}, {1} 等占位符
return MessageFormat.format(pattern, args);
} catch (IllegalArgumentException e) {
PlayerTimeMod.LOGGER.error("[PlayerTime] 格式化本地化字符串失败 (键: {})", key, e);
return pattern; // 格式化失败时返回原始模式
}
}
/**
* 获取所有本地化字符串的映射主要用于 Web API
* @return 包含所有本地化键值对的 Map
*/
public Map<String, String> getAllStrings() {
return new HashMap<>(translations); // 返回副本防止外部修改
}
}

View File

@ -7,44 +7,131 @@ import java.nio.file.*;
public class ModConfig { public class ModConfig {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final Path configPath; private final Path configPath;
// 配置项
private int webPort = 60048; private int webPort = 60048;
private String language = "zh_cn";
private boolean whitelistOnly = true; // 默认只记录白名单玩家
private int saveIntervalMinutes = 5; // 默认每5分钟保存一次
public ModConfig(Path configDir) { public ModConfig(Path configDir) {
this.configPath = configDir.resolve("playertime-config.json"); this.configPath = configDir.resolve("playertime-config.json");
loadConfig(); loadConfig();
} }
// 加载配置
private void loadConfig() { private void loadConfig() {
if (!Files.exists(configPath)) { if (!Files.exists(configPath)) {
saveConfig(); PlayerTimeMod.LOGGER.info("[在线时间] 配置文件未找到,正在创建默认配置: {}", configPath);
saveConfig(); // 创建默认配置并保存
return; return;
} }
try (Reader reader = Files.newBufferedReader(configPath)) { try (Reader reader = Files.newBufferedReader(configPath)) {
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject(); JsonElement jsonElement = JsonParser.parseReader(reader);
if (json.has("webPort")) {
webPort = json.get("webPort").getAsInt(); if (jsonElement == null || !jsonElement.isJsonObject()) {
PlayerTimeMod.LOGGER.warn("[在线时间] 配置文件为空或格式错误,正在使用默认配置并覆盖: {}", configPath);
saveConfig(); // 使用默认配置并覆盖
return;
} }
JsonObject json = jsonElement.getAsJsonObject();
// 读取 webPort
if (json.has("webPort") && json.get("webPort").isJsonPrimitive() && json.get("webPort").getAsJsonPrimitive().isNumber()) {
webPort = json.get("webPort").getAsInt();
if (webPort < 1 || webPort > 65535) {
PlayerTimeMod.LOGGER.warn("[在线时间] 配置文件中的 webPort ({}) 无效,使用默认值 {}", webPort, 60048);
webPort = 60048;
}
} else {
PlayerTimeMod.LOGGER.info("[在线时间] 配置文件缺少或 webPort 格式错误,使用默认值 {}", webPort);
// 不立即保存等待所有字段读取完毕再决定是否保存
}
// 读取 language
if (json.has("language") && json.get("language").isJsonPrimitive() && json.get("language").getAsJsonPrimitive().isString()) {
language = json.get("language").getAsString();
} else {
PlayerTimeMod.LOGGER.info("[在线时间] 配置文件缺少或 language 格式错误,使用默认值 {}", language);
}
// 读取 whitelistOnly
if (json.has("whitelistOnly") && json.get("whitelistOnly").isJsonPrimitive() && json.get("whitelistOnly").getAsJsonPrimitive().isBoolean()) {
whitelistOnly = json.get("whitelistOnly").getAsBoolean();
} else {
PlayerTimeMod.LOGGER.info("[在线时间] 配置文件缺少或 whitelistOnly 格式错误,使用默认值 {}", whitelistOnly);
}
// 读取 saveIntervalMinutes
if (json.has("saveIntervalMinutes") && json.get("saveIntervalMinutes").isJsonPrimitive() && json.get("saveIntervalMinutes").getAsJsonPrimitive().isNumber()) {
saveIntervalMinutes = json.get("saveIntervalMinutes").getAsInt();
if (saveIntervalMinutes < 0) {
PlayerTimeMod.LOGGER.warn("[在线时间] 配置文件中的 saveIntervalMinutes ({}) 无效,使用默认值 {}", saveIntervalMinutes, 5);
saveIntervalMinutes = 5;
}
} else {
PlayerTimeMod.LOGGER.info("[在线时间] 配置文件缺少或 saveIntervalMinutes 格式错误,使用默认值 {}", saveIntervalMinutes);
}
// 检查是否有新字段需要添加到配置文件
if (!json.has("webPort") || !json.has("language") || !json.has("whitelistOnly") || !json.has("saveIntervalMinutes")) {
PlayerTimeMod.LOGGER.info("[在线时间] 配置文件缺少部分字段,正在添加并保存。");
saveConfig(); // 保存以添加新字段
} else {
PlayerTimeMod.LOGGER.info("[在线时间] 配置文件加载成功: {}", configPath);
}
} catch (IOException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法读取配置文件 {},使用默认配置", configPath, e);
saveConfig(); // 发生IO错误尝试保存默认配置
} catch (JsonParseException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 配置文件 {} 格式错误,使用默认配置", configPath, e);
saveConfig(); // 发生JSON解析错误尝试保存默认配置
} catch (Exception e) { } catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 加载配置失败", e); PlayerTimeMod.LOGGER.error("[在线时间] 加载配置文件 {} 时发生未知错误,使用默认配置", configPath, e);
saveConfig(); // 发生未知错误尝试保存默认配置
} }
} }
// 保存配置
private void saveConfig() { private void saveConfig() {
JsonObject json = new JsonObject(); JsonObject json = new JsonObject();
json.addProperty("webPort", webPort); json.addProperty("webPort", webPort);
json.addProperty("language", language);
json.addProperty("whitelistOnly", whitelistOnly);
json.addProperty("saveIntervalMinutes", saveIntervalMinutes);
try { try {
Files.createDirectories(configPath.getParent()); Files.createDirectories(configPath.getParent());
try (Writer writer = Files.newBufferedWriter(configPath)) { try (Writer writer = Files.newBufferedWriter(configPath)) {
GSON.toJson(json, writer); GSON.toJson(json, writer);
} }
PlayerTimeMod.LOGGER.info("[在线时间] 配置已成功保存到 {}", configPath);
} catch (Exception e) { } catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 保存配置失败", e); PlayerTimeMod.LOGGER.error("[在线时间] 保存配置失败到 {}", configPath, e);
} }
} }
// 获取端口
public int getWebPort() { public int getWebPort() {
return webPort; return webPort;
} }
}
// 获取语言
public String getLanguage() {
return language;
}
// 获取是否只记录白名单
public boolean isWhitelistOnly() {
return whitelistOnly;
}
// 获取保存间隔分钟
public int getSaveIntervalMinutes() {
return saveIntervalMinutes;
}
}

View File

@ -1,74 +1,347 @@
package com.example.playertime; package com.example.playertime;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.fabricmc.loader.api.Version;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Util;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class PlayerTimeMod implements ModInitializer { public class PlayerTimeMod implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("PlayerTimeTracker"); public static final Logger LOGGER = LoggerFactory.getLogger("PlayerTimeTracker");
private static PlayerTimeTracker timeTracker; private static PlayerTimeTracker timeTracker;
private static WebServer webServer; private static WebServer webServer;
private static ModConfig config; private static ModConfig config;
public static LocalizationManager localizationManager;
private static final String RSS_FEED_URL = "https://git.branulf.top/Branulf/ServerPlayerOnlineTracker/releases.rss";
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); // One for update check, one for saving
@Override @Override
public void onInitialize() { public void onInitialize() {
config = new ModConfig(FabricLoader.getInstance().getConfigDir());
try { try {
LOGGER.info("[在线时间] 初始化玩家在线时长视奸MOD"); LOGGER.info("[在线时间] 初始化 玩家在线时长视奸Mod...");
// 加载配置
config = new ModConfig(FabricLoader.getInstance().getConfigDir());
// 初始化本地化管理器
localizationManager = new LocalizationManager(config.getLanguage());
// 检查更新
checkForUpdates();
// 服务器启动中事件
ServerLifecycleEvents.SERVER_STARTING.register(server -> { ServerLifecycleEvents.SERVER_STARTING.register(server -> {
timeTracker = new PlayerTimeTracker(server); LOGGER.info("[在线时间] 服务器启动中...");
timeTracker = new PlayerTimeTracker(server, config);
try { try {
webServer = new WebServer(timeTracker, config.getWebPort(), server); // 传入 MinecraftServer webServer = new WebServer(timeTracker, config.getWebPort(), server);
webServer.start(); webServer.start();
LOGGER.info("[在线时间] Web服务器在端口 " + config.getWebPort() + " 启动"); LOGGER.info("[在线时间] Web服务器在端口 {} 启动", config.getWebPort());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("[在线时间] 无法启动Web服务器", e); LOGGER.error("[在线时间] 无法启动Web服务器", e);
} }
}); });
// 服务器已启动事件
ServerLifecycleEvents.SERVER_STARTED.register(server -> {
LOGGER.info("[在线时间] 服务器已启动.");
if (timeTracker != null) {
timeTracker.loadData();
// 启动定时保存任务
int saveInterval = config.getSaveIntervalMinutes();
if (saveInterval > 0) {
scheduler.scheduleAtFixedRate(timeTracker::saveAll, saveInterval, saveInterval, TimeUnit.MINUTES);
LOGGER.info("[在线时间] 已安排每 {} 分钟定时保存玩家数据", saveInterval);
} else {
LOGGER.warn("[在线时间] 配置的保存间隔为 {} 分钟,定时保存已禁用。", saveInterval);
}
} else {
LOGGER.error("[在线时间] PlayerTimeTracker 未在 SERVER_STARTING 阶段成功初始化!");
}
});
// 玩家加入事件
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
if (timeTracker != null) { if (timeTracker != null) {
timeTracker.onPlayerJoin(handler.player); // 根据配置决定是否跟踪该玩家
if (!config.isWhitelistOnly() || server.getPlayerManager().isWhitelisted(handler.player.getGameProfile())) {
timeTracker.onPlayerJoin(handler.player);
} else {
LOGGER.debug("[在线时间] 玩家 {} ({}) 不在白名单,且配置为仅记录白名单玩家,跳过跟踪。", handler.player.getName().getString(), handler.player.getUuid());
}
} }
}); });
// 玩家离开事件
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> { ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> {
if (timeTracker != null) { if (timeTracker != null) {
timeTracker.onPlayerLeave(handler.player); if (timeTracker.isPlayerTracked(handler.player.getUuid())) {
timeTracker.onPlayerLeave(handler.player);
} else {
LOGGER.debug("[在线时间] 玩家 {} ({}) 未被跟踪,跳过离开事件处理。", handler.player.getName().getString(), handler.player.getUuid());
}
} }
}); });
// 服务器停止事件
ServerLifecycleEvents.SERVER_STOPPING.register(server -> { ServerLifecycleEvents.SERVER_STOPPING.register(server -> {
LOGGER.info("[在线时间] 服务器停止 - 保存数据"); LOGGER.info("[在线时间] 服务器停止中 - 正在保存数据...");
if (webServer != null) {
webServer.stop();
}
if (timeTracker != null) { if (timeTracker != null) {
for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) {
if (timeTracker.isPlayerTracked(player.getUuid())) {
timeTracker.onPlayerLeave(player);
}
}
timeTracker.saveAll(); timeTracker.saveAll();
} }
if (webServer != null) {
webServer.stop();
LOGGER.info("[在线时间] Web服务器已停止.");
}
scheduler.shutdownNow();
LOGGER.info("[在线时间] 定时任务已关闭.");
LOGGER.info("[在线时间] 数据保存完成Mod 已停止.");
}); });
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("[在线时间] Mod 初始化失败!", e); LOGGER.error("[在线时间] Mod初始化失败", e);
throw new RuntimeException("[在线时间] Mod 初始化失败", e); throw new RuntimeException("[在线时间] Mod初始化失败 ", e);
} }
registerCommands();
} }
public static ModConfig getConfig() { public static ModConfig getConfig() {
return config; return config;
} }
public static PlayerTimeTracker getTimeTracker() { public static PlayerTimeTracker getTimeTracker() {
return timeTracker; return timeTracker;
} }
}
public static LocalizationManager getLocalizationManager() {
return localizationManager;
}
// 注册命令
private void registerCommands() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
dispatcher.register(CommandManager.literal("onlineTime")
.requires(source -> source.hasPermissionLevel(0)) // 任何玩家都可以使用
.executes(context -> showOnlineTime(context.getSource(), 1)) // 默认显示第一页
.then(CommandManager.argument("page", IntegerArgumentType.integer(1))
.executes(context -> showOnlineTime(
context.getSource(),
IntegerArgumentType.getInteger(context, "page")
))
)
);
LOGGER.info("[在线时间] 已注册命令 /onlineTime");
});
}
// 显示在线时间
private int showOnlineTime(ServerCommandSource source, int requestedPage) {
ServerPlayerEntity player = source.getPlayer();
if (player == null) {
source.sendMessage(Text.literal(localizationManager.getString("playertime.command.error.player_only")).formatted(Formatting.RED));
return 0;
}
Util.getMainWorkerExecutor().execute(() -> {
PlayerTimeTracker tracker = getTimeTracker();
if (tracker == null) {
player.sendMessage(Text.literal(localizationManager.getString("playertime.command.error.not_initialized")).formatted(Formatting.RED), false);
return;
}
List<PlayerTimeTracker.PlayerTimeStatsWithNames> statsList = tracker.getSortedPlayerStats();
sendPaginatedMessage(player, statsList, requestedPage);
});
return 1;
}
// 发送分页消息
private void sendPaginatedMessage(ServerPlayerEntity player, List<PlayerTimeTracker.PlayerTimeStatsWithNames> statsList, int requestedPage) {
int pageSize = 10;
int totalEntries = statsList.size();
int totalPages = (totalEntries + pageSize - 1) / pageSize;
int currentPage = Math.max(1, Math.min(requestedPage, Math.max(1, totalPages)));
int fromIndex = (currentPage - 1) * pageSize;
int toIndex = Math.min(fromIndex + pageSize, totalEntries);
player.sendMessage(Text.literal(localizationManager.getString("playertime.command.title", currentPage, Math.max(1, totalPages))).formatted(Formatting.GOLD), false);
if (statsList.isEmpty()) {
player.sendMessage(Text.literal(localizationManager.getString("playertime.command.empty_stats")).formatted(Formatting.GRAY), false);
return;
}
for (int i = fromIndex; i < toIndex; i++) {
PlayerTimeTracker.PlayerTimeStatsWithNames stats = statsList.get(i);
String formattedStats = localizationManager.getString(
"playertime.stats.format",
PlayerTimeTracker.formatTime(stats.getTotalTime()),
PlayerTimeTracker.formatTime(stats.last30Days),
PlayerTimeTracker.formatTime(stats.last7Days)
);
player.sendMessage(Text.literal(String.format("§e%s§r: %s", stats.playerName, formattedStats)), false);
}
MutableText footer = Text.literal("");
if (currentPage > 1) {
footer.append(Text.literal(localizationManager.getString("playertime.command.prev_page"))
.styled(style -> style.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
"/onlineTime " + (currentPage - 1)
)).withColor(Formatting.GREEN)));
}
if (currentPage > 1 && currentPage < totalPages) {
footer.append(" ");
}
footer.append(Text.literal(localizationManager.getString("playertime.command.total_players", totalEntries)).formatted(Formatting.GRAY));
if (currentPage < totalPages) {
if (currentPage > 1 || totalEntries > 0) {
footer.append(" ");
}
footer.append(Text.literal(localizationManager.getString("playertime.command.next_page"))
.styled(style -> style.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
"/onlineTime " + (currentPage + 1)
)).withColor(Formatting.GREEN)));
}
player.sendMessage(footer, false);
}
// 检查更新
private void checkForUpdates() {
scheduler.submit(() -> {
try {
Optional<ModContainer> modContainer = FabricLoader.getInstance().getModContainer("playertime");
if (modContainer.isEmpty()) {
LOGGER.warn("[在线时间] 无法获取 Mod 容器,跳过更新检查。");
return;
}
Version currentVersion = modContainer.get().getMetadata().getVersion();
String currentVersionString = currentVersion.getFriendlyString();
LOGGER.info("[在线时间] 正在检查更新...");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new URL(RSS_FEED_URL).openStream());
doc.getDocumentElement().normalize();
NodeList itemList = doc.getElementsByTagName("item");
if (itemList.getLength() == 0) {
LOGGER.warn("[在线时间] RSS Feed 中没有找到任何发布项。");
return;
}
Element latestItem = (Element) itemList.item(0);
String latestVersionString = latestItem.getElementsByTagName("title").item(0).getTextContent();
String latestVersionLink = latestItem.getElementsByTagName("link").item(0).getTextContent();
LOGGER.info("[在线时间] 当前版本: {}, 最新版本 (RSS): {}", currentVersionString, latestVersionString);
if (isNewerVersion(latestVersionString, currentVersionString)) {
LOGGER.warn("==================================================");
LOGGER.warn("[在线时间] 发现新版本!");
LOGGER.warn("[在线时间] 当前版本: {}", currentVersionString);
LOGGER.warn("[在线时间] 最新版本: {}", latestVersionString);
LOGGER.warn("[在线时间] 下载链接: {}", latestVersionLink);
LOGGER.warn("==================================================");
} else {
LOGGER.info("[在线时间] 当前已是最新版本(或检查失败)。");
}
} catch (javax.xml.parsers.ParserConfigurationException e) {
LOGGER.error("[在线时间] 更新检查失败: XML 解析器配置错误", e);
} catch (org.xml.sax.SAXException e) {
LOGGER.error("[在线时间] 更新检查失败: XML 解析错误", e);
} catch (java.io.IOException e) {
LOGGER.error("[在线时间] 更新检查失败: 网络或文件读取错误", e);
} catch (Exception e) {
LOGGER.error("[在线时间] 更新检查时发生未知错误", e);
}
});
}
// 检查版本号是否比当前版本高
private boolean isNewerVersion(String newVersion, String currentVersion) {
if (newVersion == null || currentVersion == null || newVersion.isEmpty() || currentVersion.isEmpty()) {
return false;
}
String cleanNewVersion = newVersion.toLowerCase().startsWith("v") ? newVersion.substring(1) : newVersion;
String cleanCurrentVersion = currentVersion.toLowerCase().startsWith("v") ? currentVersion.substring(1) : currentVersion;
String[] newParts = cleanNewVersion.split("\\.");
String[] currentParts = cleanCurrentVersion.split("\\.");
int maxLength = Math.max(newParts.length, currentParts.length);
for (int i = 0; i < maxLength; i++) {
int newPart = (i < newParts.length) ? parseIntOrZero(newParts[i]) : 0;
int currentPart = (i < currentParts.length) ? parseIntOrZero(currentParts[i]) : 0;
if (newPart > currentPart) {
return true;
}
if (newPart < currentPart) {
return false;
}
}
return false;
}
// 尝试将字符串转换为整数如果转换失败则返回0
private int parseIntOrZero(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return 0;
}
}
}

View File

@ -3,240 +3,493 @@ package com.example.playertime;
import com.google.gson.*; import com.google.gson.*;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Uuids;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.stream.Collectors;
import java.util.concurrent.Executors;
public class PlayerTimeTracker { public class PlayerTimeTracker {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final MinecraftServer server; private final MinecraftServer server;
private final Path dataFile; private final Path dataFile;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final Map<UUID, PlayerTimeData> playerData = new ConcurrentHashMap<>(); private final Map<UUID, PlayerTimeData> playerData = new ConcurrentHashMap<>();
private final ModConfig config;
public PlayerTimeTracker(MinecraftServer server) { public PlayerTimeTracker(MinecraftServer server, ModConfig config) {
this.server = server; this.server = server;
this.config = config;
this.dataFile = server.getRunDirectory().resolve("player_time_data.json"); this.dataFile = server.getRunDirectory().resolve("player_time_data.json");
loadData();
} }
private boolean isWhitelisted(String playerName) { public void loadData() {
MinecraftServer server = this.server; if (!Files.exists(dataFile)) {
if (server == null) return false; PlayerTimeMod.LOGGER.info("[在线时间] 数据文件未找到 ({}),跳过加载。", dataFile);
return;
}
return server.getPlayerManager().getWhitelist() try (Reader reader = Files.newBufferedReader(dataFile, StandardCharsets.UTF_8)) {
.isAllowed(server.getUserCache().findByName(playerName).orElse(null)); JsonElement jsonElement = JsonParser.parseReader(reader);
if (jsonElement == null || !jsonElement.isJsonObject()) {
PlayerTimeMod.LOGGER.warn("[在线时间] 数据文件 ({}) 为空或格式错误,跳过加载。", dataFile);
return;
}
JsonObject root = jsonElement.getAsJsonObject();
int resetCount = 0;
int loadedCount = 0;
for (Map.Entry<String, JsonElement> entry : root.entrySet()) {
try {
UUID uuid = UUID.fromString(entry.getKey());
PlayerTimeData data = GSON.fromJson(entry.getValue(), PlayerTimeData.class);
// 检查并重置上次登录时间防止服务器崩溃导致时间计算错误
if (data.lastLogin > 0) {
PlayerTimeMod.LOGGER.warn(
"[在线时间] 在数据加载过程中发现玩家UUID{}的最后登录时间大于0{}。将其重置为0。",
uuid, data.lastLogin
);
data.lastLogin = 0;
resetCount++;
}
playerData.put(uuid, data);
loadedCount++;
} catch (IllegalArgumentException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 数据文件中的 UUID 格式无效: " + entry.getKey(), e);
} catch (JsonParseException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 解析玩家数据失败(UUID: " + entry.getKey() + ")", e);
}
}
PlayerTimeMod.LOGGER.info("[在线时间] 成功加载了 {} 名玩家的数据,重置了 {} 名玩家的上次登录时间。", loadedCount, resetCount);
} catch (IOException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法读取玩家在线时间数据文件 ({})", dataFile, e);
} catch (JsonParseException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 玩家在线时间数据文件 ({}) 格式错误", dataFile, e);
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 加载玩家在线时间数据时发生未知错误", e);
}
} }
public void onPlayerJoin(ServerPlayerEntity player) { public void onPlayerJoin(ServerPlayerEntity player) {
PlayerTimeData data = playerData.computeIfAbsent(player.getUuid(), uuid -> new PlayerTimeData()); UUID uuid = player.getUuid();
// 检查配置是否白名单
if (config.isWhitelistOnly() && !server.getPlayerManager().isWhitelisted(player.getGameProfile())) {
PlayerTimeMod.LOGGER.debug("[在线时间] 玩家 {} ({}) 不在白名单,且配置为仅记录白名单玩家,跳过加入处理。", player.getName().getString(), uuid);
return;
}
PlayerTimeData data = playerData.computeIfAbsent(uuid, k -> {
PlayerTimeMod.LOGGER.info("[在线时间] 为新玩家 {} ({}) 创建数据。", player.getName().getString(), uuid);
return new PlayerTimeData();
});
// 记录本次登录的开始时间
data.lastLogin = Instant.now().getEpochSecond(); data.lastLogin = Instant.now().getEpochSecond();
saveAsync(player.getUuid()); PlayerTimeMod.LOGGER.info("[在线时间] 玩家 {} ({}) 加入, 开始计时。", player.getName().getString(), uuid);
} }
public void onPlayerLeave(ServerPlayerEntity player) { public void onPlayerLeave(ServerPlayerEntity player) {
PlayerTimeData data = playerData.get(player.getUuid()); UUID uuid = player.getUuid();
if (data != null) { PlayerTimeData data = playerData.get(uuid);
// 防幽灵
if (data != null && data.lastLogin > 0) {
long now = Instant.now().getEpochSecond(); long now = Instant.now().getEpochSecond();
long sessionTime = now - data.lastLogin; long sessionTime = now - data.lastLogin;
data.totalTime += sessionTime;
// 维护30天滚动窗口 if (sessionTime > 0) {
data.rolling30Days.addPlayTime(now, sessionTime); data.totalTime += sessionTime;
data.rolling7Days.addPlayTime(now, sessionTime); data.rolling30Days.addPlayTime(now, sessionTime);
data.rolling7Days.addPlayTime(now, sessionTime);
data.lastLogin = 0; PlayerTimeMod.LOGGER.info("[在线时间] 玩家 {} ({}) 离开, 会话时间 {} 秒, 总计时间 {} 秒。",
saveAsync(player.getUuid()); player.getName().getString(), uuid, sessionTime, data.totalTime);
} } else {
} // 防其他因素
PlayerTimeMod.LOGGER.warn("[在线时间] 玩家 {} ({}) 离开, 但计算出的会话时间不正常 ({}), 跳过时间累加。",
public PlayerTimeStats getPlayerStats(UUID uuid) { player.getName().getString(), uuid, sessionTime);
PlayerTimeData data = playerData.get(uuid);
if (data == null) {
return null;
}
long now = Instant.now().getEpochSecond();
PlayerTimeStats stats = new PlayerTimeStats();
stats.totalTime = data.totalTime;
// 如果玩家在线添加当前会话时间
if (data.lastLogin > 0) {
stats.totalTime += (now - data.lastLogin);
}
stats.last30Days = data.rolling30Days.getTotalTime(now);
stats.last7Days = data.rolling7Days.getTotalTime(now);
return stats;
}
public Map<String, String> getWhitelistedPlayerStats() {
Map<String, String> stats = new LinkedHashMap<>();
long now = Instant.now().getEpochSecond();
// 获取白名单玩家UUID集合
Set<UUID> whitelistUuids = new HashSet<>();
for (String name : server.getPlayerManager().getWhitelist().getNames()) {
server.getUserCache().findByName(name).ifPresent(profile -> {
whitelistUuids.add(profile.getId());
});
}
// 遍历所有已记录玩家
playerData.forEach((uuid, data) -> {
if (whitelistUuids.contains(uuid)) {
String playerName = getPlayerName(uuid);
long totalTime = data.totalTime;
if (data.lastLogin > 0) {
totalTime += (now - data.lastLogin);
}
stats.put(playerName, "总时长: " + formatTime(totalTime) +
" | 30天: " + formatTime(data.rolling30Days.getTotalTime(now)) +
" | 7天: " + formatTime(data.rolling7Days.getTotalTime(now)));
} }
});
return stats; // 标记离线
data.lastLogin = 0;
} else {
PlayerTimeMod.LOGGER.debug("[在线时间] 玩家 {} ({}) 离开但数据不存在或上次登录时间为0跳过会话时间计算。", player.getName().getString(), uuid);
}
} }
public boolean isPlayerTracked(UUID uuid) {
return playerData.containsKey(uuid);
}
public List<PlayerTimeStatsWithNames> getSortedPlayerStats() {
long now = Instant.now().getEpochSecond();
List<PlayerTimeStatsWithNames> statsList = new ArrayList<>();
// 获取白名单 UUID 集合 (如果需要过滤)
Set<UUID> whitelistUuids;
if (config.isWhitelistOnly()) {
whitelistUuids = new HashSet<>();
if (server != null && server.getPlayerManager() != null && server.getUserCache() != null) {
for (String name : server.getPlayerManager().getWhitelist().getNames()) {
server.getUserCache().findByName(name).ifPresent(profile -> {
whitelistUuids.add(profile.getId());
});
}
} else {
PlayerTimeMod.LOGGER.warn("[在线时间] UserCache 或 PlayerManager 不可用,无法获取白名单列表进行过滤!");
// 异常处理返回空列表
return Collections.emptyList();
}
} else {
whitelistUuids = null;
}
for (Map.Entry<UUID, PlayerTimeData> entry : playerData.entrySet()) {
UUID uuid = entry.getKey();
PlayerTimeData data = entry.getValue();
// 是不是白名单玩家
if (config.isWhitelistOnly() && (whitelistUuids == null || !whitelistUuids.contains(uuid))) {
continue;
}
// 计算当前总时间
long currentTotalTime = data.totalTime;
// 只有当玩家在线时才计算当前会话时间
if (data.lastLogin > 0 && server.getPlayerManager().getPlayer(uuid) != null) {
long currentSessionTime = now - data.lastLogin;
if (currentSessionTime > 0) {
currentTotalTime += currentSessionTime;
}
}
// 获取滚动时间
long last30DaysTime = data.rolling30Days.getTotalTime(now);
long last7DaysTime = data.rolling7Days.getTotalTime(now);
// 获取玩家名称
String playerName = getPlayerName(uuid);
statsList.add(new PlayerTimeStatsWithNames(uuid, playerName, currentTotalTime, last30DaysTime, last7DaysTime));
}
// 按总时排序
statsList.sort(Comparator.comparingLong(PlayerTimeStatsWithNames::getTotalTime).reversed());
return statsList;
}
public String getPlayerName(UUID uuid) { public String getPlayerName(UUID uuid) {
// 尝试获取在线玩家 // 尝试获取在线玩家名称
ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid);
if (player != null) { if (player != null) {
return player.getName().getString(); return player.getName().getString();
} }
// 尝试从用户缓存获取 - 现在正确处理Optional // 尝试从 UserCache 获取名称主要用于离线服务器
Optional<GameProfile> profile = server.getUserCache().getByUuid(uuid); if (server != null && server.getUserCache() != null) {
if (profile.isPresent()) { Optional<GameProfile> profile = server.getUserCache().getByUuid(uuid);
return profile.get().getName(); if (profile.isPresent()) {
} return profile.get().getName();
return "Unknown";
}
private void loadData() {
if (!Files.exists(dataFile)) {
return;
}
try (Reader reader = Files.newBufferedReader(dataFile)) {
JsonObject root = JsonParser.parseReader(reader).getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : root.entrySet()) {
UUID uuid = UUID.fromString(entry.getKey());
playerData.put(uuid, GSON.fromJson(entry.getValue(), PlayerTimeData.class));
} }
} catch (Exception e) { } else {
PlayerTimeMod.LOGGER.error("[在线时间] 无法加载玩家在线时间数据", e); PlayerTimeMod.LOGGER.debug("[在线时间] 尝试通过 UUID 获取玩家名称时 UserCache 不可用: {}", uuid);
} }
return uuid.toString();
} }
public void saveAll() { public void saveAll() {
PlayerTimeMod.LOGGER.info("[在线时间] 开始保存所有玩家数据...");
long now = Instant.now().getEpochSecond();
JsonObject root = new JsonObject(); JsonObject root = new JsonObject();
playerData.forEach((uuid, data) -> { int savedCount = 0;
root.add(uuid.toString(), GSON.toJsonTree(data));
});
try (Writer writer = Files.newBufferedWriter(dataFile)) { for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) {
GSON.toJson(root, writer); UUID uuid = player.getUuid();
PlayerTimeData data = playerData.get(uuid);
// 只有被跟踪且没标记离线
if (data != null && data.lastLogin > 0) {
long sessionTime = now - data.lastLogin;
if (sessionTime > 0) {
data.totalTime += sessionTime;
data.rolling30Days.addPlayTime(now, sessionTime);
data.rolling7Days.addPlayTime(now, sessionTime);
// 更新 lastLogin 到当前时间防止炸鱼
data.lastLogin = now;
PlayerTimeMod.LOGGER.debug("[在线时间] 定时保存:更新玩家 {} ({}) 会话时间 {} 秒。", player.getName().getString(), uuid, sessionTime);
} else {
PlayerTimeMod.LOGGER.debug("[在线时间] 定时保存:玩家 {} ({}) 会话时间不正常 ({}),跳过更新。", player.getName().getString(), uuid, sessionTime);
}
}
}
// 遍历所有玩家数据进行保存
for (Map.Entry<UUID, PlayerTimeData> entry : playerData.entrySet()) {
UUID uuid = entry.getKey();
PlayerTimeData data = entry.getValue();
boolean isWhitelisted = false;
if (server != null && server.getPlayerManager() != null) {
// 优先检查在线玩家
ServerPlayerEntity onlinePlayer = server.getPlayerManager().getPlayer(uuid);
if (onlinePlayer != null) {
isWhitelisted = server.getPlayerManager().isWhitelisted(onlinePlayer.getGameProfile());
} else if (server.getUserCache() != null) {
// 检查离线玩家是否在白名单
Optional<GameProfile> profile = server.getUserCache().getByUuid(uuid);
if (profile.isPresent()) {
isWhitelisted = server.getPlayerManager().isWhitelisted(profile.get());
}
}
} else {
PlayerTimeMod.LOGGER.warn("[在线时间] UserCache 或 PlayerManager 不可用,无法在保存时检查白名单状态。");
// 如果无法检查白名单且配置为只记录白名单则跳过保存此玩家数据
if (config.isWhitelistOnly()) {
PlayerTimeMod.LOGGER.debug("[在线时间] 无法检查白名单状态,且配置为仅记录白名单,跳过保存玩家 {} ({}) 的数据。", getPlayerName(uuid), uuid);
continue;
}
}
if (config.isWhitelistOnly() && !isWhitelisted) {
PlayerTimeMod.LOGGER.debug("[在线时间] 配置为仅记录白名单,跳过保存非白名单玩家 {} ({}) 的数据。", getPlayerName(uuid), uuid);
continue;
}
root.add(uuid.toString(), GSON.toJsonTree(data));
savedCount++;
}
try {
Path dataDir = dataFile.getParent();
if (dataDir != null) {
Files.createDirectories(dataDir);
} else {
PlayerTimeMod.LOGGER.debug("[在线时间] 数据文件 {} 位于根目录,跳过创建父目录。", dataFile);
}
Path tempFile = dataFile.resolveSibling(dataFile.getFileName().toString() + ".tmp");
try (Writer writer = Files.newBufferedWriter(tempFile, StandardCharsets.UTF_8)) {
GSON.toJson(root, writer);
}
Files.move(tempFile, dataFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
PlayerTimeMod.LOGGER.info("[在线时间] 所有玩家数据 ({}) 已成功保存,共 {} 条记录。", dataFile, savedCount);
} catch (Exception e) { } catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法保存玩家在线时间数据", e); PlayerTimeMod.LOGGER.error("[在线时间] 无法保存所有玩家在线时间数据到 {}", dataFile, e);
} }
} }
private void saveAsync(UUID uuid) {
executor.execute(() -> {
JsonObject root;
try {
if (Files.exists(dataFile)) {
try (Reader reader = Files.newBufferedReader(dataFile)) {
root = JsonParser.parseReader(reader).getAsJsonObject();
}
} else {
root = new JsonObject();
}
} catch (Exception e) {
root = new JsonObject();
}
PlayerTimeData data = playerData.get(uuid);
if (data != null) {
root.add(uuid.toString(), GSON.toJsonTree(data));
}
try (Writer writer = Files.newBufferedWriter(dataFile)) {
GSON.toJson(root, writer);
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法保存" + uuid + "的在线时间数据", e);
}
});
}
public static String formatTime(long seconds) { public static String formatTime(long seconds) {
if (seconds < 0) seconds = 0;
long hours = seconds / 3600; long hours = seconds / 3600;
long minutes = (seconds % 3600) / 60; long minutes = (seconds % 3600) / 60;
return String.format("%dh %02dm", hours, minutes); return String.format("%dh %02dm", hours, minutes);
} }
public static class PlayerTimeData { public static class PlayerTimeData {
long totalTime = 0; long totalTime = 0; // 总在线时间
long lastLogin = 0; long lastLogin = 0; // 上次登录时间戳
RollingTimeWindow rolling30Days = new RollingTimeWindow(30); RollingTimeWindow rolling30Days = new RollingTimeWindow(30); // 最近30天
RollingTimeWindow rolling7Days = new RollingTimeWindow(7); RollingTimeWindow rolling7Days = new RollingTimeWindow(7); // 最近7天
}
public static class PlayerTimeStats {
public long totalTime;
public long last30Days;
public long last7Days;
} }
private static class RollingTimeWindow { private static class RollingTimeWindow {
private final int days; private final int days;
private final List<TimeEntry> entries = new ArrayList<>(); private final List<TimeEntry> entries = new LinkedList<>();
@SuppressWarnings("unused")
private RollingTimeWindow() {
this.days = 0;
}
public RollingTimeWindow(int days) { public RollingTimeWindow(int days) {
this.days = days; this.days = days;
} }
public void addPlayTime(long timestamp, long seconds) { public void addPlayTime(long timestamp, long seconds) {
if (seconds <= 0) return;
entries.add(new TimeEntry(timestamp, seconds)); entries.add(new TimeEntry(timestamp, seconds));
cleanUp(timestamp); cleanUp(timestamp);
} }
public long getTotalTime(long currentTime) { public long getTotalTime(long currentTime) {
cleanUp(currentTime); cleanUp(currentTime);
return entries.stream().mapToLong(e -> e.seconds).sum(); return entries.stream().mapToLong(e -> e.seconds).sum();
} }
private void cleanUp(long currentTime) { private void cleanUp(long currentTime) {
long cutoff = currentTime - (days * 24 * 3600); long cutoff = currentTime - (days * 24 * 3600L);
entries.removeIf(entry -> entry.timestamp < cutoff); entries.removeIf(entry -> entry.timestamp < cutoff);
} }
private static class TimeEntry { private static class TimeEntry {
final long timestamp; final long timestamp;
final long seconds; final long seconds;
// Gson 需要一个无参构造函数
@SuppressWarnings("unused")
private TimeEntry() {
this.timestamp = 0;
this.seconds = 0;
}
TimeEntry(long timestamp, long seconds) { TimeEntry(long timestamp, long seconds) {
this.timestamp = timestamp; this.timestamp = timestamp;
this.seconds = seconds; this.seconds = seconds;
} }
} }
} }
public static class PlayerTimeStatsWithNames {
public UUID uuid;
public String playerName;
private long totalTime;
public long last30Days;
public long last7Days;
@SuppressWarnings("unused")
private PlayerTimeStatsWithNames() {}
public PlayerTimeStatsWithNames(UUID uuid, String playerName, long totalTime, long last30Days, long last7Days) {
this.uuid = uuid;
this.playerName = playerName;
this.totalTime = totalTime;
this.last30Days = last30Days;
this.last7Days = last7Days;
}
public long getTotalTime() {
return totalTime;
}
}
public Map<UUID, PlayerTimeData> getPlayerData() { public Map<UUID, PlayerTimeData> getPlayerData() {
return Collections.unmodifiableMap(playerData); return Collections.unmodifiableMap(playerData);
} }
} public Path getDataFile() {
return this.dataFile;
}
public Map<String, List<Map<String, String>>> getOnlinePlayersCategorized() {
List<Map<String, String>> whitelisted = new ArrayList<>();
List<Map<String, String>> nonWhitelisted = new ArrayList<>();
PlayerManager playerManager = server.getPlayerManager();
Set<UUID> whitelistUuids = new HashSet<>();
if (server != null && server.getUserCache() != null) {
for (String name : playerManager.getWhitelist().getNames()) {
server.getUserCache().findByName(name).ifPresent(profile -> {
whitelistUuids.add(profile.getId());
});
}
} else {
PlayerTimeMod.LOGGER.warn("[在线时间] UserCache 不可用无法获取白名单UUID用于在线玩家分类。");
}
for (ServerPlayerEntity player : playerManager.getPlayerList()) {
Map<String, String> playerInfo = new HashMap<>();
playerInfo.put("name", player.getName().getString());
playerInfo.put("uuid", player.getUuid().toString());
if (whitelistUuids.contains(player.getUuid())) {
whitelisted.add(playerInfo);
} else {
nonWhitelisted.add(playerInfo);
}
}
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("whitelisted", whitelisted);
result.put("non_whitelisted", nonWhitelisted);
return result;
}
public Map<String, Integer> getOnlinePlayerCounts() {
int total = 0;
int whitelisted = 0;
int nonWhitelisted = 0;
PlayerManager playerManager = server.getPlayerManager();
Set<UUID> whitelistUuids = new HashSet<>();
if (server != null && server.getUserCache() != null) {
for (String name : playerManager.getWhitelist().getNames()) {
server.getUserCache().findByName(name).ifPresent(profile -> {
whitelistUuids.add(profile.getId());
});
}
} else {
PlayerTimeMod.LOGGER.warn("[在线时间] UserCache 不可用无法获取白名单UUID用于玩家计数分类。");
}
for (ServerPlayerEntity player : playerManager.getPlayerList()) {
total++;
if (whitelistUuids.contains(player.getUuid())) {
whitelisted++;
} else {
nonWhitelisted++;
}
}
Map<String, Integer> result = new HashMap<>();
result.put("total", total);
result.put("whitelisted", whitelisted);
result.put("non_whitelisted", nonWhitelisted);
return result;
}
public List<Map<String, Object>> getWhitelistPlayers() {
List<Map<String, Object>> whitelist = new ArrayList<>();
PlayerManager playerManager = server.getPlayerManager();
if (server != null && server.getUserCache() != null) {
for (String name : playerManager.getWhitelist().getNames()) {
Map<String, Object> player = new HashMap<>();
player.put("name", name);
Optional<GameProfile> profile = server.getUserCache().findByName(name);
if (profile.isPresent()) {
UUID uuid = profile.get().getId();
player.put("uuid", uuid.toString());
ServerPlayerEntity onlinePlayer = playerManager.getPlayer(uuid);
player.put("online", onlinePlayer != null);
} else {
UUID offlineUuid = Uuids.getOfflinePlayerUuid(name);
player.put("uuid", offlineUuid.toString());
ServerPlayerEntity onlinePlayer = playerManager.getPlayer(offlineUuid);
player.put("online", onlinePlayer != null);
}
whitelist.add(player);
}
} else {
PlayerTimeMod.LOGGER.warn("[在线时间] UserCache 不可用,无法获取白名单列表。");
}
return whitelist;
}
}

View File

@ -4,19 +4,28 @@ import com.google.gson.*;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.PlayerManager; import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import java.io.*; import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.*; import java.nio.file.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.stream.Collectors;
// 导入API类别忘了
import com.example.playertime.api.PlayerStatsResponse;
import com.example.playertime.api.ServerStatusResponse;
import com.example.playertime.api.OnlinePlayersResponse;
import com.example.playertime.api.PlayerCountResponse;
import com.example.playertime.api.WhitelistResponse;
import static com.mojang.text2speech.Narrator.LOGGER;
public class WebServer { public class WebServer {
private final HttpServer server; private final HttpServer server;
@ -24,11 +33,22 @@ public class WebServer {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final ExecutorService executor = Executors.newFixedThreadPool(4); private final ExecutorService executor = Executors.newFixedThreadPool(4);
private final MinecraftServer minecraftServer; private final MinecraftServer minecraftServer;
private static final Map<String, String> MIME_TYPES = Map.of(
"html", "text/html", private static final Map<String, String> MIME_TYPES = Map.ofEntries(
"css", "text/css", Map.entry("html", "text/html"),
"js", "application/javascript", Map.entry("css", "text/css"),
"json", "application/json" Map.entry("js", "application/javascript"),
Map.entry("json", "application/json"),
Map.entry("png", "image/png"),
Map.entry("jpg", "image/jpeg"),
Map.entry("jpeg", "image/jpeg"),
Map.entry("gif", "image/gif"),
Map.entry("svg", "image/svg+xml"),
Map.entry("woff", "application/font-woff"),
Map.entry("woff2", "application/font-woff2"),
Map.entry("ttf", "application/font-sfnt"),
Map.entry("eot", "application/vnd.ms-fontobject"),
Map.entry("ico", "image/x-icon")
); );
public WebServer(PlayerTimeTracker timeTracker, int port, MinecraftServer minecraftServer) throws IOException { public WebServer(PlayerTimeTracker timeTracker, int port, MinecraftServer minecraftServer) throws IOException {
@ -41,12 +61,15 @@ public class WebServer {
setupContexts(); setupContexts();
} }
// 创建HTTP服务器
private void setupContexts() { private void setupContexts() {
// API: 获取玩家统计数据
server.createContext("/api/stats", exchange -> { server.createContext("/api/stats", exchange -> {
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); handleCors(exchange);
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS"); if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type"); exchange.sendResponseHeaders(204, -1);
return;
}
if (!"GET".equals(exchange.getRequestMethod())) { if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed"); sendResponse(exchange, 405, "Method Not Allowed");
@ -54,144 +77,332 @@ public class WebServer {
} }
try { try {
// 改为使用新的白名单统计方法 List<PlayerTimeTracker.PlayerTimeStatsWithNames> statsList = timeTracker.getSortedPlayerStats();
Map<String, String> stats = timeTracker.getWhitelistedPlayerStats();
String response = new Gson().toJson(stats); List<PlayerStatsResponse> responseList = statsList.stream()
sendResponse(exchange, 200, response.getBytes(), "application/json"); .map(stats -> new PlayerStatsResponse(
stats.playerName,
stats.uuid.toString(),
stats.getTotalTime(),
PlayerTimeTracker.formatTime(stats.getTotalTime()),
stats.last30Days,
PlayerTimeTracker.formatTime(stats.last30Days),
stats.last7Days,
PlayerTimeTracker.formatTime(stats.last7Days)
))
.collect(Collectors.toList());
String response = GSON.toJson(responseList);
sendResponse(exchange, 200, response.getBytes(StandardCharsets.UTF_8), "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/stats 请求成功,返回 {} 条玩家数据。", responseList.size());
} catch (Exception e) { } catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法获得统计数据", e); PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/stats 请求失败", e);
sendResponse(exchange, 500, "Internal Server Error"); sendResponse(exchange, 500, "Internal Server Error");
} }
}); });
// 静态文件服务 // API: 获取语言文件内容不公开
server.createContext("/", exchange -> { server.createContext("/api/lang", exchange -> {
handleCors(exchange);
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1);
return;
}
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try { try {
String path = exchange.getRequestURI().getPath(); Map<String, String> langMap = PlayerTimeMod.getLocalizationManager().getAllStrings();
if (path.equals("/")) path = "/index.html"; String response = GSON.toJson(langMap);
sendResponse(exchange, 200, response.getBytes(StandardCharsets.UTF_8), "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/lang 请求成功,返回 {} 条语言字符串。", langMap.size());
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/lang 请求失败", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
// 从资源目录加载文件 // API: 获取在线玩家列表
String resourcePath = "assets/playertime/web" + path; server.createContext("/api/online-players", exchange -> {
InputStream is = getClass().getClassLoader().getResourceAsStream(resourcePath); handleCors(exchange);
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1);
return;
}
if (is == null) { if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 404, "Not Found"); sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
Map<String, List<Map<String, String>>> onlinePlayers = timeTracker.getOnlinePlayersCategorized();
OnlinePlayersResponse response = new OnlinePlayersResponse(onlinePlayers.get("whitelisted"), onlinePlayers.get("non_whitelisted"));
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/online-players 请求成功。");
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/online-players 请求失败", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
// API: 获取在线玩家数量
server.createContext("/api/player-count", exchange -> {
handleCors(exchange);
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1);
return;
}
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
Map<String, Integer> counts = timeTracker.getOnlinePlayerCounts();
PlayerCountResponse response = new PlayerCountResponse(counts.get("total"), counts.get("whitelisted"), counts.get("non_whitelisted"));
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/player-count 请求成功。");
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/player-count 请求失败", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
// API: 获取白名单列表
server.createContext("/api/whitelist", exchange -> {
handleCors(exchange);
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1);
return;
}
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
List<Map<String, Object>> whitelist = timeTracker.getWhitelistPlayers();
List<WhitelistResponse> responseList = whitelist.stream()
.map(map -> new WhitelistResponse((String)map.get("name"), (String)map.get("uuid"), (Boolean)map.get("online")))
.collect(Collectors.toList());
sendResponse(exchange, 200, GSON.toJson(responseList).getBytes(StandardCharsets.UTF_8), "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/whitelist 请求成功,返回 {} 条白名单记录。", responseList.size());
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/whitelist 请求失败", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
// API: 获取服务器状态
server.createContext("/api/server-status", exchange -> {
handleCors(exchange);
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1);
return;
}
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
Runtime runtime = Runtime.getRuntime();
ServerStatusResponse status = new ServerStatusResponse();
long maxMemory = runtime.maxMemory();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long usedMemory = totalMemory - freeMemory;
status.memory.max = maxMemory;
status.memory.total = totalMemory;
status.memory.used = usedMemory;
status.memory.free = freeMemory;
status.memory.usage_percentage = (double) usedMemory / maxMemory * 100;
status.available_processors = runtime.availableProcessors();
long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
status.uptime = uptimeMillis / 1000; //
status.uptime_formatted = formatUptime(uptimeMillis);
try {
File diskPartition = new File(".");
status.disk.total = diskPartition.getTotalSpace();
status.disk.free = diskPartition.getFreeSpace();
status.disk.usable = diskPartition.getUsableSpace();
status.disk.usage_percentage = (double) (status.disk.total - status.disk.free) / status.disk.total * 100;
} catch (Exception e) {
PlayerTimeMod.LOGGER.warn("[在线时间] 无法获取磁盘信息", e);
}
status.server.version = minecraftServer.getVersion();
status.server.player_count = minecraftServer.getCurrentPlayerCount();
status.server.max_players = minecraftServer.getMaxPlayerCount();
status.server.motd = minecraftServer.getServerMotd();
status.server.average_tick_time_ms = minecraftServer.getAverageTickTime();
long[] tickTimes = minecraftServer.getTickTimes();
if (tickTimes != null && tickTimes.length > 0) {
long[] recentTicksCopy = Arrays.copyOf(tickTimes, tickTimes.length);
status.server.recent_tick_samples_ms = Arrays.stream(recentTicksCopy)
.mapToDouble(tick -> tick / 1000000.0)
.boxed()
.collect(Collectors.toList());
} else {
status.server.recent_tick_samples_ms = Collections.emptyList();
}
sendResponse(exchange, 200, GSON.toJson(status).getBytes(StandardCharsets.UTF_8), "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/server-status 请求成功。");
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/server-status 请求失败", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
// API: 获取原始玩家数据文件内容建议最好别公开
server.createContext("/api/playerdata", exchange -> {
handleCors(exchange);
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1);
return;
}
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
Path dataFile = timeTracker.getDataFile();
if (!Files.exists(dataFile)) {
PlayerTimeMod.LOGGER.warn("[在线时间] 玩家数据文件未找到: {}", dataFile);
sendResponse(exchange, 404, "Data file not found");
return; return;
} }
// 确定内容类型 byte[] fileContent = Files.readAllBytes(dataFile);
String extension = path.substring(path.lastIndexOf('.') + 1);
String contentType = MIME_TYPES.getOrDefault(extension, "text/plain"); sendResponse(exchange, 200, fileContent, "application/json");
PlayerTimeMod.LOGGER.debug("[在线时间] 成功提供玩家数据文件 {}", dataFile);
} catch (IOException e) {
PlayerTimeMod.LOGGER.error("[在线时间] 读取玩家数据文件时出错", e);
sendResponse(exchange, 500, "Error reading data file");
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/playerdata 请求时发生未知错误", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
// 静态文件服务
server.createContext("/", exchange -> {
try {
String requestPath = exchange.getRequestURI().getPath();
String resourcePath = "assets/playertime/web" + requestPath;
if (requestPath.equals("/")) {
resourcePath += "index.html";
}
if (resourcePath.contains("..")) {
sendResponse(exchange, 403, "Forbidden");
return;
}
String finalResourcePath = resourcePath;
InputStream is = FabricLoader.getInstance().getModContainer("playertime")
.flatMap(container -> container.findPath(finalResourcePath))
.map(p -> {
try {
return p.toUri().toURL().openStream();
} catch (Exception e) {
return null;
}
})
.orElse(null);
if (is == null) {
if (!requestPath.equals("/") && !requestPath.contains(".")) {
PlayerTimeMod.LOGGER.debug("[在线时间] 找不到静态资源:{},尝试提供 index.html 作为 fallback。", resourcePath);
resourcePath = "assets/playertime/web/index.html";
String finalResourcePath1 = resourcePath;
is = FabricLoader.getInstance().getModContainer("playertime")
.flatMap(container -> container.findPath(finalResourcePath1))
.map(p -> {
try {
return p.toUri().toURL().openStream();
} catch (Exception e) {
return null;
}
})
.orElse(null);
}
if (is == null) {
PlayerTimeMod.LOGGER.warn("[在线时间] 找不到静态资源: {}", finalResourcePath);
sendResponse(exchange, 404, "Not Found");
return;
}
}
String fileName = Paths.get(resourcePath).getFileName().toString();
String extension = "";
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
extension = fileName.substring(dotIndex + 1).toLowerCase();
}
String contentType = MIME_TYPES.getOrDefault(extension, "application/octet-stream");
// 读取文件内容
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[1024]; byte[] data = new byte[4096];
int nRead; int nRead;
while ((nRead = is.read(data, 0, data.length)) != -1) { while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead); buffer.write(data, 0, nRead);
} }
buffer.flush(); buffer.flush();
is.close();
sendResponse(exchange, 200, buffer.toByteArray(), contentType); sendResponse(exchange, 200, buffer.toByteArray(), contentType);
PlayerTimeMod.LOGGER.debug("[在线时间] 提供静态文件: {}", resourcePath);
} catch (Exception e) { } catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法提供资源", e); PlayerTimeMod.LOGGER.error("[在线时间] 无法提供静态资源", e);
sendResponse(exchange, 500, "Internal Server Error"); sendResponse(exchange, 500, "Internal Server Error");
} }
}); });
server.createContext("/api/widget-data", exchange -> {
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(204, -1); // 204 No Content
return;
}
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
MinecraftServer server = minecraftServer;
PlayerManager playerManager = server.getPlayerManager();
JsonObject response = new JsonObject();
response.addProperty("onlineCount", playerManager.getCurrentPlayerCount());
// 获取白名单在线玩家
JsonArray whitelistPlayers = new JsonArray();
Map<String, Long> playerTimeMap = new HashMap<>();
// 先收集所有白名单玩家UUID
Set<UUID> whitelistUuids = new HashSet<>();
for (String name : playerManager.getWhitelist().getNames()) {
server.getUserCache().findByName(name).ifPresent(profile -> {
whitelistUuids.add(profile.getId());
});
}
// 检查在线玩家
for (ServerPlayerEntity player : playerManager.getPlayerList()) {
UUID uuid = player.getUuid();
if (whitelistUuids.contains(uuid)) {
PlayerTimeTracker.PlayerTimeStats stats = timeTracker.getPlayerStats(uuid);
if (stats != null) {
JsonObject playerJson = new JsonObject();
playerJson.addProperty("name", player.getName().getString());
playerJson.addProperty("time", PlayerTimeTracker.formatTime(stats.totalTime));
whitelistPlayers.add(playerJson);
playerTimeMap.put(player.getName().getString(), stats.totalTime);
}
}
}
response.add("whitelistPlayers", whitelistPlayers);
// 获取时长前三玩家包括离线玩家
JsonArray topPlayers = new JsonArray();
timeTracker.getPlayerData().entrySet().stream()
.filter(entry -> whitelistUuids.contains(entry.getKey())) // 只筛选白名单玩家
.sorted((a, b) -> Long.compare(b.getValue().totalTime, a.getValue().totalTime))
.limit(3)
.forEach(entry -> {
JsonObject playerJson = new JsonObject();
playerJson.addProperty("name", timeTracker.getPlayerName(entry.getKey()));
playerJson.addProperty("time", PlayerTimeTracker.formatTime(entry.getValue().totalTime));
topPlayers.add(playerJson);
});
response.add("topPlayers", topPlayers);
response.addProperty("timestamp", System.currentTimeMillis());
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
} catch (Exception e) {
PlayerTimeMod.LOGGER.error("[在线时间] 无法获得统计数据", e);
sendResponse(exchange, 500, "Internal Server Error");
}
});
server.setExecutor(executor); server.setExecutor(executor);
} }
// 跨域处理
private void handleCors(HttpExchange exchange) {
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
}
// 发送响应
private void sendResponse(HttpExchange exchange, int code, String response) throws IOException { private void sendResponse(HttpExchange exchange, int code, String response) throws IOException {
sendResponse(exchange, code, response.getBytes(StandardCharsets.UTF_8), "text/plain"); sendResponse(exchange, code, response.getBytes(StandardCharsets.UTF_8), "text/plain");
} }
private void sendResponse(HttpExchange exchange, int code, byte[] response, String contentType) throws IOException { private void sendResponse(HttpExchange exchange, int code, byte[] response, String contentType) throws IOException {
exchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
exchange.getResponseHeaders().set("Access-Control-Allow-Methods", "GET, OPTIONS");
exchange.getResponseHeaders().set("Access-Control-Allow-Headers", "Content-Type");
exchange.getResponseHeaders().set("Content-Type", contentType); exchange.getResponseHeaders().set("Content-Type", contentType);
exchange.sendResponseHeaders(code, response.length); exchange.sendResponseHeaders(code, response.length);
try (OutputStream os = exchange.getResponseBody()) { try (OutputStream os = exchange.getResponseBody()) {
@ -199,61 +410,41 @@ public class WebServer {
} }
} }
// 启动
public void start() { public void start() {
server.start(); server.start();
} }
// 停止
public void stop() { public void stop() {
server.stop(0); server.stop(3);
executor.shutdown(); executor.shutdown();
} try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
executor.shutdownNow(); // 强制关闭
// 以前ai留下的烂方法大概没用了注释也是ai的 }
} catch (InterruptedException e) {
private String generatePlayerList(Map<String, String> stats) { executor.shutdownNow();
if (stats.isEmpty()) return "<p>暂无玩家数据</p>"; Thread.currentThread().interrupt();
StringBuilder sb = new StringBuilder("<ul style='list-style-type: none; padding-left: 5px;'>");
stats.keySet().stream().limit(5).forEach(player -> {
sb.append("<li>• ").append(player).append("</li>");
});
if (stats.size() > 5) {
sb.append("<li>... 等 ").append(stats.size() - 5).append(" 位玩家</li>");
}
sb.append("</ul>");
return sb.toString();
}
// 辅助方法"Xh Ym"格式的时间转换为秒数
private long parseTimeToSeconds(String timeStr) {
String[] parts = timeStr.split(" ");
int hours = Integer.parseInt(parts[0].replace("h", ""));
int minutes = parts.length > 1 ? Integer.parseInt(parts[1].replace("m", "")) : 0;
return hours * 3600L + minutes * 60L;
}
// 读取时间数据文件
private JsonObject readTimeData(Path dataFile) throws IOException {
if (!Files.exists(dataFile)) {
return new JsonObject();
}
try (Reader reader = Files.newBufferedReader(dataFile)) {
return JsonParser.parseReader(reader).getAsJsonObject();
} }
} }
// 获取玩家总时长 // 格式化时间
private long getPlayerTotalTime(String uuid, JsonObject timeData) { private String formatUptime(long millis) {
if (!timeData.has(uuid)) { long seconds = millis / 1000;
return 0; long days = seconds / 86400;
} seconds %= 86400;
long hours = seconds / 3600;
seconds %= 3600;
long minutes = seconds / 60;
seconds %= 60;
JsonObject playerData = timeData.getAsJsonObject(uuid); StringBuilder sb = new StringBuilder();
if (playerData.has("totalTime")) { if (days > 0) sb.append(days).append("");
return playerData.get("totalTime").getAsLong(); if (hours > 0 || days > 0) sb.append(String.format("%02d小时 ", hours));
} if (minutes > 0 || hours > 0 || days > 0) sb.append(String.format("%02d分钟 ", minutes));
return 0; sb.append(String.format("%02d秒", seconds));
return sb.toString().trim();
} }
} }

View File

@ -0,0 +1,19 @@
package com.example.playertime.api;
import java.util.List;
import java.util.Map;
// 用于 /api/online-players 接口返回的在线玩家列表数据结构
public class OnlinePlayersResponse {
public List<Map<String, String>> whitelisted;
public List<Map<String, String>> non_whitelisted;
// Gson 需要一个无参构造函数
@SuppressWarnings("unused")
private OnlinePlayersResponse() {}
public OnlinePlayersResponse(List<Map<String, String>> whitelisted, List<Map<String, String>> non_whitelisted) {
this.whitelisted = whitelisted;
this.non_whitelisted = non_whitelisted;
}
}

View File

@ -0,0 +1,18 @@
package com.example.playertime.api;
// 用于 /api/player-count 接口返回的玩家数量数据结构
public class PlayerCountResponse {
public int total;
public int whitelisted;
public int non_whitelisted;
// Gson 需要一个无参构造函数
@SuppressWarnings("unused")
private PlayerCountResponse() {}
public PlayerCountResponse(int total, int whitelisted, int non_whitelisted) {
this.total = total;
this.whitelisted = whitelisted;
this.non_whitelisted = non_whitelisted;
}
}

View File

@ -0,0 +1,28 @@
package com.example.playertime.api;
// 用于 /api/stats 接口返回的玩家统计数据结构
public class PlayerStatsResponse {
public String playerName;
public String uuid;
public long totalTimeSeconds; // 总时长
public String totalTimeFormatted; // 总时长格式化字符串
public long last30DaysSeconds; // 30天时长
public String last30DaysFormatted; // 30天时长格式化字符串
public long last7DaysSeconds; // 7天时长
public String last7DaysFormatted; // 7天时长格式化字符串
// Gson 需要一个无参构造函数
@SuppressWarnings("unused")
private PlayerStatsResponse() {}
public PlayerStatsResponse(String playerName, String uuid, long totalTimeSeconds, String totalTimeFormatted, long last30DaysSeconds, String last30DaysFormatted, long last7DaysSeconds, String last7DaysFormatted) {
this.playerName = playerName;
this.uuid = uuid;
this.totalTimeSeconds = totalTimeSeconds;
this.totalTimeFormatted = totalTimeFormatted;
this.last30DaysSeconds = last30DaysSeconds;
this.last30DaysFormatted = last30DaysFormatted;
this.last7DaysSeconds = last7DaysSeconds;
this.last7DaysFormatted = last7DaysFormatted;
}
}

View File

@ -0,0 +1,37 @@
package com.example.playertime.api;
import java.util.List;
// 用于 /api/server-status 接口返回的服务器状态数据结构
public class ServerStatusResponse {
public MemoryStats memory = new MemoryStats();
public DiskStats disk = new DiskStats();
public int available_processors;
public long uptime; //
public String uptime_formatted;
public ServerInfo server = new ServerInfo();
public static class MemoryStats {
public long max; // 字节
public long total; // 字节
public long used; // 字节
public long free; // 字节
public double usage_percentage;
}
public static class DiskStats {
public long total; // 字节
public long free; // 字节
public long usable; // 字节
public double usage_percentage;
}
public static class ServerInfo {
public String version;
public String motd;
public int player_count;
public int max_players;
public double average_tick_time_ms; // 平均 MSPT
public List<Double> recent_tick_samples_ms; // 最近 Tick 样本 (毫秒)
}
}

View File

@ -0,0 +1,18 @@
package com.example.playertime.api;
// 用于 /api/whitelist 接口返回的白名单列表数据结构
public class WhitelistResponse {
public String name;
public String uuid;
public boolean online;
// Gson 需要一个无参构造函数
@SuppressWarnings("unused")
private WhitelistResponse() {}
public WhitelistResponse(String name, String uuid, boolean online) {
this.name = name;
this.uuid = uuid;
this.online = online;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -0,0 +1,65 @@
{
"playertime.command.title": "§6===== Player Online Time (Page {0}/{1}) =====",
"playertime.command.prev_page": "§a[Previous Page]",
"playertime.command.next_page": "§a[Next Page]",
"playertime.command.total_players": "§7Total {0} players",
"playertime.stats.format": "Total: {0} | 30 Days: {1} | 7 Days: {2}",
"playertime.stats.total": "Total Time",
"playertime.stats.30day": "Last 30 Days",
"playertime.stats.7day": "Last 7 Days",
"playertime.command.empty_stats": "No player online time data available.",
"playertime.command.error.not_initialized": "Player Time Mod is not fully initialized, please try again later.",
"playertime.command.error.player_only": "This command can only be executed by a player.",
"playertime.web.title": "Player online and status statistics",
"playertime.web.warning": "Data tracking starts from the mod installation time and does not include any data before installation.",
"playertime.web.status.online_players": "Online Players",
"playertime.web.status.total": "Total",
"playertime.web.status.players": "Players",
"playertime.web.status.non_players": "Non-Players",
"playertime.web.status.online_list": "Online Player List",
"playertime.web.status.online_list.players": "Players",
"playertime.web.status.online_list.non_players": "Non-Players",
"playertime.web.status.online_list.empty_players": "No players online",
"playertime.web.status.online_list.empty_non_players": "No non-players online",
"playertime.web.server_status.title": "Server Status",
"playertime.web.server_status.memory_usage": "Memory Usage",
"playertime.web.server_status.memory_used": "Used",
"playertime.web.server_status.memory_free": "Free",
"playertime.web.server_status.memory_percent": "Usage",
"playertime.web.server_status.performance": "Real-time Performance",
"playertime.web.server_status.uptime": "Server Uptime",
"playertime.web.server_status.disk_usage": "Disk Usage",
"playertime.web.server_status.disk_used": "Used",
"playertime.web.server_status.disk_free": "Free",
"playertime.web.server_status.disk_percent": "Usage",
"playertime.web.server_status.processors": "Processors",
"playertime.web.server_status.server_version": "Server Version",
"playertime.web.server_status.player_count": "Online Players",
"playertime.web.server_status.disk_total": "Total",
"playertime.web.server_status.motd": "MOTD",
"playertime.web.server_status.not_available": "N/A",
"playertime.web.stats_table.title": "Player Online Time (Whitelist)",
"playertime.web.stats_table.info": "Only tracks and displays whitelisted players.",
"playertime.web.stats_table.header.player": "Player",
"playertime.web.stats_table.header.total_time": "Total Time",
"playertime.web.stats_table.header.last_30_days": "Last 30 Days",
"playertime.web.stats_table.header.last_7_days": "Last 7 Days",
"playertime.web.stats_table.empty": "No player data available",
"playertime.web.chart.memory_used": "Used",
"playertime.web.chart.memory_free": "Free",
"playertime.web.chart.tps": "TPS",
"playertime.web.chart.mspt": "MSPT",
"playertime.web.chart.disk_used": "Used",
"playertime.web.chart.disk_free": "Free",
"playertime.web.refresh_button": "Refresh",
"playertime.web.error.load_failed": "Failed to load data, check console",
"playertime.web.footer.license": "This project is open source under the GPL3 license"
}

View File

@ -0,0 +1,67 @@
{
"playertime.command.title": "§6===== 玩家在线时长 (第 {0}/{1} 页) =====",
"playertime.command.prev_page": "§a[上一页]",
"playertime.command.next_page": "§a[下一页]",
"playertime.command.total_players": "§7共 {0} 位玩家",
"playertime.stats.format": "总时长: {0} | 30天: {1} | 7天: {2}",
"playertime.stats.total": "总时长",
"playertime.stats.30day": "30天",
"playertime.stats.7day": "7天",
"playertime.command.empty_stats": "暂无玩家在线时间数据。",
"playertime.command.error.not_initialized": "在线时间Mod未完全初始化请稍后再试。",
"playertime.command.error.player_only": "此命令只能由玩家执行。",
"playertime.web.title": "玩家在线及状态统计",
"playertime.web.warning": "数据统计时间开始于此MOD安装时间不包含安装之前的所有数据",
"playertime.web.status.online_players": "在线玩家",
"playertime.web.status.total": "总数",
"playertime.web.status.players": "玩家",
"playertime.web.status.non_players": "假人",
"playertime.web.status.online_list": "在线玩家列表",
"playertime.web.status.online_list.players": "玩家",
"playertime.web.status.online_list.non_players": "假人",
"playertime.web.status.online_list.empty_players": "暂无玩家在线",
"playertime.web.status.online_list.empty_non_players": "暂无假人在线",
"playertime.web.server_status.title": "服务器状态",
"playertime.web.server_status.memory_usage": "内存使用",
"playertime.web.server_status.memory_used": "已用",
"playertime.web.server_status.memory_free": "可用",
"playertime.web.server_status.memory_percent": "使用率",
"playertime.web.server_status.performance": "实时性能",
"playertime.web.server_status.uptime": "服务器运行时间",
"playertime.web.server_status.disk_usage": "磁盘使用",
"playertime.web.server_status.disk_used": "已用",
"playertime.web.server_status.disk_free": "可用",
"playertime.web.server_status.disk_percent": "使用率",
"playertime.web.server_status.processors": "处理器核心",
"playertime.web.server_status.server_version": "服务器版本",
"playertime.web.server_status.player_count": "在线玩家",
"playertime.web.server_status.disk_total": "总量",
"playertime.web.server_status.motd": "MOTD",
"playertime.web.server_status.not_available": "N/A",
"playertime.web.stats_table.title": "玩家在线时长 (白名单)",
"playertime.web.stats_table.info": "仅跟踪和显示列入白名单的玩家",
"playertime.web.stats_table.header.player": "玩家",
"playertime.web.stats_table.header.total_time": "总计时间",
"playertime.web.stats_table.header.last_30_days": "最近 30 天",
"playertime.web.stats_table.header.last_7_days": "最近 7 天",
"playertime.web.stats_table.empty": "暂无玩家数据",
"playertime.web.chart.memory_used": "已使用",
"playertime.web.chart.memory_free": "未使用",
"playertime.web.chart.tps": "TPS",
"playertime.web.chart.mspt": "MSPT",
"playertime.web.chart.disk_used": "已用",
"playertime.web.chart.disk_free": "可用",
"playertime.web.refresh_button": "刷新数据",
"playertime.web.error.load_failed": "加载数据失败,请检查控制台",
"playertime.web.footer.license": "本项目基于 GPL3许可证 开源"
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@ -1,70 +1,263 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="zh_cn" data-theme="light">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>[在线时间] 玩家在线时间</title> <title data-lang-key="playertime.web.title">玩家在线及状态统计</title>
<link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="icon" href="favicon.ico" type="image/x-icon">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
</head> </head>
<body> <body>
<div class="container"> <div class="app-container">
<div class="header"> <!-- 顶部导航栏 -->
<h1>玩家在线时间统计</h1> <nav class="navbar">
<div class="navbar-content">
<div class="navbar-left">
<h1 class="app-title" data-lang-key="playertime.web.title">玩家在线时间统计</h1>
</div>
<div class="navbar-right">
<button id="theme-toggle" class="theme-toggle" aria-label="切换主题">
<i class="fas fa-moon theme-icon"></i>
<i class="fas fa-sun theme-icon"></i>
</button>
</div>
</div>
</nav>
<button id="theme-toggle" class="theme-toggle" aria-label="切换主题"> <div class="main-content">
<i class="fas fa-moon"></i> <!-- 警告信息 -->
<i class="fas fa-sun"></i> <div class="notification warning" data-lang-key="playertime.web.warning">
</button> <i class="fas fa-exclamation-circle"></i>
</div> <span>数据统计时间开始于此MOD安装时间不包含安装之前的所有数据</span>
<div class="warning">数据统计时间开始于此MOD安装时间不包含安装之前的所有数据</div> </div>
<br>
<!-- 新增的在线状态卡片 --> <!-- 在线玩家卡片 -->
<div class="status-cards"> <section class="dashboard-section">
<div class="status-card"> <div class="section-header">
<h3>当前在线</h3> <h2>在线状态</h2>
<div class="online-count" id="online-count">0</div> </div>
</div>
<div class="status-card"> <div class="stats-grid">
<h3>在线玩家</h3> <!-- 玩家计数卡片 -->
<ul class="online-players" id="online-players"></ul> <div class="stat-card accent-blue">
</div> <div class="stat-icon">
<div class="status-card"> <i class="fas fa-users"></i>
<h3>时长前三</h3> </div>
<ul class="top-players" id="top-players"></ul> <div class="stat-content">
</div> <div class="stat-value" id="total-count">0</div>
<div class="stat-label" data-lang-key="playertime.web.status.total">总数</div>
</div>
</div>
<div class="stat-card accent-green">
<div class="stat-icon">
<i class="fas fa-user"></i>
</div>
<div class="stat-content">
<div class="stat-value" id="whitelist-count">0</div>
<div class="stat-label" data-lang-key="playertime.web.status.players">玩家</div>
</div>
</div>
<div class="stat-card accent-purple">
<div class="stat-icon">
<i class="fas fa-robot"></i>
</div>
<div class="stat-content">
<div class="stat-value" id="non-whitelist-count">0</div>
<div class="stat-label" data-lang-key="playertime.web.status.non_players">假人</div>
</div>
</div>
</div>
<!-- 在线玩家列表 -->
<div class="player-lists-container">
<div class="player-list-card">
<div class="player-list-header">
<h3 data-lang-key="playertime.web.status.online_list.players">玩家</h3>
<span class="player-count-badge" id="whitelist-count-badge">0</span>
</div>
<ul class="player-list" id="whitelist-players"></ul>
</div>
<div class="player-list-card">
<div class="player-list-header">
<h3 data-lang-key="playertime.web.status.online_list.non_players">假人</h3>
<span class="player-count-badge" id="non-whitelist-count-badge">0</span>
</div>
<ul class="player-list" id="non-whitelist-players"></ul>
</div>
</div>
</section>
<!-- 服务器状态 -->
<section class="dashboard-section">
<div class="section-header">
<h2 data-lang-key="playertime.web.server_status.title">服务器状态</h2>
<div class="uptime-display">
<i class="fas fa-clock"></i>
<span id="uptime">加载中...</span>
</div>
</div>
<div class="server-stats-grid">
<!-- 内存使用 -->
<div class="stat-card">
<div class="stat-header">
<i class="fas fa-memory"></i>
<h3 data-lang-key="playertime.web.server_status.memory_usage">内存使用</h3>
</div>
<div class="chart-wrapper">
<canvas id="memory-chart"></canvas>
</div>
<div class="memory-stats">
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.memory_used">已用</span>
<span id="memory-used">0</span> MB
</div>
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.memory_free">可用</span>
<span id="memory-free">0</span> MB
</div>
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.memory_percent">使用率</span>
<span id="memory-percent">0</span>%
</div>
</div>
</div>
<!-- 磁盘使用 -->
<div class="stat-card">
<div class="stat-header">
<i class="fas fa-hard-drive"></i>
<h3 data-lang-key="playertime.web.server_status.disk_usage">磁盘使用</h3>
</div>
<div class="chart-wrapper">
<canvas id="disk-chart"></canvas>
</div>
<div class="memory-stats">
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.disk_total">总量</span>
<span id="disk-total">0</span> GB
</div>
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.disk_used">已用</span>
<span id="disk-used">0</span> GB
</div>
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.disk_free">可用</span>
<span id="disk-free">0</span> GB
</div>
<div class="memory-stat">
<span data-lang-key="playertime.web.server_status.disk_percent">使用率</span>
<span id="disk-percent">0</span>%
</div>
</div>
</div>
<!-- 服务器信息 -->
<div class="stat-card">
<div class="stat-header">
<i class="fas fa-server"></i>
<h3 data-lang-key="playertime.web.server_status.server_info">服务器信息</h3>
</div>
<div class="server-info">
<div class="info-item">
<span data-lang-key="playertime.web.server_status.server_version">服务器版本</span>
<span id="server-version">未知</span>
</div>
<div class="info-item">
<span data-lang-key="playertime.web.server_status.processors">处理器核心</span>
<span id="processors">0</span>
</div>
<div class="info-item">
<span data-lang-key="playertime.web.server_status.player_count">在线玩家</span>
<span id="server-player-count">0</span>/<span id="server-max-players">0</span>
</div>
<div class="info-item">
<span data-lang-key="playertime.web.server_status.motd">MOTD</span>
<span id="server-motd">未知</span>
</div>
</div>
</div>
</div>
<!-- 实时性能卡片(单独一行) -->
<div class="performance-card">
<div class="stat-header">
<i class="fas fa-tachometer-alt"></i>
<h3 data-lang-key="playertime.web.server_status.performance">实时性能</h3>
</div>
<div class="performance-content">
<div class="performance-metrics">
<div class="metric-card">
<span class="metric-label" data-lang-key="playertime.web.chart.tps">TPS</span>
<span class="metric-value" id="tps-value">0.0</span>
</div>
<div class="metric-card">
<span class="metric-label" data-lang-key="playertime.web.chart.mspt">MSPT</span>
<span class="metric-value" id="mspt-value">0.0</span>
</div>
</div>
<div class="chart-container">
<canvas id="performance-chart"></canvas>
</div>
</div>
</div>
</section>
<!-- 玩家在线时长 -->
<section class="dashboard-section">
<div class="section-header">
<h2 data-lang-key="playertime.web.stats_table.title">玩家在线时长 (白名单)</h2>
<div class="section-actions">
<button id="refresh-btn" class="fluent-button primary">
<i class="fas fa-sync-alt"></i>
<span data-lang-key="playertime.web.refresh_button">刷新数据</span>
</button>
</div>
</div>
<div class="info-note">
<i class="fas fa-info-circle"></i>
<span data-lang-key="playertime.web.stats_table.info">仅跟踪和显示列入白名单的玩家</span>
</div>
<div class="table-container">
<table id="stats-table">
<thead>
<tr>
<th data-lang-key="playertime.web.stats_table.header.player">玩家</th>
<th data-lang-key="playertime.web.stats_table.header.total_time">总计时间</th>
<th data-lang-key="playertime.web.stats_table.header.last_30_days">最近 30 天</th>
<th data-lang-key="playertime.web.stats_table.header.last_7_days">最近 7 天</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</section>
</div> </div>
<div class="controls"> <footer class="footer">
<button id="refresh-btn" class="refresh-btn"> <div class="footer-content">
<i class="fas fa-sync-alt"></i> <div class="license-info">
<span>刷新数据</span> <p data-lang-key="playertime.web.footer.license">本项目基于 GPL3许可证 开源</p>
</button> <p>Copyright © 2025 <a href="https://git.branulf.top/BRanulf" target="_blank">BRanulf</a></p>
<p class="info-note">仅跟踪和显示列入白名单的玩家</p> </div>
</div> </div>
<div class="stats-container"> </footer>
<table id="stats-table">
<thead>
<tr>
<th>玩家</th>
<th>总计时间</th>
<th>最近 30 天</th>
<th>最近 7 天</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div> </div>
<script src="js/app.js"></script>
<footer class="license-footer">
<div class="license-info">
<p>本项目基于 <a href="https://opensource.org/licenses/MIT" target="_blank">MIT许可证</a> 开源</p>
<p>Copyright © 2025 <a href="https://git.branulf.top/BRanulf" target="_blank">BRanulf</a></p>
</div>
</footer>
<div class="floating-refresh-btn">
<button id="floating-refresh-btn" class="fluent-button primary floating" title="刷新数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
<script src="js/app.js"></script>
</body> </body>
</html> </html>

View File

@ -1,115 +1,543 @@
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const refreshBtn = document.getElementById('refresh-btn'); // 初始化变量
const themeToggle = document.getElementById('theme-toggle'); const tpsHistory = Array(60).fill(20);
const statsTable = document.getElementById('stats-table').getElementsByTagName('tbody')[0]; const msptHistory = Array(60).fill(0);
const onlineCountEl = document.getElementById('online-count'); const performanceLabels = Array(60).fill('');
const onlinePlayersEl = document.getElementById('online-players'); let memoryChart = null;
const topPlayersEl = document.getElementById('top-players'); let performanceChart = null;
let diskChart = null;
let lang = {};
// 初始化主题 // DOM元素
const elements = {
refreshBtn: document.getElementById('refresh-btn'),
themeToggle: document.getElementById('theme-toggle'),
statsTableBody: document.getElementById('stats-table')?.getElementsByTagName('tbody')[0],
statsTableHeader: document.getElementById('stats-table')?.getElementsByTagName('thead')[0],
whitelistPlayers: document.getElementById('whitelist-players'),
nonWhitelistPlayers: document.getElementById('non-whitelist-players'),
totalCount: document.getElementById('total-count'),
whitelistCount: document.getElementById('whitelist-count'),
nonWhitelistCount: document.getElementById('non-whitelist-count'),
memoryUsed: document.getElementById('memory-used'),
memoryFree: document.getElementById('memory-free'),
memoryPercent: document.getElementById('memory-percent'),
diskTotal: document.getElementById('disk-total'),
diskUsed: document.getElementById('disk-used'),
diskFree: document.getElementById('disk-free'),
diskPercent: document.getElementById('disk-percent'),
processors: document.getElementById('processors'),
serverVersion: document.getElementById('server-version'),
serverPlayerCount: document.getElementById('server-player-count'),
serverMaxPlayers: document.getElementById('server-max-players'),
serverMotd: document.getElementById('server-motd'),
uptime: document.getElementById('uptime'),
tpsValue: document.getElementById('tps-value'),
msptValue: document.getElementById('mspt-value'),
floatingRefreshBtn: document.getElementById('floating-refresh-btn')
};
// 加载保存的主题
const savedTheme = localStorage.getItem('theme') || 'light'; const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme); document.documentElement.setAttribute('data-theme', savedTheme);
// 主题切换功能 // 初始设置:加载语言,初始化图表,加载数据,设置刷新间隔
themeToggle.addEventListener('click', () => { loadLanguage().then(() => {
translatePage();
initCharts();
loadAllData();
// 设置定期刷新每10秒一次后续加入配置文件
const refreshInterval = setInterval(loadAllData, 10000);
console.log('数据刷新间隔设置为10秒。');
}).catch(error => {
console.error('加载语言或初始数据失败:', error);
showError('加载语言或初始数据失败。请检查控制台。');
});
if (elements.themeToggle) {
elements.themeToggle.addEventListener('click', toggleTheme);
}
if (elements.refreshBtn) {
elements.refreshBtn.addEventListener('click', handleRefresh);
}
if (elements.floatingRefreshBtn) {
elements.floatingRefreshBtn.addEventListener('click', handleRefresh);
}
async function loadLanguage() {
try {
const response = await fetch('/api/lang');
if (!response.ok) {
const errorText = await response.text();
console.error(`获取/api/lang时HTTP错误! 状态: ${response.status}, 内容: ${errorText}`);
throw new Error(`HTTP错误! 状态: ${response.status}`);
}
lang = await response.json();
console.log('语言文件加载成功。');
} catch (error) {
console.error('无法从/api/lang加载语言文件:', error);
lang = {};
}
}
function translatePage() {
document.querySelectorAll('[data-lang-key]').forEach(element => {
const key = element.getAttribute('data-lang-key');
if (lang[key]) {
if (element.tagName === 'TITLE') {
document.title = lang[key];
} else {
element.textContent = lang[key];
}
} else {
}
});
// 加载语言后更新图表标签
if (memoryChart) {
memoryChart.data.labels = [getLangString('playertime.web.chart.memory_used'), getLangString('playertime.web.chart.memory_free')];
memoryChart.update();
}
if (performanceChart) {
performanceChart.data.datasets[0].label = getLangString('playertime.web.chart.tps');
performanceChart.data.datasets[1].label = getLangString('playertime.web.chart.mspt');
if (performanceChart.options.scales.y.title) performanceChart.options.scales.y.title.text = getLangString('playertime.web.chart.tps');
if (performanceChart.options.scales.y1.title) performanceChart.options.scales.y1.title.text = getLangString('playertime.web.chart.mspt');
performanceChart.update();
}
if (diskChart) {
diskChart.data.labels = [getLangString('playertime.web.chart.disk_used'), getLangString('playertime.web.chart.disk_free')];
diskChart.update();
}
}
// 获取语言字符串
function getLangString(key, ...args) {
const pattern = lang[key] || key;
try {
let result = pattern;
args.forEach((arg, index) => {
result = result.replace(new RegExp('\\{' + index + '\\}', 'g'), arg);
});
return result;
} catch (e) {
console.error(`格式化键的字符串失败: ${key}`, e);
return pattern;
}
}
// 切换主题
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme'); const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'light' ? 'dark' : 'light'; const newTheme = currentTheme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newTheme); document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme); localStorage.setItem('theme', newTheme);
});
loadAllData();
refreshBtn.addEventListener('click', function() {
refreshBtn.classList.add('loading');
loadAllData();
setTimeout(() => {
refreshBtn.classList.remove('loading');
}, 1000);
});
function loadAllData() {
// 加载统计数据
fetch('/api/stats')
.then(response => response.json())
.then(data => {
updateTable(data);
})
.catch(error => {
console.error('获取统计信息时出错:', error);
showError('未能加载玩家统计信息。 检查控制台以获取详细信息');
});
// 加载在线状态数据
fetch('/api/widget-data')
.then(response => response.json())
.then(data => {
updateOnlineStatus(data);
})
.catch(error => {
console.error('获取在线状态时出错:', error);
showError('未能加载在线状态信息。 检查控制台以获取详细信息');
});
} }
function updateTable(statsData) {
statsTable.innerHTML = '';
Object.entries(statsData).forEach(([playerName, statString]) => { // 防呆
const row = statsTable.insertRow(); function handleRefresh() {
if (this.classList.contains('loading')) return;
const nameCell = row.insertCell(0); this.classList.add('loading');
nameCell.textContent = playerName; loadAllData().finally(() => {
setTimeout(() => {
const stats = {}; this.classList.remove('loading');
statString.split(" | ").forEach(part => { }, 500);
const [label, value] = part.split(": ");
stats[label.trim()] = value;
});
const totalCell = row.insertCell(1);
totalCell.textContent = stats["总时长"];
const thirtyCell = row.insertCell(2);
thirtyCell.textContent = stats["30天"];
const sevenCell = row.insertCell(3);
sevenCell.textContent = stats["7天"];
}); });
} }
function updateOnlineStatus(data) {
// 更新在线人数
onlineCountEl.textContent = data.onlineCount;
// 更新在线玩家列表 async function loadAllData() {
onlinePlayersEl.innerHTML = ''; try {
if (data.whitelistPlayers && data.whitelistPlayers.length > 0) { const [statsData, onlinePlayersData, playerCountsData, serverStatusData] = await Promise.all([
data.whitelistPlayers.forEach(player => { fetchData('/api/stats'),
const li = document.createElement('li'); fetchData('/api/online-players'),
li.innerHTML = ` fetchData('/api/player-count'),
<span class="player-name">${player.name}</span> fetchData('/api/server-status')
<span class="player-time">${player.time}</span> ]);
`;
onlinePlayersEl.appendChild(li); updateTable(statsData);
}); updateOnlinePlayers(onlinePlayersData);
} else { updatePlayerCounts(playerCountsData);
onlinePlayersEl.innerHTML = '<li>暂无在线玩家</li>'; updateServerStatus(serverStatusData);
} catch (error) {
console.error('加载数据出错:', error);
showError(getLangString('playertime.web.error.load_failed'));
}
}
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
const errorBody = await response.text().catch(() => '未知错误');
throw new Error(`HTTP错误! 状态: ${response.status}, URL: ${url}, 内容: ${errorBody}`);
}
return response.json();
}
function updateTable(data) {
if (!elements.statsTableBody || !elements.statsTableHeader) return;
elements.statsTableBody.innerHTML = '';
const headers = elements.statsTableHeader.querySelectorAll('th[data-lang-key]');
headers.forEach(th => {
const key = th.getAttribute('data-lang-key');
if (lang[key]) {
th.textContent = lang[key];
}
});
if (!Array.isArray(data) || data.length === 0) {
const row = elements.statsTableBody.insertRow();
const cell = row.insertCell(0);
cell.colSpan = 4;
cell.textContent = getLangString('playertime.web.stats_table.empty');
cell.style.textAlign = 'center';
cell.style.fontStyle = 'italic';
return;
} }
// 更新时长前三玩家 data.forEach(player => {
topPlayersEl.innerHTML = ''; const row = elements.statsTableBody.insertRow();
if (data.topPlayers && data.topPlayers.length > 0) { row.insertCell(0).textContent = player.playerName;
data.topPlayers.forEach(player => { row.insertCell(1).textContent = player.totalTimeFormatted;
const li = document.createElement('li'); row.insertCell(2).textContent = player.last30DaysFormatted;
li.innerHTML = ` row.insertCell(3).textContent = player.last7DaysFormatted;
<span class="player-name">${player.name}</span> });
<span class="player-time">${player.time}</span> }
`;
topPlayersEl.appendChild(li); // 更新在线玩家列表
function updateOnlinePlayers(data) {
if (!elements.whitelistPlayers || !elements.nonWhitelistPlayers) return;
const updateList = (element, players, emptyMessageKey) => {
element.innerHTML = '';
if (players?.length > 0) {
players.forEach(player => {
const li = document.createElement('li');
li.innerHTML = `<span class="player-name">${player.name}</span>`;
element.appendChild(li);
});
} else {
element.innerHTML = `<li>${getLangString(emptyMessageKey)}</li>`;
}
};
updateList(elements.whitelistPlayers, data.whitelisted, 'playertime.web.status.online_list.empty_players');
updateList(elements.nonWhitelistPlayers, data.non_whitelisted, 'playertime.web.status.online_list.empty_non_players');
}
// 更新在线玩家计数
function updatePlayerCounts(data) {
if (elements.totalCount) elements.totalCount.textContent = data.total || 0;
if (elements.whitelistCount) elements.whitelistCount.textContent = data.whitelisted || 0;
if (elements.nonWhitelistCount) elements.nonWhitelistCount.textContent = data.non_whitelisted || 0;
document.getElementById('whitelist-count-badge').textContent = data.whitelisted || 0;
document.getElementById('non-whitelist-count-badge').textContent = data.non_whitelisted || 0;
}
// 更新服务器状态信息和图表
function updateServerStatus(data) {
if (data.memory) {
const usedMB = Math.round(data.memory.used / (1024 * 1024));
const freeMB = Math.round(data.memory.free / (1024 * 1024));
const percent = Math.round(data.memory.usage_percentage);
if (memoryChart) {
memoryChart.data.datasets[0].data = [usedMB, freeMB];
memoryChart.data.labels = [getLangString('playertime.web.chart.memory_used'), getLangString('playertime.web.chart.memory_free')];
memoryChart.update();
}
if (elements.memoryUsed) elements.memoryUsed.textContent = usedMB;
if (elements.memoryFree) elements.memoryFree.textContent = freeMB;
if (elements.memoryPercent) elements.memoryPercent.textContent = percent;
}
// 更新性能统计和图表TPS/MSPT
if (data.server) {
const mspt = data.server.average_tick_time_ms || 0;
const tps = Math.min(20, 1000 / (mspt || 1)).toFixed(1);
if (elements.tpsValue) elements.tpsValue.textContent = tps;
if (elements.msptValue) elements.msptValue.textContent = mspt.toFixed(1);
if (performanceChart) {
tpsHistory.shift();
tpsHistory.push(parseFloat(tps));
msptHistory.shift();
msptHistory.push(mspt);
performanceChart.data.datasets[0].data = tpsHistory;
performanceChart.data.datasets[1].data = msptHistory;
performanceChart.update('none');
setMetricColor(elements.tpsValue, parseFloat(tps), 18, 15, false);
setMetricColor(elements.msptValue, mspt, 50, 60, true);
}
}
// 更新磁盘统计和图表
if (data.disk && data.disk.total > 0) {
const totalGB = Math.round(data.disk.total / (1024 * 1024 * 1024));
const usedGB = Math.round((data.disk.total - data.disk.free) / (1024 * 1024 * 1024));
const freeGB = Math.round(data.disk.free / (1024 * 1024 * 1024));
const percent = Math.round(data.disk.usage_percentage);
if (diskChart) {
diskChart.data.datasets[0].data = [usedGB, freeGB];
diskChart.data.labels = [getLangString('playertime.web.chart.disk_used'), getLangString('playertime.web.chart.disk_free')];
diskChart.update();
}
if (elements.diskTotal) elements.diskTotal.textContent = totalGB;
if (elements.diskUsed) elements.diskUsed.textContent = usedGB;
if (elements.diskFree) elements.diskFree.textContent = freeGB;
if (elements.diskPercent) elements.diskPercent.textContent = percent;
} else if (data.disk && data.disk.total === 0) {
if (elements.diskTotal) elements.diskTotal.textContent = getLangString('playertime.web.server_status.not_available') || 'N/A';
if (elements.diskUsed) elements.diskUsed.textContent = getLangString('playertime.web.server_status.not_available') || 'N/A';
if (elements.diskFree) elements.diskFree.textContent = getLangString('playertime.web.server_status.not_available') || 'N/A';
if (elements.diskPercent) elements.diskPercent.textContent = getLangString('playertime.web.server_status.not_available') || 'N/A';
if (diskChart) {
diskChart.data.datasets[0].data = [1, 0];
diskChart.data.labels = [getLangString('playertime.web.server_status.not_available') || 'N/A', ''];
diskChart.update();
}
}
// 更新服务器信息
if (elements.processors) elements.processors.textContent = data.available_processors || 0;
if (data.server) {
if (elements.serverVersion) elements.serverVersion.textContent = data.server.version || '未知';
if (elements.serverPlayerCount) elements.serverPlayerCount.textContent = data.server.player_count || 0;
if (elements.serverMaxPlayers) elements.serverMaxPlayers.textContent = data.server.max_players || 0;
if (elements.serverMotd) elements.serverMotd.textContent = data.server.motd || '未知';
}
// 更新运行时间
if (elements.uptime) elements.uptime.textContent = data.uptime_formatted || '加载中...';
}
function initCharts() {
// 内存图表
const memoryCtx = document.getElementById('memory-chart')?.getContext('2d');
if (memoryCtx) {
memoryChart = new Chart(memoryCtx, {
type: 'doughnut',
data: {
labels: [getLangString('playertime.web.chart.memory_used'), getLangString('playertime.web.chart.memory_free')],
datasets: [{
data: [0, 100],
backgroundColor: ['#4361ee', '#e9ecef'],
borderColor: [
getComputedStyle(document.documentElement).getPropertyValue('--card-bg').trim(),
getComputedStyle(document.documentElement).getPropertyValue('--card-bg').trim()
],
borderWidth: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
labels: {
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw;
return `${label}: ${value} MB`;
}
}
}
}
}
});
}
// 性能图表TPS/MSPT
const perfCtx = document.getElementById('performance-chart')?.getContext('2d');
if (perfCtx) {
performanceChart = new Chart(perfCtx, {
type: 'line',
data: {
labels: performanceLabels,
datasets: [
{
label: getLangString('playertime.web.chart.tps'),
data: tpsHistory,
borderColor: '#4CAF50',
backgroundColor: 'rgba(76, 175, 80, 0.1)',
borderWidth: 2,
pointRadius: 2,
pointHoverRadius: 4,
tension: 0.3,
yAxisID: 'y'
},
{
label: getLangString('playertime.web.chart.mspt'),
data: msptHistory,
borderColor: '#FF5722',
backgroundColor: 'rgba(255, 87, 34, 0.1)',
borderWidth: 2,
pointRadius: 2,
pointHoverRadius: 4,
tension: 0.3,
yAxisID: 'y1'
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 500
},
plugins: {
legend: {
position: 'top',
labels: {
boxWidth: 12,
padding: 20,
font: {
size: 12
},
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
}
},
tooltip: {
mode: 'index',
intersect: false,
bodySpacing: 8,
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.dataset.yAxisID === 'y') {
label += context.raw.toFixed(1);
} else {
label += context.raw.toFixed(1) + ' ms';
}
return label;
}
}
}
},
scales: {
x: {
grid: {
display: false,
color: getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim()
},
ticks: {
display: false
}
},
y: {
type: 'linear',
display: true,
position: 'left',
title: {
display: true,
text: getLangString('playertime.web.chart.tps'),
font: {
weight: 'bold',
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
},
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
},
min: 0,
max: 20,
grid: {
color: getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim()
},
ticks: {
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
}
},
y1: {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: getLangString('playertime.web.chart.mspt'),
font: {
weight: 'bold',
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
},
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
},
min: 0,
suggestedMax: 100,
grid: {
drawOnChartArea: false,
color: getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim()
},
ticks: {
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
}
}
}
}
});
}
// 磁盘图表
const diskCtx = document.getElementById('disk-chart')?.getContext('2d');
if (diskCtx) {
diskChart = new Chart(diskCtx, {
type: 'doughnut',
data: {
labels: [getLangString('playertime.web.chart.disk_used'), getLangString('playertime.web.chart.disk_free')],
datasets: [{
data: [0, 100],
backgroundColor: ['#4361ee', '#e9ecef'],
borderColor: [
getComputedStyle(document.documentElement).getPropertyValue('--card-bg').trim(),
getComputedStyle(document.documentElement).getPropertyValue('--card-bg').trim()
],
borderWidth: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
labels: {
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim()
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw;
return `${label}: ${value} GB`;
}
}
}
}
}
}); });
} else {
topPlayersEl.innerHTML = '<li>暂无数据</li>';
} }
} }
@ -121,20 +549,41 @@ document.addEventListener('DOMContentLoaded', function() {
setTimeout(() => { setTimeout(() => {
errorEl.classList.add('show'); errorEl.classList.add('show');
}, 10);
setTimeout(() => {
errorEl.classList.remove('show');
setTimeout(() => { setTimeout(() => {
document.body.removeChild(errorEl); errorEl.classList.remove('show');
}, 300); setTimeout(() => document.body.removeChild(errorEl), 300);
}, 5000); }, 5000);
}, 10);
} }
function parseTime(timeStr) { function setMetricColor(element, value, goodThreshold, badThreshold, reverse = false) {
const [hPart, mPart] = timeStr.split(' '); if (!element) return;
const hours = parseInt(hPart.replace('h', ''));
const minutes = parseInt(mPart.replace('m', '')); const numValue = parseFloat(value);
return hours * 60 + minutes; let color = '';
const successColor = getComputedStyle(document.documentElement).getPropertyValue('--success-color').trim();
const warningColor = getComputedStyle(document.documentElement).getPropertyValue('--warning-color').trim();
const dangerColor = getComputedStyle(document.documentElement).getPropertyValue('--danger-color').trim();
if (reverse) { // 值越低越好例如MSPT
if (numValue <= goodThreshold) {
color = successColor;
} else if (numValue <= badThreshold) {
color = warningColor;
} else {
color = dangerColor;
}
} else { // 值越高越好例如TPS
if (numValue >= goodThreshold) {
color = successColor;
} else if (numValue >= badThreshold) {
color = warningColor;
} else {
color = dangerColor;
}
}
element.style.color = color;
} }
}); });

View File

@ -1,3 +1,5 @@
{ {
"webPort": 60048 "webPort": 60048,
} "language": "zh_cn",
"autoSaveSeconds": 60
}

View File

@ -2,11 +2,17 @@
"schemaVersion": 1, "schemaVersion": 1,
"id": "playertime", "id": "playertime",
"version": "${version}", "version": "${version}",
"name": "玩家在线时长统计Mod", "name": "ServerPlayerOnlineTracker",
"description": "", "description": "A simple server mod that can display some status information and online players. With web server.",
"authors": [], "authors": [
"contact": {}, "BRanulf"
"license": "MIT", ],
"contact": {
"homepage": "https://git.branulf.top/Branulf",
"sources": "https://git.branulf.top/Branulf/ServerPlayerOnlineTracker"
},
"icon": "assets/playertime/icon540.png",
"license": "GPL3",
"environment": "server", "environment": "server",
"entrypoints": { "entrypoints": {
"main": [ "main": [

View File

@ -0,0 +1 @@
public field net/minecraft/server/MinecraftServer workerExecutor Ljava/util/concurrent/Executor;

View File

@ -1,231 +0,0 @@
<!--下面全是嵌入式卡片的代码复制后找个位置直接粘贴就行个人建议body的最下面-->
<!--记得更改serverUrl地址端口后面建议别动-->
<div id="minecraft-card-container"></div>
<script>
// 感谢deepseek大爹
// ===== 配置 =====
const config = {
serverUrl: "http://localhost:60048/api/widget-data",
updateInterval: 5000,
cardWidth: "300px"
};
(function initCard() {
if(localStorage.getItem('mcCardClosed')) return;
const card = createCard();
document.getElementById('minecraft-card-container').appendChild(card);
setupDragAndClose(card);
fetchData(card).then(() => {
setInterval(() => fetchData(card), config.updateInterval);
});
setTimeout(() => card.style.display = 'block', 100);
})();
function createCard() {
const card = document.createElement('div');
card.id = 'mc-status-card';
card.style.cssText = `
position: fixed; width: ${config.cardWidth}; z-index: 99999;
right: 20px; bottom: 20px; border-radius: 12px; background: white;
box-shadow: 0 4px 20px rgba(0,0,0,0.15); font-family: 'Segoe UI', sans-serif;
overflow: hidden; transition: all 0.2s; display: none;
`;
card.innerHTML = `
<div class="card-header" style="cursor:move;background:linear-gradient(135deg,#6a11cb 0%,#2575fc 100%);
color:white;padding:12px 15px;position:relative;">
<span>服务器玩家状态</span>
<span class="close-btn" style="position:absolute;right:10px;top:10px;color:white;
opacity:0.8;cursor:pointer;transition:opacity 0.2s;">×</span>
</div>
<div class="card-body" style="padding:0;">
<div class="loading" style="padding:20px;text-align:center;">
<div style="width:20px;height:20px;margin:0 auto 10px;border:3px solid rgba(0,0,0,0.1);
border-radius:50%;border-top-color:#2575fc;animation:spin 1s linear infinite;"></div>
<p>连接服务器中...</p>
</div>
</div>
`;
return card;
}
async function fetchData(card) {
const body = card.querySelector('.card-body');
try {
// 方案1尝试直接请求如果同源
let data = await tryDirectFetch();
// 方案2如果失败则使用服务器端代理
if(!data) data = await tryServerProxy();
if(data) {
renderCard(body, data);
} else {
throw new Error('所有数据获取方式均失败');
}
} catch(error) {
body.innerHTML = `
<div style="padding:20px;text-align:center;">
<p style="color:#dc3545;">⚠️ 数据加载失败</p>
<small style="color:#6c757d;">${error.message}</small>
<button onclick="location.reload()" style="margin-top:10px;padding:5px 10px;
background:#f8f9fa;border:1px solid #ddd;border-radius:4px;cursor:pointer;">
重试
</button>
</div>
`;
console.error('数据获取失败:', error);
}
}
async function tryDirectFetch() {
try {
const response = await fetch(config.serverUrl, {
headers: { 'Accept': 'application/json' }
});
return await fetchWidgetData();
} catch {
return null;
}
}
async function fetchWidgetData() {
try {
const response = await fetch('http://localhost:60048/api/widget-data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('获取到的数据:', data);
return data;
} catch (error) {
console.error('获取widget数据时出错:', error);
return {
onlineCount: 0,
whitelistPlayers: [],
topPlayers: [],
timestamp: Date.now()
};
}
}
async function tryServerProxy() {
try {
// 备用的暂时不用deepseek建议留着
const proxyUrl = 'http:// ' +
encodeURIComponent(config.serverUrl);
const response = await fetch(proxyUrl);
return await response.json();
} catch {
return null;
}
}
function renderCard(container, data) {
container.innerHTML = `
<div style="display:flex;align-items:center;padding:10px 15px;border-bottom:1px solid rgba(0,0,0,0.05);">
<span style="font-size:1.2rem;margin-right:12px;color:#2575fc;">👥</span>
<span>在线玩家</span>
<span style="margin-left:auto;background:#0d6efd;color:white;
padding:0.25em 0.6em;border-radius:50rem;font-size:0.75em;">
${data.onlineCount}
</span>
</div>
${data.topPlayers?.length ? `
<div style="padding:8px 15px;background:#f8f9fa;">
<small><span style="color:#ffc107">🏆</span> 时长前三</small>
</div>
${data.topPlayers.map(p => renderPlayer(p)).join('')}
` : ''}
<div style="padding:8px 15px;background:#f8f9fa;">
<small><span style="color:#2575fc">ⓘ</span> 在线玩家</small>
</div>
<div style="max-height:150px;overflow-y:auto;">
${data.whitelistPlayers?.length ?
data.whitelistPlayers.map(p => renderPlayer(p)).join('') :
'<div style="padding:15px;text-align:center;color:#6c757d;font-style:italic">无在线玩家</div>'
}
</div>
<div style="padding:8px;text-align:center;color:#6c757d;font-size:0.8em;">
更新: ${formatTime(data.timestamp)}
</div>
`;
}
function renderPlayer(player) {
return `
<div style="display:flex;align-items:center;padding:8px 15px;border-bottom:1px solid rgba(0,0,0,0.05);">
<div style="width:24px;height:24px;border-radius:50%;background:#e9ecef;margin-right:10px;
display:flex;align-items:center;justify-content:center;font-size:12px;color:#495057;">
${player.name.charAt(0).toUpperCase()}
</div>
<span style="flex-grow:1;">${player.name}</span>
<span style="font-size:0.9rem;color:#6c757d;">${player.time}</span>
</div>
`;
}
function setupDragAndClose(card) {
const header = card.querySelector('.card-header');
let isDragging = false, offsetX, offsetY;
header.addEventListener('mousedown', (e) => {
if(e.target.classList.contains('close-btn')) return;
isDragging = true;
offsetX = e.clientX - card.getBoundingClientRect().left;
offsetY = e.clientY - card.getBoundingClientRect().top;
card.style.cursor = 'grabbing';
});
document.addEventListener('mousemove', (e) => {
if(!isDragging) return;
card.style.left = (e.clientX - offsetX) + 'px';
card.style.top = (e.clientY - offsetY) + 'px';
card.style.right = 'auto';
card.style.bottom = 'auto';
});
document.addEventListener('mouseup', () => {
isDragging = false;
card.style.cursor = 'grab';
});
card.querySelector('.close-btn').addEventListener('click', () => {
card.style.display = 'none';
localStorage.setItem('mcCardClosed', 'true');
});
}
function formatTime(timestamp) {
const now = Date.now();
const diff = (now - timestamp) / 1000;
if(diff < 60) return '刚刚';
if(diff < 3600) return `${Math.floor(diff/60)}分钟前`;
return `${Math.floor(diff/3600)}小时前`;
}
document.head.insertAdjacentHTML('beforeend', `
<style>
@keyframes spin { to { transform: rotate(360deg); } }
#mc-status-card:hover { transform: translateY(-2px); box-shadow: 0 6px 25px rgba(0,0,0,0.2); }
</style>
`);
</script>