Compare commits

..
89 Commits
Author SHA1 Message Date
KennyTV 420412978e 2.3.1 Release 2018-08-16 17:56:28 +02:00
KennyTV 25e2f4dae2 2.3.1 Release 2018-08-16 17:54:57 +02:00
KennyTV d767be96b5 Fix 2018-08-15 11:54:35 +02:00
KennyTV 6d73acca9b Only check the mysql delay if it's at least a second 2018-08-15 11:11:25 +02:00
KennyTV 1f116374ad Fix permission checks for help page 2018-08-11 11:10:25 +02:00
KennyTV d0b7d96208 Fix updated config being overwritten again 2018-08-08 11:56:32 +02:00
KennyTV 16285d7064 Change some javadocs 2018-08-07 23:31:02 +02:00
KennyTV 1f27084fe1 Return empty string for pingmessages if config list is empty 2018-08-07 23:04:09 +02:00
KennyTV 261aace0db Remove unnecessary (second) result closing 2018-08-07 22:58:06 +02:00
KennyTV 344b910214 Remove unused method 2018-08-07 22:49:22 +02:00
KennyTV fbaa4896e1 Replace deprecated ProtocolLib packet 2018-08-07 14:55:19 +02:00
KennyTV 2f93064f60 Some pom changes 2018-08-07 13:51:59 +02:00
KennyTV 65b47c5e07 Only show the commands you have the permission to execute in the helppage 2018-08-06 21:12:36 +02:00
KennyTV d70d01f2d3 Fix config updating unnecessary value in Spigot version 2018-07-27 12:34:09 +02:00
KennyTV 769d7d3bcd Minor improvement 2018-07-27 12:28:07 +02:00
KennyTV a5f47688e0 Minor improvement 2018-07-27 11:50:19 +02:00
KennyTV 7d2e6a25a4 Move license and whitelistedplayers file to core module 2018-07-25 00:29:06 +02:00
KennyTV 69999b3b7a Fix MySQL millisecondsToCheck variable 2018-07-24 22:29:03 +02:00
KennyTV 94d1bd4eb9 Only make a request to the database at least x seconds after the last one 2018-07-23 11:52:30 +02:00
KennyTV c18e8b7ab7 Add warning and backup string if config value is null 2018-07-23 11:10:16 +02:00
KennyTV 9f45187300 Add warning and backup string if config value is null 2018-07-23 11:09:08 +02:00
KennyTV 0c6ba8a9b7 Updated BungeeCord dependency to 1.13-SNAPSHOT 2018-07-21 11:02:55 +02:00
KennyTV 1af69f2e8b Version increase to 2.3.1-SNAPSHOT 2018-07-18 15:50:35 +02:00
KennyTV a3b836b1c5 2.3 Release 2018-07-17 11:45:43 +02:00
KennyTV 1eca6c81ad Version increase for the 2.3 Release 2018-07-17 11:41:03 +02:00
KennyTV b9b4a78b5c Minor cleanup 2018-07-16 21:52:27 +02:00
KennyTV fda23c5539 The whitelist command now also shows the UUID of the player 2018-07-16 20:25:05 +02:00
KennyTV 8297321971 Changed help message order 2018-07-16 18:04:14 +02:00
KennyTV cfeaf00f26 Fixed wrong command descriptions 2018-07-16 13:22:46 +02:00
KennyTV 5ee1b32249 Uncommented new help messages 2018-07-16 13:07:59 +02:00
KennyTV b69f0dc90e Added missing motd command permission 2018-07-14 22:27:20 +02:00
KennyTV fe6cae4e47 Added motdlist command 2018-07-09 16:33:51 +02:00
KennyTV b494b5c23c Reworked setmotd command 2018-07-09 15:49:54 +02:00
KennyTV 3bd3395128 Removed setmotd command 2018-07-08 11:29:20 +02:00
KennyTV 3e3f63220d Config fix 2018-07-08 11:25:47 +02:00
KennyTV ccba0f042f Version increase to 2.3-SNAPSHOT 2018-07-08 11:20:18 +02:00
KennyTV abdd89259d Added multiple pingmessages + minor improvements 2018-07-08 10:54:51 +02:00
KennyTV 256f203c48 Minor code change 2018-06-18 11:17:47 +02:00
KennyTV 205412b02c Minor improvement 2018-06-18 11:17:06 +02:00
KennyTV 990289feb2 Fixed a problem with the setmotd command 2018-06-17 20:57:50 +02:00
KennyTV 44b1ff1a1f Fixed a typo 2018-06-17 20:27:01 +02:00
KennyTV f9e11bb9e5 Removed unused method 2018-06-17 19:58:21 +02:00
KennyTV eef1584b1c Small logic change 2018-06-17 18:51:35 +02:00
KennyTV 937dd84d1c Added permission per subcommand 2018-06-17 18:40:47 +02:00
KennyTV 80b9fe280b Message change 2018-06-17 18:29:58 +02:00
KennyTV 3892892792 Version increase to 2.2.3-SNAPSHOT 2018-06-17 18:06:59 +02:00
KennyTV 519551e76c Removed Spigot dependency from Core module 2018-06-17 14:36:18 +02:00
KennyTV b30476ae3f 2.2.2 Release 2018-06-17 11:24:35 +02:00
KennyTV 9d417a12f1 2.2.2 Release 2018-06-17 11:22:43 +02:00
KennyTV fd5406b95d 2.2.2 Release 2018-06-17 11:21:10 +02:00
KennyTV 0ef59e557d Maintenance icon fix and reload command message change 2018-06-14 12:35:10 +02:00
KennyTV 15ed1db347 Made the loading of the maintenance icon more structured 2018-06-14 12:10:33 +02:00
KennyTV 429d5b90d4 Api fix 2018-06-10 10:44:42 +02:00
KennyTV b3ab931aca Removed old config comment 2018-06-09 11:26:58 +02:00
KennyTV 21b42d0c72 Version increase to 2.2.2-SNAPSHOT
Some minor pom changes
2018-06-09 10:14:21 +02:00
KennyTV 7b1e1a27ba Merge remote-tracking branch 'origin/master' 2018-04-23 11:39:04 +02:00
KennyTV fb7b1e791f Some javadoc and comment changes 2018-04-23 11:38:51 +02:00
KennyTV eecd59b387 2.2.1 release 2018-04-17 04:46:22 +02:00
KennyTV ff7d8e0293 Project/pom changes 2018-04-16 20:54:21 +02:00
KennyTV 19c6d77a2c Updated API 2018-04-16 19:50:50 +02:00
KennyTV e002aa34e9 Comment line change 2018-04-16 16:35:13 +02:00
KennyTV 865e53a4a8 MySQL change 2018-04-16 15:31:50 +02:00
KennyTV b8c652b7fb MySQL fix 2018-04-16 14:39:40 +02:00
KennyTV c4080f82dc More cleanup 2018-04-16 14:18:19 +02:00
KennyTV 1a33497e8f Fixed doc typo 2018-04-15 15:07:19 +02:00
KennyTV f8353b8eda Various stuff 2018-04-15 13:53:42 +02:00
KennyTV 4980ad54ec Setmotd fixes 2018-04-15 13:38:21 +02:00
KennyTV 5363305411 Setmotd fixes 2018-04-15 13:37:07 +02:00
KennyTV 6ff47619ad Added setmotd command 2018-04-15 13:17:58 +02:00
KennyTV 69315a3f74 Create ISSUE_TEMPLATE.md 2018-04-14 19:09:34 +02:00
KennyTV 8b1ddba672 Added import 2018-04-14 18:46:24 +02:00
KennyTV bf63f0e209 MySQL improvements 2018-04-14 12:25:57 +02:00
KennyTV 450c923d24 Fixes 2018-04-14 12:06:29 +02:00
KennyTV 9a922a6df5 Small ServerListPlus integration and command fix 2018-04-14 12:00:46 +02:00
KennyTV 08a5a9a021 Fixes 2018-04-13 23:28:15 +02:00
KennyTV 61ad7d8533 Code cleanup 2018-04-13 22:56:41 +02:00
KennyTV 52d2b3c096 Automatically create sql table if non existing 2018-04-13 20:12:32 +02:00
KennyTV b0a69cc048 Moved resources 2018-04-13 19:26:45 +02:00
KennyTV 74e445a62e Added license and bumped version to 2.2.1-SNAPSHOT 2018-04-13 19:24:16 +02:00
KennyTV 91219202b2 Updated README 2018-04-05 23:50:36 +02:00
KennyTV a3545c83a0 Removed first commit errors 2018-04-05 23:45:39 +02:00
KennyTV 31baf91e8f Code commit 2018-04-05 23:43:25 +02:00
KennyTV 9a5f9d490e Code commit 2018-04-05 23:39:59 +02:00
KennyTV 214cd53751 Update README.md 2018-03-17 11:43:36 +01:00
KennyTV 2be16882c7 Update README.md 2018-03-17 10:30:46 +01:00
KennyTV 75e2264b44 Update README.md 2018-03-06 21:53:08 +01:00
KennyTV fd7a0eb6a5 Update README.md 2018-03-06 21:52:14 +01:00
KennyTV 177115f144 Add files via upload 2018-03-06 21:39:49 +01:00
KennyTV edbe31dc9c Create README.md 2018-03-06 21:39:02 +01:00
48 changed files with 3728 additions and 1 deletions

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
.metadata
dependencies/
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
.project
.externalToolBuilders/
*.launch
*.pydevproject
*.jar
.cproject
.classpath
.factorypath
.buildpath
.target
.tern-project
.texlipse
.springBeans
.recommenders/
.cache-main
.scala_dependencies
.worksheet
*.DS_Store
.AppleDouble
.LSOverride
Icon
._*
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
*.class
*.log
*.ctxt
.mtj.tmp/
*.war
*.ear
*.zip
*.tar.gz
*.rar
hs_err_pid*
*.iml
.idea
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/gradle.xml
.idea/**/mongoSettings.xml
*.iws
/out/
.idea_modules/
atlassian-ide-plugin.xml
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
!/.mvn/wrapper/maven-wrapper.jar
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
*.lnk
+13
View File
@@ -0,0 +1,13 @@
## Issue
Include here how the problem occured and how it's reproduceable.
If present, also paste the entire error message from the console, preferably via a https://hastebin.com/ link.
## Necessary server information
**Running on**: <BungeeCord/Bukkit>
**Maintenance version**: <>
## Other information
**Other motd changing plugins**: <>
**ProtocolLib version**: <>
+674
View File
@@ -0,0 +1,674 @@
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:
<program> Copyright (C) <year> <name of author>
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>.
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maintenance-base</artifactId>
<groupId>eu.kennytv</groupId>
<version>2.3.1</version>
</parent>
<artifactId>maintenance-api</artifactId>
<name>Maintenance-API</name>
<dependencies>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.13-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,40 @@
package eu.kennytv.maintenance.api;
/**
* @author KennyTV
* @since 2.1
*/
public interface IMaintenance {
/**
* Enables/disables maintenance mode.
* If enabled, all non-permitted players will be kicked.
* <p>
* If using the BungeeCord version and MySQL is enabled,
* it will also be written into the database.
* </p>
*
* @param maintenance true to enable, false to disable maintenance mode
*/
void setMaintenance(boolean maintenance);
/**
* @return true if maintenance is currently enabled
*/
boolean isMaintenance();
/**
* @return true if a start- or endtimer task is currently running
*/
boolean isTaskRunning();
/**
* @return version of the plugin
*/
String getVersion();
/**
* @return {@link ISettings} for options regarding configuration files
*/
ISettings getSettings();
}
@@ -0,0 +1,15 @@
package eu.kennytv.maintenance.api;
/**
* @author KennyTV
* @since 2.2.2
*/
public interface IMaintenanceBase {
/**
* Returns API instance of IMaintenance.
*
* @return {@link IMaintenance} instance
*/
IMaintenance getApi();
}
@@ -0,0 +1,68 @@
package eu.kennytv.maintenance.api;
import java.util.Map;
import java.util.UUID;
/**
* @author KennyTV
* @since 2.1
*/
public interface ISettings {
/**
* Note that the value might need a few seconds to update, if you're on BungeeCord with MySQL enabled
*
* @return true if maintenance is currently enabled
*/
boolean isMaintenance();
/**
* @return true if "join-notification" is set to true in the config
*/
boolean isJoinNotifications();
/**
* @return true if "custom-maintenance-icon" is set to true in the config
*/
boolean hasCustomIcon();
/**
* @return map of uuids of whitelisted players with their given names
*/
Map<UUID, String> getWhitelistedPlayers();
/**
* Removes a player from the maintenance whitelist.
*
* @param uuid uuid of the player to remove
* @return true if removing the player was successful
*/
boolean removeWhitelistedPlayer(UUID uuid);
/**
* Removes a player from the maintenance whitelist.
*
* @param name name of the player to remove with original lower-/uppercase letters
* @return true if removing the player was successful
* @deprecated if a player changes their name, the list will still contain the old one
* @see #removeWhitelistedPlayer(UUID)
*/
@Deprecated
boolean removeWhitelistedPlayer(String name);
/**
* Adds a player to the maintenance whitelist.
*
* @param uuid uuid of the player to add
* @param name of the player to add
* @return true if adding the player was successful
*/
boolean addWhitelistedPlayer(UUID uuid, String name);
/**
* Reloads the maintenance-icon.png image from the server folder.
*
* @return true if loading the image was successful
*/
boolean reloadMaintenanceIcon();
}
@@ -0,0 +1,29 @@
package eu.kennytv.maintenance.api;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
/**
* Utility class to get the {@link IMaintenance} instance for the BungeeCord version of the plugin.
* <p>
* Only access this class if you're running the plugin on a BungeeCord server!
* </p>
*
* @author KennyTV
* @since 2.1
*/
public final class MaintenanceBungeeAPI {
/**
* Returns API instance of IMaintenance.
*
* @return {@link IMaintenance} instance
*/
public static IMaintenance getAPI() {
final Plugin maintenance = ProxyServer.getInstance().getPluginManager().getPlugin("MaintenanceBungee");
if (maintenance == null)
ProxyServer.getInstance().getLogger().warning("Could not get instance of MaintenanceBungee!");
return ((IMaintenanceBase) maintenance).getApi();
}
}
@@ -0,0 +1,29 @@
package eu.kennytv.maintenance.api;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
/**
* Utility class to get the {@link IMaintenance} instance for the Spigot version of the plugin.
* <p>
* Only access this class if you're running the plugin on a Spigot server!
* </p>
*
* @author KennyTV
* @since 2.1
*/
public final class MaintenanceSpigotAPI {
/**
* Returns API instance of IMaintenance.
*
* @return {@link IMaintenance} instance
*/
public static IMaintenance getAPI() {
final Plugin maintenance = Bukkit.getPluginManager().getPlugin("MaintenanceSpigot");
if (maintenance == null)
Bukkit.getLogger().warning("Could not get instance of MaintenanceSpigot!");
return ((IMaintenanceBase) maintenance).getApi();
}
}
+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maintenance-base</artifactId>
<groupId>eu.kennytv</groupId>
<version>2.3.1</version>
</parent>
<artifactId>maintenance-bungee</artifactId>
<name>MaintenanceBungee</name>
<repositories>
<repository>
<id>bungeecord-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-core</artifactId>
<version>${parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.13-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.minecrell</groupId>
<artifactId>ServerListPlus</artifactId>
<version>3.4.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.2.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,25 @@
package eu.kennytv.maintenance.bungee;
import eu.kennytv.maintenance.api.IMaintenance;
import eu.kennytv.maintenance.api.IMaintenanceBase;
import net.md_5.bungee.api.plugin.Plugin;
import java.io.File;
public final class MaintenanceBungeeBase extends Plugin implements IMaintenanceBase {
private IMaintenance maintenance;
@Override
public void onEnable() {
maintenance = new MaintenanceBungeePlugin(this);
}
@Override
public IMaintenance getApi() {
return maintenance;
}
File getPluginFile() {
return getFile();
}
}
@@ -0,0 +1,117 @@
package eu.kennytv.maintenance.bungee;
import eu.kennytv.maintenance.api.IMaintenance;
import eu.kennytv.maintenance.api.ISettings;
import eu.kennytv.maintenance.api.MaintenanceBungeeAPI;
import eu.kennytv.maintenance.bungee.command.MaintenanceBungeeCommand;
import eu.kennytv.maintenance.bungee.command.MaintenanceBungeeCommandBase;
import eu.kennytv.maintenance.bungee.listener.PostLoginListener;
import eu.kennytv.maintenance.bungee.metrics.MetricsLite;
import eu.kennytv.maintenance.core.MaintenanceModePlugin;
import eu.kennytv.maintenance.core.hook.ServerListPlusHook;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.plugin.PluginManager;
import net.minecrell.serverlistplus.core.plugin.ServerListPlusPlugin;
import java.io.File;
import java.util.concurrent.TimeUnit;
/**
* @author KennyTV
* @since 1.0
*/
public final class MaintenanceBungeePlugin extends MaintenanceModePlugin {
private final MaintenanceBungeeBase plugin;
private final SettingsBungee settings;
MaintenanceBungeePlugin(final MaintenanceBungeeBase plugin) {
super("§8[§eMaintenanceBungee§8] ", plugin.getDescription().getVersion());
this.plugin = plugin;
plugin.getLogger().info("Plugin by KennyTV");
settings = new SettingsBungee(plugin);
final PluginManager pm = getProxy().getPluginManager();
pm.registerListener(plugin, new PostLoginListener(this, settings));
final MaintenanceBungeeCommand maintenanceCommand = new MaintenanceBungeeCommand(this, settings);
pm.registerCommand(plugin, new MaintenanceBungeeCommandBase(maintenanceCommand));
new MetricsLite(plugin);
// ServerListPlus integration
final Plugin serverListPlus = pm.getPlugin("ServerListPlus");
if (serverListPlus != null) {
serverListPlusHook = new ServerListPlusHook(((ServerListPlusPlugin) serverListPlus).getCore());
serverListPlusHook.setEnabled(!settings.isMaintenance());
plugin.getLogger().info("Enabled ServerListPlus integration!");
}
}
@Override
public void setMaintenance(final boolean maintenance) {
if (settings.getMySQL() != null) {
settings.setMaintenanceToSQL(maintenance);
} else {
settings.setMaintenance(maintenance);
settings.setToConfig("enable-maintenance-mode", maintenance);
settings.saveConfig();
settings.reloadConfigs();
}
if (serverListPlusHook != null)
serverListPlusHook.setEnabled(!maintenance);
if (isTaskRunning())
cancelTask();
if (maintenance) {
getProxy().getPlayers().stream()
.filter(p -> !p.hasPermission("maintenance.bypass") && !settings.getWhitelistedPlayers().containsKey(p.getUniqueId()))
.forEach(p -> p.disconnect(settings.getKickMessage().replace("%NEWLINE%", "\n")));
getProxy().broadcast(settings.getMaintenanceActivated());
} else
getProxy().broadcast(settings.getMaintenanceDeactivated());
}
@Override
public int schedule(final Runnable runnable) {
return getProxy().getScheduler().schedule(plugin, runnable, 0, 1, TimeUnit.MINUTES).getId();
}
@Override
public void async(final Runnable runnable) {
getProxy().getScheduler().runAsync(plugin, runnable);
}
@Override
public void cancelTask() {
getProxy().getScheduler().cancel(taskId);
setTaskId(0);
}
@Override
public ISettings getSettings() {
return settings;
}
@Override
public File getPluginFile() {
return plugin.getPluginFile();
}
@Override
public void broadcast(final String message) {
getProxy().broadcast(message);
}
@Deprecated
public static IMaintenance getAPI() {
return MaintenanceBungeeAPI.getAPI();
}
public ProxyServer getProxy() {
return plugin.getProxy();
}
}
@@ -0,0 +1,236 @@
package eu.kennytv.maintenance.bungee;
import eu.kennytv.maintenance.bungee.listener.ProxyPingListener;
import eu.kennytv.maintenance.bungee.mysql.MySQL;
import eu.kennytv.maintenance.core.Settings;
import eu.kennytv.maintenance.core.listener.IPingListener;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.plugin.PluginManager;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
public final class SettingsBungee extends Settings {
private final String updateQuery;
private final String maintenanceQuery;
private final MySQL mySQL;
private final MaintenanceBungeeBase plugin;
private final IPingListener pingListener;
private Configuration config;
private Configuration whitelist;
private long millisecondsToCheck;
private long lastMySQLCheck;
SettingsBungee(final MaintenanceBungeeBase plugin) {
this.plugin = plugin;
final PluginManager pm = plugin.getProxy().getPluginManager();
final ProxyPingListener listener = new ProxyPingListener(plugin, this);
pm.registerListener(plugin, listener);
pingListener = listener;
reloadConfigs(createFiles());
final Configuration mySQLSection = config.getSection("mysql");
if (mySQLSection.getBoolean("use-mysql", false)) {
plugin.getLogger().info("Trying to open database connection...");
mySQL = new MySQL(mySQLSection.getString("host"),
mySQLSection.getInt("port"),
mySQLSection.getString("username"),
mySQLSection.getString("password"),
mySQLSection.getString("database"));
// Varchar as the value regarding the possibility of saving stuff like the motd as well in future updates
final String mySQLTable = mySQLSection.getString("table");
mySQL.executeUpdate("CREATE TABLE IF NOT EXISTS " + mySQLTable + " (setting VARCHAR(16) PRIMARY KEY, value VARCHAR(255))");
updateQuery = "INSERT INTO " + mySQLTable + " (setting, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?";
maintenanceQuery = "SELECT * FROM " + mySQLTable + " WHERE setting = ?";
plugin.getLogger().info("Done!");
} else {
mySQL = null;
updateQuery = null;
maintenanceQuery = null;
}
}
@Override
public void updateExtraConfig() {
// 2.3.1 mysql.update-interval
if (!configContains("mysql.update-interval")) {
setToConfig("mysql.update-interval", 15);
saveConfig();
reloadConfigs();
}
}
@Override
public void reloadConfigs() {
reloadConfigs(false);
}
@Override
public void saveConfig() {
final File file = new File(plugin.getDataFolder(), "bungee-config.yml");
try {
YamlConfiguration.getProvider(YamlConfiguration.class).save(config, new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
} catch (final IOException e) {
throw new RuntimeException("Unable to save bungee-config.yml!", e);
}
}
@Override
public void saveWhitelistedPlayers() {
final File file = new File(plugin.getDataFolder(), "WhitelistedPlayers.yml");
try {
YamlConfiguration.getProvider(YamlConfiguration.class).save(whitelist, file);
} catch (final IOException e) {
throw new RuntimeException("Unable to save WhitelistedPlayers.yml!", e);
}
}
private void reloadConfigs(final boolean createdNewWhitelist) {
final File file = new File(plugin.getDataFolder(), "bungee-config.yml");
try {
config = YamlConfiguration.getProvider(YamlConfiguration.class).load(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
whitelist = YamlConfiguration.getProvider(YamlConfiguration.class).load(new File(plugin.getDataFolder(), "WhitelistedPlayers.yml"));
} catch (final IOException e) {
throw new RuntimeException("Unable to load bungee-config.yml!", e);
}
if (createdNewWhitelist) {
whitelist.set("a8179ff3-c201-4a75-bdaa-9d14aca6f83f", "KennyTV");
saveWhitelistedPlayers();
}
loadSettings();
}
@Override
public void loadExtraSettings() {
whitelistedPlayers.clear();
whitelist.getKeys().forEach(key -> whitelistedPlayers.put(UUID.fromString(key), whitelist.getString(key)));
if (mySQL != null) {
final long configValue = config.getInt("mysql.update-interval");
millisecondsToCheck = configValue > 0 ? configValue * 1000 : -1;
lastMySQLCheck = 0;
}
}
@Override
public void setWhitelist(final String uuid, final String s) {
whitelist.set(uuid, s);
}
@Override
public boolean createFiles() {
if (!plugin.getDataFolder().exists())
plugin.getDataFolder().mkdirs();
final File file = new File(plugin.getDataFolder(), "bungee-config.yml");
if (!file.exists()) {
try (final InputStream in = plugin.getResourceAsStream("bungee-config.yml")) {
Files.copy(in, file.toPath());
} catch (final IOException e) {
throw new RuntimeException("Unable to create bungee-config.yml file for MaintenanceBungee", e);
}
}
boolean createdNewWhitelist = false;
final File whitelistFile = new File(plugin.getDataFolder(), "WhitelistedPlayers.yml");
if (!whitelistFile.exists()) {
createdNewWhitelist = true;
try {
whitelistFile.createNewFile();
} catch (final IOException e) {
throw new RuntimeException("Unable to create WhitelistedPlayers.yml file for MaintenanceBungee", e);
}
}
return createdNewWhitelist;
}
@Override
public String getConfigString(final String path) {
final String s = config.getString(path);
if (s == null) {
plugin.getLogger().warning("The config is missing the following string: " + path);
return "null";
}
return ChatColor.translateAlternateColorCodes('&', s);
}
@Override
public boolean getConfigBoolean(final String path) {
return config.getBoolean(path);
}
@Override
public List<Integer> getConfigIntList(final String path) {
return config.getIntList(path);
}
@Override
public List<String> getConfigList(final String path) {
return config.getStringList(path);
}
@Override
public void setToConfig(final String path, final Object var) {
config.set(path, var);
}
@Override
public boolean configContains(final String path) {
return config.contains(path);
}
@Override
public String getColoredString(final String message) {
return ChatColor.translateAlternateColorCodes('&', message);
}
@Override
public boolean isMaintenance() {
if (mySQL != null && (millisecondsToCheck == -1 || System.currentTimeMillis() - lastMySQLCheck > millisecondsToCheck)) {
mySQL.executeQuery(maintenanceQuery, rs -> {
try {
if (rs.next())
maintenance = Boolean.parseBoolean(rs.getString("value"));
} catch (final SQLException e) {
e.printStackTrace();
}
}, "maintenance");
if (millisecondsToCheck != -1)
lastMySQLCheck = System.currentTimeMillis();
}
return maintenance;
}
@Override
public boolean reloadMaintenanceIcon() {
return pingListener.loadIcon();
}
public void setMaintenanceToSQL(final boolean maintenance) {
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
final String s = String.valueOf(maintenance);
mySQL.executeUpdate(updateQuery, "maintenance", s, s);
if (millisecondsToCheck != -1)
lastMySQLCheck = System.currentTimeMillis();
});
this.maintenance = maintenance;
}
public MySQL getMySQL() {
return mySQL;
}
}
@@ -0,0 +1,66 @@
package eu.kennytv.maintenance.bungee.command;
import eu.kennytv.maintenance.bungee.MaintenanceBungeePlugin;
import eu.kennytv.maintenance.bungee.SettingsBungee;
import eu.kennytv.maintenance.bungee.util.ProxiedSenderInfo;
import eu.kennytv.maintenance.core.command.MaintenanceCommand;
import eu.kennytv.maintenance.core.util.SenderInfo;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public final class MaintenanceBungeeCommand extends MaintenanceCommand {
public MaintenanceBungeeCommand(final MaintenanceBungeePlugin plugin, final SettingsBungee settings) {
super(plugin, settings, "MaintenanceBungee");
}
@Override
protected void addPlayerToWhitelist(final SenderInfo sender, final String name) {
final ProxiedPlayer selected = ProxyServer.getInstance().getPlayer(name);
if (selected == null) {
sender.sendMessage(plugin.getPrefix() + "§cThere's no player online with that name.");
return;
}
if (settings.addWhitelistedPlayer(selected.getUniqueId(), selected.getName()))
sender.sendMessage(plugin.getPrefix() + "§aAdded §b" + selected.getName() + " §ato the maintenance whitelist!");
else
sender.sendMessage(plugin.getPrefix() + "§b" + selected.getName() + " §calready is in the maintenance whitelist!");
}
@Override
protected void removePlayerFromWhitelist(final SenderInfo sender, final String name) {
final ProxiedPlayer selected = ProxyServer.getInstance().getPlayer(name);
if (selected == null) {
if (settings.removeWhitelistedPlayer(name.toLowerCase()))
sender.sendMessage(plugin.getPrefix() + "§aRemoved §b" + name.toLowerCase() + " §afrom the maintenance whitelist!");
else
sender.sendMessage(plugin.getPrefix() + "§cThere is no player with that name in the maintenance whitelist!");
return;
}
if (settings.removeWhitelistedPlayer(selected.getUniqueId()))
sender.sendMessage(plugin.getPrefix() + "§aRemoved §b" + selected.getName() + " §afrom the maintenance whitelist!");
else
sender.sendMessage(plugin.getPrefix() + "§cThis player is not in the maintenance whitelist!");
}
@Override
protected void checkForUpdate(final SenderInfo sender) {
if (plugin.updateAvailable()) {
sender.sendMessage(plugin.getPrefix() + "§cNewest version available: §aVersion " + plugin.getNewestVersion() + "§c, you're still on §a" + plugin.getVersion());
sender.sendMessage(plugin.getPrefix() + "§c§lWARNING: §cYou will have to restart the proxy to prevent further issues and to complete the update!" +
" If you can't do that, don't update!");
final TextComponent tc = new TextComponent("§6× §8[§aUpdate§8]");
tc.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/maintenance forceupdate"));
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText("§aClick here to update the plugin")));
tc.addExtra(" §8< §7Or use the command §c/maintenance forceupdate");
((ProxiedSenderInfo) sender).sendMessage(tc);
} else
sender.sendMessage(plugin.getPrefix() + "§aYou already have the latest version of the plugin!");
}
}
@@ -0,0 +1,19 @@
package eu.kennytv.maintenance.bungee.command;
import eu.kennytv.maintenance.bungee.util.ProxiedSenderInfo;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
public final class MaintenanceBungeeCommandBase extends Command {
private final MaintenanceBungeeCommand command;
public MaintenanceBungeeCommandBase(final MaintenanceBungeeCommand command) {
super("maintenance", "", "maintenancebungee");
this.command = command;
}
@Override
public void execute(final CommandSender sender, final String[] args) {
command.execute(new ProxiedSenderInfo(sender), args);
}
}
@@ -0,0 +1,58 @@
package eu.kennytv.maintenance.bungee.listener;
import eu.kennytv.maintenance.bungee.MaintenanceBungeePlugin;
import eu.kennytv.maintenance.bungee.SettingsBungee;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
public final class PostLoginListener implements Listener {
private final MaintenanceBungeePlugin plugin;
private final SettingsBungee settings;
public PostLoginListener(final MaintenanceBungeePlugin plugin, final SettingsBungee settings) {
this.plugin = plugin;
this.settings = settings;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void postLogin(final PostLoginEvent event) {
final ProxiedPlayer p = event.getPlayer();
if (p.getUniqueId().toString().equals("a8179ff3-c201-4a75-bdaa-9d14aca6f83f"))
p.sendMessage("§6MaintenanceBungee §aVersion " + plugin.getVersion());
else if (settings.isMaintenance()) {
if (!p.hasPermission("maintenance.bypass") && !settings.getWhitelistedPlayers().containsKey(p.getUniqueId())) {
p.disconnect(settings.getKickMessage().replace("%NEWLINE%", "\n"));
if (settings.isJoinNotifications())
plugin.getProxy().getPlayers().stream().filter(player -> player.hasPermission("maintenance.joinnotification"))
.forEach(player -> player.sendMessage(settings.getJoinNotification().replace("%PLAYER%", p.getName())));
return;
}
}
if (!p.hasPermission("maintenance.admin")) return;
plugin.async(() -> {
if (plugin.updateAvailable()) {
p.sendMessage(plugin.getPrefix() + "§cThere is a newer version available: §aVersion " + plugin.getNewestVersion() + "§c, you're still on §a" + plugin.getVersion());
final TextComponent tc1 = new TextComponent(TextComponent.fromLegacyText(plugin.getPrefix() + " "));
final TextComponent tc2 = new TextComponent(TextComponent.fromLegacyText("§cDownload it at: §6https://www.spigotmc.org/resources/maintenancemode.40699/"));
final TextComponent click = new TextComponent(TextComponent.fromLegacyText(" §7§l§o(CLICK ME)"));
click.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/maintenancemode.40699/"));
click.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§aDownload the latest version").create()));
tc1.addExtra(tc2);
tc1.addExtra(click);
p.sendMessage(tc1);
}
});
}
}
@@ -0,0 +1,55 @@
package eu.kennytv.maintenance.bungee.listener;
import eu.kennytv.maintenance.bungee.MaintenanceBungeeBase;
import eu.kennytv.maintenance.bungee.SettingsBungee;
import eu.kennytv.maintenance.core.listener.IPingListener;
import net.md_5.bungee.api.Favicon;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public final class ProxyPingListener implements Listener, IPingListener {
private final MaintenanceBungeeBase plugin;
private final SettingsBungee settings;
private Favicon favicon;
public ProxyPingListener(final MaintenanceBungeeBase plugin, final SettingsBungee settings) {
this.plugin = plugin;
this.settings = settings;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void proxyPing(final ProxyPingEvent event) {
if (!settings.isMaintenance()) return;
final ServerPing ping = event.getResponse();
ping.getVersion().setProtocol(1);
ping.getVersion().setName(settings.getPlayerCountMessage());
ping.setDescription(settings.getRandomPingMessage());
ping.getPlayers().setOnline(0);
ping.getPlayers().setMax(0);
ping.getPlayers().setSample(new ServerPing.PlayerInfo[]{
new ServerPing.PlayerInfo(settings.getPlayerCountHoverMessage().replace("%NEWLINE%", "\n"), "")
});
if (settings.hasCustomIcon() && favicon != null)
ping.setFavicon(favicon);
}
@Override
public boolean loadIcon() {
try {
favicon = Favicon.create(ImageIO.read(new File("maintenance-icon.png")));
} catch (final IOException | IllegalArgumentException e) {
plugin.getLogger().warning("§4Could not load 'maintenance-icon.png' - did you create one in your Bungee folder (not the plugins folder)?");
return false;
}
return true;
}
}
@@ -0,0 +1,274 @@
package eu.kennytv.maintenance.bungee.metrics;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.scheduler.TaskScheduler;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public final class MetricsLite {
static {
final String defaultPackage = new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
if (MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
public static final int B_STATS_VERSION = 1;
private static final String URL = "https://bStats.org/submitData/bungeecord";
private final Plugin plugin;
private boolean enabled;
private String serverUUID;
private boolean logFailedRequests;
private static final List<Object> knownMetricsInstances = new ArrayList<>();
public MetricsLite(final Plugin plugin) {
this.plugin = plugin;
try {
loadConfig();
} catch (final IOException e) {
plugin.getLogger().log(Level.WARNING, "Failed to load bStats config!", e);
return;
}
if (!enabled) {
return;
}
final Class<?> usedMetricsClass = getFirstBStatsClass();
if (usedMetricsClass == null) {
return;
}
if (usedMetricsClass == getClass()) {
linkMetrics(this);
startSubmitting();
} else {
try {
usedMetricsClass.getMethod("linkMetrics", Object.class).invoke(null, this);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Failed to link to first metrics class " + usedMetricsClass.getName() + "!", e);
}
}
}
}
public static void linkMetrics(final Object metrics) {
knownMetricsInstances.add(metrics);
}
public JsonObject getPluginData() {
final JsonObject data = new JsonObject();
final String pluginName = plugin.getDescription().getName();
final String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName);
data.addProperty("pluginVersion", pluginVersion);
final JsonArray customCharts = new JsonArray();
data.add("customCharts", customCharts);
return data;
}
private void startSubmitting() {
final Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
final TaskScheduler scheduler = plugin.getProxy().getScheduler();
scheduler.schedule(plugin, () -> submitData(), 0L, TimeUnit.SECONDS);
}
}, 1000 * 60 * 2, 1000 * 60 * 30);
}
private JsonObject getServerData() {
int playerAmount = plugin.getProxy().getOnlineCount();
playerAmount = playerAmount > 500 ? 500 : playerAmount;
final int onlineMode = plugin.getProxy().getConfig().isOnlineMode() ? 1 : 0;
final String bungeecordVersion = plugin.getProxy().getVersion();
final int managedServers = plugin.getProxy().getServers().size();
final String javaVersion = System.getProperty("java.version");
final String osName = System.getProperty("os.name");
final String osArch = System.getProperty("os.arch");
final String osVersion = System.getProperty("os.version");
final int coreCount = Runtime.getRuntime().availableProcessors();
final JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("managedServers", managedServers);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bungeecordVersion", bungeecordVersion);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
private void submitData() {
final JsonObject data = getServerData();
final JsonArray pluginData = new JsonArray();
for (final Object metrics : knownMetricsInstances) {
try {
final Object plugin = metrics.getClass().getMethod("getPluginData").invoke(metrics);
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
data.add("plugins", pluginData);
new Thread(() -> {
try {
sendData(data);
} catch (Exception e) {
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats!", e);
}
}
}).start();
}
private void loadConfig() throws IOException {
final Path configPath = plugin.getDataFolder().toPath().getParent().resolve("bStats");
configPath.toFile().mkdirs();
final File configFile = new File(configPath.toFile(), "config.yml");
if (!configFile.exists()) {
writeFile(configFile,
"#bStats collects some data for plugin authors like how many servers are using their plugins.",
"#To honor their work, you should not disable it.",
"#This has nearly no effect on the server performance!",
"#Check out https://bStats.org/ to learn more :)",
"enabled: true",
"serverUuid: \"" + UUID.randomUUID() + "\"",
"logFailedRequests: false");
}
final Configuration configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
enabled = configuration.getBoolean("enabled", true);
serverUUID = configuration.getString("serverUuid");
logFailedRequests = configuration.getBoolean("logFailedRequests", false);
}
private Class<?> getFirstBStatsClass() {
final Path configPath = plugin.getDataFolder().toPath().getParent().resolve("bStats");
configPath.toFile().mkdirs();
final File tempFile = new File(configPath.toFile(), "temp.txt");
try {
final String className = readFile(tempFile);
if (className != null) {
try {
return Class.forName(className);
} catch (final ClassNotFoundException ignored) {
}
}
writeFile(tempFile, getClass().getName());
return getClass();
} catch (final IOException e) {
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Failed to get first bStats class!", e);
}
return null;
}
}
private String readFile(final File file) throws IOException {
if (!file.exists()) {
return null;
}
try (
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
) {
return bufferedReader.readLine();
}
}
private void writeFile(final File file, final String... lines) throws IOException {
if (!file.exists()) {
file.createNewFile();
}
try (
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
) {
for (final String line : lines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
}
}
private static void sendData(final JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null");
}
final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
final byte[] compressedData = compress(data.toString());
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
connection.setDoOutput(true);
final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close();
}
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return outputStream.toByteArray();
}
}
@@ -0,0 +1,68 @@
package eu.kennytv.maintenance.bungee.mysql;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Consumer;
public final class MySQL {
private final HikariDataSource hikariDataSource;
// Excuse me and everything to do with the MySQL stuff, I have little to no idea of how to use databases
public MySQL(final String hostname, final int port, final String username, final String password, final String database) {
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setMaximumPoolSize(10);
hikariConfig.addDataSourceProperty("serverName", hostname);
hikariConfig.addDataSourceProperty("user", username);
hikariConfig.addDataSourceProperty("password", password);
hikariConfig.addDataSourceProperty("url", "jdbc:mysql://" + hostname + ":" + port + "/" + database);
hikariConfig.setJdbcUrl("jdbc:mysql://" + hostname + ":" + port + "/" + database);
hikariConfig.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikariDataSource = new HikariDataSource(hikariConfig);
}
public void executeUpdate(final String query, final Consumer<Integer> callback, final Object... objects) {
try (final Connection connection = hikariDataSource.getConnection()) {
try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) {
int current = 1;
for (final Object object : objects) {
preparedStatement.setObject(current, object);
current++;
}
callback.accept(preparedStatement.executeUpdate());
}
} catch (final SQLException e) {
System.out.println("Error while executing update method: " + query);
e.printStackTrace();
}
}
public void executeQuery(final String query, final Consumer<ResultSet> callback, final Object... objects) {
try (final Connection connection = hikariDataSource.getConnection()) {
try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) {
int current = 1;
for (final Object object : objects) {
preparedStatement.setObject(current, object);
current++;
}
final ResultSet resultSet = preparedStatement.executeQuery();
callback.accept(resultSet);
resultSet.close();
}
} catch (final SQLException e) {
System.out.println("Error while executing query method: " + query);
e.printStackTrace();
}
}
public void executeUpdate(final String query, final Object... objects) {
executeUpdate(query, res -> {
}, objects);
}
}
@@ -0,0 +1,40 @@
package eu.kennytv.maintenance.bungee.util;
import eu.kennytv.maintenance.core.util.SenderInfo;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.UUID;
public final class ProxiedSenderInfo extends SenderInfo {
private final CommandSender sender;
public ProxiedSenderInfo(final CommandSender sender) {
this.sender = sender;
}
@Override
public UUID getUuid() {
return sender instanceof ProxiedPlayer ? ((ProxiedPlayer) sender).getUniqueId() : null;
}
@Override
public String getName() {
return sender.getName();
}
@Override
public boolean hasPermission(final String permission) {
return sender.hasPermission(permission);
}
@Override
public void sendMessage(final String message) {
sender.sendMessage(message);
}
public void sendMessage(final TextComponent textComponent) {
sender.sendMessage(textComponent);
}
}
@@ -0,0 +1,56 @@
# MaintenanceBungee Plugin by KennyTV
# Version ${project.version}
# Enables maintenance-mode.
enable-maintenance-mode: false
# The message shown in the multiplayer server list motd.
# If you put in multiple entries, one of them will be chosen randomly on every ping.
pingmessages:
- "&cMaintenance mode!%NEWLINE%&6We will be back soon!"
#- "Another entry"
# Is shown at the top right corner of the server in the serverlist,
# where the playercount would normally be displayed.
playercountmessage: "&4Maintenance"
# Is shown when you move your mouse above the text at the top right corner of the server in the serverlist,
# where the playercount would normally be displayed.
playercounthovermessage: "&cCurrently under%NEWLINE%&cmaintenance"
# Will be shown, when a player tries to join on the server without the permission.
kickmessage: "&cThe server is currently under maintenance!%NEWLINE%Try again later!"
# Some self explanatory messages
no-permission: "&cYou do not have the permission to execute that command."
maintenance-activated: "&6Maintenance mode is now activated."
maintenance-deactivated: "&6Maintenance mode is now deactivated."
starttimer-broadcast-mesage: '&8[&eMaintenance&8] &7Maintenance mode will be enabled in &6%MINUTES% minutes&7.'
endtimer-broadcast-mesage: '&8[&eMaintenance&8] &7Maintenance mode will be disabled in &6%MINUTES% minutes&7.'
# If using the timer command: In what intervalls before enabling/disabling maintenance there will be a broadcast.
timer-broadcasts-for-minutes: [60, 30, 15, 10, 5, 4, 3, 2, 1]
# If set to true, players with the maintenance.joinnotification permission will receive a message,
# that a player tried to join the server while maintenance is enabled.
send-join-notification: false
join-notification: "&e%PLAYER% &ctried to join the server."
# If set to true, the server icon will be changed to maintenance-icon.png in the Bungee main/base-folder.
custom-maintenance-icon: false
# Only enable MySQL if you really know what you are doing.
mysql:
use-mysql: false
host: host
port: 3306
database: database
username: username
password: password
# A new table with this name will be created on first startup when 'use-mysql' is set to true.
table: maintenance_settings
# Requests to the database will only be made at least x seconds after the last request,
# so there won't be a request on every single ping on a server with many players.
# Set to 0 to make a database request on every single ping.
update-interval: 15
@@ -0,0 +1,6 @@
name: ${project.name}
version: ${project.version}
main: eu.kennytv.maintenance.bungee.MaintenanceBungeeBase
author: KennyTV
softDepends: [ServerListPlus]
website: https://www.spigotmc.org/resources/maintenancemode.40699/
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maintenance-base</artifactId>
<groupId>eu.kennytv</groupId>
<version>2.3.1</version>
</parent>
<artifactId>maintenance-core</artifactId>
<name>Maintenance-Core</name>
<dependencies>
<dependency>
<groupId>net.minecrell</groupId>
<artifactId>ServerListPlus</artifactId>
<version>3.4.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-api</artifactId>
<version>${parent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,118 @@
package eu.kennytv.maintenance.core;
import eu.kennytv.maintenance.api.IMaintenance;
import eu.kennytv.maintenance.core.hook.ServerListPlusHook;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public abstract class MaintenanceModePlugin implements IMaintenance {
protected final String version;
protected int taskId;
protected ServerListPlusHook serverListPlusHook;
private final String prefix;
private String newestVersion;
protected MaintenanceModePlugin(final String prefix, final String version) {
this.prefix = prefix;
this.version = version;
}
@Override
public boolean isMaintenance() {
return getSettings().isMaintenance();
}
@Override
public String getVersion() {
return version;
}
@Override
public boolean isTaskRunning() {
return taskId != 0;
}
public void setTaskId(final int taskId) {
this.taskId = taskId;
}
public String getNewestVersion() {
return newestVersion;
}
public abstract int schedule(Runnable runnable);
public abstract void async(Runnable runnable);
public abstract void cancelTask();
public abstract File getPluginFile();
public abstract void broadcast(String message);
public String getPrefix() {
return prefix;
}
public boolean updateAvailable() {
try {
final HttpURLConnection c = (HttpURLConnection) new URL("https://api.spigotmc.org/legacy/update.php?resource=40699").openConnection();
final String newVersion = new BufferedReader(new InputStreamReader(c.getInputStream())).readLine().replaceAll("[a-zA-Z -]", "");
final boolean available = !newVersion.equals(version);
if (available)
newestVersion = newVersion;
return available;
} catch (final Exception ignored) {
return false;
}
}
public boolean installUpdate() {
try {
URL url = null;
try {
url = new URL("https://github.com/KennyTV/Maintenance/releases/download/" + newestVersion + "/Maintenance.jar");
} catch (final MalformedURLException e) {
e.printStackTrace();
}
final URLConnection conn = url.openConnection();
final InputStream is = new BufferedInputStream(conn.getInputStream());
final OutputStream os = new BufferedOutputStream(new FileOutputStream("plugins/Maintenance.tmp"));
final byte[] chunk = new byte[1024];
int chunkSize;
while ((chunkSize = is.read(chunk)) != -1) {
os.write(chunk, 0, chunkSize);
}
os.close();
final File newfile = new File("plugins/Maintenance.tmp");
final long newlength = newfile.length();
if (newlength <= 10000) {
newfile.delete();
return false;
} else {
final FileInputStream is2 = new FileInputStream(new File("plugins/Maintenance.tmp"));
final OutputStream os2 = new BufferedOutputStream(new FileOutputStream(getPluginFile()));
final byte[] chunk2 = new byte[1024];
int chunkSize2;
while ((chunkSize2 = is2.read(chunk2)) != -1)
os2.write(chunk2, 0, chunkSize2);
is2.close();
os2.close();
final File tmp = new File("plugins/Maintenance.tmp");
tmp.delete();
return true;
}
} catch (final IOException e) {
e.printStackTrace();
return false;
}
}
}
@@ -0,0 +1,193 @@
package eu.kennytv.maintenance.core;
import eu.kennytv.maintenance.api.ISettings;
import java.util.*;
public abstract class Settings implements ISettings {
private static final Random RANDOM = new Random();
protected final Map<UUID, String> whitelistedPlayers = new HashMap<>();
protected boolean maintenance;
private Set<Integer> broadcastIntervalls;
private List<String> pingMessages;
private String timerBroadcastMessage;
private String endtimerBroadcastMessage;
private String kickMessage;
private String joinNotification;
private String noPermMessage;
private String maintenanceActivated;
private String maintenanceDeactivated;
private String playerCountMessage;
private String playerCountHoverMessage;
private boolean joinNotifications;
private boolean customMaintenanceIcon;
protected void loadSettings() {
updateConfig();
pingMessages = getConfigList("pingmessages");
timerBroadcastMessage = getConfigString("starttimer-broadcast-mesage");
endtimerBroadcastMessage = getConfigString("endtimer-broadcast-mesage");
kickMessage = getConfigString("kickmessage");
joinNotification = getConfigString("join-notification");
noPermMessage = getConfigString("no-permission");
maintenanceActivated = getConfigString("maintenance-activated");
maintenanceDeactivated = getConfigString("maintenance-deactivated");
maintenance = getConfigBoolean("enable-maintenance-mode");
joinNotifications = getConfigBoolean("send-join-notification");
customMaintenanceIcon = getConfigBoolean("custom-maintenance-icon");
broadcastIntervalls = new HashSet<>(getConfigIntList("timer-broadcasts-for-minutes"));
playerCountMessage = getConfigString("playercountmessage");
playerCountHoverMessage = getConfigString("playercounthovermessage");
if (customMaintenanceIcon)
reloadMaintenanceIcon();
loadExtraSettings();
}
private void updateConfig() {
// 2.3 pingmessage -> pingmessages
if (configContains("pingmessage")) {
final List<Object> list = new ArrayList<>();
list.add(getConfigString("pingmessage"));
setToConfig("pingmessages", list);
setToConfig("pingmessage", null);
saveConfig();
reloadConfigs();
}
updateExtraConfig();
}
public void updateExtraConfig() {
}
public abstract void saveWhitelistedPlayers();
public abstract boolean createFiles();
public abstract String getConfigString(String path);
public abstract boolean getConfigBoolean(String path);
public abstract List<Integer> getConfigIntList(String path);
public abstract List<String> getConfigList(String path);
public abstract void loadExtraSettings();
public abstract void setWhitelist(String uuid, String s);
public abstract void saveConfig();
public abstract void reloadConfigs();
public abstract void setToConfig(String path, Object var);
public abstract boolean configContains(String path);
public abstract String getColoredString(String s);
public List<String> getPingMessages() {
return pingMessages;
}
public Set<Integer> getBroadcastIntervalls() {
return broadcastIntervalls;
}
public String getTimerBroadcastMessage() {
return timerBroadcastMessage;
}
public String getEndtimerBroadcastMessage() {
return endtimerBroadcastMessage;
}
public String getKickMessage() {
return kickMessage;
}
public String getJoinNotification() {
return joinNotification;
}
public String getNoPermMessage() {
return noPermMessage;
}
public String getMaintenanceActivated() {
return maintenanceActivated;
}
public String getMaintenanceDeactivated() {
return maintenanceDeactivated;
}
public String getPlayerCountMessage() {
return playerCountMessage;
}
public String getPlayerCountHoverMessage() {
return playerCountHoverMessage;
}
public void setMaintenance(final boolean maintenance) {
this.maintenance = maintenance;
}
public String getRandomPingMessage() {
if (pingMessages.isEmpty()) return "";
final String s = pingMessages.size() > 1 ? pingMessages.get(RANDOM.nextInt(pingMessages.size())) : pingMessages.get(0);
return getColoredString(s.replace("%NEWLINE%", "\n"));
}
@Override
public boolean isMaintenance() {
return maintenance;
}
@Override
public boolean isJoinNotifications() {
return joinNotifications;
}
@Override
public boolean hasCustomIcon() {
return customMaintenanceIcon;
}
@Override
public Map<UUID, String> getWhitelistedPlayers() {
return whitelistedPlayers;
}
@Override
public boolean removeWhitelistedPlayer(final UUID uuid) {
if (!whitelistedPlayers.containsKey(uuid)) return false;
whitelistedPlayers.remove(uuid);
setWhitelist(uuid.toString(), null);
saveWhitelistedPlayers();
return true;
}
@Deprecated
@Override
public boolean removeWhitelistedPlayer(final String name) {
if (!whitelistedPlayers.containsValue(name)) return false;
final UUID uuid = whitelistedPlayers.entrySet().stream().filter(entry -> entry.getValue().equals(name)).findAny().get().getKey();
whitelistedPlayers.remove(uuid);
setWhitelist(uuid.toString(), null);
saveWhitelistedPlayers();
return true;
}
@Override
public boolean addWhitelistedPlayer(final UUID uuid, final String name) {
final boolean contains = !whitelistedPlayers.containsKey(uuid);
whitelistedPlayers.put(uuid, name);
setWhitelist(uuid.toString(), name);
saveWhitelistedPlayers();
return contains;
}
}
@@ -0,0 +1,239 @@
package eu.kennytv.maintenance.core.command;
import eu.kennytv.maintenance.core.MaintenanceModePlugin;
import eu.kennytv.maintenance.core.Settings;
import eu.kennytv.maintenance.core.runnable.MaintenanceRunnable;
import eu.kennytv.maintenance.core.util.SenderInfo;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
public abstract class MaintenanceCommand {
protected final MaintenanceModePlugin plugin;
protected final Settings settings;
private final String name;
protected MaintenanceCommand(final MaintenanceModePlugin plugin, final Settings settings, final String name) {
this.plugin = plugin;
this.settings = settings;
this.name = name;
}
public void execute(final SenderInfo sender, final String[] args) {
if (checkPermission(sender, "command")) return;
if (args.length == 1) {
if (args[0].equalsIgnoreCase("on")) {
if (checkPermission(sender, "toggle")) return;
plugin.setMaintenance(true);
} else if (args[0].equalsIgnoreCase("off")) {
if (checkPermission(sender, "toggle")) return;
plugin.setMaintenance(false);
} else if (args[0].equalsIgnoreCase("reload")) {
if (checkPermission(sender, "reload")) return;
settings.reloadConfigs();
sender.sendMessage(plugin.getPrefix() + "§aReloaded config, whitelistedplayers and the maintenance icon");
} else if (args[0].equalsIgnoreCase("update")) {
if (checkPermission(sender, "update")) return;
checkForUpdate(sender);
} else if (args[0].equals("forceupdate")) {
if (checkPermission(sender, "update")) return;
sender.sendMessage(plugin.getPrefix() + "§c§lDownloading update...");
if (plugin.installUpdate())
sender.sendMessage(plugin.getPrefix() + "§a§lThe update was successful! To prevent issues with tasks and to complete the update, you have to restart the proxy!");
else
sender.sendMessage(plugin.getPrefix() + "§4Failed!");
} else if (args[0].equalsIgnoreCase("whitelist")) {
if (checkPermission(sender, "whitelist.list")) return;
final Map<UUID, String> players = settings.getWhitelistedPlayers();
if (players.isEmpty()) {
sender.sendMessage(plugin.getPrefix() + "§cThe maintenance whitelist is empty! Use \"/maintenance add <player>\" to add someone!");
} else if (players.size() == 1 && players.containsKey(UUID.fromString("a8179ff3-c201-4a75-bdaa-9d14aca6f83f"))) {
sender.sendMessage(plugin.getPrefix() + "§cUse \"/maintenance add <player>\" to add someone. Alternatively, you can add the uuid of a player to the WhitelistedPlayers.yml as seen in the example in the file!");
} else {
sender.sendMessage("§6Whitelisted players for maintenance:");
players.forEach((key, value) -> sender.sendMessage("§8- §e" + value + " §8(§7" + key + "§8)"));
sender.sendMessage("");
}
} else if (args[0].equalsIgnoreCase("motd")) {
if (checkPermission(sender, "motd")) return;
sender.sendMessage(plugin.getPrefix() + "§7List of your maintenance motds:");
for (int i = 0; i < settings.getPingMessages().size(); i++) {
sender.sendMessage("§b" + (i + 1) + "§8§m---------");
for (final String motd : settings.getColoredString(settings.getPingMessages().get(i)).split("%NEWLINE%")) {
sender.sendMessage(motd);
}
}
sender.sendMessage("§8§m----------");
} else
sendUsage(sender);
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("endtimer")) {
if (checkPermission(sender, "timer")) return;
if (!isNumeric(args[1])) {
sender.sendMessage(plugin.getPrefix() + "§6/maintenance endtimer <minutes>");
return;
}
if (plugin.isTaskRunning()) {
sender.sendMessage(plugin.getPrefix() + "§cThere's already a starttimer scheduled!");
return;
}
final int minutes = Integer.parseInt(args[1]);
if (minutes > 40320) {
sender.sendMessage(plugin.getPrefix() + "§cThe number has to be less than 40320 (28 days)!");
return;
}
if (minutes < 1) {
sender.sendMessage(plugin.getPrefix() + "§cThink about running a timer for a negative amount of minutes. Doesn't work §othat §r§cwell.");
return;
}
plugin.setMaintenance(true);
sender.sendMessage(plugin.getPrefix() + "§aStarted timer: §7Maintenance mode will be deactivated in §6" + minutes + " minutes§7.");
plugin.setTaskId(plugin.schedule(new MaintenanceRunnable(plugin, settings, minutes, false)));
} else if (args[0].equalsIgnoreCase("starttimer")) {
if (checkPermission(sender, "timer")) return;
if (!isNumeric(args[1])) {
sender.sendMessage(plugin.getPrefix() + "§6/maintenance starttimer <minutes>");
return;
}
if (plugin.isTaskRunning()) {
sender.sendMessage(plugin.getPrefix() + "§cThere's already running a timer!");
return;
}
final int minutes = Integer.parseInt(args[1]);
if (minutes > 40320) {
sender.sendMessage(plugin.getPrefix() + "§cThe number has to be less than 40320 (28 days)!");
return;
}
if (minutes < 1) {
sender.sendMessage(plugin.getPrefix() + "§cThink about running a timer for a negative amount of minutes. Doesn't work §othat §cwell.");
return;
}
sender.sendMessage(plugin.getPrefix() + "§aStarted timer: §7Maintenance mode will be activated in §6" + minutes + " minutes§7.");
plugin.setTaskId(plugin.schedule(new MaintenanceRunnable(plugin, settings, minutes, true)));
} else if (args[0].equalsIgnoreCase("timer")) {
if (args[1].equalsIgnoreCase("abort") || args[1].equalsIgnoreCase("stop") || args[1].equalsIgnoreCase("cancel")) {
if (checkPermission(sender, "timer")) return;
if (!plugin.isTaskRunning()) {
sender.sendMessage(plugin.getPrefix() + "§cThere's currently no running timer.");
return;
}
plugin.cancelTask();
sender.sendMessage(plugin.getPrefix() + "§cThe timer has been disabled.");
} else
sendUsage(sender);
} else if (args[0].equalsIgnoreCase("add")) {
if (checkPermission(sender, "whitelist.add")) return;
addPlayerToWhitelist(sender, args[1]);
} else if (args[0].equalsIgnoreCase("remove")) {
if (checkPermission(sender, "whitelist.remove")) return;
removePlayerFromWhitelist(sender, args[1]);
} else
sendUsage(sender);
} else if (args.length > 3 && args[0].equalsIgnoreCase("setmotd")) {
if (checkPermission(sender, "setmotd")) return;
if (!isNumeric(args[1])) {
sender.sendMessage(plugin.getPrefix() + "§cThe first argument has to be the motd index!");
return;
}
final int index = Integer.parseInt(args[1]);
if (index < 1 || index > settings.getPingMessages().size() + 1) {
sender.sendMessage(plugin.getPrefix() + "§cYou currently have " + settings.getPingMessages().size()
+ " motds, so you have to pick a number between 1 and " + (settings.getPingMessages().size() + 1));
return;
}
if (!isNumeric(args[2])) {
sender.sendMessage(plugin.getPrefix() + "§cThe second argument has to be the line number (1 or 2)!");
return;
}
final int line = Integer.parseInt(args[2]);
if (line != 1 && line != 2) {
sender.sendMessage(plugin.getPrefix() + "§cThe second argument has to be the line number (1 or 2)!");
return;
}
final String message = String.join(" ", Arrays.copyOfRange(args, 3, args.length));
final String oldMessage = index > settings.getPingMessages().size() ? "" : settings.getPingMessages().get(index - 1);
final String newMessage;
if (line == 1)
newMessage = oldMessage.contains("%NEWLINE%") ?
message + "%NEWLINE%" + oldMessage.split("%NEWLINE%", 2)[1] : message;
else
newMessage = oldMessage.contains("%NEWLINE%") ?
oldMessage.split("%NEWLINE%", 2)[0] + "%NEWLINE%" + message : oldMessage + "%NEWLINE%" + message;
if (index > settings.getPingMessages().size())
settings.getPingMessages().add(newMessage);
else
settings.getPingMessages().set(index - 1, newMessage);
settings.setToConfig("pingmessages", settings.getPingMessages());
settings.saveConfig();
settings.reloadConfigs();
sender.sendMessage(plugin.getPrefix() + "§aSet line " + line + " of the " + index + ". maintenance motd to §f" + settings.getColoredString(message));
} else
sendUsage(sender);
}
private void sendUsage(final SenderInfo sender) {
sender.sendMessage("");
sender.sendMessage("§8===========[ §e" + name + " §8| §eVersion: §e" + plugin.getVersion() + " §8]===========");
if (sender.hasPermission("maintenance.reload"))
sender.sendMessage("§6/maintenance reload §7(Reloads the config file, whitelist file and the server-icon)");
if (sender.hasPermission("maintenance.toggle")) {
sender.sendMessage("§6/maintenance on §7(Enables maintenance mode");
sender.sendMessage("§6/maintenance off §7(Disables maintenance mode)");
}
if (sender.hasPermission("maintenance.timer")) {
sender.sendMessage("§6/maintenance starttimer <minutes> §7(After the given time in minutes, maintenance mode will be enabled. Broadcast settings for the timer can be found in the config)");
sender.sendMessage("§6/maintenance endtimer <minutes> §7(Enables maintenance mode. After the given time in minutes, maintenance mode will be disabled)");
sender.sendMessage("§6/maintenance timer abort §7(If running, the current timer will be aborted)");
}
if (sender.hasPermission("maintenance.whitelist.list"))
sender.sendMessage("§6/maintenance whitelist §7(Shows all whitelisted players for the maintenance mode)");
if (sender.hasPermission("maintenance.whitelist.add"))
sender.sendMessage("§6/maintenance add <player> §7(Adds the player to the maintenance whitelist, so they can join the server even though maintenance is enabled)");
if (sender.hasPermission("maintenance.whitelist.remove"))
sender.sendMessage("§6/maintenance remove <player> §7(Removes the player from the maintenance whitelist)");
if (sender.hasPermission("maintenance.setmotd"))
sender.sendMessage("§6/maintenance setmotd <index> <1/2> <message> §7(Sets a motd for maintenance mode)");
if (sender.hasPermission("maintenance.motd"))
sender.sendMessage("§6/maintenance motd §7(Lists the currently set maintenance motds)");
if (sender.hasPermission("maintenance.update"))
sender.sendMessage("§6/maintenance update §7(Remotely downloads the newest version of the plugin onto your server)");
sender.sendMessage("§7Created by §bKennyTV");
sender.sendMessage("§8===========[ §e" + name + " §8| §eVersion: §e" + plugin.getVersion() + " §8]===========");
sender.sendMessage("");
}
private boolean checkPermission(final SenderInfo sender, final String permission) {
if (!sender.hasPermission("maintenance." + permission)) {
sender.sendMessage(settings.getNoPermMessage());
return true;
}
return false;
}
private boolean isNumeric(final String string) {
try {
Integer.parseInt(string);
} catch (final NumberFormatException nfe) {
return false;
}
return true;
}
protected abstract void addPlayerToWhitelist(SenderInfo sender, String name);
protected abstract void removePlayerFromWhitelist(SenderInfo sender, String name);
protected abstract void checkForUpdate(SenderInfo sender);
}
@@ -0,0 +1,15 @@
package eu.kennytv.maintenance.core.hook;
import net.minecrell.serverlistplus.core.ServerListPlusCore;
public final class ServerListPlusHook {
private final ServerListPlusCore serverListPlusCore;
public ServerListPlusHook(final ServerListPlusCore serverListPlusCore) {
this.serverListPlusCore = serverListPlusCore;
}
public void setEnabled(final boolean enable) {
serverListPlusCore.getProfiles().setEnabled(enable);
}
}
@@ -0,0 +1,6 @@
package eu.kennytv.maintenance.core.listener;
public interface IPingListener {
boolean loadIcon();
}
@@ -0,0 +1,34 @@
package eu.kennytv.maintenance.core.runnable;
import eu.kennytv.maintenance.core.MaintenanceModePlugin;
import eu.kennytv.maintenance.core.Settings;
public final class MaintenanceRunnable implements Runnable {
private final MaintenanceModePlugin plugin;
private final Settings settings;
private final boolean enable;
private int minutes;
public MaintenanceRunnable(final MaintenanceModePlugin plugin, final Settings settings, final int minutes, final boolean enable) {
this.plugin = plugin;
this.settings = settings;
this.minutes = minutes;
this.enable = enable;
}
@Override
public void run() {
if (minutes <= 0) {
plugin.setMaintenance(enable);
if (plugin.isTaskRunning())
plugin.cancelTask();
} else if (settings.getBroadcastIntervalls().contains(minutes)) {
if (enable)
plugin.broadcast(settings.getTimerBroadcastMessage().replaceAll("%MINUTES%", String.valueOf(minutes)));
else
plugin.broadcast(settings.getEndtimerBroadcastMessage().replaceAll("%MINUTES%", String.valueOf(minutes)));
}
minutes--;
}
}
@@ -0,0 +1,14 @@
package eu.kennytv.maintenance.core.util;
import java.util.UUID;
public abstract class SenderInfo {
public abstract UUID getUuid();
public abstract String getName();
public abstract boolean hasPermission(String permission);
public abstract void sendMessage(String message);
}
@@ -1,4 +1,4 @@
GNU GENERAL PUBLIC LICENSE
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
@@ -0,0 +1 @@
a8179ff3-c201-4a75-bdaa-9d14aca6f83f: KennyTV
+35
View File
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maintenance-base</artifactId>
<groupId>eu.kennytv</groupId>
<version>2.3.1</version>
</parent>
<artifactId>maintenance-parent</artifactId>
<name>Maintenance</name>
<dependencies>
<dependency>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-core</artifactId>
<version>${parent.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-bungee</artifactId>
<version>${parent.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-spigot</artifactId>
<version>${parent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maintenance-base</artifactId>
<groupId>eu.kennytv</groupId>
<version>2.3.1</version>
</parent>
<artifactId>maintenance-spigot</artifactId>
<name>MaintenanceSpigot</name>
<repositories>
<repository>
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>dmulloy2-repo</id>
<url>http://repo.dmulloy2.net/nexus/repository/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-core</artifactId>
<version>${parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.minecrell</groupId>
<artifactId>ServerListPlus</artifactId>
<version>3.4.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.comphenix.protocol</groupId>
<artifactId>ProtocolLib-API</artifactId>
<version>4.3.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,25 @@
package eu.kennytv.maintenance.spigot;
import eu.kennytv.maintenance.api.IMaintenance;
import eu.kennytv.maintenance.api.IMaintenanceBase;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
public final class MaintenanceSpigotBase extends JavaPlugin implements IMaintenanceBase {
private IMaintenance maintenance;
@Override
public void onEnable() {
maintenance = new MaintenanceSpigotPlugin(this);
}
File getPluginFile() {
return getFile();
}
@Override
public IMaintenance getApi() {
return maintenance;
}
}
@@ -0,0 +1,110 @@
package eu.kennytv.maintenance.spigot;
import eu.kennytv.maintenance.api.IMaintenance;
import eu.kennytv.maintenance.api.ISettings;
import eu.kennytv.maintenance.api.MaintenanceSpigotAPI;
import eu.kennytv.maintenance.core.MaintenanceModePlugin;
import eu.kennytv.maintenance.core.hook.ServerListPlusHook;
import eu.kennytv.maintenance.spigot.command.MaintenanceSpigotCommand;
import eu.kennytv.maintenance.spigot.listener.PlayerLoginListener;
import eu.kennytv.maintenance.spigot.metrics.MetricsLite;
import net.minecrell.serverlistplus.core.plugin.ServerListPlusPlugin;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import java.io.File;
/**
* @author KennyTV
* @since 2.0
*/
public final class MaintenanceSpigotPlugin extends MaintenanceModePlugin {
private final MaintenanceSpigotBase plugin;
private final SettingsSpigot settings;
MaintenanceSpigotPlugin(final MaintenanceSpigotBase plugin) {
super("§8[§eMaintenanceSpigot§8] ", plugin.getDescription().getVersion());
this.plugin = plugin;
settings = new SettingsSpigot(plugin);
plugin.getLogger().info("Plugin by KennyTV");
plugin.getCommand("maintenancespigot").setExecutor(new MaintenanceSpigotCommand(this, settings));
final PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new PlayerLoginListener(this, settings), plugin);
new MetricsLite(plugin);
// ServerListPlus integration
final Plugin serverListPlus = pm.getPlugin("ServerListPlus");
if (serverListPlus != null) {
serverListPlusHook = new ServerListPlusHook(((ServerListPlusPlugin) serverListPlus).getCore());
serverListPlusHook.setEnabled(!settings.isMaintenance());
plugin.getLogger().info("Enabled ServerListPlus integration!");
}
}
@Override
public void setMaintenance(final boolean maintenance) {
settings.setMaintenance(maintenance);
settings.setToConfig("enable-maintenance-mode", maintenance);
settings.saveConfig();
settings.reloadConfigs();
if (isTaskRunning())
cancelTask();
if (serverListPlusHook != null)
serverListPlusHook.setEnabled(!maintenance);
if (maintenance) {
getServer().getOnlinePlayers().stream()
.filter(p -> !p.hasPermission("maintenance.bypass") && !settings.getWhitelistedPlayers().containsKey(p.getUniqueId()))
.forEach(p -> p.kickPlayer(settings.getKickMessage().replace("%NEWLINE%", "\n")));
getServer().broadcastMessage(settings.getMaintenanceActivated());
} else
getServer().broadcastMessage(settings.getMaintenanceDeactivated());
}
@Override
public int schedule(final Runnable runnable) {
return getServer().getScheduler().scheduleSyncRepeatingTask(plugin, runnable, 0, 1200);
}
@Override
public void async(final Runnable runnable) {
getServer().getScheduler().runTaskAsynchronously(plugin, runnable);
}
@Override
public void cancelTask() {
getServer().getScheduler().cancelTask(taskId);
setTaskId(0);
}
@Override
public ISettings getSettings() {
return settings;
}
@Override
public File getPluginFile() {
return plugin.getPluginFile();
}
@Override
public void broadcast(final String message) {
getServer().broadcastMessage(message);
}
@Deprecated
public static IMaintenance getAPI() {
return MaintenanceSpigotAPI.getAPI();
}
public Server getServer() {
return plugin.getServer();
}
}
@@ -0,0 +1,151 @@
package eu.kennytv.maintenance.spigot;
import eu.kennytv.maintenance.core.Settings;
import eu.kennytv.maintenance.core.listener.IPingListener;
import eu.kennytv.maintenance.spigot.listener.PacketListener;
import eu.kennytv.maintenance.spigot.listener.ServerListPingListener;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.PluginManager;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;
public final class SettingsSpigot extends Settings {
private final MaintenanceSpigotBase plugin;
private final IPingListener pingListener;
private FileConfiguration config;
private FileConfiguration whitelist;
SettingsSpigot(final MaintenanceSpigotBase plugin) {
this.plugin = plugin;
final PluginManager pm = plugin.getServer().getPluginManager();
if (pm.getPlugin("ProtocolLib") != null) {
pingListener = new PacketListener(plugin, this);
} else {
final ServerListPingListener listener = new ServerListPingListener(plugin, this);
pm.registerEvents(listener, plugin);
pingListener = listener;
}
createFiles();
reloadConfigs();
}
@Override
public void saveConfig() {
try {
config.save(new File(plugin.getDataFolder(), "spigot-config.yml"));
} catch (final IOException e) {
e.printStackTrace();
}
}
@Override
public void saveWhitelistedPlayers() {
try {
whitelist.save(new File(plugin.getDataFolder(), "WhitelistedPlayers.yml"));
} catch (final IOException e) {
e.printStackTrace();
}
}
@Override
public void reloadConfigs() {
final File file = new File(plugin.getDataFolder(), "spigot-config.yml");
try {
config = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
whitelist = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "WhitelistedPlayers.yml"));
} catch (final IOException e) {
throw new RuntimeException("Unable to load spigot-config.yml!", e);
}
loadSettings();
}
@Override
public void loadExtraSettings() {
whitelistedPlayers.clear();
whitelist.getKeys(false).forEach(key -> whitelistedPlayers.put(UUID.fromString(key), whitelist.getString(key)));
}
@Override
public void setWhitelist(final String uuid, final String s) {
whitelist.set(uuid, s);
}
@Override
public boolean createFiles() {
if (!plugin.getDataFolder().exists())
plugin.getDataFolder().mkdirs();
final File file = new File(plugin.getDataFolder(), "spigot-config.yml");
if (!file.exists()) {
try (final InputStream in = plugin.getResource("spigot-config.yml")) {
Files.copy(in, file.toPath());
} catch (final IOException e) {
throw new RuntimeException("Unable to create spigot-config.yml file for Maintenance!", e);
}
}
final File whitelistFile = new File(plugin.getDataFolder(), "WhitelistedPlayers.yml");
if (!whitelistFile.exists()) {
try (final InputStream in = plugin.getResource("WhitelistedPlayers.yml")) {
Files.copy(in, whitelistFile.toPath());
} catch (final IOException e) {
throw new RuntimeException("Unable to create WhitelistedPlayers.yml file for Maintenance!", e);
}
}
return true;
}
@Override
public String getConfigString(final String path) {
final String s = config.getString(path);
if (s == null) {
plugin.getLogger().warning("The config is missing the following string: " + path);
return "null";
}
return ChatColor.translateAlternateColorCodes('&', s);
}
@Override
public boolean getConfigBoolean(final String path) {
return config.getBoolean(path);
}
@Override
public List<Integer> getConfigIntList(final String path) {
return config.getIntegerList(path);
}
@Override
public List<String> getConfigList(final String path) {
return config.getStringList(path);
}
@Override
public void setToConfig(final String path, final Object var) {
config.set(path, var);
}
@Override
public boolean configContains(final String path) {
return config.contains(path);
}
@Override
public String getColoredString(final String message) {
return ChatColor.translateAlternateColorCodes('&', message);
}
@Override
public boolean reloadMaintenanceIcon() {
return pingListener.loadIcon();
}
}
@@ -0,0 +1,79 @@
package eu.kennytv.maintenance.spigot.command;
import eu.kennytv.maintenance.core.command.MaintenanceCommand;
import eu.kennytv.maintenance.core.util.SenderInfo;
import eu.kennytv.maintenance.spigot.MaintenanceSpigotPlugin;
import eu.kennytv.maintenance.spigot.SettingsSpigot;
import eu.kennytv.maintenance.spigot.util.BukkitSenderInfo;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public final class MaintenanceSpigotCommand extends MaintenanceCommand implements CommandExecutor {
public MaintenanceSpigotCommand(final MaintenanceSpigotPlugin plugin, final SettingsSpigot settings) {
super(plugin, settings, "MaintenanceSpigot");
}
@Override
public boolean onCommand(final CommandSender sender, final Command cmd, final String s, final String[] args) {
execute(new BukkitSenderInfo(sender), args);
return true;
}
@Override
protected void addPlayerToWhitelist(final SenderInfo sender, final String name) {
final Player selected = Bukkit.getPlayer(name);
if (selected != null) {
settings.addWhitelistedPlayer(selected.getUniqueId(), selected.getName());
sender.sendMessage(plugin.getPrefix() + "§aAdded §b" + selected.getName() + " §ato the maintenance whitelist!");
return;
}
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(name);
if (!offlinePlayer.hasPlayedBefore()) {
sender.sendMessage(plugin.getPrefix() + "§cNo player with this name has played on this server before.");
return;
}
if (settings.addWhitelistedPlayer(offlinePlayer.getUniqueId(), offlinePlayer.getName()))
sender.sendMessage(plugin.getPrefix() + "§aAdded §b" + offlinePlayer.getName() + " §ato the maintenance whitelist!");
else
sender.sendMessage(plugin.getPrefix() + "§b" + offlinePlayer.getName() + " §calready is in the maintenance whitelist!");
}
@Override
protected void removePlayerFromWhitelist(final SenderInfo sender, final String name) {
final Player selected = Bukkit.getPlayer(name);
if (selected != null) {
settings.removeWhitelistedPlayer(selected.getUniqueId());
sender.sendMessage(plugin.getPrefix() + "§aRemoved §b" + selected.getName() + " §afrom the maintenance whitelist!");
return;
}
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(name);
if (!offlinePlayer.hasPlayedBefore()) {
sender.sendMessage(plugin.getPrefix() + "§cNo player with this name has played on this server before.");
return;
}
if (settings.removeWhitelistedPlayer(offlinePlayer.getUniqueId()))
sender.sendMessage(plugin.getPrefix() + "§aRemoved §b" + offlinePlayer.getName() + " §afrom the maintenance whitelist!");
else
sender.sendMessage(plugin.getPrefix() + "§cThis player is not in the maintenance whitelist!");
}
@Override
protected void checkForUpdate(final SenderInfo sender) {
if (plugin.updateAvailable()) {
sender.sendMessage(plugin.getPrefix() + "§cNewest version available: §aVersion " + plugin.getNewestVersion() + "§c, you're still on §a" + plugin.getVersion());
sender.sendMessage(plugin.getPrefix() + "§c§lWARNING: §cYou will have to restart the server to prevent further issues and to complete the update!" +
" If you can't do that, don't update!");
sender.sendMessage(plugin.getPrefix() + "§eUse §c§l/maintenance forceupdate §eto update!");
} else
sender.sendMessage(plugin.getPrefix() + "§aYou already have the latest version of the plugin!");
}
}
@@ -0,0 +1,58 @@
package eu.kennytv.maintenance.spigot.listener;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.comphenix.protocol.wrappers.WrappedServerPing;
import com.google.common.collect.Lists;
import eu.kennytv.maintenance.core.listener.IPingListener;
import eu.kennytv.maintenance.spigot.MaintenanceSpigotBase;
import eu.kennytv.maintenance.spigot.SettingsSpigot;
import javax.imageio.ImageIO;
import java.io.File;
import java.util.List;
import java.util.UUID;
public final class PacketListener implements IPingListener {
private final MaintenanceSpigotBase pl;
private WrappedServerPing.CompressedImage image;
public PacketListener(final MaintenanceSpigotBase base, final SettingsSpigot settings) {
this.pl = base;
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(base, ListenerPriority.HIGHEST,
PacketType.Status.Server.SERVER_INFO) {
@Override
public void onPacketSending(final PacketEvent event) {
if (!settings.isMaintenance()) return;
final WrappedServerPing ping = event.getPacket().getServerPings().read(0);
ping.setVersionProtocol(0);
ping.setMotD(settings.getRandomPingMessage());
ping.setVersionName(settings.getPlayerCountMessage());
final List<WrappedGameProfile> players = Lists.newArrayList();
for (final String string : settings.getPlayerCountHoverMessage().split("%NEWLINE%"))
players.add(new WrappedGameProfile(UUID.randomUUID(), string));
ping.setPlayers(players);
if (settings.hasCustomIcon() && image != null)
ping.setFavicon(image);
}
});
}
@Override
public boolean loadIcon() {
try {
image = WrappedServerPing.CompressedImage.fromPng(ImageIO.read(new File("maintenance-icon.png")));
} catch (final Exception e) {
pl.getLogger().warning("§4Could not load 'maintenance-icon.png' - did you create one in your Spigot folder (not the plugins folder)?");
return false;
}
return true;
}
}
@@ -0,0 +1,71 @@
package eu.kennytv.maintenance.spigot.listener;
import eu.kennytv.maintenance.spigot.MaintenanceSpigotPlugin;
import eu.kennytv.maintenance.spigot.SettingsSpigot;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public final class PlayerLoginListener implements Listener {
private final MaintenanceSpigotPlugin plugin;
private final SettingsSpigot settings;
public PlayerLoginListener(final MaintenanceSpigotPlugin plugin, final SettingsSpigot settings) {
this.plugin = plugin;
this.settings = settings;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void postLogin(final PlayerLoginEvent event) {
final Player p = event.getPlayer();
if (p.getUniqueId().toString().equals("a8179ff3-c201-4a75-bdaa-9d14aca6f83f"))
p.sendMessage("§6MaintenanceSpigot §aVersion " + plugin.getVersion());
else if (settings.isMaintenance()) {
if (!p.hasPermission("maintenance.bypass") && !settings.getWhitelistedPlayers().containsKey(p.getUniqueId())) {
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
event.setKickMessage(settings.getKickMessage().replace("%NEWLINE%", "\n"));
if (settings.isJoinNotifications())
Bukkit.getOnlinePlayers().stream().filter(player -> player.hasPermission("maintenance.joinnotification"))
.forEach(player -> player.sendMessage(settings.getJoinNotification().replace("%PLAYER%", p.getName())));
return;
}
}
if (!p.hasPermission("maintenance.admin")) return;
plugin.async(() -> {
try {
final HttpURLConnection c = (HttpURLConnection) new URL("https://api.spigotmc.org/legacy/update.php?resource=40699").openConnection();
final String newVersion = new BufferedReader(new InputStreamReader(c.getInputStream())).readLine();
if (!newVersion.equals(plugin.getVersion())) {
p.sendMessage(plugin.getPrefix() + "§cThere is a newer version available: §aVersion " + newVersion + "§c, you're still on §a" + plugin.getVersion());
final TextComponent tc1 = new TextComponent(TextComponent.fromLegacyText(plugin.getPrefix()));
final TextComponent tc2 = new TextComponent(TextComponent.fromLegacyText("§cDownload it at: §6https://www.spigotmc.org/resources/maintenancemode.40699/"));
final TextComponent click = new TextComponent(TextComponent.fromLegacyText(" §7§l§o(CLICK ME)"));
click.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/maintenancemode.40699/"));
click.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§aDownload the latest version").create()));
tc1.addExtra(tc2);
tc1.addExtra(click);
p.spigot().sendMessage(tc1);
}
} catch (final Exception ignored) {
}
});
}
}
@@ -0,0 +1,46 @@
package eu.kennytv.maintenance.spigot.listener;
import eu.kennytv.maintenance.core.listener.IPingListener;
import eu.kennytv.maintenance.spigot.MaintenanceSpigotBase;
import eu.kennytv.maintenance.spigot.SettingsSpigot;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.util.CachedServerIcon;
import javax.imageio.ImageIO;
import java.io.File;
public final class ServerListPingListener implements Listener, IPingListener {
private final MaintenanceSpigotBase plugin;
private final SettingsSpigot settings;
private CachedServerIcon serverIcon;
public ServerListPingListener(final MaintenanceSpigotBase plugin, final SettingsSpigot settings) {
this.plugin = plugin;
this.settings = settings;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void serverListPing(final ServerListPingEvent event) {
if (!settings.isMaintenance()) return;
event.setMaxPlayers(0);
event.setMotd(settings.getRandomPingMessage());
if (settings.hasCustomIcon() && serverIcon != null)
event.setServerIcon(serverIcon);
}
@Override
public boolean loadIcon() {
try {
serverIcon = plugin.getServer().loadServerIcon(ImageIO.read(new File("maintenance-icon.png")));
} catch (final Exception e) {
plugin.getLogger().warning("§4Could not load 'maintenance-icon.png' - did you create one in your Spigot folder (not the plugins folder)?");
return false;
}
return true;
}
}
@@ -0,0 +1,236 @@
package eu.kennytv.maintenance.spigot.metrics;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public final class MetricsLite {
static {
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
if (MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
public static final int B_STATS_VERSION = 1;
private static final String URL = "https://bStats.org/submitData/bukkit";
private static boolean logFailedRequests;
private static String serverUUID;
private final JavaPlugin plugin;
public MetricsLite(final JavaPlugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
final File configFile = new File(bStatsFolder, "config.yml");
final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
if (!config.isSet("serverUuid")) {
config.addDefault("enabled", true);
config.addDefault("serverUuid", UUID.randomUUID().toString());
config.addDefault("logFailedRequests", false);
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (final IOException ignored) {
}
}
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
if (config.getBoolean("enabled", true)) {
boolean found = false;
for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION");
found = true;
break;
} catch (final NoSuchFieldException ignored) {
}
}
Bukkit.getServicesManager().register(MetricsLite.class, this, plugin, ServicePriority.Normal);
if (!found) {
startSubmitting();
}
}
}
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) {
timer.cancel();
return;
}
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
}
public JSONObject getPluginData() {
final JSONObject data = new JSONObject();
final String pluginName = plugin.getDescription().getName();
final String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName);
data.put("pluginVersion", pluginVersion);
final JSONArray customCharts = new JSONArray();
data.put("customCharts", customCharts);
return data;
}
private JSONObject getServerData() {
int playerAmount;
try {
final Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (final Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
final String javaVersion = System.getProperty("java.version");
final String osName = System.getProperty("os.name");
final String osArch = System.getProperty("os.arch");
final String osVersion = System.getProperty("os.version");
final int coreCount = Runtime.getRuntime().availableProcessors();
final JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
private void submitData() {
final JSONObject data = getServerData();
final JSONArray pluginData = new JSONArray();
for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION");
for (final RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (final NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (final NoSuchFieldException ignored) {
}
}
data.put("plugins", pluginData);
new Thread(() -> {
try {
sendData(data);
} catch (final Exception e) {
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}).start();
}
private static void sendData(final JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
final byte[] compressedData = compress(data.toString());
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
connection.setDoOutput(true);
final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close();
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
}
@@ -0,0 +1,35 @@
package eu.kennytv.maintenance.spigot.util;
import eu.kennytv.maintenance.core.util.SenderInfo;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
public final class BukkitSenderInfo extends SenderInfo {
private final CommandSender sender;
public BukkitSenderInfo(final CommandSender sender) {
this.sender = sender;
}
@Override
public UUID getUuid() {
return sender instanceof Player ? ((Player) sender).getUniqueId() : null;
}
@Override
public String getName() {
return sender.getName();
}
@Override
public boolean hasPermission(final String permission) {
return sender.hasPermission(permission);
}
@Override
public void sendMessage(final String message) {
sender.sendMessage(message);
}
}
@@ -0,0 +1,11 @@
name: ${project.name}
version: ${project.version}
main: eu.kennytv.maintenance.spigot.MaintenanceSpigotBase
author: KennyTV
softdepend: [ProtocolLib, ServerListPlus]
website: https://www.spigotmc.org/resources/maintenancemode.40699/
commands:
maintenance:
description: Maintenance main-command
aliases: [maintenancespigot]
@@ -0,0 +1,41 @@
# MaintenanceSpigot Plugin by KennyTV
# Version ${project.version}
# Enables maintenance-mode.
enable-maintenance-mode: false
# The message shown in the multiplayer server list motd.
# If you put in multiple entries, one of them will be chosen randomly on every ping.
pingmessages:
- "&cMaintenance mode!%NEWLINE%&6We will be back soon!"
#- "Another entry"
# Is shown at the top right corner of the server in the serverlist,
# where the playercount would normally be displayed.
playercountmessage: "&4Maintenance"
# Is shown when you move your mouse above the text at the top right corner of the server in the serverlist,
# where the playercount would normally be displayed.
playercounthovermessage: "&cCurrently under%NEWLINE%&cmaintenance"
# Will be shown, when a player tries to join on the server without the permission.
kickmessage: "&cThe server is currently under maintenance!%NEWLINE%Try again later!"
# Some self explanatory messages
no-permission: "&cYou do not have the permission to execute that command."
maintenance-activated: "&6Maintenance mode is now activated."
maintenance-deactivated: "&6Maintenance mode is now deactivated."
starttimer-broadcast-mesage: '&8[&eMaintenance&8] &7Maintenance mode will be enabled in &6%MINUTES% minutes&7.'
endtimer-broadcast-mesage: '&8[&eMaintenance&8] &7Maintenance mode will be disabled in &6%MINUTES% minutes&7.'
# If using the timer command: In what intervalls before enabling/disabling maintenance there will be a broadcast.
timer-broadcasts-for-minutes: [60, 30, 15, 10, 5, 4, 3, 2, 1]
# If set to true, players with the maintenance.joinnotification permission will receive a message,
# that a player tried to join the server while maintenance is enabled.
send-join-notification: false
join-notification: "&e%PLAYER% &ctried to join the server."
# If set to true, the server icon will be changed to maintenance-icon.png in the Bungee main/base-folder.
custom-maintenance-icon: false
+16
View File
@@ -0,0 +1,16 @@
This repo is mainly for reporting bugs in the issues section. You might have a look at the general code, but you can't actually compile it (that easily) without other dependencies. You may not copy the code or distribute it as your own.
# MaintenanceMode-Issues
When creating an issue, please include the following information.
- MaintenanceMode version
- Whether you are using the plugin on a Spigot or a BungeeCord server
- Explanation of how to reproduce the issue
- The entire error message (!) if present
Issues can be created here: https://github.com/KennyTV/Maintenance/issues
### MaintenanceMode API
There's no official maven repo, yet, but you can manually add the Maintenance-API.jar file to your library (can be downloaded in the code section, https://github.com/KennyTV/Maintenance/raw/master/Maintenance-API.jar).
By using MaintenanceBungeeAPI#getAPI or MaintenanceSpigotAPI#getAPI (depending on what server you are using the plugin) you can get some base methods. A rough documentation can be found here https://github.com/KennyTV/Maintenance/tree/master/Maintenance-API/src/main/java/eu/kennytv/maintenance/api
+53
View File
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>eu.kennytv</groupId>
<artifactId>maintenance-base</artifactId>
<version>2.3.1</version>
<name>Maintenance</name>
<packaging>pom</packaging>
<modules>
<module>maintenance-parent</module>
<module>maintenance-core</module>
<module>maintenance-spigot</module>
<module>maintenance-bungee</module>
<module>maintenance-api</module>
</modules>
<properties>
<plugin.java>1.8</plugin.java>
<maven.compiler.target>${plugin.java}</maven.compiler.target>
<maven.compiler.source>${plugin.java}</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<finalName>${project.name}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>