Compare commits
22 Commits
1.14.514.1
...
master
Author | SHA1 | Date | |
---|---|---|---|
![]() |
e5eca44059 | ||
![]() |
c3e4a1b483 | ||
![]() |
75bacc1ec7 | ||
![]() |
0d9e2db5ee | ||
![]() |
eef2bbebad | ||
![]() |
a5b4efc36e | ||
![]() |
62ef19006a | ||
![]() |
a69adaf749 | ||
![]() |
7e03e0edfa | ||
![]() |
d3523f2442 | ||
![]() |
a21701a766 | ||
![]() |
10f52e130e | ||
![]() |
1ffa91a98a | ||
![]() |
23a0518ca7 | ||
![]() |
4ce44dbecf | ||
![]() |
c58a6a071d | ||
![]() |
ad90b6e3f4 | ||
![]() |
651e7f69f7 | ||
![]() |
550894e8e4 | ||
59333dbd2d | |||
d12af686b3 | |||
![]() |
64623693e9 |
699
LICENSE.txt
699
LICENSE.txt
@ -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>.
|
||||||
|
|
||||||
本软件按"原样"提供,不提供任何明示或暗示的保证,包括但不限于对适销性、
|
|
||||||
特定用途适用性和非侵权性的保证。在任何情况下,作者或版权持有人均不对
|
|
||||||
任何索赔、损害或其他责任负责,无论是在合同、侵权还是其他诉讼中,
|
|
||||||
由软件或软件的使用或其他交易引起、由软件引起或与之相关的。
|
|
||||||
|
25
README.md
25
README.md
@ -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
24
README_EN.md
Normal 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`~~
|
@ -92,3 +92,5 @@ publishing {
|
|||||||
// retrieving dependencies.
|
// retrieving dependencies.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -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.121
|
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
|
||||||
|
108
src/main/java/com/example/playertime/LocalizationManager.java
Normal file
108
src/main/java/com/example/playertime/LocalizationManager.java
Normal 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); // 返回副本,防止外部修改
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
@ -6,19 +6,31 @@ 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.CommandManager;
|
||||||
import net.minecraft.server.command.ServerCommandSource;
|
import net.minecraft.server.command.ServerCommandSource;
|
||||||
import net.minecraft.server.network.ServerPlayerEntity;
|
import net.minecraft.server.network.ServerPlayerEntity;
|
||||||
import net.minecraft.text.ClickEvent;
|
import net.minecraft.text.ClickEvent;
|
||||||
import net.minecraft.text.MutableText;
|
import net.minecraft.text.MutableText;
|
||||||
import net.minecraft.text.Text;
|
import net.minecraft.text.Text;
|
||||||
|
import net.minecraft.util.Formatting;
|
||||||
import net.minecraft.util.Util;
|
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.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class PlayerTimeMod implements ModInitializer {
|
public class PlayerTimeMod implements ModInitializer {
|
||||||
@ -26,54 +38,106 @@ public class PlayerTimeMod implements ModInitializer {
|
|||||||
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();
|
registerCommands();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,18 +145,20 @@ public class PlayerTimeMod implements ModInitializer {
|
|||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public static PlayerTimeTracker getTimeTracker() {
|
public static PlayerTimeTracker getTimeTracker() {
|
||||||
return timeTracker;
|
return timeTracker;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static LocalizationManager getLocalizationManager() {
|
||||||
|
return localizationManager;
|
||||||
|
}
|
||||||
|
|
||||||
public static void registerCommands() {
|
// 注册命令
|
||||||
|
private void registerCommands() {
|
||||||
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
|
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
|
||||||
dispatcher.register(CommandManager.literal("onlineTime")
|
dispatcher.register(CommandManager.literal("onlineTime")
|
||||||
.requires(source -> source.hasPermissionLevel(0))
|
.requires(source -> source.hasPermissionLevel(0)) // 任何玩家都可以使用
|
||||||
.executes(context -> showOnlineTime(context.getSource(), 1)) // 默认第一页
|
.executes(context -> showOnlineTime(context.getSource(), 1)) // 默认显示第一页
|
||||||
.then(CommandManager.argument("page", IntegerArgumentType.integer(1))
|
.then(CommandManager.argument("page", IntegerArgumentType.integer(1))
|
||||||
.executes(context -> showOnlineTime(
|
.executes(context -> showOnlineTime(
|
||||||
context.getSource(),
|
context.getSource(),
|
||||||
@ -100,93 +166,182 @@ public class PlayerTimeMod implements ModInitializer {
|
|||||||
))
|
))
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
LOGGER.info("[在线时间] 已注册命令 /onlineTime");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int showOnlineTime(ServerCommandSource source, int requestedPage) {
|
// 显示在线时间
|
||||||
|
private int showOnlineTime(ServerCommandSource source, int requestedPage) {
|
||||||
ServerPlayerEntity player = source.getPlayer();
|
ServerPlayerEntity player = source.getPlayer();
|
||||||
if (player == null) return 0;
|
if (player == null) {
|
||||||
|
source.sendMessage(Text.literal(localizationManager.getString("playertime.command.error.player_only")).formatted(Formatting.RED));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
CompletableFuture.runAsync(() -> {
|
Util.getMainWorkerExecutor().execute(() -> {
|
||||||
PlayerTimeTracker tracker = getTimeTracker();
|
PlayerTimeTracker tracker = getTimeTracker();
|
||||||
if (tracker != null) {
|
if (tracker == null) {
|
||||||
Map<String, String> stats = tracker.getWhitelistedPlayerStats();
|
player.sendMessage(Text.literal(localizationManager.getString("playertime.command.error.not_initialized")).formatted(Formatting.RED), false);
|
||||||
|
return;
|
||||||
List<String> sorted = stats.entrySet().stream()
|
|
||||||
.sorted((a, b) -> comparePlayTime(b.getValue(), a.getValue()))
|
|
||||||
.map(entry -> formatPlayerTime(entry.getKey(), entry.getValue()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
sendPaginatedMessage(player, sorted, requestedPage);
|
|
||||||
}
|
}
|
||||||
}, Util.getMainWorkerExecutor());
|
|
||||||
|
List<PlayerTimeTracker.PlayerTimeStatsWithNames> statsList = tracker.getSortedPlayerStats();
|
||||||
|
|
||||||
|
sendPaginatedMessage(player, statsList, requestedPage);
|
||||||
|
});
|
||||||
|
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 发送分页消息
|
||||||
|
private void sendPaginatedMessage(ServerPlayerEntity player, List<PlayerTimeTracker.PlayerTimeStatsWithNames> statsList, int requestedPage) {
|
||||||
private static int comparePlayTime(String a, String b) {
|
|
||||||
return Long.compare(parseTimeToSeconds(a), parseTimeToSeconds(b));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static long parseTimeToSeconds(String timeStr) {
|
|
||||||
long seconds = 0;
|
|
||||||
String[] parts = timeStr.split(" ");
|
|
||||||
for (String part : parts) {
|
|
||||||
if (part.contains("h")) {
|
|
||||||
seconds += Integer.parseInt(part.replace("h", "")) * 3600;
|
|
||||||
} else if (part.contains("m")) {
|
|
||||||
seconds += Integer.parseInt(part.replace("m", "")) * 60;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return seconds;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String formatPlayerTime(String name, String timeStr) {
|
|
||||||
return String.format("§e%s§r: %s", name, timeStr.split(" \\| ")[0]); // 只显示总时长
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void sendPaginatedMessage(ServerPlayerEntity player, List<String> lines, int page) {
|
|
||||||
int pageSize = 10;
|
int pageSize = 10;
|
||||||
int totalPages = (lines.size() + pageSize - 1) / pageSize;
|
int totalEntries = statsList.size();
|
||||||
page = Math.max(1, Math.min(page, totalPages));
|
int totalPages = (totalEntries + pageSize - 1) / pageSize;
|
||||||
|
int currentPage = Math.max(1, Math.min(requestedPage, Math.max(1, totalPages)));
|
||||||
|
|
||||||
int from = (page - 1) * pageSize;
|
int fromIndex = (currentPage - 1) * pageSize;
|
||||||
int to = Math.min(from + pageSize, lines.size());
|
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);
|
||||||
player.sendMessage(Text.literal("§6===== 玩家在线时长 (第 " + page + "/" + totalPages + " 页) ====="), false);
|
|
||||||
|
|
||||||
// 内容
|
if (statsList.isEmpty()) {
|
||||||
for (int i = from; i < to; i++) {
|
player.sendMessage(Text.literal(localizationManager.getString("playertime.command.empty_stats")).formatted(Formatting.GRAY), false);
|
||||||
player.sendMessage(Text.literal(lines.get(i)), 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("");
|
MutableText footer = Text.literal("");
|
||||||
if (page > 1) {
|
if (currentPage > 1) {
|
||||||
int finalPage = page;
|
footer.append(Text.literal(localizationManager.getString("playertime.command.prev_page"))
|
||||||
footer.append(Text.literal("§a[上一页]")
|
|
||||||
.styled(style -> style.withClickEvent(new ClickEvent(
|
.styled(style -> style.withClickEvent(new ClickEvent(
|
||||||
ClickEvent.Action.RUN_COMMAND,
|
ClickEvent.Action.RUN_COMMAND,
|
||||||
"/onlineTime " + (finalPage - 1)
|
"/onlineTime " + (currentPage - 1)
|
||||||
)))
|
)).withColor(Formatting.GREEN)));
|
||||||
.append(" "));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
footer.append(Text.literal("§7共 " + lines.size() + " 位玩家"));
|
if (currentPage > 1 && currentPage < totalPages) {
|
||||||
|
footer.append(" ");
|
||||||
|
}
|
||||||
|
footer.append(Text.literal(localizationManager.getString("playertime.command.total_players", totalEntries)).formatted(Formatting.GRAY));
|
||||||
|
|
||||||
if (page < totalPages) {
|
|
||||||
int finalPage1 = page;
|
if (currentPage < totalPages) {
|
||||||
footer.append(" ").append(Text.literal("§a[下一页]")
|
if (currentPage > 1 || totalEntries > 0) {
|
||||||
|
footer.append(" ");
|
||||||
|
}
|
||||||
|
footer.append(Text.literal(localizationManager.getString("playertime.command.next_page"))
|
||||||
.styled(style -> style.withClickEvent(new ClickEvent(
|
.styled(style -> style.withClickEvent(new ClickEvent(
|
||||||
ClickEvent.Action.RUN_COMMAND,
|
ClickEvent.Action.RUN_COMMAND,
|
||||||
"/onlineTime " + (finalPage1 + 1)
|
"/onlineTime " + (currentPage + 1)
|
||||||
))));
|
)).withColor(Formatting.GREEN)));
|
||||||
}
|
}
|
||||||
|
|
||||||
player.sendMessage(footer, false);
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
@ -1,10 +1,10 @@
|
|||||||
package com.example.playertime;
|
package com.example.playertime;
|
||||||
|
|
||||||
import com.google.gson.*;
|
import com.google.gson.*;
|
||||||
import com.mojang.authlib.GameProfile;
|
|
||||||
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;
|
||||||
@ -17,8 +17,15 @@ 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;
|
||||||
@ -26,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 {
|
||||||
@ -43,142 +61,73 @@ 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");
|
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
|
|
||||||
|
|
||||||
|
|
||||||
if (!"GET".equals(exchange.getRequestMethod())) {
|
|
||||||
sendResponse(exchange, 405, "Method Not Allowed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 改为使用新的白名单统计方法
|
|
||||||
Map<String, String> stats = timeTracker.getWhitelistedPlayerStats();
|
|
||||||
String response = new Gson().toJson(stats);
|
|
||||||
sendResponse(exchange, 200, response.getBytes(), "application/json");
|
|
||||||
} catch (Exception e) {
|
|
||||||
PlayerTimeMod.LOGGER.error("[在线时间] 无法获得统计数据", e);
|
|
||||||
sendResponse(exchange, 500, "Internal Server Error");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 静态文件服务
|
|
||||||
server.createContext("/", exchange -> {
|
|
||||||
try {
|
|
||||||
String path = exchange.getRequestURI().getPath();
|
|
||||||
if (path.equals("/")) path = "/index.html";
|
|
||||||
|
|
||||||
// 从资源目录加载文件
|
|
||||||
String resourcePath = "assets/playertime/web" + path;
|
|
||||||
InputStream is = getClass().getClassLoader().getResourceAsStream(resourcePath);
|
|
||||||
|
|
||||||
if (is == null) {
|
|
||||||
sendResponse(exchange, 404, "Not Found");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 确定内容类型
|
|
||||||
String extension = path.substring(path.lastIndexOf('.') + 1);
|
|
||||||
String contentType = MIME_TYPES.getOrDefault(extension, "text/plain");
|
|
||||||
|
|
||||||
// 读取文件内容
|
|
||||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
|
||||||
byte[] data = new byte[1024];
|
|
||||||
int nRead;
|
|
||||||
while ((nRead = is.read(data, 0, data.length)) != -1) {
|
|
||||||
buffer.write(data, 0, nRead);
|
|
||||||
}
|
|
||||||
buffer.flush();
|
|
||||||
|
|
||||||
sendResponse(exchange, 200, buffer.toByteArray(), contentType);
|
|
||||||
} catch (Exception e) {
|
|
||||||
PlayerTimeMod.LOGGER.error("[在线时间] 无法提供资源", e);
|
|
||||||
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())) {
|
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||||
exchange.sendResponseHeaders(204, -1); // 204 No Content
|
exchange.sendResponseHeaders(204, -1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (!"GET".equals(exchange.getRequestMethod())) {
|
if (!"GET".equals(exchange.getRequestMethod())) {
|
||||||
sendResponse(exchange, 405, "Method Not Allowed");
|
sendResponse(exchange, 405, "Method Not Allowed");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
MinecraftServer server = minecraftServer;
|
List<PlayerTimeTracker.PlayerTimeStatsWithNames> statsList = timeTracker.getSortedPlayerStats();
|
||||||
PlayerManager playerManager = server.getPlayerManager();
|
|
||||||
|
|
||||||
JsonObject response = new JsonObject();
|
List<PlayerStatsResponse> responseList = statsList.stream()
|
||||||
response.addProperty("onlineCount", playerManager.getCurrentPlayerCount());
|
.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());
|
||||||
|
|
||||||
JsonArray whitelistPlayers = new JsonArray();
|
String response = GSON.toJson(responseList);
|
||||||
Map<String, Long> playerTimeMap = new HashMap<>();
|
sendResponse(exchange, 200, response.getBytes(StandardCharsets.UTF_8), "application/json");
|
||||||
|
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/stats 请求成功,返回 {} 条玩家数据。", responseList.size());
|
||||||
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) {
|
} 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("/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 {
|
||||||
|
Map<String, String> langMap = PlayerTimeMod.getLocalizationManager().getAllStrings();
|
||||||
|
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: 获取在线玩家列表
|
||||||
server.createContext("/api/online-players", exchange -> {
|
server.createContext("/api/online-players", exchange -> {
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
|
handleCors(exchange);
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
|
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
|
|
||||||
|
|
||||||
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||||
exchange.sendResponseHeaders(204, -1);
|
exchange.sendResponseHeaders(204, -1);
|
||||||
return;
|
return;
|
||||||
@ -190,50 +139,19 @@ public class WebServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
PlayerManager playerManager = minecraftServer.getPlayerManager();
|
Map<String, List<Map<String, String>>> onlinePlayers = timeTracker.getOnlinePlayersCategorized();
|
||||||
JsonObject response = new JsonObject();
|
OnlinePlayersResponse response = new OnlinePlayersResponse(onlinePlayers.get("whitelisted"), onlinePlayers.get("non_whitelisted"));
|
||||||
|
|
||||||
// 获取白名单玩家UUID集合
|
|
||||||
Set<UUID> whitelistUuids = new HashSet<>();
|
|
||||||
for (String name : playerManager.getWhitelist().getNames()) {
|
|
||||||
minecraftServer.getUserCache().findByName(name).ifPresent(profile -> {
|
|
||||||
whitelistUuids.add(profile.getId());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 分类玩家
|
|
||||||
JsonArray whitelistedPlayers = new JsonArray();
|
|
||||||
JsonArray nonWhitelistedPlayers = new JsonArray();
|
|
||||||
|
|
||||||
for (ServerPlayerEntity player : playerManager.getPlayerList()) {
|
|
||||||
UUID uuid = player.getUuid();
|
|
||||||
JsonObject playerJson = new JsonObject();
|
|
||||||
playerJson.addProperty("name", player.getName().getString());
|
|
||||||
playerJson.addProperty("uuid", uuid.toString());
|
|
||||||
|
|
||||||
if (whitelistUuids.contains(uuid)) {
|
|
||||||
whitelistedPlayers.add(playerJson);
|
|
||||||
} else {
|
|
||||||
nonWhitelistedPlayers.add(playerJson);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
response.add("whitelisted", whitelistedPlayers);
|
|
||||||
response.add("non_whitelisted", nonWhitelistedPlayers);
|
|
||||||
|
|
||||||
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
|
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
|
||||||
|
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/online-players 请求成功。");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
PlayerTimeMod.LOGGER.error("[在线时间] 无法获取在线玩家列表", e);
|
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/online-players 请求失败", e);
|
||||||
sendResponse(exchange, 500, "Internal Server Error");
|
sendResponse(exchange, 500, "Internal Server Error");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 玩家计数
|
// API: 获取在线玩家数量
|
||||||
server.createContext("/api/player-count", exchange -> {
|
server.createContext("/api/player-count", exchange -> {
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
|
handleCors(exchange);
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
|
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
|
|
||||||
|
|
||||||
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||||
exchange.sendResponseHeaders(204, -1);
|
exchange.sendResponseHeaders(204, -1);
|
||||||
return;
|
return;
|
||||||
@ -245,46 +163,19 @@ public class WebServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
PlayerManager playerManager = minecraftServer.getPlayerManager();
|
Map<String, Integer> counts = timeTracker.getOnlinePlayerCounts();
|
||||||
JsonObject response = new JsonObject();
|
PlayerCountResponse response = new PlayerCountResponse(counts.get("total"), counts.get("whitelisted"), counts.get("non_whitelisted"));
|
||||||
|
|
||||||
// 获取白名单玩家UUID集合
|
|
||||||
Set<UUID> whitelistUuids = new HashSet<>();
|
|
||||||
for (String name : playerManager.getWhitelist().getNames()) {
|
|
||||||
minecraftServer.getUserCache().findByName(name).ifPresent(profile -> {
|
|
||||||
whitelistUuids.add(profile.getId());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 分类计数
|
|
||||||
int whitelistedCount = 0;
|
|
||||||
int nonWhitelistedCount = 0;
|
|
||||||
|
|
||||||
for (ServerPlayerEntity player : playerManager.getPlayerList()) {
|
|
||||||
if (whitelistUuids.contains(player.getUuid())) {
|
|
||||||
whitelistedCount++;
|
|
||||||
} else {
|
|
||||||
nonWhitelistedCount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
response.addProperty("total", playerManager.getCurrentPlayerCount());
|
|
||||||
response.addProperty("whitelisted", whitelistedCount);
|
|
||||||
response.addProperty("non_whitelisted", nonWhitelistedCount);
|
|
||||||
|
|
||||||
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
|
sendResponse(exchange, 200, GSON.toJson(response).getBytes(StandardCharsets.UTF_8), "application/json");
|
||||||
|
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/player-count 请求成功。");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
PlayerTimeMod.LOGGER.error("[在线时间] 无法获取玩家计数", e);
|
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/player-count 请求失败", e);
|
||||||
sendResponse(exchange, 500, "Internal Server Error");
|
sendResponse(exchange, 500, "Internal Server Error");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 白名单玩家
|
// API: 获取白名单列表
|
||||||
server.createContext("/api/whitelist", exchange -> {
|
server.createContext("/api/whitelist", exchange -> {
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
|
handleCors(exchange);
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
|
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
|
|
||||||
|
|
||||||
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||||
exchange.sendResponseHeaders(204, -1);
|
exchange.sendResponseHeaders(204, -1);
|
||||||
return;
|
return;
|
||||||
@ -296,41 +187,22 @@ public class WebServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
PlayerManager playerManager = minecraftServer.getPlayerManager();
|
List<Map<String, Object>> whitelist = timeTracker.getWhitelistPlayers();
|
||||||
JsonArray whitelist = new JsonArray();
|
List<WhitelistResponse> responseList = whitelist.stream()
|
||||||
|
.map(map -> new WhitelistResponse((String)map.get("name"), (String)map.get("uuid"), (Boolean)map.get("online")))
|
||||||
for (String name : playerManager.getWhitelist().getNames()) {
|
.collect(Collectors.toList());
|
||||||
JsonObject player = new JsonObject();
|
sendResponse(exchange, 200, GSON.toJson(responseList).getBytes(StandardCharsets.UTF_8), "application/json");
|
||||||
player.addProperty("name", name);
|
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/whitelist 请求成功,返回 {} 条白名单记录。", responseList.size());
|
||||||
|
|
||||||
// 尝试获取UUID
|
|
||||||
Optional<GameProfile> profile = minecraftServer.getUserCache().findByName(name);
|
|
||||||
if (profile.isPresent()) {
|
|
||||||
player.addProperty("uuid", profile.get().getId().toString());
|
|
||||||
|
|
||||||
// 检查是否在线
|
|
||||||
ServerPlayerEntity onlinePlayer = playerManager.getPlayer(profile.get().getId());
|
|
||||||
player.addProperty("online", onlinePlayer != null);
|
|
||||||
} else {
|
|
||||||
player.addProperty("online", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
whitelist.add(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
sendResponse(exchange, 200, GSON.toJson(whitelist).getBytes(StandardCharsets.UTF_8), "application/json");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
PlayerTimeMod.LOGGER.error("[在线时间] 无法获取白名单", e);
|
PlayerTimeMod.LOGGER.error("[在线时间] 处理 /api/whitelist 请求失败", e);
|
||||||
sendResponse(exchange, 500, "Internal Server Error");
|
sendResponse(exchange, 500, "Internal Server Error");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 服务器状态
|
|
||||||
server.createContext("/api/server-status", 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");
|
|
||||||
|
|
||||||
|
// API: 获取服务器状态
|
||||||
|
server.createContext("/api/server-status", exchange -> {
|
||||||
|
handleCors(exchange);
|
||||||
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||||
exchange.sendResponseHeaders(204, -1);
|
exchange.sendResponseHeaders(204, -1);
|
||||||
return;
|
return;
|
||||||
@ -343,86 +215,194 @@ public class WebServer {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
Runtime runtime = Runtime.getRuntime();
|
Runtime runtime = Runtime.getRuntime();
|
||||||
JsonObject status = new JsonObject();
|
ServerStatusResponse status = new ServerStatusResponse();
|
||||||
|
|
||||||
long maxMemory = runtime.maxMemory();
|
long maxMemory = runtime.maxMemory();
|
||||||
long totalMemory = runtime.totalMemory();
|
long totalMemory = runtime.totalMemory();
|
||||||
long freeMemory = runtime.freeMemory();
|
long freeMemory = runtime.freeMemory();
|
||||||
long usedMemory = totalMemory - freeMemory;
|
long usedMemory = totalMemory - freeMemory;
|
||||||
|
|
||||||
JsonObject memory = new JsonObject();
|
status.memory.max = maxMemory;
|
||||||
memory.addProperty("max", maxMemory);
|
status.memory.total = totalMemory;
|
||||||
memory.addProperty("total", totalMemory);
|
status.memory.used = usedMemory;
|
||||||
memory.addProperty("used", usedMemory);
|
status.memory.free = freeMemory;
|
||||||
memory.addProperty("free", freeMemory);
|
status.memory.usage_percentage = (double) usedMemory / maxMemory * 100;
|
||||||
memory.addProperty("usage_percentage", (double) usedMemory / maxMemory * 100);
|
|
||||||
status.add("memory", memory);
|
|
||||||
|
|
||||||
status.addProperty("available_processors", runtime.availableProcessors());
|
status.available_processors = runtime.availableProcessors();
|
||||||
|
|
||||||
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
|
long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
|
||||||
status.addProperty("uptime", uptime);
|
status.uptime = uptimeMillis / 1000; // 秒
|
||||||
status.addProperty("uptime_formatted", formatUptime(uptime));
|
status.uptime_formatted = formatUptime(uptimeMillis);
|
||||||
|
|
||||||
File diskPartition = new File(".");
|
try {
|
||||||
long totalSpace = diskPartition.getTotalSpace();
|
File diskPartition = new File(".");
|
||||||
long freeSpace = diskPartition.getFreeSpace();
|
status.disk.total = diskPartition.getTotalSpace();
|
||||||
long usableSpace = diskPartition.getUsableSpace();
|
status.disk.free = diskPartition.getFreeSpace();
|
||||||
|
status.disk.usable = diskPartition.getUsableSpace();
|
||||||
JsonObject disk = new JsonObject();
|
status.disk.usage_percentage = (double) (status.disk.total - status.disk.free) / status.disk.total * 100;
|
||||||
disk.addProperty("total", totalSpace);
|
} catch (Exception e) {
|
||||||
disk.addProperty("free", freeSpace);
|
PlayerTimeMod.LOGGER.warn("[在线时间] 无法获取磁盘信息", e);
|
||||||
disk.addProperty("usable", usableSpace);
|
}
|
||||||
disk.addProperty("usage_percentage", (double) (totalSpace - freeSpace) / totalSpace * 100);
|
|
||||||
status.add("disk", disk);
|
|
||||||
|
status.server.version = minecraftServer.getVersion();
|
||||||
JsonObject serverInfo = new JsonObject();
|
status.server.player_count = minecraftServer.getCurrentPlayerCount();
|
||||||
serverInfo.addProperty("version", minecraftServer.getVersion());
|
status.server.max_players = minecraftServer.getMaxPlayerCount();
|
||||||
serverInfo.addProperty("player_count", minecraftServer.getCurrentPlayerCount());
|
status.server.motd = minecraftServer.getServerMotd();
|
||||||
serverInfo.addProperty("max_players", minecraftServer.getMaxPlayerCount());
|
|
||||||
|
status.server.average_tick_time_ms = minecraftServer.getAverageTickTime();
|
||||||
serverInfo.addProperty("average_tick_time_ms", minecraftServer.getAverageTickTime());
|
long[] tickTimes = minecraftServer.getTickTimes();
|
||||||
|
if (tickTimes != null && tickTimes.length > 0) {
|
||||||
long[] tickTimes = minecraftServer.getTickTimes();
|
long[] recentTicksCopy = Arrays.copyOf(tickTimes, tickTimes.length);
|
||||||
if (tickTimes != null && tickTimes.length > 0) {
|
status.server.recent_tick_samples_ms = Arrays.stream(recentTicksCopy)
|
||||||
double recentAvgTickTime = Arrays.stream(tickTimes).average().orElse(0) / 1000000.0;
|
.mapToDouble(tick -> tick / 1000000.0)
|
||||||
serverInfo.addProperty("recent_avg_tick_time_ms", recentAvgTickTime);
|
.boxed()
|
||||||
|
.collect(Collectors.toList());
|
||||||
JsonArray recentTicks = new JsonArray();
|
} else {
|
||||||
int sampleCount = Math.min(10, tickTimes.length);
|
status.server.recent_tick_samples_ms = Collections.emptyList();
|
||||||
for (int i = 0; i < sampleCount; i++) {
|
|
||||||
recentTicks.add(tickTimes[i] / 1000000.0);
|
|
||||||
}
|
|
||||||
serverInfo.add("recent_tick_samples_ms", recentTicks);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
status.add("server", serverInfo);
|
|
||||||
|
|
||||||
sendResponse(exchange, 200, GSON.toJson(status).getBytes(StandardCharsets.UTF_8), "application/json");
|
sendResponse(exchange, 200, GSON.toJson(status).getBytes(StandardCharsets.UTF_8), "application/json");
|
||||||
|
PlayerTimeMod.LOGGER.debug("[在线时间] API /api/server-status 请求成功。");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
PlayerTimeMod.LOGGER.error("[在线时间] 无法获取服务器状态", 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] fileContent = Files.readAllBytes(dataFile);
|
||||||
|
|
||||||
|
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");
|
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();
|
||||||
|
byte[] data = new byte[4096];
|
||||||
|
int nRead;
|
||||||
|
while ((nRead = is.read(data, 0, data.length)) != -1) {
|
||||||
|
buffer.write(data, 0, nRead);
|
||||||
|
}
|
||||||
|
buffer.flush();
|
||||||
|
is.close();
|
||||||
|
|
||||||
|
sendResponse(exchange, 200, buffer.toByteArray(), contentType);
|
||||||
|
PlayerTimeMod.LOGGER.debug("[在线时间] 提供静态文件: {}", resourcePath);
|
||||||
|
|
||||||
|
} 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()) {
|
||||||
@ -430,51 +410,26 @@ 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 String formatUptime(long millis) {
|
private String formatUptime(long millis) {
|
||||||
long seconds = millis / 1000;
|
long seconds = millis / 1000;
|
||||||
long days = seconds / 86400;
|
long days = seconds / 86400;
|
||||||
@ -484,19 +439,12 @@ public class WebServer {
|
|||||||
long minutes = seconds / 60;
|
long minutes = seconds / 60;
|
||||||
seconds %= 60;
|
seconds %= 60;
|
||||||
|
|
||||||
return String.format("%d天 %02d小时 %02d分钟 %02d秒", days, hours, minutes, seconds);
|
StringBuilder sb = new StringBuilder();
|
||||||
}
|
if (days > 0) sb.append(days).append("天 ");
|
||||||
|
if (hours > 0 || days > 0) sb.append(String.format("%02d小时 ", hours));
|
||||||
|
if (minutes > 0 || hours > 0 || days > 0) sb.append(String.format("%02d分钟 ", minutes));
|
||||||
|
sb.append(String.format("%02d秒", seconds));
|
||||||
|
|
||||||
// 获取玩家总时长
|
return sb.toString().trim();
|
||||||
private long getPlayerTotalTime(String uuid, JsonObject timeData) {
|
|
||||||
if (!timeData.has(uuid)) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject playerData = timeData.getAsJsonObject(uuid);
|
|
||||||
if (playerData.has("totalTime")) {
|
|
||||||
return playerData.get("totalTime").getAsLong();
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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 样本 (毫秒)
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
BIN
src/main/resources/assets/playertime/icon540.png
Normal file
BIN
src/main/resources/assets/playertime/icon540.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 21 KiB |
65
src/main/resources/assets/playertime/lang/en_us.json
Normal file
65
src/main/resources/assets/playertime/lang/en_us.json
Normal 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"
|
||||||
|
}
|
67
src/main/resources/assets/playertime/lang/zh_cn.json
Normal file
67
src/main/resources/assets/playertime/lang/zh_cn.json
Normal 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
BIN
src/main/resources/assets/playertime/web/favicon.ico
Normal file
BIN
src/main/resources/assets/playertime/web/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 40 KiB |
@ -1,128 +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/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">
|
||||||
<button id="theme-toggle" class="theme-toggle" aria-label="切换主题">
|
<div class="navbar-left">
|
||||||
<i class="fas fa-moon"></i>
|
<h1 class="app-title" data-lang-key="playertime.web.title">玩家在线时间统计</h1>
|
||||||
<i class="fas fa-sun"></i>
|
</div>
|
||||||
</button>
|
<div class="navbar-right">
|
||||||
</div>
|
<button id="theme-toggle" class="theme-toggle" aria-label="切换主题">
|
||||||
<div class="warning">数据统计时间开始于此MOD安装时间,不包含安装之前的所有数据</div>
|
<i class="fas fa-moon theme-icon"></i>
|
||||||
<br>
|
<i class="fas fa-sun theme-icon"></i>
|
||||||
|
</button>
|
||||||
<!-- 更新后的状态卡片 -->
|
|
||||||
<div class="status-cards">
|
|
||||||
<div class="status-card">
|
|
||||||
<h3>在线玩家</h3>
|
|
||||||
<div class="player-counts">
|
|
||||||
<div class="count-item">
|
|
||||||
<span class="count-label">总数:</span>
|
|
||||||
<span class="count-value" id="total-count">0</span>
|
|
||||||
</div>
|
|
||||||
<div class="count-item">
|
|
||||||
<span class="count-label">玩家:</span>
|
|
||||||
<span class="count-value" id="whitelist-count">0</span>
|
|
||||||
</div>
|
|
||||||
<div class="count-item">
|
|
||||||
<span class="count-label">假人:</span>
|
|
||||||
<span class="count-value" id="non-whitelist-count">0</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="status-card">
|
</nav>
|
||||||
<h3>在线玩家列表</h3>
|
|
||||||
<div class="player-lists">
|
<div class="main-content">
|
||||||
<div class="player-list">
|
<!-- 警告信息 -->
|
||||||
<h4>玩家</h4>
|
<div class="notification warning" data-lang-key="playertime.web.warning">
|
||||||
<ul class="online-players" id="whitelist-players"></ul>
|
<i class="fas fa-exclamation-circle"></i>
|
||||||
</div>
|
<span>数据统计时间开始于此MOD安装时间,不包含安装之前的所有数据</span>
|
||||||
<div class="player-list">
|
|
||||||
<h4>假人</h4>
|
|
||||||
<ul class="online-players" id="non-whitelist-players"></ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 服务器状态可视化 -->
|
<!-- 在线玩家卡片 -->
|
||||||
<div class="status-section">
|
<section class="dashboard-section">
|
||||||
<h2>服务器状态</h2>
|
<div class="section-header">
|
||||||
<div class="status-grid">
|
<h2>在线状态</h2>
|
||||||
<div class="status-item">
|
</div>
|
||||||
<h3>内存使用</h3>
|
|
||||||
<canvas id="memory-chart"></canvas>
|
<div class="stats-grid">
|
||||||
<div class="memory-stats">
|
<!-- 玩家计数卡片 -->
|
||||||
<div>已用: <span id="memory-used">0</span> MB</div>
|
<div class="stat-card accent-blue">
|
||||||
<div>可用: <span id="memory-free">0</span> MB</div>
|
<div class="stat-icon">
|
||||||
<div>使用率: <span id="memory-percent">0</span>%</div>
|
<i class="fas fa-users"></i>
|
||||||
|
</div>
|
||||||
|
<div class="stat-content">
|
||||||
|
<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>
|
</div>
|
||||||
|
|
||||||
<div class="status-item">
|
<!-- 在线玩家列表 -->
|
||||||
<h3>实时性能</h3>
|
<div class="player-lists-container">
|
||||||
<div class="chart-container">
|
<div class="player-list-card">
|
||||||
<div class="metric-display">
|
<div class="player-list-header">
|
||||||
<div class="metric">
|
<h3 data-lang-key="playertime.web.status.online_list.players">玩家</h3>
|
||||||
<span class="metric-label">TPS:</span>
|
<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>
|
<span class="metric-value" id="tps-value">0.0</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="metric">
|
<div class="metric-card">
|
||||||
<span class="metric-label">MSPT:</span>
|
<span class="metric-label" data-lang-key="playertime.web.chart.mspt">MSPT</span>
|
||||||
<span class="metric-value" id="mspt-value">0.0</span>
|
<span class="metric-value" id="mspt-value">0.0</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="chart-wrapper">
|
<div class="chart-container">
|
||||||
<canvas id="performance-chart"></canvas>
|
<canvas id="performance-chart"></canvas>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
|
<footer class="footer">
|
||||||
|
<div class="footer-content">
|
||||||
|
<div class="license-info">
|
||||||
|
<p data-lang-key="playertime.web.footer.license">本项目基于 GPL3许可证 开源</p>
|
||||||
|
<p>Copyright © 2025 <a href="https://git.branulf.top/BRanulf" target="_blank">BRanulf</a></p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</footer>
|
||||||
|
|
||||||
<!-- 玩家时长统计表格 -->
|
|
||||||
<h2>玩家在线时长 (白名单)</h2>
|
|
||||||
<div class="controls">
|
|
||||||
<button id="refresh-btn" class="refresh-btn">
|
|
||||||
<i class="fas fa-sync-alt"></i>
|
|
||||||
<span>刷新数据</span>
|
|
||||||
</button>
|
|
||||||
<p class="info-note">仅跟踪和显示列入白名单的玩家</p>
|
|
||||||
</div>
|
|
||||||
<div class="stats-container">
|
|
||||||
|
|
||||||
|
|
||||||
<table id="stats-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>玩家</th>
|
|
||||||
<th>总计时间</th>
|
|
||||||
<th>最近 30 天</th>
|
|
||||||
<th>最近 7 天</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody></tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<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>
|
<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>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
@ -1,15 +1,19 @@
|
|||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
// 1. 首先初始化所有变量
|
// 初始化变量
|
||||||
const tpsHistory = Array(30).fill(20);
|
const tpsHistory = Array(60).fill(20);
|
||||||
const msptHistory = Array(30).fill(50);
|
const msptHistory = Array(60).fill(0);
|
||||||
|
const performanceLabels = Array(60).fill('');
|
||||||
let memoryChart = null;
|
let memoryChart = null;
|
||||||
let performanceChart = null;
|
let performanceChart = null;
|
||||||
|
let diskChart = null;
|
||||||
|
let lang = {};
|
||||||
|
|
||||||
// 2. 获取DOM元素(带安全检查)
|
// DOM元素
|
||||||
const elements = {
|
const elements = {
|
||||||
refreshBtn: document.getElementById('refresh-btn'),
|
refreshBtn: document.getElementById('refresh-btn'),
|
||||||
themeToggle: document.getElementById('theme-toggle'),
|
themeToggle: document.getElementById('theme-toggle'),
|
||||||
statsTable: document.getElementById('stats-table')?.getElementsByTagName('tbody')[0],
|
statsTableBody: document.getElementById('stats-table')?.getElementsByTagName('tbody')[0],
|
||||||
|
statsTableHeader: document.getElementById('stats-table')?.getElementsByTagName('thead')[0],
|
||||||
whitelistPlayers: document.getElementById('whitelist-players'),
|
whitelistPlayers: document.getElementById('whitelist-players'),
|
||||||
nonWhitelistPlayers: document.getElementById('non-whitelist-players'),
|
nonWhitelistPlayers: document.getElementById('non-whitelist-players'),
|
||||||
totalCount: document.getElementById('total-count'),
|
totalCount: document.getElementById('total-count'),
|
||||||
@ -18,20 +22,38 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
memoryUsed: document.getElementById('memory-used'),
|
memoryUsed: document.getElementById('memory-used'),
|
||||||
memoryFree: document.getElementById('memory-free'),
|
memoryFree: document.getElementById('memory-free'),
|
||||||
memoryPercent: document.getElementById('memory-percent'),
|
memoryPercent: document.getElementById('memory-percent'),
|
||||||
avgTick: document.getElementById('avg-tick'),
|
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'),
|
uptime: document.getElementById('uptime'),
|
||||||
tpsValue: document.getElementById('tps-value'),
|
tpsValue: document.getElementById('tps-value'),
|
||||||
msptValue: document.getElementById('mspt-value')
|
msptValue: document.getElementById('mspt-value'),
|
||||||
|
floatingRefreshBtn: document.getElementById('floating-refresh-btn')
|
||||||
};
|
};
|
||||||
|
|
||||||
// 3. 初始化主题
|
// 加载保存的主题
|
||||||
const savedTheme = localStorage.getItem('theme') || 'light';
|
const savedTheme = localStorage.getItem('theme') || 'light';
|
||||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
document.documentElement.setAttribute('data-theme', savedTheme);
|
||||||
|
|
||||||
// 4. 初始化图表(必须在其他函数之前)
|
// 初始设置:加载语言,初始化图表,加载数据,设置刷新间隔
|
||||||
initCharts();
|
loadLanguage().then(() => {
|
||||||
|
translatePage();
|
||||||
|
initCharts();
|
||||||
|
loadAllData();
|
||||||
|
// 设置定期刷新(每10秒一次),后续加入配置文件
|
||||||
|
const refreshInterval = setInterval(loadAllData, 10000);
|
||||||
|
console.log('数据刷新间隔设置为10秒。');
|
||||||
|
}).catch(error => {
|
||||||
|
console.error('加载语言或初始数据失败:', error);
|
||||||
|
showError('加载语言或初始数据失败。请检查控制台。');
|
||||||
|
});
|
||||||
|
|
||||||
// 5. 事件监听器
|
|
||||||
if (elements.themeToggle) {
|
if (elements.themeToggle) {
|
||||||
elements.themeToggle.addEventListener('click', toggleTheme);
|
elements.themeToggle.addEventListener('click', toggleTheme);
|
||||||
}
|
}
|
||||||
@ -40,86 +62,74 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
elements.refreshBtn.addEventListener('click', handleRefresh);
|
elements.refreshBtn.addEventListener('click', handleRefresh);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. 初始加载数据
|
if (elements.floatingRefreshBtn) {
|
||||||
loadAllData();
|
elements.floatingRefreshBtn.addEventListener('click', handleRefresh);
|
||||||
|
}
|
||||||
|
|
||||||
// 7. 设置定时刷新(10秒)
|
|
||||||
const refreshInterval = setInterval(loadAllData, 10000);
|
|
||||||
|
|
||||||
/*** 功能函数 ***/
|
async function loadLanguage() {
|
||||||
function initCharts() {
|
try {
|
||||||
// 内存图表
|
const response = await fetch('/api/lang');
|
||||||
const memoryCtx = document.getElementById('memory-chart')?.getContext('2d');
|
if (!response.ok) {
|
||||||
if (memoryCtx) {
|
const errorText = await response.text();
|
||||||
memoryChart = new Chart(memoryCtx, {
|
console.error(`获取/api/lang时HTTP错误! 状态: ${response.status}, 内容: ${errorText}`);
|
||||||
type: 'doughnut',
|
throw new Error(`HTTP错误! 状态: ${response.status}`);
|
||||||
data: {
|
}
|
||||||
labels: ['已使用', '未使用'],
|
lang = await response.json();
|
||||||
datasets: [{
|
console.log('语言文件加载成功。');
|
||||||
data: [0, 100],
|
} catch (error) {
|
||||||
backgroundColor: ['#4361ee', '#e9ecef']
|
console.error('无法从/api/lang加载语言文件:', error);
|
||||||
}]
|
lang = {};
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 性能图表
|
|
||||||
const perfCtx = document.getElementById('performance-chart')?.getContext('2d');
|
|
||||||
if (perfCtx) {
|
|
||||||
performanceChart = new Chart(perfCtx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels: Array(30).fill(''),
|
|
||||||
datasets: [
|
|
||||||
{
|
|
||||||
label: 'TPS',
|
|
||||||
data: tpsHistory,
|
|
||||||
borderColor: '#4CAF50',
|
|
||||||
tension: 0.1,
|
|
||||||
yAxisID: 'y'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'MSPT',
|
|
||||||
data: msptHistory,
|
|
||||||
borderColor: '#FF5722',
|
|
||||||
tension: 0.1,
|
|
||||||
yAxisID: 'y1'
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
interaction: {
|
|
||||||
mode: 'index',
|
|
||||||
intersect: false
|
|
||||||
},
|
|
||||||
scales: {
|
|
||||||
y: {
|
|
||||||
type: 'linear',
|
|
||||||
display: true,
|
|
||||||
position: 'left',
|
|
||||||
title: { display: true, text: 'TPS' },
|
|
||||||
min: 0,
|
|
||||||
max: 20
|
|
||||||
},
|
|
||||||
y1: {
|
|
||||||
type: 'linear',
|
|
||||||
display: true,
|
|
||||||
position: 'right',
|
|
||||||
title: { display: true, text: 'MSPT (ms)' },
|
|
||||||
min: 0,
|
|
||||||
grid: { drawOnChartArea: false }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
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';
|
||||||
@ -127,68 +137,86 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
localStorage.setItem('theme', newTheme);
|
localStorage.setItem('theme', newTheme);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 防呆
|
||||||
function handleRefresh() {
|
function handleRefresh() {
|
||||||
|
if (this.classList.contains('loading')) return;
|
||||||
|
|
||||||
this.classList.add('loading');
|
this.classList.add('loading');
|
||||||
loadAllData();
|
loadAllData().finally(() => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.classList.remove('loading');
|
this.classList.remove('loading');
|
||||||
}, 1000);
|
}, 500);
|
||||||
}
|
|
||||||
|
|
||||||
async function loadAllData() {
|
|
||||||
try {
|
|
||||||
await Promise.all([
|
|
||||||
fetchData('/api/stats', updateTable),
|
|
||||||
fetchData('/api/online-players', updateOnlinePlayers),
|
|
||||||
fetchData('/api/player-count', updatePlayerCounts),
|
|
||||||
fetchData('/api/server-status', updateServerStatus)
|
|
||||||
]);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('加载数据出错:', error);
|
|
||||||
showError('加载数据失败,请检查控制台');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchData(url, callback) {
|
|
||||||
try {
|
|
||||||
const response = await fetch(url);
|
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
|
||||||
const data = await response.json();
|
|
||||||
callback(data);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`获取 ${url} 数据失败:`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateTable(data) {
|
|
||||||
if (!elements.statsTable) return;
|
|
||||||
|
|
||||||
elements.statsTable.innerHTML = '';
|
|
||||||
const sortedPlayers = Object.entries(data)
|
|
||||||
.map(([name, statString]) => {
|
|
||||||
const stats = {};
|
|
||||||
statString.split(" | ").forEach(part => {
|
|
||||||
const [label, value] = part.split(": ");
|
|
||||||
stats[label.trim()] = value;
|
|
||||||
});
|
|
||||||
return { name, stats };
|
|
||||||
})
|
|
||||||
.sort((a, b) => parseTimeToSeconds(b.stats["总时长"]) - parseTimeToSeconds(a.stats["总时长"]));
|
|
||||||
|
|
||||||
sortedPlayers.forEach(player => {
|
|
||||||
const row = elements.statsTable.insertRow();
|
|
||||||
row.insertCell(0).textContent = player.name;
|
|
||||||
row.insertCell(1).textContent = player.stats["总时长"];
|
|
||||||
row.insertCell(2).textContent = player.stats["30天"];
|
|
||||||
row.insertCell(3).textContent = player.stats["7天"];
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async function loadAllData() {
|
||||||
|
try {
|
||||||
|
const [statsData, onlinePlayersData, playerCountsData, serverStatusData] = await Promise.all([
|
||||||
|
fetchData('/api/stats'),
|
||||||
|
fetchData('/api/online-players'),
|
||||||
|
fetchData('/api/player-count'),
|
||||||
|
fetchData('/api/server-status')
|
||||||
|
]);
|
||||||
|
|
||||||
|
updateTable(statsData);
|
||||||
|
updateOnlinePlayers(onlinePlayersData);
|
||||||
|
updatePlayerCounts(playerCountsData);
|
||||||
|
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 => {
|
||||||
|
const row = elements.statsTableBody.insertRow();
|
||||||
|
row.insertCell(0).textContent = player.playerName;
|
||||||
|
row.insertCell(1).textContent = player.totalTimeFormatted;
|
||||||
|
row.insertCell(2).textContent = player.last30DaysFormatted;
|
||||||
|
row.insertCell(3).textContent = player.last7DaysFormatted;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新在线玩家列表
|
||||||
function updateOnlinePlayers(data) {
|
function updateOnlinePlayers(data) {
|
||||||
if (!elements.whitelistPlayers || !elements.nonWhitelistPlayers) return;
|
if (!elements.whitelistPlayers || !elements.nonWhitelistPlayers) return;
|
||||||
|
|
||||||
const updateList = (element, players, emptyMessage) => {
|
const updateList = (element, players, emptyMessageKey) => {
|
||||||
element.innerHTML = '';
|
element.innerHTML = '';
|
||||||
if (players?.length > 0) {
|
if (players?.length > 0) {
|
||||||
players.forEach(player => {
|
players.forEach(player => {
|
||||||
@ -197,29 +225,34 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
element.appendChild(li);
|
element.appendChild(li);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
element.innerHTML = `<li>${emptyMessage}</li>`;
|
element.innerHTML = `<li>${getLangString(emptyMessageKey)}</li>`;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
updateList(elements.whitelistPlayers, data.whitelisted, '暂无玩家在线');
|
updateList(elements.whitelistPlayers, data.whitelisted, 'playertime.web.status.online_list.empty_players');
|
||||||
updateList(elements.nonWhitelistPlayers, data.non_whitelisted, '暂无假人在线');
|
updateList(elements.nonWhitelistPlayers, data.non_whitelisted, 'playertime.web.status.online_list.empty_non_players');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 更新在线玩家计数
|
||||||
function updatePlayerCounts(data) {
|
function updatePlayerCounts(data) {
|
||||||
if (elements.totalCount) elements.totalCount.textContent = data.total || 0;
|
if (elements.totalCount) elements.totalCount.textContent = data.total || 0;
|
||||||
if (elements.whitelistCount) elements.whitelistCount.textContent = data.whitelisted || 0;
|
if (elements.whitelistCount) elements.whitelistCount.textContent = data.whitelisted || 0;
|
||||||
if (elements.nonWhitelistCount) elements.nonWhitelistCount.textContent = data.non_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) {
|
function updateServerStatus(data) {
|
||||||
// 更新内存信息
|
|
||||||
if (data.memory) {
|
if (data.memory) {
|
||||||
const usedMB = Math.round(data.memory.used / (1024 * 1024));
|
const usedMB = Math.round(data.memory.used / (1024 * 1024));
|
||||||
const freeMB = Math.round((data.memory.max - data.memory.used) / (1024 * 1024));
|
const freeMB = Math.round(data.memory.free / (1024 * 1024));
|
||||||
const percent = Math.round(data.memory.usage_percentage);
|
const percent = Math.round(data.memory.usage_percentage);
|
||||||
|
|
||||||
if (memoryChart) {
|
if (memoryChart) {
|
||||||
memoryChart.data.datasets[0].data = [usedMB, freeMB];
|
memoryChart.data.datasets[0].data = [usedMB, freeMB];
|
||||||
|
memoryChart.data.labels = [getLangString('playertime.web.chart.memory_used'), getLangString('playertime.web.chart.memory_free')];
|
||||||
memoryChart.update();
|
memoryChart.update();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -228,71 +261,284 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
if (elements.memoryPercent) elements.memoryPercent.textContent = percent;
|
if (elements.memoryPercent) elements.memoryPercent.textContent = percent;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新性能信息
|
// 更新性能统计和图表(TPS/MSPT)
|
||||||
if (data.server) {
|
if (data.server) {
|
||||||
// 计算TPS (限制在0-20之间)
|
const mspt = data.server.average_tick_time_ms || 0;
|
||||||
const tps = Math.min(20, 1000 / (data.server.average_tick_time_ms || 50)).toFixed(1);
|
const tps = Math.min(20, 1000 / (mspt || 1)).toFixed(1);
|
||||||
const mspt = data.server.average_tick_time_ms.toFixed(1);
|
|
||||||
|
|
||||||
// 更新显示
|
|
||||||
if (elements.tpsValue) elements.tpsValue.textContent = tps;
|
if (elements.tpsValue) elements.tpsValue.textContent = tps;
|
||||||
if (elements.msptValue) elements.msptValue.textContent = mspt;
|
if (elements.msptValue) elements.msptValue.textContent = mspt.toFixed(1);
|
||||||
|
|
||||||
// 更新图表数据
|
|
||||||
if (performanceChart) {
|
if (performanceChart) {
|
||||||
// 更新历史数据
|
|
||||||
tpsHistory.shift();
|
tpsHistory.shift();
|
||||||
tpsHistory.push(parseFloat(tps));
|
tpsHistory.push(parseFloat(tps));
|
||||||
msptHistory.shift();
|
msptHistory.shift();
|
||||||
msptHistory.push(parseFloat(mspt));
|
msptHistory.push(mspt);
|
||||||
|
|
||||||
// 只更新数据不重新创建图表
|
|
||||||
performanceChart.data.datasets[0].data = tpsHistory;
|
performanceChart.data.datasets[0].data = tpsHistory;
|
||||||
performanceChart.data.datasets[1].data = msptHistory;
|
performanceChart.data.datasets[1].data = msptHistory;
|
||||||
performanceChart.update();
|
|
||||||
|
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.avgTick) elements.avgTick.textContent = data.server.average_tick_time_ms?.toFixed(2) || '0';
|
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 (performanceChart && data.server) {
|
if (elements.processors) elements.processors.textContent = data.available_processors || 0;
|
||||||
// 计算TPS和MSPT
|
if (data.server) {
|
||||||
const tps = Math.min(20, 1000 / (data.server.average_tick_time_ms || 50)).toFixed(1);
|
if (elements.serverVersion) elements.serverVersion.textContent = data.server.version || '未知';
|
||||||
const mspt = data.server.average_tick_time_ms.toFixed(1);
|
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 || '未知';
|
||||||
tpsHistory.shift();
|
|
||||||
tpsHistory.push(parseFloat(tps));
|
|
||||||
msptHistory.shift();
|
|
||||||
msptHistory.push(parseFloat(mspt));
|
|
||||||
|
|
||||||
// 只更新数据(不重新创建图表)
|
|
||||||
performanceChart.data.datasets[0].data = tpsHistory;
|
|
||||||
performanceChart.data.datasets[1].data = msptHistory;
|
|
||||||
|
|
||||||
// 平滑更新
|
|
||||||
performanceChart.update('none');
|
|
||||||
|
|
||||||
// 更新数值显示
|
|
||||||
if (elements.tpsValue) elements.tpsValue.textContent = tps;
|
|
||||||
if (elements.msptValue) elements.msptValue.textContent = mspt;
|
|
||||||
|
|
||||||
// 根据数值设置颜色
|
|
||||||
setMetricColor(elements.tpsValue, tps, 15, 10);
|
|
||||||
setMetricColor(elements.msptValue, mspt, 50, 100, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (elements.uptime) elements.uptime.textContent = data.uptime_formatted || '0';
|
// 更新运行时间
|
||||||
|
if (elements.uptime) elements.uptime.textContent = data.uptime_formatted || '加载中...';
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseTimeToSeconds(timeStr) {
|
|
||||||
if (!timeStr) return 0;
|
function initCharts() {
|
||||||
return timeStr.split(' ').reduce((total, part) => {
|
// 内存图表
|
||||||
if (part.includes('h')) return total + parseInt(part.replace('h', '')) * 3600;
|
const memoryCtx = document.getElementById('memory-chart')?.getContext('2d');
|
||||||
if (part.includes('m')) return total + parseInt(part.replace('m', '')) * 60;
|
if (memoryCtx) {
|
||||||
return total;
|
memoryChart = new Chart(memoryCtx, {
|
||||||
}, 0);
|
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`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showError(message) {
|
function showError(message) {
|
||||||
@ -310,119 +556,34 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}, 10);
|
}, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
function initPerformanceChart() {
|
function setMetricColor(element, value, goodThreshold, badThreshold, reverse = false) {
|
||||||
const perfCtx = document.getElementById('performance-chart')?.getContext('2d');
|
|
||||||
if (!perfCtx) return null;
|
|
||||||
|
|
||||||
return new Chart(perfCtx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels: Array(30).fill(''),
|
|
||||||
datasets: [
|
|
||||||
{
|
|
||||||
label: 'TPS',
|
|
||||||
data: tpsHistory,
|
|
||||||
borderColor: '#4CAF50',
|
|
||||||
backgroundColor: 'rgba(76, 175, 80, 0.1)',
|
|
||||||
borderWidth: 2,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 5,
|
|
||||||
tension: 0.3,
|
|
||||||
yAxisID: 'y'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'MSPT',
|
|
||||||
data: msptHistory,
|
|
||||||
borderColor: '#FF5722',
|
|
||||||
backgroundColor: 'rgba(255, 87, 34, 0.1)',
|
|
||||||
borderWidth: 2,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 5,
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
tooltip: {
|
|
||||||
mode: 'index',
|
|
||||||
intersect: false,
|
|
||||||
bodySpacing: 8
|
|
||||||
}
|
|
||||||
},
|
|
||||||
scales: {
|
|
||||||
x: {
|
|
||||||
grid: {
|
|
||||||
display: false
|
|
||||||
},
|
|
||||||
ticks: {
|
|
||||||
maxRotation: 0,
|
|
||||||
autoSkip: true,
|
|
||||||
maxTicksLimit: 10
|
|
||||||
}
|
|
||||||
},
|
|
||||||
y: {
|
|
||||||
type: 'linear',
|
|
||||||
display: true,
|
|
||||||
position: 'left',
|
|
||||||
title: {
|
|
||||||
display: true,
|
|
||||||
text: 'TPS',
|
|
||||||
font: {
|
|
||||||
weight: 'bold'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
min: 0,
|
|
||||||
max: 20,
|
|
||||||
grid: {
|
|
||||||
color: 'rgba(0, 0, 0, 0.05)'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
y1: {
|
|
||||||
type: 'linear',
|
|
||||||
display: true,
|
|
||||||
position: 'right',
|
|
||||||
title: {
|
|
||||||
display: true,
|
|
||||||
text: 'MSPT (ms)',
|
|
||||||
font: {
|
|
||||||
weight: 'bold'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
min: 0,
|
|
||||||
grid: {
|
|
||||||
drawOnChartArea: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function setMetricColor(element, value, warnThreshold, dangerThreshold, reverse = false) {
|
|
||||||
if (!element) return;
|
if (!element) return;
|
||||||
|
|
||||||
const numValue = parseFloat(value);
|
const numValue = parseFloat(value);
|
||||||
element.style.color =
|
let color = '';
|
||||||
reverse ?
|
|
||||||
(numValue > dangerThreshold ? '#FF5722' : numValue > warnThreshold ? '#FFC107' : '#4CAF50') :
|
|
||||||
(numValue < dangerThreshold ? '#FF5722' : numValue < warnThreshold ? '#FFC107' : '#4CAF50');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
{
|
{
|
||||||
"webPort": 60048
|
"webPort": 60048,
|
||||||
|
"language": "zh_cn",
|
||||||
|
"autoSaveSeconds": 60
|
||||||
}
|
}
|
@ -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": [
|
||||||
|
1
src/main/resources/playertime.accesswideners
Normal file
1
src/main/resources/playertime.accesswideners
Normal file
@ -0,0 +1 @@
|
|||||||
|
public field net/minecraft/server/MinecraftServer workerExecutor Ljava/util/concurrent/Executor;
|
231
嵌入式卡片看这里.txt
231
嵌入式卡片看这里.txt
@ -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>
|
|
Loading…
x
Reference in New Issue
Block a user