├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src
└── main
├── java
└── dev
│ └── _2lstudios
│ └── chatsentinel
│ ├── bukkit
│ ├── ChatSentinel.java
│ ├── commands
│ │ └── ChatSentinelCommand.java
│ ├── listeners
│ │ ├── AsyncPlayerChatListener.java
│ │ ├── PlayerJoinListener.java
│ │ ├── PlayerQuitListener.java
│ │ └── ServerCommandListener.java
│ ├── modules
│ │ └── BukkitModuleManager.java
│ └── utils
│ │ └── ConfigUtil.java
│ ├── bungee
│ ├── ChatSentinel.java
│ ├── commands
│ │ └── ChatSentinelCommand.java
│ ├── listeners
│ │ ├── ChatListener.java
│ │ ├── PlayerDisconnectListener.java
│ │ └── PostLoginListener.java
│ ├── modules
│ │ └── BungeeModuleManager.java
│ └── utils
│ │ └── ConfigUtil.java
│ ├── shared
│ ├── chat
│ │ ├── ChatEventResult.java
│ │ ├── ChatNotificationManager.java
│ │ ├── ChatPlayer.java
│ │ └── ChatPlayerManager.java
│ ├── modules
│ │ ├── BlacklistModerationModule.java
│ │ ├── CapsModerationModule.java
│ │ ├── CooldownModerationModule.java
│ │ ├── FloodModerationModule.java
│ │ ├── GeneralModule.java
│ │ ├── MessagesModule.java
│ │ ├── ModerationModule.java
│ │ ├── ModuleManager.java
│ │ ├── SyntaxModerationModule.java
│ │ └── WhitelistModule.java
│ └── utils
│ │ ├── PatternUtil.java
│ │ ├── PlaceholderUtil.java
│ │ ├── ReflectionUtil.java
│ │ └── VersionUtil.java
│ └── velocity
│ ├── ChatSentinel.java
│ ├── commands
│ └── ChatSentinelCommand.java
│ ├── listeners
│ ├── ChatListener.java
│ ├── PlayerDisconnectListener.java
│ └── PostLoginListener.java
│ ├── modules
│ └── VelocityModuleManager.java
│ └── utils
│ ├── ConfigUtil.java
│ └── Constants.java
└── resources
├── blacklist.yml
├── bungee.yml
├── config.yml
├── messages.yml
├── plugin.yml
└── whitelist.yml
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: ['https://paypal.me/LinsaFTW']
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compilation output directory
2 | /target
3 |
4 | # IDE settings directory
5 | /.settings
6 | /.vscode
7 |
8 | # IDE java settings
9 | /.classpath
10 | /.project
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ChatSentinel
2 | Light plugin to prevent Spam/Swearing on your Spigot/Bungee/Velocity server.
3 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | dev._2lstudios.chatsentinel
5 | ChatSentinel
6 | jar
7 |
8 | ChatSentinel
9 | Advanced chat management plugin
10 | 1.0.2
11 | https://builtbybit.com/resources/23698/
12 |
13 |
14 | chatsentinel
15 | 2LS
16 | UTF-8
17 |
18 |
19 |
20 |
21 | spigot-repo
22 | https://hub.spigotmc.org/nexus/content/repositories/snapshots/
23 |
24 |
25 | bungeecord-repo
26 | https://oss.sonatype.org/content/repositories/snapshots
27 |
28 |
29 | velocity-repo
30 | https://repo.papermc.io/repository/maven-public/
31 |
32 |
33 |
34 |
35 |
36 | org.spigotmc
37 | spigot-api
38 | 1.19-R0.1-SNAPSHOT
39 | provided
40 |
41 |
42 | net.md-5
43 | bungeecord-api
44 | 1.19-R0.1-SNAPSHOT
45 | jar
46 | provided
47 |
48 |
49 | com.velocitypowered
50 | velocity-api
51 | 3.3.0-SNAPSHOT
52 | provided
53 |
54 |
55 |
56 |
57 | ${project.artifactId}
58 | src/main/java
59 | clean install
60 |
61 |
62 | src/main/resources
63 | true
64 |
65 |
66 |
67 |
68 |
69 | maven-compiler-plugin
70 | 3.8.1
71 |
72 | 1.8
73 | 1.8
74 |
75 |
76 |
77 | org.codehaus.mojo
78 | templating-maven-plugin
79 | 3.0.0
80 |
81 |
82 | filter-src
83 |
84 | filter-sources
85 |
86 |
87 | ${basedir}/src/main/java-templates
88 | ${project.build.directory}/generated-sources/java-templates
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/ChatSentinel.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
4 | import org.bukkit.Bukkit;
5 | import org.bukkit.Server;
6 | import org.bukkit.command.ConsoleCommandSender;
7 | import org.bukkit.entity.Player;
8 | import org.bukkit.plugin.PluginManager;
9 | import org.bukkit.plugin.java.JavaPlugin;
10 |
11 | import dev._2lstudios.chatsentinel.bukkit.commands.ChatSentinelCommand;
12 | import dev._2lstudios.chatsentinel.bukkit.listeners.AsyncPlayerChatListener;
13 | import dev._2lstudios.chatsentinel.bukkit.listeners.PlayerJoinListener;
14 | import dev._2lstudios.chatsentinel.bukkit.listeners.PlayerQuitListener;
15 | import dev._2lstudios.chatsentinel.bukkit.listeners.ServerCommandListener;
16 | import dev._2lstudios.chatsentinel.bukkit.modules.BukkitModuleManager;
17 | import dev._2lstudios.chatsentinel.bukkit.utils.ConfigUtil;
18 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
19 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
20 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
21 | import dev._2lstudios.chatsentinel.shared.modules.CooldownModerationModule;
22 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
23 | import dev._2lstudios.chatsentinel.shared.modules.MessagesModule;
24 | import dev._2lstudios.chatsentinel.shared.modules.ModerationModule;
25 | import dev._2lstudios.chatsentinel.shared.modules.SyntaxModerationModule;
26 |
27 | public class ChatSentinel extends JavaPlugin {
28 | // Static instance
29 | private static ChatSentinel instance;
30 |
31 | public static ChatSentinel getInstance() {
32 | return instance;
33 | }
34 |
35 | public static void setInstance(ChatSentinel instance) {
36 | ChatSentinel.instance = instance;
37 | }
38 |
39 | // Module Manager
40 | private BukkitModuleManager moduleManager;
41 |
42 | public BukkitModuleManager getModuleManager() {
43 | return moduleManager;
44 | }
45 |
46 | @Override
47 | public void onEnable() {
48 | setInstance(this);
49 |
50 | ConfigUtil configUtil = new ConfigUtil(this);
51 | Server server = getServer();
52 |
53 | moduleManager = new BukkitModuleManager(configUtil);
54 | GeneralModule generalModule = moduleManager.getGeneralModule();
55 | ChatPlayerManager chatPlayerManager = new ChatPlayerManager();
56 | ChatNotificationManager chatNotificationManager = new ChatNotificationManager();
57 | PluginManager pluginManager = server.getPluginManager();
58 |
59 | pluginManager.registerEvents(new AsyncPlayerChatListener(chatPlayerManager, chatNotificationManager), this);
60 | pluginManager.registerEvents(new PlayerJoinListener(generalModule, chatPlayerManager, chatNotificationManager), this);
61 | pluginManager.registerEvents(new PlayerQuitListener(moduleManager.getGeneralModule(), chatPlayerManager, chatNotificationManager), this);
62 | pluginManager.registerEvents(new ServerCommandListener(chatPlayerManager, chatNotificationManager), this);
63 |
64 | getCommand("chatsentinel").setExecutor(new ChatSentinelCommand(chatPlayerManager, chatNotificationManager, moduleManager, server));
65 |
66 | getServer().getScheduler().runTaskTimerAsynchronously(this, () -> {
67 | if (generalModule.needsNicknameCompile()) {
68 | generalModule.compileNicknamesPattern();
69 | }
70 | }, 20L, 20L);
71 | }
72 |
73 | public void dispatchCommmands(ModerationModule moderationModule, ChatPlayer chatPlayer, String[][] placeholders) {
74 | Server server = getServer();
75 |
76 | server.getScheduler().runTask(this, () -> {
77 | ConsoleCommandSender console = server.getConsoleSender();
78 |
79 | for (String command : moderationModule.getCommands(placeholders)) {
80 | server.dispatchCommand(console, command);
81 | }
82 | });
83 |
84 | chatPlayer.clearWarns();
85 | }
86 |
87 | public void dispatchNotification(ModerationModule moderationModule, String[][] placeholders, ChatNotificationManager chatNotificationManager) {
88 | Server server = getServer();
89 | String notificationMessage = moderationModule.getWarnNotification(placeholders);
90 |
91 | if (notificationMessage != null && !notificationMessage.isEmpty()) {
92 | for (ChatPlayer chatPlayer : chatNotificationManager.getAllPlayers()) {
93 | Player player = Bukkit.getPlayer(chatPlayer.getUniqueId());
94 | if (player != null) {
95 | player.sendMessage(notificationMessage);
96 | }
97 | }
98 |
99 | server.getConsoleSender().sendMessage(notificationMessage);
100 | }
101 | }
102 |
103 | public String[][] getPlaceholders(Player player, ChatPlayer chatPlayer, ModerationModule moderationModule, String message) {
104 | String playerName = player.getName();
105 | int warns = chatPlayer.getWarns(moderationModule);
106 | int maxWarns = moderationModule.getMaxWarns();
107 | float remainingTime = moduleManager.getCooldownModule().getRemainingTime(chatPlayer, message);
108 |
109 | return new String[][] {
110 | { "%player%", "%message%", "%warns%", "%maxwarns%", "%cooldown%" },
111 | { playerName, message, String.valueOf(warns), String.valueOf(maxWarns), String.valueOf(remainingTime) }
112 | };
113 | }
114 |
115 | public void sendWarning(String[][] placeholders, ModerationModule moderationModule, Player player, String lang) {
116 | String warnMessage = moduleManager.getMessagesModule().getWarnMessage(placeholders, lang, moderationModule.getName());
117 |
118 | if (warnMessage != null && !warnMessage.isEmpty()) {
119 | player.sendMessage(warnMessage);
120 | }
121 | }
122 |
123 | public ChatEventResult processEvent(ChatPlayer chatPlayer, Player player, String originalMessage, ChatNotificationManager chatNotificationManager) {
124 | ChatEventResult finalResult = new ChatEventResult(originalMessage, false, false);
125 | MessagesModule messagesModule = moduleManager.getMessagesModule();
126 | String playerName = player.getName();
127 | String lang = chatPlayer.getLocale();
128 | ModerationModule[] moderationModulesToProcess = {
129 | moduleManager.getSyntaxModule(),
130 | moduleManager.getCapsModule(),
131 | moduleManager.getCooldownModule(),
132 | moduleManager.getFloodModule(),
133 | moduleManager.getBlacklistModule()
134 | };
135 |
136 | for (ModerationModule moderationModule : moderationModulesToProcess) {
137 | // Do not check annormal commands (unless syntax or cooldown)
138 | boolean isCommmand = originalMessage.startsWith("/");
139 | boolean isNormalCommmand = ChatSentinel.getInstance().getModuleManager().getGeneralModule()
140 | .isCommand(originalMessage);
141 | if (!(moderationModule instanceof SyntaxModerationModule) &&
142 | !(moderationModule instanceof CooldownModerationModule) &&
143 | isCommmand &&
144 | !isNormalCommmand) {
145 | continue;
146 | }
147 |
148 | // Get the modified message
149 | String message = finalResult.getMessage();
150 |
151 | // Check if player has bypass
152 | if (player.hasPermission(moderationModule.getBypassPermission())) {
153 | continue;
154 | }
155 |
156 | // Process
157 | ChatEventResult result = moderationModule.processEvent(chatPlayer, messagesModule, playerName, message, lang);
158 |
159 | // Skip result
160 | if (result != null) {
161 | // Add warning
162 | chatPlayer.addWarn(moderationModule);
163 |
164 | // Get placeholders
165 | String[][] placeholders = ChatSentinel.getInstance().getPlaceholders(player, chatPlayer, moderationModule,
166 | message);
167 |
168 | // Send warning
169 | ChatSentinel.getInstance().sendWarning(placeholders, moderationModule, player, lang);
170 |
171 | // Send punishment comamnds
172 | if (moderationModule.hasExceededWarns(chatPlayer)) {
173 | ChatSentinel.getInstance().dispatchCommmands(moderationModule, chatPlayer, placeholders);
174 | }
175 |
176 | // Send admin notification
177 | ChatSentinel.getInstance().dispatchNotification(moderationModule, placeholders, chatNotificationManager);
178 |
179 | // Update message
180 | finalResult.setMessage(result.getMessage());
181 |
182 | // Update hide
183 | if (result.isHide())
184 | finalResult.setHide(true);
185 |
186 | // Update cancelled
187 | if (result.isCancelled()) {
188 | finalResult.setCancelled(true);
189 | break;
190 | }
191 | }
192 | }
193 |
194 | return finalResult;
195 | }
196 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/commands/ChatSentinelCommand.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.commands;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
4 | import org.bukkit.Server;
5 | import org.bukkit.command.Command;
6 | import org.bukkit.command.CommandExecutor;
7 | import org.bukkit.command.CommandSender;
8 | import org.bukkit.entity.Player;
9 |
10 | import dev._2lstudios.chatsentinel.bukkit.modules.BukkitModuleManager;
11 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
12 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
13 | import dev._2lstudios.chatsentinel.shared.modules.MessagesModule;
14 |
15 | public class ChatSentinelCommand implements CommandExecutor {
16 | private ChatPlayerManager chatPlayerManager;
17 | private ChatNotificationManager chatNotificationManager;
18 | private BukkitModuleManager moduleManager;
19 | private Server server;
20 |
21 | public ChatSentinelCommand(ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager, BukkitModuleManager moduleManager, Server server) {
22 | this.chatPlayerManager = chatPlayerManager;
23 | this.chatNotificationManager = chatNotificationManager;
24 | this.moduleManager = moduleManager;
25 | this.server = server;
26 | }
27 |
28 | @Override
29 | public boolean onCommand(CommandSender sender, Command command, String label,
30 | String[] args) {
31 | MessagesModule messagesModule = moduleManager.getMessagesModule();
32 | String lang;
33 | ChatPlayer chatPlayer = null;
34 |
35 | if (sender instanceof Player) {
36 | chatPlayer = chatPlayerManager.getPlayer(((Player) sender));
37 | lang = chatPlayer.getLocale();
38 | } else {
39 | lang = "en";
40 | }
41 |
42 | if (sender.hasPermission("chatsentinel.admin")) {
43 | if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
44 | sender.sendMessage(messagesModule.getHelp(lang));
45 | } else if (args[0].equalsIgnoreCase("reload")) {
46 | moduleManager.reloadData();
47 |
48 | sender.sendMessage(messagesModule.getReload(lang));
49 | } else if (args[0].equalsIgnoreCase("notify")) {
50 | if (sender instanceof Player) {
51 | boolean notify = chatNotificationManager.containsPlayer(chatPlayer);
52 |
53 | if (notify) {
54 | chatNotificationManager.removePlayer(chatPlayer);
55 | sender.sendMessage(messagesModule.getNotifyDisabled(lang));
56 | } else {
57 | chatNotificationManager.addPlayer(chatPlayer);
58 | sender.sendMessage(messagesModule.getNotifyEnabled(lang));
59 | }
60 | } else {
61 | sender.sendMessage(messagesModule.getUnknownCommand(lang));
62 | }
63 | } else if (args[0].equalsIgnoreCase("clear")) {
64 | StringBuilder emptyLines = new StringBuilder();
65 | String newLine = "\n ";
66 | String[][] placeholders = { { "%player%" }, { sender.getName() } };
67 |
68 | for (int i = 0; i < 128; i++) {
69 | emptyLines.append(newLine);
70 | }
71 |
72 | emptyLines.append(messagesModule.getCleared(placeholders, lang));
73 |
74 | for (Player player : server.getOnlinePlayers()) {
75 | player.sendMessage(emptyLines.toString());
76 | }
77 | } else {
78 | sender.sendMessage(messagesModule.getUnknownCommand(lang));
79 | }
80 | } else {
81 | sender.sendMessage(messagesModule.getNoPermission(lang));
82 | }
83 |
84 | return true;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/listeners/AsyncPlayerChatListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.listeners;
2 |
3 | import java.util.Collection;
4 |
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
6 | import org.bukkit.entity.Player;
7 | import org.bukkit.event.EventHandler;
8 | import org.bukkit.event.EventPriority;
9 | import org.bukkit.event.Listener;
10 | import org.bukkit.event.player.AsyncPlayerChatEvent;
11 |
12 | import dev._2lstudios.chatsentinel.bukkit.ChatSentinel;
13 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
14 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
15 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
16 |
17 | public class AsyncPlayerChatListener implements Listener {
18 | private ChatPlayerManager chatPlayerManager;
19 | private ChatNotificationManager chatNotificationManager;
20 |
21 | public AsyncPlayerChatListener(ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
22 | this.chatPlayerManager = chatPlayerManager;
23 | this.chatNotificationManager = chatNotificationManager;
24 | }
25 |
26 | @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
27 | public void onAsyncPlayerChat(AsyncPlayerChatEvent event) {
28 | // Get player
29 | Player player = event.getPlayer();
30 |
31 | // Check if player has bypass
32 | if (player.hasPermission("chatsentinel.bypass")) {
33 | return;
34 | }
35 |
36 | // Get event variables
37 | String message = event.getMessage();
38 | Collection recipents = event.getRecipients();
39 |
40 | // Do not check uncheckable commands
41 | if (message.startsWith("/") && !ChatSentinel.getInstance().getModuleManager().getGeneralModule().isCommand(message)) {
42 | return;
43 | }
44 |
45 | // Get chat player
46 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
47 |
48 | // Process the event
49 | ChatEventResult finalResult = ChatSentinel.getInstance().processEvent(chatPlayer, player, message, chatNotificationManager);
50 |
51 | // Apply modifiers to event
52 | if (finalResult.isHide()) {
53 | recipents.removeIf(player1 -> player1 != player);
54 | } else if (finalResult.isCancelled()) {
55 | event.setCancelled(true);
56 | } else {
57 | event.setMessage(finalResult.getMessage());
58 | }
59 |
60 | // Set last message
61 | if (!event.isCancelled()) {
62 | chatPlayer.addLastMessage(finalResult.getMessage(), System.currentTimeMillis());
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/listeners/PlayerJoinListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.listeners;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
4 | import org.bukkit.entity.Player;
5 | import org.bukkit.event.EventHandler;
6 | import org.bukkit.event.Listener;
7 | import org.bukkit.event.player.PlayerJoinEvent;
8 |
9 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
10 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
11 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
12 |
13 | public class PlayerJoinListener implements Listener {
14 | private GeneralModule generalModule;
15 | private ChatPlayerManager chatPlayerManager;
16 | private ChatNotificationManager chatNotificationManager;
17 |
18 | public PlayerJoinListener(GeneralModule generalModule, ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
19 | this.generalModule = generalModule;
20 | this.chatPlayerManager = chatPlayerManager;
21 | this.chatNotificationManager = chatNotificationManager;
22 | }
23 |
24 | @EventHandler(ignoreCancelled = true)
25 | public void onPlayerJoin(PlayerJoinEvent event) {
26 | Player player = event.getPlayer();
27 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
28 |
29 | if (chatPlayer != null) {
30 | // Reset the locale of the player if already exists
31 | chatPlayer.setLocale(null);
32 |
33 | // Set notifications
34 | if (player.hasPermission("chatsentinel.notify")) {
35 | chatNotificationManager.addPlayer(chatPlayer);
36 | }
37 |
38 | // Add the nickname
39 | generalModule.addNickname(player.getName());
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/listeners/PlayerQuitListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.listeners;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
6 | import org.bukkit.entity.Player;
7 | import org.bukkit.event.EventHandler;
8 | import org.bukkit.event.Listener;
9 | import org.bukkit.event.player.PlayerQuitEvent;
10 |
11 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
12 |
13 | public class PlayerQuitListener implements Listener {
14 | private GeneralModule generalModule;
15 | private ChatPlayerManager chatPlayerManager;
16 | private ChatNotificationManager chatNotificationManager;
17 |
18 | public PlayerQuitListener(GeneralModule generalModule, ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
19 | this.generalModule = generalModule;
20 | this.chatPlayerManager = chatPlayerManager;
21 | this.chatNotificationManager = chatNotificationManager;
22 | }
23 |
24 | @EventHandler
25 | public void onPlayerQuit(PlayerQuitEvent event) {
26 | generalModule.removeNickname(event.getPlayer().getName());
27 | Player player = event.getPlayer();
28 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
29 |
30 | if (chatPlayer != null && chatNotificationManager.containsPlayer(chatPlayer)) {
31 | chatNotificationManager.removePlayer(chatPlayer);
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/listeners/ServerCommandListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.listeners;
2 |
3 | import java.util.Collection;
4 |
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
6 | import org.bukkit.entity.Player;
7 | import org.bukkit.event.EventHandler;
8 | import org.bukkit.event.EventPriority;
9 | import org.bukkit.event.Listener;
10 | import org.bukkit.event.player.PlayerCommandPreprocessEvent;
11 |
12 | import dev._2lstudios.chatsentinel.bukkit.ChatSentinel;
13 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
14 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
15 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
16 |
17 | public class ServerCommandListener implements Listener {
18 | private ChatPlayerManager chatPlayerManager;
19 | private ChatNotificationManager chatNotificationManager;
20 |
21 | public ServerCommandListener(ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
22 | this.chatPlayerManager = chatPlayerManager;
23 | this.chatNotificationManager = chatNotificationManager;
24 | }
25 |
26 | @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
27 | public void onServerCommand(PlayerCommandPreprocessEvent event) {
28 | // Get player
29 | Player player = event.getPlayer();
30 |
31 | // Check if player has bypass
32 | if (player.hasPermission("chatsentinel.bypass")) {
33 | return;
34 | }
35 |
36 | // Get event variables
37 | String message = event.getMessage();
38 | Collection recipents = event.getRecipients();
39 |
40 | // Get chat player
41 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
42 |
43 | // Process the event
44 | ChatEventResult finalResult = ChatSentinel.getInstance().processEvent(chatPlayer, player, message, chatNotificationManager);
45 |
46 | // Apply modifiers to event
47 | if (finalResult.isHide()) {
48 | recipents.removeIf(player1 -> player1 != player);
49 | } else if (finalResult.isCancelled()) {
50 | event.setCancelled(true);
51 | } else {
52 | event.setMessage(finalResult.getMessage());
53 | }
54 |
55 | // Set last message
56 | if (!event.isCancelled()) {
57 | chatPlayer.addLastMessage(finalResult.getMessage(), System.currentTimeMillis());
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/modules/BukkitModuleManager.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.modules;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import org.bukkit.configuration.Configuration;
7 | import org.bukkit.configuration.ConfigurationSection;
8 |
9 | import dev._2lstudios.chatsentinel.bukkit.utils.ConfigUtil;
10 | import dev._2lstudios.chatsentinel.shared.modules.ModuleManager;
11 |
12 | public class BukkitModuleManager extends ModuleManager {
13 | private ConfigUtil configUtil;
14 |
15 | public BukkitModuleManager(ConfigUtil configUtil) {
16 | super();
17 | this.configUtil = configUtil;
18 | reloadData();
19 | }
20 |
21 | @Override
22 | public void reloadData() {
23 | configUtil.create("%datafolder%/config.yml");
24 | configUtil.create("%datafolder%/messages.yml");
25 | configUtil.create("%datafolder%/whitelist.yml");
26 | configUtil.create("%datafolder%/blacklist.yml");
27 |
28 | Configuration blacklistYml = configUtil.get("%datafolder%/blacklist.yml");
29 | Configuration configYml = configUtil.get("%datafolder%/config.yml");
30 | Configuration messagesYml = configUtil.get("%datafolder%/messages.yml");
31 | Configuration whitelistYml = configUtil.get("%datafolder%/whitelist.yml");
32 | Map> locales = new HashMap<>();
33 |
34 | for (String lang : messagesYml.getConfigurationSection("langs").getKeys(false)) {
35 | ConfigurationSection langSection = messagesYml.getConfigurationSection("langs." + lang);
36 | Map messages = new HashMap<>();
37 |
38 | for (String key : langSection.getKeys(false)) {
39 | String value = langSection.getString(key);
40 |
41 | messages.put(key, value);
42 | }
43 |
44 | locales.put(lang, messages);
45 | }
46 |
47 | getCapsModule().loadData(configYml.getBoolean("caps.enabled"), configYml.getBoolean("caps.replace"),
48 | configYml.getInt("caps.max"), configYml.getInt("caps.warn.max"),
49 | configYml.getString("caps.warn.notification"),
50 | configYml.getStringList("caps.punishments").toArray(new String[0]));
51 | getCooldownModule().loadData(configYml.getBoolean("cooldown.enabled"),
52 | configYml.getInt("cooldown.time.repeat-global"), configYml.getInt("cooldown.time.repeat"),
53 | configYml.getInt("cooldown.time.normal"), configYml.getInt("cooldown.time.command"));
54 | getFloodModule().loadData(configYml.getBoolean("flood.enabled"), configYml.getBoolean("flood.replace"),
55 | configYml.getInt("flood.warn.max"), configYml.getString("flood.pattern"),
56 | configYml.getString("flood.warn.notification"),
57 | configYml.getStringList("flood.punishments").toArray(new String[0]));
58 | getMessagesModule().loadData(messagesYml.getString("default"), locales);
59 | getGeneralModule().loadData(configYml.getBoolean("general.sanitize", true),
60 | configYml.getBoolean("general.sanitize-names", true),
61 | configYml.getBoolean("general.filter-other", false),
62 | configYml.getStringList("general.commands"));
63 | getWhitelistModule().loadData(configYml.getBoolean("whitelist.enabled"),
64 | whitelistYml.getStringList("expressions").toArray(new String[0]));
65 | boolean censorshipEnabled = configYml.getBoolean("blacklist.censorship.enabled", false);
66 | String censorshipReplacement = configYml.getString("blacklist.censorship.replacement", "***");
67 | getBlacklistModule().loadData(configYml.getBoolean("blacklist.enabled"),
68 | configYml.getBoolean("blacklist.fake_message"), censorshipEnabled, censorshipReplacement,
69 | configYml.getInt("blacklist.warn.max"), configYml.getString("blacklist.warn.notification"),
70 | configYml.getStringList("blacklist.punishments").toArray(new String[0]),
71 | blacklistYml.getStringList("expressions").toArray(new String[0]),
72 | configYml.getBoolean("blacklist.block_raw_message"));
73 | getSyntaxModule().loadData(configYml.getBoolean("syntax.enabled"), configYml.getInt("syntax.warn.max"),
74 | configYml.getString("syntax.warn.notification"),
75 | configYml.getStringList("syntax.whitelist").toArray(new String[0]),
76 | configYml.getStringList("syntax.punishments").toArray(new String[0]));
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bukkit/utils/ConfigUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bukkit.utils;
2 |
3 | import org.bukkit.configuration.file.YamlConfiguration;
4 | import org.bukkit.plugin.Plugin;
5 |
6 | import java.io.File;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.nio.file.Files;
10 | import java.util.logging.Level;
11 |
12 | public class ConfigUtil {
13 | private Plugin plugin;
14 |
15 | public ConfigUtil(Plugin plugin) {
16 | this.plugin = plugin;
17 | }
18 |
19 | public YamlConfiguration get(String filePath) {
20 | File dataFolder = plugin.getDataFolder();
21 | File file = new File(filePath.replace("%datafolder%", dataFolder.toPath().toString()));
22 |
23 | if (file.exists())
24 | return YamlConfiguration.loadConfiguration(file);
25 | else
26 | return new YamlConfiguration();
27 | }
28 |
29 | public void create(String file) {
30 | try {
31 | File dataFolder = plugin.getDataFolder();
32 |
33 | file = file.replace("%datafolder%", dataFolder.toPath().toString());
34 |
35 | File configFile = new File(file);
36 |
37 | if (!configFile.exists()) {
38 | String[] files = file.split("/");
39 | InputStream inputStream = plugin.getClass().getClassLoader()
40 | .getResourceAsStream(files[files.length - 1]);
41 | File parentFile = configFile.getParentFile();
42 |
43 | if (parentFile != null)
44 | parentFile.mkdirs();
45 |
46 | if (inputStream != null) {
47 | Files.copy(inputStream, configFile.toPath());
48 | plugin.getLogger().log(Level.INFO, ("[%pluginname%] File " + configFile + " has been created!")
49 | .replace("%pluginname%", plugin.getDescription().getName()));
50 | } else
51 | configFile.createNewFile();
52 | }
53 | } catch (IOException e) {
54 | plugin.getLogger().log(Level.INFO, ("[%pluginname%] Unable to create configuration file!")
55 | .replace("%pluginname%", plugin.getDescription().getName()));
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/ChatSentinel.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import dev._2lstudios.chatsentinel.bungee.commands.ChatSentinelCommand;
6 | import dev._2lstudios.chatsentinel.bungee.listeners.ChatListener;
7 | import dev._2lstudios.chatsentinel.bungee.listeners.PlayerDisconnectListener;
8 | import dev._2lstudios.chatsentinel.bungee.listeners.PostLoginListener;
9 | import dev._2lstudios.chatsentinel.bungee.modules.BungeeModuleManager;
10 | import dev._2lstudios.chatsentinel.bungee.utils.ConfigUtil;
11 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
12 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
13 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
14 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
15 | import dev._2lstudios.chatsentinel.shared.modules.CooldownModerationModule;
16 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
17 | import dev._2lstudios.chatsentinel.shared.modules.MessagesModule;
18 | import dev._2lstudios.chatsentinel.shared.modules.ModerationModule;
19 | import dev._2lstudios.chatsentinel.shared.modules.SyntaxModerationModule;
20 | import net.md_5.bungee.api.CommandSender;
21 | import net.md_5.bungee.api.ProxyServer;
22 | import net.md_5.bungee.api.connection.ProxiedPlayer;
23 | import net.md_5.bungee.api.connection.Server;
24 | import net.md_5.bungee.api.plugin.Plugin;
25 | import net.md_5.bungee.api.plugin.PluginManager;
26 |
27 | public class ChatSentinel extends Plugin {
28 | // Static instance
29 | private static ChatSentinel instance;
30 |
31 | public static ChatSentinel getInstance() {
32 | return instance;
33 | }
34 |
35 | public static void setInstance(ChatSentinel instance) {
36 | ChatSentinel.instance = instance;
37 | }
38 |
39 | // Module Manager
40 | private BungeeModuleManager moduleManager;
41 |
42 | public BungeeModuleManager getModuleManager() {
43 | return moduleManager;
44 | }
45 |
46 | @Override
47 | public void onEnable() {
48 | setInstance(this);
49 |
50 | ConfigUtil configUtil = new ConfigUtil(this);
51 |
52 | configUtil.create("%datafolder%/config.yml");
53 | configUtil.create("%datafolder%/messages.yml");
54 | configUtil.create("%datafolder%/whitelist.yml");
55 | configUtil.create("%datafolder%/blacklist.yml");
56 |
57 | ProxyServer server = getProxy();
58 | moduleManager = new BungeeModuleManager(configUtil);
59 | GeneralModule generalModule = moduleManager.getGeneralModule();
60 | ChatPlayerManager chatPlayerManager = new ChatPlayerManager();
61 | ChatNotificationManager chatNotificationManager = new ChatNotificationManager();
62 | PluginManager pluginManager = server.getPluginManager();
63 |
64 | pluginManager.registerListener(this, new ChatListener(chatPlayerManager, chatNotificationManager));
65 | pluginManager.registerListener(this, new PlayerDisconnectListener(generalModule, chatPlayerManager, chatNotificationManager));
66 | pluginManager.registerListener(this, new PostLoginListener(generalModule, chatPlayerManager, chatNotificationManager));
67 |
68 | pluginManager.registerCommand(this, new ChatSentinelCommand(chatPlayerManager, chatNotificationManager, moduleManager, server));
69 |
70 | getProxy().getScheduler().schedule(this, () -> {
71 | if (generalModule.needsNicknameCompile()) {
72 | generalModule.compileNicknamesPattern();
73 | }
74 | }, 1000L, 1000L, TimeUnit.MILLISECONDS);
75 | }
76 |
77 | public void dispatchCommmands(ModerationModule moderationModule, ChatPlayer chatPlayer, String[][] placeholders) {
78 | ProxyServer server = getProxy();
79 |
80 | server.getScheduler().runAsync(this, () -> {
81 | CommandSender console = server.getConsole();
82 |
83 | for (String command : moderationModule.getCommands(placeholders)) {
84 | server.getPluginManager().dispatchCommand(console, command);
85 | }
86 | });
87 |
88 | chatPlayer.clearWarns();
89 | }
90 |
91 | public void dispatchNotification(ModerationModule moderationModule, String[][] placeholders, ChatNotificationManager chatNotificationManager) {
92 | ProxyServer server = getProxy();
93 | String notificationMessage = moderationModule.getWarnNotification(placeholders);
94 |
95 | if (notificationMessage != null && !notificationMessage.isEmpty()) {
96 | for (ChatPlayer chatPlayer : chatNotificationManager.getAllPlayers()) {
97 | ProxiedPlayer player = server.getPlayer(chatPlayer.getUniqueId());
98 | if (player != null) {
99 | player.sendMessage(notificationMessage);
100 | }
101 | }
102 |
103 | server.getConsole().sendMessage(notificationMessage);
104 | }
105 | }
106 |
107 | public String[][] getPlaceholders(ProxiedPlayer player, ChatPlayer chatPlayer, ModerationModule moderationModule, String message) {
108 | String playerName = player.getName();
109 | int warns = chatPlayer.getWarns(moderationModule);
110 | int maxWarns = moderationModule.getMaxWarns();
111 | float remainingTime = moduleManager.getCooldownModule().getRemainingTime(chatPlayer, message);
112 | Server server = player.getServer();
113 | String serverName = server != null ? server.getInfo().getName() : "";
114 |
115 | return new String[][] {
116 | { "%player%", "%message%", "%warns%", "%maxwarns%", "%cooldown%", "%server_name%" },
117 | { playerName, message, String.valueOf(warns), String.valueOf(maxWarns), String.valueOf(remainingTime), serverName }
118 | };
119 | }
120 |
121 | public void sendWarning(String[][] placeholders, ModerationModule moderationModule, ProxiedPlayer player, String lang) {
122 | String warnMessage = moduleManager.getMessagesModule().getWarnMessage(placeholders, lang, moderationModule.getName());
123 |
124 | if (warnMessage != null && !warnMessage.isEmpty()) {
125 | player.sendMessage(warnMessage);
126 | }
127 | }
128 |
129 | public ChatEventResult processEvent(ChatPlayer chatPlayer, ProxiedPlayer player, String originalMessage, ChatNotificationManager chatNotificationManager) {
130 | ChatEventResult finalResult = new ChatEventResult(originalMessage, false, false);
131 | MessagesModule messagesModule = moduleManager.getMessagesModule();
132 | String playerName = player.getName();
133 | String lang = chatPlayer.getLocale();
134 | ModerationModule[] moderationModulesToProcess = {
135 | moduleManager.getSyntaxModule(),
136 | moduleManager.getCapsModule(),
137 | moduleManager.getCooldownModule(),
138 | moduleManager.getFloodModule(),
139 | moduleManager.getBlacklistModule()
140 | };
141 |
142 | for (ModerationModule moderationModule : moderationModulesToProcess) {
143 | // Do not check annormal commands (unless syntax or cooldown)
144 | boolean isCommmand = originalMessage.startsWith("/");
145 | boolean isNormalCommmand = ChatSentinel.getInstance().getModuleManager().getGeneralModule()
146 | .isCommand(originalMessage);
147 | if (!(moderationModule instanceof SyntaxModerationModule) &&
148 | !(moderationModule instanceof CooldownModerationModule) &&
149 | isCommmand &&
150 | !isNormalCommmand) {
151 | continue;
152 | }
153 |
154 | // Get the modified message
155 | String message = finalResult.getMessage();
156 |
157 | // Check if player has bypass
158 | if (player.hasPermission(moderationModule.getBypassPermission())) {
159 | continue;
160 | }
161 |
162 | // Process
163 | ChatEventResult result = moderationModule.processEvent(chatPlayer, messagesModule, playerName, message, lang);
164 |
165 | // Skip result
166 | if (result != null) {
167 | // Add warning
168 | chatPlayer.addWarn(moderationModule);
169 |
170 | // Get placeholders
171 | String[][] placeholders = ChatSentinel.getInstance().getPlaceholders(player, chatPlayer, moderationModule,
172 | message);
173 |
174 | // Send warning
175 | ChatSentinel.getInstance().sendWarning(placeholders, moderationModule, player, lang);
176 |
177 | // Send punishment comamnds
178 | if (moderationModule.hasExceededWarns(chatPlayer)) {
179 | ChatSentinel.getInstance().dispatchCommmands(moderationModule, chatPlayer, placeholders);
180 | }
181 |
182 | // Send admin notification
183 | ChatSentinel.getInstance().dispatchNotification(moderationModule, placeholders, chatNotificationManager);
184 |
185 | // Update message
186 | finalResult.setMessage(result.getMessage());
187 |
188 | // Update hide
189 | if (result.isHide())
190 | finalResult.setHide(true);
191 |
192 | // Update cancelled
193 | if (result.isCancelled()) {
194 | finalResult.setCancelled(true);
195 | break;
196 | }
197 | }
198 | }
199 |
200 | return finalResult;
201 | }
202 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/commands/ChatSentinelCommand.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee.commands;
2 |
3 | import dev._2lstudios.chatsentinel.bungee.modules.BungeeModuleManager;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
6 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
7 | import dev._2lstudios.chatsentinel.shared.modules.MessagesModule;
8 | import net.md_5.bungee.api.CommandSender;
9 | import net.md_5.bungee.api.ProxyServer;
10 | import net.md_5.bungee.api.chat.TextComponent;
11 | import net.md_5.bungee.api.connection.ProxiedPlayer;
12 | import net.md_5.bungee.api.plugin.Command;
13 |
14 | public class ChatSentinelCommand extends Command {
15 | private ChatPlayerManager chatPlayerManager;
16 | private ChatNotificationManager chatNotificationManager;
17 | private BungeeModuleManager moduleManager;
18 | private ProxyServer server;
19 |
20 | public ChatSentinelCommand(ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager, BungeeModuleManager moduleManager, ProxyServer server) {
21 | super("chatsentinel");
22 | this.chatPlayerManager = chatPlayerManager;
23 | this.chatNotificationManager = chatNotificationManager;
24 | this.moduleManager = moduleManager;
25 | this.server = server;
26 | }
27 |
28 | private void sendMessage(CommandSender sender, String message) {
29 | sender.sendMessage(TextComponent.fromLegacyText(message));
30 | }
31 |
32 | @Override
33 | public void execute(CommandSender sender, String[] args) {
34 | MessagesModule messagesModule = moduleManager.getMessagesModule();
35 | String lang;
36 | ChatPlayer chatPlayer = null;
37 |
38 | if (sender instanceof ProxiedPlayer) {
39 | chatPlayer = chatPlayerManager.getPlayer(((ProxiedPlayer) sender));
40 | lang = chatPlayer.getLocale();
41 | } else {
42 | lang = "en";
43 | }
44 |
45 | if (sender.hasPermission("chatsentinel.admin")) {
46 | if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
47 | sendMessage(sender, messagesModule.getHelp(lang));
48 | } else if (args[0].equalsIgnoreCase("reload")) {
49 | moduleManager.reloadData();
50 |
51 | sendMessage(sender, messagesModule.getReload(lang));
52 | } else if (args[0].equalsIgnoreCase("clear")) {
53 | StringBuilder emptyLines = new StringBuilder();
54 | String newLine = "\n ";
55 | String[][] placeholders = { { "%player%" }, { sender.getName() } };
56 |
57 | for (int i = 0; i < 128; i++) {
58 | emptyLines.append(newLine);
59 | }
60 |
61 | emptyLines.append(messagesModule.getCleared(placeholders, lang));
62 |
63 | for (ProxiedPlayer player : server.getPlayers()) {
64 | sendMessage(player, emptyLines.toString());
65 | }
66 | } else if (args[0].equalsIgnoreCase("notify")) {
67 | if (sender instanceof ProxiedPlayer) {
68 | boolean notify = chatNotificationManager.containsPlayer(chatPlayer);
69 |
70 | if (notify) {
71 | chatNotificationManager.removePlayer(chatPlayer);
72 | sender.sendMessage(messagesModule.getNotifyDisabled(lang));
73 | } else {
74 | chatNotificationManager.addPlayer(chatPlayer);
75 | sender.sendMessage(messagesModule.getNotifyEnabled(lang));
76 | }
77 | } else {
78 | sender.sendMessage(messagesModule.getUnknownCommand(lang));
79 | }
80 | } else {
81 | sendMessage(sender, messagesModule.getUnknownCommand(lang));
82 | }
83 | } else {
84 | sendMessage(sender, messagesModule.getNoPermission(lang));
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/listeners/ChatListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee.listeners;
2 |
3 | import dev._2lstudios.chatsentinel.bungee.ChatSentinel;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
6 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
7 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
8 | import net.md_5.bungee.api.connection.Connection;
9 | import net.md_5.bungee.api.connection.ProxiedPlayer;
10 | import net.md_5.bungee.api.event.ChatEvent;
11 | import net.md_5.bungee.api.plugin.Listener;
12 | import net.md_5.bungee.event.EventHandler;
13 | import net.md_5.bungee.event.EventPriority;
14 |
15 | public class ChatListener implements Listener {
16 | private ChatPlayerManager chatPlayerManager;
17 | private ChatNotificationManager chatNotificationManager;
18 |
19 | public ChatListener(ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
20 | this.chatPlayerManager = chatPlayerManager;
21 | this.chatNotificationManager = chatNotificationManager;
22 | }
23 |
24 | @EventHandler(priority = EventPriority.LOW)
25 | public void onChatEvent(ChatEvent event) {
26 | if (event.isCancelled()) {
27 | return;
28 | }
29 |
30 | // Sender
31 | Connection sender = event.getSender();
32 |
33 | if (!(sender instanceof ProxiedPlayer)) {
34 | return;
35 | }
36 |
37 | // Get player
38 | ProxiedPlayer player = (ProxiedPlayer) sender;
39 |
40 | // Check if player has bypass
41 | if (player.hasPermission("chatsentinel.bypass")) {
42 | return;
43 | }
44 |
45 | // Get event variables
46 | String message = event.getMessage();
47 |
48 | // Get chat player
49 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
50 |
51 | // Process the event
52 | ChatEventResult finalResult = ChatSentinel.getInstance().processEvent(chatPlayer, player, message, chatNotificationManager);
53 |
54 | // Apply modifiers to event
55 | if (finalResult.isCancelled()) {
56 | event.setCancelled(true);
57 | } else {
58 | event.setMessage(finalResult.getMessage());
59 | }
60 |
61 | // Set last message
62 | if (!event.isCancelled()) {
63 | chatPlayer.addLastMessage(finalResult.getMessage(), System.currentTimeMillis());
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/listeners/PlayerDisconnectListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee.listeners;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
6 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
7 | import net.md_5.bungee.api.connection.ProxiedPlayer;
8 | import net.md_5.bungee.api.event.PlayerDisconnectEvent;
9 | import net.md_5.bungee.api.plugin.Listener;
10 | import net.md_5.bungee.event.EventHandler;
11 |
12 | public class PlayerDisconnectListener implements Listener {
13 | private GeneralModule generalModule;
14 | private ChatPlayerManager chatPlayerManager;
15 | private ChatNotificationManager chatNotificationManager;
16 |
17 | public PlayerDisconnectListener(GeneralModule generalModule, ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
18 | this.generalModule = generalModule;
19 | this.chatPlayerManager = chatPlayerManager;
20 | this.chatNotificationManager = chatNotificationManager;
21 | }
22 |
23 | @EventHandler
24 | public void onPlayerDisconnect(PlayerDisconnectEvent event) {
25 | generalModule.removeNickname(event.getPlayer().getName());
26 |
27 | ProxiedPlayer player = event.getPlayer();
28 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
29 | if (chatPlayer != null && chatNotificationManager.containsPlayer(chatPlayer)) {
30 | chatNotificationManager.removePlayer(chatPlayer);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/listeners/PostLoginListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee.listeners;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
6 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
7 | import net.md_5.bungee.api.connection.ProxiedPlayer;
8 | import net.md_5.bungee.api.event.PostLoginEvent;
9 | import net.md_5.bungee.api.plugin.Listener;
10 | import net.md_5.bungee.event.EventHandler;
11 |
12 | public class PostLoginListener implements Listener {
13 | private GeneralModule generalModule;
14 | private ChatPlayerManager chatPlayerManager;
15 | private ChatNotificationManager chatNotificationManager;
16 |
17 | public PostLoginListener(GeneralModule generalModule, ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
18 | this.generalModule = generalModule;
19 | this.chatPlayerManager = chatPlayerManager;
20 | this.chatNotificationManager = chatNotificationManager;
21 | }
22 |
23 | @EventHandler
24 | public void onPostLogin(PostLoginEvent event) {
25 | ProxiedPlayer player = event.getPlayer();
26 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
27 |
28 | if (chatPlayer != null) {
29 | // Reset the locale of the player if already exists
30 | chatPlayer.setLocale(null);
31 |
32 | // Set notifications
33 | if (player.hasPermission("chatsentinel.notify")) {
34 | chatNotificationManager.addPlayer(chatPlayer);
35 | }
36 |
37 | // Add the nickname
38 | generalModule.addNickname(player.getName());
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/modules/BungeeModuleManager.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee.modules;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import dev._2lstudios.chatsentinel.bungee.utils.ConfigUtil;
7 | import dev._2lstudios.chatsentinel.shared.modules.ModuleManager;
8 | import net.md_5.bungee.config.Configuration;
9 |
10 | public class BungeeModuleManager extends ModuleManager {
11 | private ConfigUtil configUtil;
12 |
13 | public BungeeModuleManager(ConfigUtil configUtil) {
14 | this.configUtil = configUtil;
15 | reloadData();
16 | }
17 |
18 | @Override
19 | public void reloadData() {
20 | configUtil.create("%datafolder%/config.yml");
21 | configUtil.create("%datafolder%/messages.yml");
22 | configUtil.create("%datafolder%/blacklist.yml");
23 | configUtil.create("%datafolder%/whitelist.yml");
24 |
25 | Configuration blacklistYml = configUtil.get("%datafolder%/blacklist.yml");
26 | Configuration configYml = configUtil.get("%datafolder%/config.yml");
27 | Configuration messagesYml = configUtil.get("%datafolder%/messages.yml");
28 | Configuration whitelistYml = configUtil.get("%datafolder%/whitelist.yml");
29 | Map> locales = new HashMap<>();
30 |
31 | for (String lang : messagesYml.getSection("langs").getKeys()) {
32 | Configuration langSection = messagesYml.getSection("langs." + lang);
33 | Map messages = new HashMap<>();
34 |
35 | for (String key : langSection.getKeys()) {
36 | String value = langSection.getString(key);
37 |
38 | messages.put(key, value);
39 | }
40 |
41 | locales.put(lang, messages);
42 | }
43 |
44 | getCapsModule().loadData(configYml.getBoolean("caps.enabled"), configYml.getBoolean("caps.replace"),
45 | configYml.getInt("caps.max"), configYml.getInt("caps.warn.max"),
46 | configYml.getString("caps.warn.notification"),
47 | configYml.getStringList("caps.punishments").toArray(new String[0]));
48 | getCooldownModule().loadData(configYml.getBoolean("cooldown.enabled"),
49 | configYml.getInt("cooldown.time.repeat-global"), configYml.getInt("cooldown.time.repeat"),
50 | configYml.getInt("cooldown.time.normal"), configYml.getInt("cooldown.time.command"));
51 | getFloodModule().loadData(configYml.getBoolean("flood.enabled"), configYml.getBoolean("flood.replace"),
52 | configYml.getInt("flood.warn.max"), configYml.getString("flood.pattern"),
53 | configYml.getString("flood.warn.notification"),
54 | configYml.getStringList("flood.punishments").toArray(new String[0]));
55 | getMessagesModule().loadData(messagesYml.getString("default"), locales);
56 | getGeneralModule().loadData(configYml.getBoolean("general.sanitize", true),
57 | configYml.getBoolean("general.sanitize-names", true),
58 | configYml.getBoolean("general.filter-other", false),
59 | configYml.getStringList("general.commands"));
60 | getWhitelistModule().loadData(configYml.getBoolean("whitelist.enabled"),
61 | whitelistYml.getStringList("expressions").toArray(new String[0]));
62 | boolean censorshipEnabled = configYml.getBoolean("blacklist.censorship.enabled", false);
63 | String censorshipReplacement = configYml.getString("blacklist.censorship.replacement", "***");
64 | getBlacklistModule().loadData(configYml.getBoolean("blacklist.enabled"),
65 | configYml.getBoolean("blacklist.fake_message"), censorshipEnabled, censorshipReplacement,
66 | configYml.getInt("blacklist.warn.max"), configYml.getString("blacklist.warn.notification"),
67 | configYml.getStringList("blacklist.punishments").toArray(new String[0]),
68 | blacklistYml.getStringList("expressions").toArray(new String[0]),
69 | configYml.getBoolean("blacklist.block_raw_message"));
70 | getSyntaxModule().loadData(configYml.getBoolean("syntax.enabled"), configYml.getInt("syntax.warn.max"),
71 | configYml.getString("syntax.warn.notification"),
72 | configYml.getStringList("syntax.whitelist").toArray(new String[0]),
73 | configYml.getStringList("syntax.punishments").toArray(new String[0]));
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/bungee/utils/ConfigUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.bungee.utils;
2 |
3 | import net.md_5.bungee.api.plugin.Plugin;
4 | import net.md_5.bungee.config.Configuration;
5 | import net.md_5.bungee.config.ConfigurationProvider;
6 | import net.md_5.bungee.config.YamlConfiguration;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.nio.file.Files;
12 | import java.util.logging.Level;
13 |
14 | public class ConfigUtil {
15 | private Plugin plugin;
16 |
17 | public ConfigUtil(Plugin plugin) {
18 | this.plugin = plugin;
19 | }
20 |
21 | public Configuration get(String file) {
22 | File dataFolder = plugin.getDataFolder();
23 |
24 | file = file.replace("%datafolder%", dataFolder.toPath().toString());
25 |
26 | try {
27 | return ConfigurationProvider.getProvider(YamlConfiguration.class).load(new File(file));
28 | } catch (IOException e) {
29 | e.printStackTrace();
30 | return null;
31 | }
32 | }
33 |
34 | public void create(String file) {
35 | try {
36 | File dataFolder = plugin.getDataFolder();
37 |
38 | file = file.replace("%datafolder%", dataFolder.toPath().toString());
39 |
40 | File configFile = new File(file);
41 |
42 | if (!configFile.exists()) {
43 | String[] files = file.split("/");
44 | InputStream inputStream = plugin.getClass().getClassLoader()
45 | .getResourceAsStream(files[files.length - 1]);
46 | File parentFile = configFile.getParentFile();
47 |
48 | if (parentFile != null)
49 | parentFile.mkdirs();
50 |
51 | if (inputStream != null) {
52 | Files.copy(inputStream, configFile.toPath());
53 | plugin.getLogger().log(Level.INFO, ("[%pluginname%] File " + configFile + " has been created!")
54 | .replace("%pluginname%", plugin.getDescription().getName()));
55 | } else
56 | configFile.createNewFile();
57 | }
58 | } catch (IOException e) {
59 | plugin.getLogger().log(Level.INFO, ("[%pluginname%] Unable to create configuration file!")
60 | .replace("%pluginname%", plugin.getDescription().getName()));
61 | }
62 | }
63 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/chat/ChatEventResult.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.chat;
2 |
3 | public class ChatEventResult {
4 | private String message;
5 | private boolean cancelled;
6 | private boolean hide;
7 |
8 | public ChatEventResult(String message, boolean cancelled, boolean hide) {
9 | this.message = message;
10 | this.cancelled = cancelled;
11 | this.hide = hide;
12 | }
13 |
14 | public ChatEventResult(String message, boolean cancelled) {
15 | this(message, cancelled, false);
16 | }
17 |
18 | public String getMessage() {
19 | return message;
20 | }
21 |
22 | public void setMessage(String message) {
23 | this.message = message;
24 | }
25 |
26 | public boolean isCancelled() {
27 | return cancelled;
28 | }
29 |
30 | public void setCancelled(boolean cancelled) {
31 | this.cancelled = cancelled;
32 | }
33 |
34 | public boolean isHide() {
35 | return hide;
36 | }
37 |
38 | public void setHide(boolean hide) {
39 | this.hide = hide;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/chat/ChatNotificationManager.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.chat;
2 |
3 | import java.util.*;
4 |
5 | public class ChatNotificationManager {
6 | private final List notifiedChatPlayers = new ArrayList<>();
7 |
8 | public void addPlayer(ChatPlayer chatPlayer) {
9 | notifiedChatPlayers.add(chatPlayer);
10 | }
11 |
12 | public boolean containsPlayer(ChatPlayer chatPlayer) {
13 | return notifiedChatPlayers.contains(chatPlayer);
14 | }
15 |
16 | public void removePlayer(ChatPlayer chatPlayer) {
17 | notifiedChatPlayers.remove(chatPlayer);
18 | }
19 |
20 | public List getAllPlayers() {
21 | return notifiedChatPlayers;
22 | }
23 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/chat/ChatPlayer.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.chat;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Deque;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 | import java.util.UUID;
8 |
9 | import dev._2lstudios.chatsentinel.shared.modules.ModerationModule;
10 |
11 | public class ChatPlayer {
12 | private int historySize = 3;
13 | private UUID uuid;
14 | private Map warns;
15 | private Deque lastMessages;
16 | private String locale = null;
17 | private long lastMessageTime;
18 | private boolean notify = false;
19 |
20 | public ChatPlayer(UUID uuid) {
21 | this.uuid = uuid;
22 | this.warns = new HashMap<>();
23 | this.lastMessages = new ArrayDeque<>(historySize);
24 | this.lastMessageTime = 0;
25 | }
26 |
27 | public int getWarns(ModerationModule moderationModule) {
28 | return this.warns.getOrDefault(moderationModule, 0);
29 | }
30 |
31 | public int addWarn(ModerationModule moderationModule) {
32 | int warns = this.warns.getOrDefault(moderationModule, 0) + 1;
33 |
34 | this.warns.put(moderationModule, warns);
35 |
36 | return warns;
37 | }
38 |
39 | public String removeDigits(String str) {
40 | // Converting the given string
41 | // into a character array
42 | char[] charArray = str.toCharArray();
43 | String result = "";
44 |
45 | // Traverse the character array
46 | for (int i = 0; i < charArray.length; i++) {
47 | // Check if the specified character is not digit
48 | // then add this character into result variable
49 | if (!Character.isDigit(charArray[i])) {
50 | result = result + charArray[i];
51 | }
52 | }
53 |
54 | return result;
55 | }
56 |
57 | public boolean isLastMessage(String message) {
58 | // Check if message is null
59 | if (message != null) {
60 | // Remove digits from message
61 | message = removeDigits(message);
62 |
63 | // Get the length of the message
64 | int length = message.length();
65 |
66 | // Iterate over last messages
67 | for (String lastMessage : lastMessages) {
68 | // Check if equals the last message
69 | if (message.equals(lastMessage)) {
70 | return true;
71 | }
72 | // Check if equals last message length
73 | if (length > 16 && length == lastMessage.length()) {
74 | return true;
75 | }
76 | }
77 | }
78 |
79 | return false;
80 | }
81 |
82 | public long getLastMessageTime() {
83 | return this.lastMessageTime;
84 | }
85 |
86 | public void addLastMessage(String lastMessage, long lastMessageTime) {
87 | if (lastMessages.size() > historySize) {
88 | lastMessages.removeLast();
89 | }
90 | lastMessages.offerFirst(removeDigits(lastMessage));
91 | this.lastMessageTime = lastMessageTime;
92 | }
93 |
94 | public void clearWarns() {
95 | this.warns.clear();
96 | }
97 |
98 | public UUID getUniqueId() {
99 | return uuid;
100 | }
101 |
102 | public String getLocale() {
103 | return hasLocale() ? locale : "en";
104 | }
105 |
106 | public void setLocale(String locale) {
107 | this.locale = locale;
108 | }
109 |
110 | public boolean hasLocale() {
111 | return this.locale != null;
112 | }
113 |
114 | public void setNotify(boolean notify) {
115 | this.notify = notify;
116 | }
117 |
118 | public boolean isNotify() {
119 | return notify;
120 | }
121 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/chat/ChatPlayerManager.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.chat;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.UUID;
6 |
7 | import net.md_5.bungee.api.connection.ProxiedPlayer;
8 |
9 | public class ChatPlayerManager {
10 | private final Map chatPlayers = new HashMap<>();
11 |
12 | public ChatPlayer getPlayer(UUID uuid) {
13 | return chatPlayers.computeIfAbsent(uuid, ChatPlayer::new);
14 | }
15 |
16 | public ChatPlayer getPlayer(ProxiedPlayer player) {
17 | return getPlayer(player.getUniqueId());
18 | }
19 |
20 | public ChatPlayer getPlayer(org.bukkit.entity.Player player) {
21 | return getPlayer(player.getUniqueId());
22 | }
23 |
24 | public ChatPlayer getPlayer(com.velocitypowered.api.proxy.Player player) {
25 | return getPlayer(player.getUniqueId());
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/BlacklistModerationModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import java.util.regex.Pattern;
4 |
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
6 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
7 | import dev._2lstudios.chatsentinel.shared.utils.PatternUtil;
8 |
9 | public class BlacklistModerationModule extends ModerationModule {
10 | private ModuleManager moduleManager;
11 |
12 | private boolean fakeMessage;
13 | private boolean blockRawMessage;
14 | private Pattern pattern;
15 |
16 | private boolean censorshipEnabled;
17 | private String censorshipReplacement;
18 |
19 | public BlacklistModerationModule(ModuleManager moduleManager) {
20 | this.moduleManager = moduleManager;
21 | }
22 |
23 | public void loadData(boolean enabled, boolean fakeMessage, boolean censorshipEnabled, String censorshipReplacement, int maxWarns,
24 | String warnNotification, String[] commands, String[] patterns, boolean blockRawMessage) {
25 | setEnabled(enabled);
26 | setMaxWarns(maxWarns);
27 | setWarnNotification(warnNotification);
28 | setCommands(commands);
29 | this.fakeMessage = fakeMessage;
30 | this.censorshipEnabled = censorshipEnabled;
31 | this.censorshipReplacement = censorshipReplacement;
32 | this.pattern = PatternUtil.compile(patterns);
33 | this.blockRawMessage = blockRawMessage;
34 | }
35 |
36 | public boolean isFakeMessage() {
37 | return this.fakeMessage;
38 | }
39 |
40 | public boolean isCensorshipEnabled() {
41 | return censorshipEnabled;
42 | }
43 |
44 | public String getCensorshipReplacement() {
45 | return censorshipReplacement;
46 | }
47 |
48 | public boolean isBlockRawMessage() {
49 | return this.blockRawMessage;
50 | }
51 |
52 | public Pattern getPattern() {
53 | return pattern;
54 | }
55 |
56 | @Override
57 | public ChatEventResult processEvent(ChatPlayer chatPlayer, MessagesModule messagesModule, String playerName,
58 | String message, String lang) {
59 | if (!isEnabled()) {
60 | return null;
61 | }
62 |
63 | boolean cancelled = false;
64 | boolean hide = false;
65 |
66 | GeneralModule generalModule = moduleManager.getGeneralModule();
67 | WhitelistModule whitelistModule = moduleManager.getWhitelistModule();
68 |
69 | String sanitizedMessage = message;
70 |
71 | // Filter the arguments of the commands
72 | if (sanitizedMessage.startsWith("/") && message.contains(" ")) {
73 | sanitizedMessage = sanitizedMessage.substring(message.indexOf(" "));
74 | }
75 |
76 | // Remove weird stuff
77 | if (generalModule.isSanitizeEnabled()) {
78 | sanitizedMessage = generalModule.sanitize(message);
79 | }
80 |
81 | // Remove names
82 | if (generalModule.isSanitizeNames()) {
83 | sanitizedMessage = generalModule.sanitizeNames(message);
84 | }
85 |
86 | // Remove whitelisted stuff
87 | if (whitelistModule.isEnabled()) {
88 | sanitizedMessage = whitelistModule.getPattern().matcher(message).replaceAll("");
89 | }
90 |
91 | if (pattern.matcher(sanitizedMessage).find()) {
92 | if (isFakeMessage()) {
93 | hide = true;
94 | } else if (isCensorshipEnabled()) {
95 | message = pattern.matcher(message).replaceAll(getCensorshipReplacement());
96 | } else if (isBlockRawMessage()) {
97 | cancelled = true;
98 | }
99 |
100 | return new ChatEventResult(message, cancelled, hide);
101 | }
102 |
103 | return null;
104 | }
105 |
106 | @Override
107 | public String getName() {
108 | return "Blacklist";
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/CapsModerationModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 |
6 | public class CapsModerationModule extends ModerationModule {
7 | private boolean replace;
8 | private int maxCaps;
9 |
10 | public void loadData(boolean enabled, boolean replace, int max, int maxWarns,
11 | String warnNotification, String[] commands) {
12 | setEnabled(enabled);
13 | setMaxWarns(maxWarns);
14 | setWarnNotification(warnNotification);
15 | setCommands(commands);
16 | this.replace = replace;
17 | this.maxCaps = max;
18 | }
19 |
20 | public boolean isReplace() {
21 | return this.replace;
22 | }
23 |
24 | public long capsCount(String string) {
25 | return string.codePoints().filter(c -> c >= 'A' && c <= 'Z').count();
26 | }
27 |
28 | @Override
29 | public ChatEventResult processEvent(ChatPlayer chatPlayer, MessagesModule messagesModule, String playerName,
30 | String originalMessage, String lang) {
31 | if (isEnabled() && this.capsCount(originalMessage) > maxCaps) {
32 | boolean cancelled = false;
33 |
34 | if (isReplace()) {
35 | originalMessage = originalMessage.toLowerCase();
36 | } else {
37 | cancelled = true;
38 | }
39 |
40 | return new ChatEventResult(originalMessage, cancelled);
41 | }
42 |
43 | return null;
44 | }
45 |
46 | @Override
47 | public String getName() {
48 | return "Caps";
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/CooldownModerationModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 |
6 | public class CooldownModerationModule extends ModerationModule {
7 | private int repeatTimeGlobal;
8 | private int repeatTime;
9 | private int normalTime;
10 | private int commandTime;
11 |
12 | private long lastMessageTime = 0L;
13 | private String lastMessage = "";
14 |
15 | public void loadData(boolean enabled, int repeatTimeGlobal, int repeatTime,
16 | int normalTime,
17 | int commandTime) {
18 | setEnabled(enabled);
19 | this.repeatTimeGlobal = repeatTimeGlobal;
20 | this.repeatTime = repeatTime;
21 | this.normalTime = normalTime;
22 | this.commandTime = commandTime;
23 | }
24 |
25 | public float getRemainingTime(ChatPlayer chatPlayer, String message) {
26 | if (isEnabled() && message != null) {
27 | long currentTime = System.currentTimeMillis();
28 | long lastMessageTimePassed = currentTime - chatPlayer.getLastMessageTime();
29 | long lastMessageTimePassedGlobal = currentTime - this.lastMessageTime;
30 | long remainingTime;
31 |
32 | if (message.startsWith("/")) {
33 | remainingTime = this.commandTime - lastMessageTimePassed;
34 | } else if (chatPlayer.isLastMessage(message) && lastMessageTimePassed < this.repeatTime) {
35 | remainingTime = this.repeatTime - lastMessageTimePassed;
36 | } else if (this.lastMessage.equals(message) && lastMessageTimePassedGlobal < this.repeatTimeGlobal) {
37 | remainingTime = this.repeatTimeGlobal - lastMessageTimePassedGlobal;
38 | } else {
39 | remainingTime = this.normalTime - lastMessageTimePassed;
40 | }
41 |
42 | if (remainingTime > 0) {
43 | return ((int) (remainingTime / 100F)) / 10F;
44 | }
45 | }
46 |
47 | return 0;
48 | }
49 |
50 | @Override
51 | public ChatEventResult processEvent(ChatPlayer chatPlayer, MessagesModule messagesModule, String playerName,
52 | String originalMessage, String lang) {
53 | if (isEnabled() && getRemainingTime(chatPlayer, originalMessage) > 0) {
54 | return new ChatEventResult(originalMessage, true);
55 | }
56 |
57 | return null;
58 | }
59 |
60 | @Override
61 | public String getName() {
62 | return "Cooldown";
63 | }
64 |
65 | @Override
66 | public String getWarnNotification(String[][] placeholders) {
67 | return null;
68 | }
69 |
70 | public void setLastMessage(String lastMessage, long lastMessageTime) {
71 | this.lastMessage = lastMessage;
72 | this.lastMessageTime = lastMessageTime;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/FloodModerationModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import java.util.regex.Pattern;
4 |
5 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
6 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
7 |
8 | public class FloodModerationModule extends ModerationModule {
9 | private boolean replace;
10 | private Pattern pattern;
11 |
12 | public void loadData(boolean enabled, boolean replace, int maxWarns, String pattern,
13 | String warnNotification, String[] commands) {
14 | setEnabled(enabled);
15 | setMaxWarns(maxWarns);
16 | setWarnNotification(warnNotification);
17 | setCommands(commands);
18 | this.replace = replace;
19 | this.pattern = Pattern.compile(pattern);
20 | }
21 |
22 | public boolean isReplace() {
23 | return this.replace;
24 | }
25 |
26 | public String replace(String string) {
27 | return pattern.matcher(string).replaceAll("");
28 | }
29 |
30 | @Override
31 | public ChatEventResult processEvent(ChatPlayer chatPlayer, MessagesModule messagesModule, String playerName,
32 | String message, String lang) {
33 | if (isEnabled() && pattern.matcher(message).find()) {
34 | boolean cancelled = true;
35 |
36 | if (isReplace()) {
37 | String replacedString = replace(message);
38 |
39 | if (!replacedString.isEmpty()) {
40 | message = replacedString;
41 | cancelled = false;
42 | }
43 | }
44 |
45 | return new ChatEventResult(message, cancelled);
46 | }
47 |
48 | return null;
49 | }
50 |
51 | @Override
52 | public String getName() {
53 | return "Flood";
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/GeneralModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import java.text.Normalizer;
4 | import java.util.Collection;
5 | import java.util.HashSet;
6 | import java.util.regex.Pattern;
7 |
8 | public class GeneralModule {
9 | private Pattern nonAlphaNumericPattern = Pattern.compile("[^a-zA-Z0-9]");
10 | private Pattern nicknamesPattern = Pattern.compile("");
11 | private Collection nicknames = new HashSet<>();
12 | private Collection commands;
13 | private boolean sanitize;
14 | private boolean sanitizeNames;
15 | private boolean filterOther;
16 |
17 | public void loadData(boolean sanitize, boolean sanitizeNames, boolean filterOther,
18 | Collection commands) {
19 | this.sanitize = sanitize;
20 | this.sanitizeNames = sanitizeNames;
21 | this.filterOther = filterOther;
22 | this.commands = commands;
23 | }
24 |
25 | public boolean isSanitizeEnabled() {
26 | return sanitize;
27 | }
28 |
29 | /*
30 | * Removes non latin words Credit:
31 | * https://stackoverflow.com/users/636009/david-conrad
32 | */
33 | public String sanitize(String message) {
34 | char[] out = new char[message.length()];
35 |
36 | message = Normalizer.normalize(message, Normalizer.Form.NFD);
37 |
38 | for (int j = 0, i = 0, n = message.length(); i < n; ++i) {
39 | char c = message.charAt(i);
40 |
41 | if (c <= '\u007F') {
42 | out[j++] = c;
43 | }
44 | }
45 |
46 | return new String(out).replace("(punto)", ".").replace("(dot)", ".").trim();
47 | }
48 |
49 | public boolean isSanitizeNames() {
50 | return sanitizeNames;
51 | }
52 |
53 | public String removeNonAlphanumeric(String text) {
54 | return nonAlphaNumericPattern.matcher(text).replaceAll("");
55 | }
56 |
57 | private boolean needsNicknameCompile = false;
58 |
59 | public boolean needsNicknameCompile() {
60 | return needsNicknameCompile;
61 | }
62 |
63 | public void compileNicknamesPattern() {
64 | needsNicknameCompile = false;
65 |
66 | StringBuilder stringBuilder = new StringBuilder();
67 | boolean first = true;
68 |
69 | for (String nickname : nicknames) {
70 | if (!first) {
71 | stringBuilder.append("|");
72 | } else {
73 | first = false;
74 | }
75 |
76 | stringBuilder.append("(?i)(" + nickname + ")");
77 | }
78 |
79 | nicknamesPattern = Pattern.compile(stringBuilder.toString());
80 | }
81 |
82 | public Pattern getNicknamesPattern() {
83 | return nicknamesPattern;
84 | }
85 |
86 | public void addNickname(String nickname) {
87 | // Remove alphanumeric to avoid errors
88 | nicknames.add(removeNonAlphanumeric(nickname));
89 |
90 | // Compile the pattern with the nicknames
91 | needsNicknameCompile = true;
92 | }
93 |
94 | public void removeNickname(String nickname) {
95 | // Remove alphanumeric to avoid errors
96 | nicknames.remove(removeNonAlphanumeric(nickname));
97 |
98 | // Compile the pattern with the nicknames
99 | needsNicknameCompile = true;
100 | }
101 |
102 | public String sanitizeNames(String message) {
103 | return nicknamesPattern.matcher(message).replaceAll("");
104 | }
105 |
106 | public boolean isCommand(String message) {
107 | message = message.toLowerCase();
108 |
109 | for (String command : commands) {
110 | if (message.startsWith(command + ' '))
111 | return true;
112 | }
113 |
114 | return false;
115 | }
116 |
117 | public boolean isFilterOther() {
118 | return filterOther;
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/MessagesModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import dev._2lstudios.chatsentinel.shared.utils.PlaceholderUtil;
7 |
8 | public class MessagesModule {
9 | private Map> locales;
10 | private String defaultLang = "en";
11 |
12 | public void loadData(String defaultLang, Map> messages) {
13 | this.locales = messages;
14 | this.defaultLang = defaultLang;
15 | }
16 |
17 | private String getString(String lang, String path) {
18 | Map messages = locales.getOrDefault(lang, locales.getOrDefault(defaultLang, locales.getOrDefault("en", new HashMap<>())));
19 |
20 | return messages.getOrDefault(path, "");
21 | }
22 |
23 | public String getCleared(String[][] placeholders, String lang) {
24 | return PlaceholderUtil.replacePlaceholders(getString(lang, "cleared"), placeholders);
25 | }
26 |
27 | public String getReload(String lang) {
28 | return PlaceholderUtil.replacePlaceholders(getString(lang, "reload"));
29 | }
30 |
31 | public String getHelp(String lang) {
32 | return PlaceholderUtil.replacePlaceholders(getString(lang, "help"));
33 | }
34 |
35 | public String getUnknownCommand(String lang) {
36 | return PlaceholderUtil.replacePlaceholders(getString(lang, "unknown_command"));
37 | }
38 |
39 | public String getNoPermission(String lang) {
40 | return PlaceholderUtil.replacePlaceholders(getString(lang, "no_permission"));
41 | }
42 |
43 | public String getWarnMessage(String[][] placeholders, String lang, String module) {
44 | String moduleLowerCase = module.toLowerCase();
45 |
46 | return PlaceholderUtil.replacePlaceholders(getString(lang, moduleLowerCase + "_warn_message"), placeholders);
47 | }
48 |
49 | public String getFiltered(String lang) {
50 | return PlaceholderUtil.replacePlaceholders(getString(lang, "filtered"));
51 | }
52 |
53 | public String getNotifyEnabled(String lang) {
54 | return PlaceholderUtil.replacePlaceholders(getString(lang, "notify-enabled"));
55 | }
56 |
57 | public String getNotifyDisabled(String lang) {
58 | return PlaceholderUtil.replacePlaceholders(getString(lang, "notify-disabled"));
59 | }
60 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/ModerationModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 | import dev._2lstudios.chatsentinel.shared.utils.PlaceholderUtil;
6 |
7 | public abstract class ModerationModule {
8 | private boolean enabled = true;
9 | private int maxWarns = 0;
10 | private String warnNotification = null;
11 | private String[] commands = new String[0];
12 |
13 | public boolean isEnabled() {
14 | return enabled;
15 | }
16 |
17 | public int getMaxWarns() {
18 | return maxWarns;
19 | }
20 |
21 | public void setEnabled(boolean enabled) {
22 | this.enabled = enabled;
23 | }
24 |
25 | public void setMaxWarns(int maxWarns) {
26 | this.maxWarns = maxWarns;
27 | }
28 |
29 | public String getWarnNotification(String[][] placeholders) {
30 | if (!this.warnNotification.isEmpty()) {
31 | return PlaceholderUtil.replacePlaceholders(this.warnNotification, placeholders);
32 | }
33 |
34 | return null;
35 | }
36 |
37 | public void setWarnNotification(String warnNotification) {
38 | this.warnNotification = warnNotification;
39 | }
40 |
41 | public boolean hasExceededWarns(ChatPlayer chatPlayer) {
42 | return chatPlayer.getWarns(this) >= maxWarns && maxWarns > 0;
43 | }
44 |
45 | public abstract String getName();
46 |
47 | public abstract ChatEventResult processEvent(ChatPlayer chatPlayer, MessagesModule messagesModule, String playerName, String originalMessage, String lang);
48 |
49 | public String getBypassPermission() {
50 | return "chatsentinel.bypass." + getName();
51 | }
52 |
53 | public String[] getCommands(String[][] placeholders) {
54 | if (this.commands.length > 0) {
55 | String[] cmds = this.commands.clone();
56 |
57 | for (int i = 0; i < cmds.length; i++) {
58 | cmds[i] = PlaceholderUtil.replacePlaceholders(cmds[i], placeholders);
59 | }
60 |
61 | return cmds;
62 | } else
63 | return new String[0];
64 | }
65 |
66 | public void setCommands(String[] commands) {
67 | this.commands = commands;
68 | }
69 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/ModuleManager.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | public abstract class ModuleManager {
4 | private CapsModerationModule capsModule;
5 | private CooldownModerationModule cooldownModule;
6 | private FloodModerationModule floodModule;
7 | private MessagesModule messagesModule;
8 | private GeneralModule generalModule;
9 | private BlacklistModerationModule blacklistModule;
10 | private SyntaxModerationModule syntaxModule;
11 | private WhitelistModule whitelistModule;
12 |
13 | public ModuleManager() {
14 | this.capsModule = new CapsModerationModule();
15 | this.cooldownModule = new CooldownModerationModule();
16 | this.floodModule = new FloodModerationModule();
17 | this.blacklistModule = new BlacklistModerationModule(this);
18 | this.syntaxModule = new SyntaxModerationModule();
19 | this.messagesModule = new MessagesModule();
20 | this.generalModule = new GeneralModule();
21 | this.whitelistModule = new WhitelistModule();
22 | }
23 |
24 | public CooldownModerationModule getCooldownModule() {
25 | return cooldownModule;
26 | }
27 |
28 | public CapsModerationModule getCapsModule() {
29 | return capsModule;
30 | }
31 |
32 | public FloodModerationModule getFloodModule() {
33 | return floodModule;
34 | }
35 |
36 | public BlacklistModerationModule getBlacklistModule() {
37 | return blacklistModule;
38 | }
39 |
40 | public SyntaxModerationModule getSyntaxModule() {
41 | return syntaxModule;
42 | }
43 |
44 | public MessagesModule getMessagesModule() {
45 | return messagesModule;
46 | }
47 |
48 | public GeneralModule getGeneralModule() {
49 | return generalModule;
50 | }
51 |
52 | public WhitelistModule getWhitelistModule() {
53 | return whitelistModule;
54 | }
55 |
56 | public abstract void reloadData();
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/SyntaxModerationModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
4 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
5 |
6 | public class SyntaxModerationModule extends ModerationModule {
7 | private String[] whitelist;
8 |
9 | public void loadData(boolean enabled, int maxWarns, String warnNotification,
10 | String[] whitelist, String[] commands) {
11 | setEnabled(enabled);
12 | setMaxWarns(maxWarns);
13 | setWarnNotification(warnNotification);
14 | setCommands(commands);
15 | this.whitelist = whitelist;
16 | }
17 |
18 | public boolean isWhitelisted(String message) {
19 | if (whitelist.length > 0)
20 | for (String string : whitelist)
21 | if (message.startsWith(string))
22 | return true;
23 |
24 | return false;
25 | }
26 |
27 | @Override
28 | public ChatEventResult processEvent(ChatPlayer chatPlayer, MessagesModule messagesModule, String playerName,
29 | String message, String lang) {
30 | if (isEnabled() && !isWhitelisted(message) && hasSyntax(message)) {
31 | return new ChatEventResult(message, true);
32 | }
33 |
34 | return null;
35 | }
36 |
37 | @Override
38 | public String getName() {
39 | return "Syntax";
40 | }
41 |
42 | private boolean hasSyntax(String message) {
43 | if (message.startsWith("/")) {
44 | String command;
45 |
46 | if (message.contains(" ")) {
47 | command = message.split(" ")[0];
48 | } else {
49 | command = message;
50 | }
51 |
52 | String[] syntax = command.split(":");
53 |
54 | if (syntax.length > 1) {
55 | return true;
56 | }
57 | }
58 |
59 | return false;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/modules/WhitelistModule.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.modules;
2 |
3 | import java.util.regex.Pattern;
4 |
5 | import dev._2lstudios.chatsentinel.shared.utils.PatternUtil;
6 |
7 | public class WhitelistModule {
8 | private boolean enabled;
9 | private Pattern pattern;
10 |
11 | public void loadData(boolean enabled, String[] patterns) {
12 | this.enabled = enabled;
13 | this.pattern = PatternUtil.compile(patterns);
14 | }
15 |
16 | public Pattern getPattern() {
17 | return pattern;
18 | }
19 |
20 | public boolean isEnabled() {
21 | return enabled;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/utils/PatternUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.utils;
2 |
3 | import java.util.Collection;
4 | import java.util.regex.Pattern;
5 |
6 | public class PatternUtil {
7 | public static Pattern compile(String[] patterns) {
8 | StringBuilder patternBuilder = new StringBuilder();
9 |
10 | for (String entry : patterns) {
11 | if (patternBuilder.length() <= 0) {
12 | patternBuilder.append("(" + entry);
13 | } else {
14 | patternBuilder.append(")|(" + entry);
15 | }
16 | }
17 |
18 | patternBuilder.append(")");
19 |
20 | return Pattern.compile("(?i)" + patternBuilder.toString());
21 | }
22 |
23 | public static Pattern compile(Collection patterns) {
24 | StringBuilder patternBuilder = new StringBuilder();
25 |
26 | for (String entry : patterns) {
27 | if (patternBuilder.length() <= 0) {
28 | patternBuilder.append("(" + entry);
29 | } else {
30 | patternBuilder.append(")|(" + entry);
31 | }
32 | }
33 |
34 | patternBuilder.append(")");
35 |
36 | return Pattern.compile("(?i)" + patternBuilder.toString());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/utils/PlaceholderUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.utils;
2 |
3 | public class PlaceholderUtil {
4 | public static String replacePlaceholders(String string, String[] ...placeholders) {
5 | string = string.replace('\u0026', '\u00a7');
6 |
7 | if (placeholders != null && placeholders.length > 0) {
8 | for (int i = 0; i < placeholders[0].length; i++) {
9 | String id = placeholders[0][i], value = placeholders[1][i];
10 |
11 | string = string.replace(id, value);
12 | }
13 | }
14 |
15 | return string;
16 | }
17 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/utils/ReflectionUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.utils;
2 |
3 | import java.lang.invoke.MethodHandle;
4 | import java.lang.invoke.MethodHandles;
5 | import java.lang.invoke.MethodType;
6 | import java.lang.reflect.Field;
7 | import java.lang.reflect.Method;
8 |
9 | import org.bukkit.entity.Player;
10 | import org.bukkit.entity.Player.Spigot;
11 |
12 | public final class ReflectionUtil {
13 | private static final MethodHandle getLocalePlayerMethod = localePlayer();
14 | private static final MethodHandle getLocaleSpigotMethod = localeSpigot();
15 | private static final MethodHandle getHandleMethod = handleMethod();
16 | private static Field pingField = null;
17 |
18 | private static MethodHandle localePlayer() {
19 | try {
20 | MethodHandles.Lookup lookup = MethodHandles.publicLookup();
21 | return lookup.findVirtual(Player.class, "getLocale", MethodType.methodType(String.class));
22 | } catch (NoSuchMethodException | IllegalAccessException e) {
23 | return null;
24 | }
25 | }
26 |
27 | private static MethodHandle localeSpigot() {
28 | try {
29 | MethodHandles.Lookup lookup = MethodHandles.publicLookup();
30 | return lookup.findVirtual(Spigot.class, "getLocale", MethodType.methodType(String.class));
31 | } catch (NoSuchMethodException | IllegalAccessException e) {
32 | return null;
33 | }
34 | }
35 |
36 | private static MethodHandle handleMethod() {
37 | MethodHandles.Lookup lookup = MethodHandles.lookup();
38 | try {
39 | Method method = Player.class.getMethod("getHandle");
40 | method.setAccessible(true);
41 | return lookup.unreflect(method);
42 | } catch (IllegalAccessException | NoSuchMethodException | SecurityException e) {
43 | return null;
44 | }
45 | }
46 |
47 | public static MethodHandle getLocalePlayerMethod() {
48 | return getLocalePlayerMethod;
49 | }
50 |
51 | public static MethodHandle getLocaleSpigotMethod() {
52 | return getLocaleSpigotMethod;
53 | }
54 |
55 | public static MethodHandle getHandleMethod() {
56 | return getHandleMethod;
57 | }
58 |
59 | public static Field getPingField(Object playerHandle) throws NoSuchFieldException, SecurityException {
60 | return pingField == null ? pingField = playerHandle.getClass().getField("ping") : pingField;
61 | }
62 |
63 | private ReflectionUtil() {}
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/shared/utils/VersionUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.shared.utils;
2 |
3 | import java.lang.invoke.MethodHandle;
4 | import java.util.Locale;
5 |
6 | import org.bukkit.entity.Player;
7 |
8 | import net.md_5.bungee.api.connection.ProxiedPlayer;
9 |
10 | public class VersionUtil {
11 | private static boolean oneDotNine = false;
12 |
13 | public static void start(String version) {
14 | oneDotNine = !version.contains("1.8") && !version.contains("1.7");
15 | }
16 |
17 | public static boolean isOneDotNine() {
18 | return oneDotNine;
19 | }
20 |
21 | private static String trimLocale(String locale) {
22 | return locale.substring(0, 2);
23 | }
24 |
25 | public static String getLocale(Player player) {
26 | String locale = null;
27 |
28 | if (player != null && player.isOnline()) {
29 | MethodHandle getLocaleMethod = ReflectionUtil.getLocalePlayerMethod();
30 |
31 | try {
32 | if (getLocaleMethod != null) {
33 | locale = getLocaleMethod.invoke(player).toString();
34 | } else {
35 | getLocaleMethod = ReflectionUtil.getLocaleSpigotMethod();
36 | if (getLocaleMethod != null) {
37 | locale = getLocaleMethod.invoke(player.spigot()).toString();
38 | }
39 | }
40 | } catch (Throwable t) {
41 | // The player is invalid, ignore
42 | }
43 |
44 |
45 | if (locale != null && locale.length() > 1) {
46 | locale = locale.substring(0, 2);
47 | }
48 | }
49 |
50 | return locale;
51 | }
52 |
53 | public static String getLocale(ProxiedPlayer player) {
54 | Locale locale = player.getLocale();
55 |
56 | if (locale != null) {
57 | String localeString = locale.toString();
58 |
59 | if (localeString.length() > 1) {
60 | return trimLocale(localeString);
61 | }
62 | }
63 |
64 | return "en";
65 | }
66 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/ChatSentinel.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity;
2 |
3 | import com.google.inject.Inject;
4 | import com.velocitypowered.api.command.CommandManager;
5 | import com.velocitypowered.api.command.CommandMeta;
6 | import com.velocitypowered.api.command.CommandSource;
7 | import com.velocitypowered.api.command.SimpleCommand;
8 | import com.velocitypowered.api.event.EventManager;
9 | import com.velocitypowered.api.event.Subscribe;
10 | import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
11 | import com.velocitypowered.api.plugin.Plugin;
12 | import com.velocitypowered.api.plugin.annotation.DataDirectory;
13 | import com.velocitypowered.api.proxy.Player;
14 | import com.velocitypowered.api.proxy.ProxyServer;
15 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
16 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
17 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
18 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
19 | import dev._2lstudios.chatsentinel.shared.modules.*;
20 | import dev._2lstudios.chatsentinel.velocity.commands.ChatSentinelCommand;
21 | import dev._2lstudios.chatsentinel.velocity.listeners.ChatListener;
22 | import dev._2lstudios.chatsentinel.velocity.listeners.PlayerDisconnectListener;
23 | import dev._2lstudios.chatsentinel.velocity.listeners.PostLoginListener;
24 | import dev._2lstudios.chatsentinel.velocity.modules.VelocityModuleManager;
25 | import dev._2lstudios.chatsentinel.velocity.utils.ConfigUtil;
26 | import dev._2lstudios.chatsentinel.velocity.utils.Constants;
27 | import net.kyori.adventure.text.Component;
28 | import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
29 | import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
30 |
31 | import java.nio.file.Path;
32 | import java.util.Optional;
33 | import java.util.concurrent.TimeUnit;
34 |
35 | @Plugin(
36 | id = Constants.ID,
37 | name = Constants.NAME,
38 | version = Constants.VERSION,
39 | description = Constants.DESCRIPTION,
40 | url = Constants.URL,
41 | authors = Constants.AUTHOR
42 | )
43 | public class ChatSentinel {
44 |
45 | private final ProxyServer server;
46 | private final ComponentLogger logger;
47 | private final Path dataDirectory;
48 | private VelocityModuleManager moduleManager;
49 | private GeneralModule generalModule;
50 | private ChatPlayerManager chatPlayerManager;
51 | private ChatNotificationManager chatNotificationManager;
52 |
53 | @Inject
54 | public ChatSentinel(ProxyServer server, ComponentLogger logger, @DataDirectory Path dataDirectory) {
55 | this.server = server;
56 | this.logger = logger;
57 | this.dataDirectory = dataDirectory;
58 | }
59 |
60 | @Subscribe
61 | public void onProxyInitialize(ProxyInitializeEvent event) {
62 |
63 | ConfigUtil configUtil = new ConfigUtil(this);
64 |
65 | moduleManager = new VelocityModuleManager(configUtil);
66 | generalModule = moduleManager.getGeneralModule();
67 | chatPlayerManager = new ChatPlayerManager();
68 | chatNotificationManager = new ChatNotificationManager();
69 |
70 | EventManager eventManager = server.getEventManager();
71 | eventManager.register(this, new ChatListener(this));
72 | eventManager.register(this, new PlayerDisconnectListener(generalModule, chatPlayerManager, chatNotificationManager));
73 | eventManager.register(this, new PostLoginListener(generalModule, chatPlayerManager, chatNotificationManager));
74 |
75 | CommandManager commandManager = server.getCommandManager();
76 | CommandMeta commandMeta = commandManager.metaBuilder("chatsentinel")
77 | .plugin(this)
78 | .build();
79 | SimpleCommand chatSentinelCommand = new ChatSentinelCommand(chatPlayerManager, chatNotificationManager, moduleManager, server);
80 |
81 | commandManager.register(commandMeta, chatSentinelCommand);
82 |
83 | server.getScheduler().buildTask(this, () -> {
84 | if (generalModule.needsNicknameCompile()) {
85 | generalModule.compileNicknamesPattern();
86 | }
87 | }).delay(1L, TimeUnit.SECONDS).repeat(1L, TimeUnit.SECONDS).schedule();
88 | }
89 |
90 | public void dispatchCommmands(ModerationModule moderationModule, ChatPlayer chatPlayer, String[][] placeholders) {
91 | server.getScheduler().buildTask(this, () -> {
92 | CommandSource console = server.getConsoleCommandSource();
93 |
94 | for (String command : moderationModule.getCommands(placeholders)) {
95 | server.getCommandManager().executeAsync(console, command);
96 | }
97 | }).schedule();
98 |
99 | chatPlayer.clearWarns();
100 | }
101 |
102 | public void dispatchNotification(ModerationModule moderationModule, String[][] placeholders) {
103 | ProxyServer server = getServer();
104 | String notificationMessage = moderationModule.getWarnNotification(placeholders);
105 |
106 | if (notificationMessage != null && !notificationMessage.isEmpty()) {
107 | for (ChatPlayer chatPlayer : chatNotificationManager.getAllPlayers()) {
108 | Optional player = server.getPlayer(chatPlayer.getUniqueId());
109 | player.ifPresent(player1 -> player1.sendMessage(Component.text(notificationMessage)));
110 | }
111 |
112 | logger.info(LegacyComponentSerializer.legacySection().deserialize(notificationMessage));
113 | }
114 | }
115 |
116 | public String[][] getPlaceholders(Player player, ChatPlayer chatPlayer, ModerationModule moderationModule, String message) {
117 | String playerName = player.getUsername();
118 | int warns = chatPlayer.getWarns(moderationModule);
119 | int maxWarns = moderationModule.getMaxWarns();
120 | float remainingTime = moduleManager.getCooldownModule().getRemainingTime(chatPlayer, message);
121 |
122 | return new String[][] {
123 | { "%player%", "%message%", "%warns%", "%maxwarns%", "%cooldown%" },
124 | { playerName, message, String.valueOf(warns), String.valueOf(maxWarns), String.valueOf(remainingTime) }
125 | };
126 | }
127 |
128 | public void sendWarning(String[][] placeholders, ModerationModule moderationModule, Player player, String lang) {
129 | String warnMessage = moduleManager.getMessagesModule().getWarnMessage(placeholders, lang, moderationModule.getName());
130 |
131 | if (warnMessage != null && !warnMessage.isEmpty()) {
132 | player.sendMessage(Component.text(warnMessage));
133 | }
134 | }
135 |
136 | public ChatEventResult processEvent(ChatPlayer chatPlayer, Player player, String originalMessage) {
137 | ChatEventResult finalResult = new ChatEventResult(originalMessage, false, false);
138 | MessagesModule messagesModule = moduleManager.getMessagesModule();
139 | String playerName = player.getUsername();
140 | String lang = chatPlayer.getLocale();
141 | ModerationModule[] moderationModulesToProcess = {
142 | moduleManager.getSyntaxModule(),
143 | moduleManager.getCapsModule(),
144 | moduleManager.getCooldownModule(),
145 | moduleManager.getFloodModule(),
146 | moduleManager.getBlacklistModule()
147 | };
148 |
149 | for (ModerationModule moderationModule : moderationModulesToProcess) {
150 | // Do not check annormal commands (unless syntax or cooldown)
151 | boolean isCommmand = originalMessage.startsWith("/");
152 | boolean isNormalCommmand = moduleManager.getGeneralModule()
153 | .isCommand(originalMessage);
154 | if (!(moderationModule instanceof SyntaxModerationModule) &&
155 | !(moderationModule instanceof CooldownModerationModule) &&
156 | isCommmand &&
157 | !isNormalCommmand) {
158 | continue;
159 | }
160 |
161 | // Get the modified message
162 | String message = finalResult.getMessage();
163 |
164 | // Check if player has bypass
165 | if (player.hasPermission(moderationModule.getBypassPermission())) {
166 | continue;
167 | }
168 |
169 | // Process
170 | ChatEventResult result = moderationModule.processEvent(chatPlayer, messagesModule, playerName, message, lang);
171 |
172 | // Skip result
173 | if (result != null) {
174 | // Add warning
175 | chatPlayer.addWarn(moderationModule);
176 |
177 | // Get placeholders
178 | String[][] placeholders = getPlaceholders(player, chatPlayer, moderationModule,
179 | message);
180 |
181 | // Send warning
182 | sendWarning(placeholders, moderationModule, player, lang);
183 |
184 | // Send punishment comamnds
185 | if (moderationModule.hasExceededWarns(chatPlayer)) {
186 | dispatchCommmands(moderationModule, chatPlayer, placeholders);
187 | }
188 |
189 | // Send admin notification
190 | dispatchNotification(moderationModule, placeholders);
191 |
192 | // Update message
193 | finalResult.setMessage(result.getMessage());
194 |
195 | // Update hide
196 | if (result.isHide())
197 | finalResult.setHide(true);
198 |
199 | // Update cancelled
200 | if (result.isCancelled()) {
201 | finalResult.setCancelled(true);
202 | break;
203 | }
204 | }
205 | }
206 |
207 | return finalResult;
208 | }
209 |
210 | public ProxyServer getServer() {
211 | return server;
212 | }
213 |
214 | public ComponentLogger getLogger() {
215 | return logger;
216 | }
217 |
218 | public Path getDataDirectory() {
219 | return dataDirectory;
220 | }
221 |
222 | public ChatPlayerManager getChatPlayerManager() {
223 | return chatPlayerManager;
224 | }
225 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/commands/ChatSentinelCommand.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.commands;
2 |
3 | import com.velocitypowered.api.command.CommandSource;
4 | import com.velocitypowered.api.command.SimpleCommand;
5 | import com.velocitypowered.api.proxy.Player;
6 | import com.velocitypowered.api.proxy.ProxyServer;
7 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
8 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
9 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
10 | import dev._2lstudios.chatsentinel.shared.modules.MessagesModule;
11 | import dev._2lstudios.chatsentinel.velocity.modules.VelocityModuleManager;
12 | import net.kyori.adventure.text.Component;
13 | import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
14 |
15 | import java.util.ArrayList;
16 | import java.util.List;
17 | import java.util.concurrent.CompletableFuture;
18 | import java.util.stream.Collectors;
19 | import java.util.stream.Stream;
20 |
21 | public class ChatSentinelCommand implements SimpleCommand {
22 | private final ChatPlayerManager chatPlayerManager;
23 | private final ChatNotificationManager chatNotificationManager;
24 | private final VelocityModuleManager moduleManager;
25 | private final ProxyServer server;
26 |
27 | public ChatSentinelCommand(ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager, VelocityModuleManager moduleManager, ProxyServer server) {
28 | this.chatPlayerManager = chatPlayerManager;
29 | this.chatNotificationManager = chatNotificationManager;
30 | this.moduleManager = moduleManager;
31 | this.server = server;
32 | }
33 |
34 | private void sendMessage(CommandSource sender, String message) {
35 | sender.sendMessage(LegacyComponentSerializer.legacySection().deserialize(message));
36 | }
37 |
38 | @Override
39 | public boolean hasPermission(final Invocation invocation) {
40 | return invocation.source().hasPermission("chatsentinel.admin");
41 | }
42 |
43 | @Override
44 | public CompletableFuture> suggestAsync(final Invocation invocation) {
45 | return CompletableFuture.completedFuture(Stream.of("help", "reload", "clear", "notify")
46 | .collect(Collectors.toCollection(ArrayList::new)));
47 | }
48 |
49 | @Override
50 | public void execute(final Invocation invocation) {
51 | MessagesModule messagesModule = moduleManager.getMessagesModule();
52 | String lang;
53 | ChatPlayer chatPlayer = null;
54 | CommandSource sender = invocation.source();
55 | String[] args = invocation.arguments();
56 |
57 | if (sender instanceof Player) {
58 | chatPlayer = chatPlayerManager.getPlayer((Player) sender);
59 | lang = chatPlayer.getLocale();
60 | } else {
61 | lang = "en";
62 | }
63 |
64 | if (sender.hasPermission("chatsentinel.admin")) {
65 | if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
66 | sendMessage(sender, messagesModule.getHelp(lang));
67 | } else if (args[0].equalsIgnoreCase("reload")) {
68 | moduleManager.reloadData();
69 |
70 | sendMessage(sender, messagesModule.getReload(lang));
71 | } else if (args[0].equalsIgnoreCase("clear")) {
72 | if (sender instanceof Player) {
73 | StringBuilder emptyLines = new StringBuilder();
74 | String newLine = "\n ";
75 | String[][] placeholders;
76 | placeholders = new String[][]{ { "%player%" }, { ((Player) sender).getUsername() } };
77 |
78 | for (int i = 0; i < 128; i++) {
79 | emptyLines.append(newLine);
80 | }
81 |
82 | emptyLines.append(messagesModule.getCleared(placeholders, lang));
83 |
84 | for (Player player : server.getAllPlayers()) {
85 | sendMessage(player, emptyLines.toString());
86 | }
87 | }
88 | } else if (args[0].equalsIgnoreCase("notify")) {
89 | if (sender instanceof Player) {
90 | boolean notify = chatNotificationManager.containsPlayer(chatPlayer);
91 |
92 | if (notify) {
93 | chatNotificationManager.removePlayer(chatPlayer);
94 | sendMessage(sender, messagesModule.getNotifyDisabled(lang));
95 | } else {
96 | chatNotificationManager.addPlayer(chatPlayer);
97 | sendMessage(sender, messagesModule.getNotifyEnabled(lang));
98 | }
99 | } else {
100 | sendMessage(sender, messagesModule.getUnknownCommand(lang));
101 | }
102 | } else {
103 | sendMessage(sender, messagesModule.getUnknownCommand(lang));
104 | }
105 | } else {
106 | sendMessage(sender, messagesModule.getNoPermission(lang));
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/listeners/ChatListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.listeners;
2 |
3 | import com.velocitypowered.api.event.PostOrder;
4 | import com.velocitypowered.api.event.Subscribe;
5 | import com.velocitypowered.api.event.player.PlayerChatEvent;
6 | import com.velocitypowered.api.proxy.Player;
7 | import dev._2lstudios.chatsentinel.velocity.ChatSentinel;
8 | import dev._2lstudios.chatsentinel.shared.chat.ChatEventResult;
9 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
10 |
11 | public class ChatListener {
12 | private final ChatSentinel plugin;
13 |
14 | public ChatListener(ChatSentinel plugin) {
15 | this.plugin = plugin;
16 | }
17 |
18 | @Subscribe(order = PostOrder.LAST)
19 | public void onChatEvent(PlayerChatEvent event) {
20 | if (!event.getResult().isAllowed()) {
21 | return;
22 | }
23 |
24 | // Sender
25 | Player player = event.getPlayer();
26 |
27 | if (player == null) {
28 | return;
29 | }
30 |
31 | // Check if player has bypass
32 | if (player.hasPermission("chatsentinel.bypass")) {
33 | return;
34 | }
35 |
36 | // Get event variables
37 | String message = event.getMessage();
38 |
39 | // Get chat player
40 | ChatPlayer chatPlayer = plugin.getChatPlayerManager().getPlayer(player);
41 |
42 | // Process the event
43 | ChatEventResult finalResult = plugin.processEvent(chatPlayer, player, message);
44 |
45 | // Apply modifiers to event
46 | if (finalResult.isCancelled()) {
47 | event.setResult(PlayerChatEvent.ChatResult.denied());
48 | } else {
49 | event.setResult(PlayerChatEvent.ChatResult.message(finalResult.getMessage()));
50 | }
51 |
52 | // Set last message
53 | if (event.getResult().isAllowed()) {
54 | chatPlayer.addLastMessage(finalResult.getMessage(), System.currentTimeMillis());
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/listeners/PlayerDisconnectListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.listeners;
2 |
3 | import com.velocitypowered.api.event.Subscribe;
4 | import com.velocitypowered.api.event.connection.DisconnectEvent;
5 | import com.velocitypowered.api.proxy.Player;
6 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
7 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
8 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
9 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
10 |
11 | public class PlayerDisconnectListener {
12 | private final GeneralModule generalModule;
13 | private final ChatPlayerManager chatPlayerManager;
14 | private final ChatNotificationManager chatNotificationManager;
15 |
16 | public PlayerDisconnectListener(GeneralModule generalModule, ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
17 | this.generalModule = generalModule;
18 | this.chatPlayerManager = chatPlayerManager;
19 | this.chatNotificationManager = chatNotificationManager;
20 | }
21 |
22 | @Subscribe
23 | public void onPlayerDisconnect(DisconnectEvent event) {
24 | generalModule.removeNickname(event.getPlayer().getUsername());
25 |
26 | Player player = event.getPlayer();
27 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
28 | if (chatPlayer != null && chatNotificationManager.containsPlayer(chatPlayer)) {
29 | chatNotificationManager.removePlayer(chatPlayer);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/listeners/PostLoginListener.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.listeners;
2 |
3 | import com.velocitypowered.api.event.Subscribe;
4 | import com.velocitypowered.api.event.connection.PostLoginEvent;
5 | import com.velocitypowered.api.proxy.Player;
6 | import dev._2lstudios.chatsentinel.shared.chat.ChatNotificationManager;
7 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayer;
8 | import dev._2lstudios.chatsentinel.shared.chat.ChatPlayerManager;
9 | import dev._2lstudios.chatsentinel.shared.modules.GeneralModule;
10 |
11 | public class PostLoginListener {
12 | private final GeneralModule generalModule;
13 | private final ChatPlayerManager chatPlayerManager;
14 | private final ChatNotificationManager chatNotificationManager;
15 |
16 | public PostLoginListener(GeneralModule generalModule, ChatPlayerManager chatPlayerManager, ChatNotificationManager chatNotificationManager) {
17 | this.generalModule = generalModule;
18 | this.chatPlayerManager = chatPlayerManager;
19 | this.chatNotificationManager = chatNotificationManager;
20 | }
21 |
22 | @Subscribe
23 | public void onPostLogin(PostLoginEvent event) {
24 | Player player = event.getPlayer();
25 | ChatPlayer chatPlayer = chatPlayerManager.getPlayer(player);
26 |
27 | if (chatPlayer != null) {
28 | // Reset the locale of the player if already exists
29 | chatPlayer.setLocale(null);
30 |
31 | // Set notifications
32 | if (player.hasPermission("chatsentinel.notify")) {
33 | chatNotificationManager.addPlayer(chatPlayer);
34 | }
35 |
36 | // Add the nickname
37 | generalModule.addNickname(player.getUsername());
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/modules/VelocityModuleManager.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.modules;
2 |
3 | import dev._2lstudios.chatsentinel.velocity.utils.ConfigUtil;
4 | import dev._2lstudios.chatsentinel.shared.modules.ModuleManager;
5 | import org.spongepowered.configurate.CommentedConfigurationNode;
6 | import org.spongepowered.configurate.ConfigurationNode;
7 |
8 | import java.util.HashMap;
9 | import java.util.Map;
10 | import java.util.stream.Collectors;
11 |
12 | public class VelocityModuleManager extends ModuleManager {
13 | private final ConfigUtil configUtil;
14 |
15 | public VelocityModuleManager(ConfigUtil configUtil) {
16 | this.configUtil = configUtil;
17 | reloadData();
18 | }
19 |
20 | @Override
21 | public void reloadData() {
22 | configUtil.create("config.yml");
23 | configUtil.create("messages.yml");
24 | configUtil.create("blacklist.yml");
25 | configUtil.create("whitelist.yml");
26 |
27 | CommentedConfigurationNode blacklistYml = configUtil.get("blacklist.yml");
28 | CommentedConfigurationNode configYml = configUtil.get("config.yml");
29 | CommentedConfigurationNode messagesYml = configUtil.get("messages.yml");
30 | CommentedConfigurationNode whitelistYml = configUtil.get("whitelist.yml");
31 | Map> locales = new HashMap<>();
32 |
33 | for (Object lang : messagesYml.node("langs").childrenMap().keySet()) {
34 | ConfigurationNode langSection = messagesYml.node("langs", lang);
35 | Map messages = new HashMap<>();
36 |
37 | for (Object key : langSection.childrenMap().keySet()) {
38 | String value = langSection.node(key).getString();
39 |
40 | messages.put((String) key, value);
41 | }
42 |
43 | locales.put((String) lang, messages);
44 | }
45 |
46 | getCapsModule().loadData(configYml.node("caps", "enabled").getBoolean(),
47 | configYml.node("caps", "replace").getBoolean(),
48 | configYml.node("caps", "max").getInt(), configYml.node("caps", "warn", "max").getInt(),
49 | configYml.node("caps", "warn", "notification").getString(),
50 | configYml.node("caps", "punishments").childrenList().stream()
51 | .map(ConfigurationNode::getString)
52 | .toArray(String[]::new));
53 | getCapsModule().loadData(configYml.node("caps", "enabled").getBoolean(),
54 | configYml.node("caps", "replace").getBoolean(),
55 | configYml.node("caps", "max").getInt(), configYml.node("caps", "warn", "max").getInt(),
56 | configYml.node("caps", "warn", "notification").getString(),
57 | configYml.node("caps", "punishments").childrenList().stream()
58 | .map(ConfigurationNode::getString)
59 | .toArray(String[]::new));
60 | getCooldownModule().loadData(configYml.node("cooldown", "enabled").getBoolean(),
61 | configYml.node("cooldown", "time", "repeat-global").getInt(),
62 | configYml.node("cooldown", "time", "repeat").getInt(),
63 | configYml.node("cooldown", "time", "normal").getInt(),
64 | configYml.node("cooldown", "time", "command").getInt());
65 | getFloodModule().loadData(configYml.node("flood", "enabled").getBoolean(),
66 | configYml.node("flood", "replace").getBoolean(),
67 | configYml.node("flood", "warn", "max").getInt(), configYml.node("flood", "pattern").getString(),
68 | configYml.node("flood", "warn", "notification").getString(),
69 | configYml.node("flood", "punishments").childrenList().stream()
70 | .map(ConfigurationNode::getString)
71 | .toArray(String[]::new));
72 | getMessagesModule().loadData(messagesYml.node("default").getString(), locales);
73 | getGeneralModule().loadData(configYml.node("general", "sanitize").getBoolean(true),
74 | configYml.node("general", "sanitize-names").getBoolean(true),
75 | configYml.node("general", "filter-other").getBoolean(false),
76 | configYml.node("general", "commands").childrenList().stream()
77 | .map(ConfigurationNode::getString)
78 | .collect(Collectors.toList()));
79 | getWhitelistModule().loadData(configYml.node("whitelist", "enabled").getBoolean(),
80 | whitelistYml.node("expressions").childrenList().stream()
81 | .map(ConfigurationNode::getString)
82 | .toArray(String[]::new));
83 | boolean censorshipEnabled = configYml.node("blacklist", "censorship", "enabled").getBoolean(false);
84 | String censorshipReplacement = configYml.node("blacklist", "censorship", "replacement").getString("***");
85 | getBlacklistModule().loadData(configYml.node("blacklist", "enabled").getBoolean(),
86 | configYml.node("blacklist", "fake_message").getBoolean(),
87 | censorshipEnabled,
88 | censorshipReplacement,
89 | configYml.node("blacklist", "warn", "max").getInt(),
90 | configYml.node("blacklist", "warn", "notification").getString(),
91 | configYml.node("blacklist", "punishments").childrenList().stream()
92 | .map(ConfigurationNode::getString)
93 | .toArray(String[]::new),
94 | blacklistYml.node("expressions").childrenList().stream()
95 | .map(ConfigurationNode::getString)
96 | .toArray(String[]::new),
97 | configYml.node("blacklist", "block_raw_message").getBoolean());
98 | getSyntaxModule().loadData(configYml.node("syntax", "enabled").getBoolean(),
99 | configYml.node("syntax", "warn", "max").getInt(),
100 | configYml.node("syntax", "warn", "notification").getString(),
101 | configYml.node("syntax", "whitelist").childrenList().stream()
102 | .map(ConfigurationNode::getString)
103 | .toArray(String[]::new),
104 | configYml.node("syntax", "punishments").childrenList().stream()
105 | .map(ConfigurationNode::getString)
106 | .toArray(String[]::new));
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/utils/ConfigUtil.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.utils;
2 |
3 | import dev._2lstudios.chatsentinel.velocity.ChatSentinel;
4 | import org.spongepowered.configurate.CommentedConfigurationNode;
5 | import org.spongepowered.configurate.ConfigurateException;
6 | import org.spongepowered.configurate.loader.ConfigurationLoader;
7 | import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
8 |
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.nio.file.Files;
12 | import java.nio.file.Path;
13 |
14 | public class ConfigUtil {
15 | private final ChatSentinel plugin;
16 |
17 | public ConfigUtil(ChatSentinel plugin) {
18 | this.plugin = plugin;
19 | }
20 |
21 | public CommentedConfigurationNode get(String file) {
22 | try {
23 | Path dataDirectory = plugin.getDataDirectory();
24 | final ConfigurationLoader loader = YamlConfigurationLoader.builder().path(dataDirectory.resolve(file)).build();
25 | return loader.load();
26 | } catch (ConfigurateException e) {
27 | plugin.getLogger().error("An error occurred while trying to load {} config file.", file, e);
28 | return null;
29 | }
30 | }
31 |
32 | public void create(String file) {
33 | try {
34 | Path dataDirectory = plugin.getDataDirectory();
35 |
36 | if (Files.notExists(dataDirectory)) {
37 | Files.createDirectory(dataDirectory);
38 | }
39 |
40 | Path configFile = dataDirectory.resolve(file);
41 |
42 | if (Files.notExists(configFile)) {
43 | InputStream inputStream = plugin.getClass().getClassLoader()
44 | .getResourceAsStream(file);
45 |
46 | if (inputStream != null) {
47 | Files.copy(inputStream, configFile);
48 | plugin.getLogger().info("File {} has been created!", configFile);
49 | } else {
50 | Files.createFile(configFile);
51 | }
52 | }
53 | } catch (IOException e) {
54 | plugin.getLogger().info("Unable to create configuration file!");
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/src/main/java/dev/_2lstudios/chatsentinel/velocity/utils/Constants.java:
--------------------------------------------------------------------------------
1 | package dev._2lstudios.chatsentinel.velocity.utils;
2 |
3 | public class Constants {
4 | public static final String ID = "chatsentinel";
5 | public static final String NAME = "ChatSentinel";
6 | public static final String VERSION = "1.0.1";
7 | public static final String DESCRIPTION = "Advanced chat management plugin";
8 | public static final String URL = "https://builtbybit.com/resources/23698/";
9 | public static final String AUTHOR = "2LS";
10 | }
--------------------------------------------------------------------------------
/src/main/resources/blacklist.yml:
--------------------------------------------------------------------------------
1 | # This plugin uses Regex for checking messages.
2 | expressions:
3 | # IPs and Websites
4 | - ([\d]{1,3}[., ]{1,}){3,}([\d]{1,3})
5 | - ([ &.,]|^)([\w]{5,})([., ]){1,}(com|org|net|biz|info|name|mobi|kz|tk|server.pro|serv.nu)([ &.,]|$)
6 | # Swearing (Spanish)
7 | - boludito
8 | - chot(o|a)
9 | - concha
10 | - (ca|k)gon
11 | - forrit(o|a)
12 | - fracasad(o|a)
13 | - garcha
14 | - imbecil
15 | - maric(on|a)
16 | - mierda
17 | - ojete
18 | - put(o|a|ito)
19 | - pija
20 | - pelotudo
21 | - poronga
22 | - rat(a|ita)
23 | - ( |^)trol(o|a)( |&)
24 | # Spaglish
25 | - idiot(a)?
26 | # Swearing (English)
27 | - asshole
28 | - bitch
29 | - cunt
30 | - dick
31 | - fuck(er)?
32 | - loser
33 | - pussy
34 | # Miscelaneous
35 | - (LiquidBounce)([ ])(Hacked)([ ])(Client)([ ])(by)([ ])(CCBlueX)
36 |
--------------------------------------------------------------------------------
/src/main/resources/bungee.yml:
--------------------------------------------------------------------------------
1 | name: ${name}
2 | description: ${description}
3 | author: ${author}
4 | version: ${version}
5 | url: ${url}
6 | main: dev._2lstudios.chatsentinel.bungee.ChatSentinel
7 | commands:
8 | chatsentinel:
9 | description: "Main command for ChatSentinel plugin"
10 |
--------------------------------------------------------------------------------
/src/main/resources/config.yml:
--------------------------------------------------------------------------------
1 | # Cleans up whitelisted expressions from the message
2 | # This is basically a bypass for certain patterns
3 | whitelist:
4 | enabled: true
5 |
6 | general:
7 | # If enabled, other checks will ignore non-latin characters to improve detection.
8 | sanitize: true
9 |
10 | # If enabled, other checks will ignore player names to improve detection.
11 | sanitize-names: true
12 |
13 | # Filter and remove non-latin characters from all messages.
14 | filter-other: false
15 |
16 | # Commands that will be treated as normal messages
17 | commands:
18 | - /broadcast
19 | - /ebroadcast
20 | - /bc
21 | - /ebc
22 | - /tell
23 | - /etell
24 | - /msg
25 | - /emsg
26 | - /reply
27 | - /ereply
28 | - /r
29 | - /er
30 | - /global
31 | - /g
32 |
33 | # Checks if the player is using blacklisted words.
34 | blacklist:
35 | enabled: true
36 |
37 | # Show a fake message to the player to make him think his message was sent.
38 | # This doesnt work if the plugin is on BungeeCord.
39 | fake_message: false
40 |
41 | # Hide the words the player wrote with a ***
42 | censorship:
43 | enabled: false
44 | # Replacement to be used
45 | replacement: "***"
46 |
47 | warn:
48 | # Amount of warns required to execute the commands.
49 | # Set to -1 to disable this feature completely.
50 | max: 3
51 |
52 | # Sends a notification to players with chatsentinel.notify permission.
53 | # Set to "" to disable this feature completely.
54 | # You can use %server% on BungeeCord to get the server name.
55 | notification: "&c&lCS: &e%player% &ffailed &6Swearing &7(&c%message%&7)"
56 |
57 | # You need a mute plugin for ChatSentinel to mute players. (Recommended: LiteBans/AdvancedBans)
58 | # Set to [] to disable this feature completely.
59 | punishments:
60 | - "mute -s %player% Offensive Language (%message%) 1d"
61 |
62 | # if fake_message is false
63 | # and if censorship is false
64 | # The message will be cancelled.
65 | block_raw_message: true
66 |
67 | # Checks if messages have too many caps.
68 | caps:
69 | enabled: true
70 |
71 | # If this is true it will replace the caps with low-case letters.
72 | replace: true
73 |
74 | # Maximum amount of caps allowed.
75 | max: 8
76 |
77 | warn:
78 | # Amount of warns required to execute the commands.
79 | # Set to -1 to disable this feature completely.
80 | max: -1
81 |
82 | # Sends a notification to players with chatsentinel.notify permission.
83 | # Set to "" to disable this feature completely.
84 | notification: "&c&lCS: &e%player% &ffailed &6Caps &7(&c%message%&7)"
85 |
86 | # You need a mute plugin for ChatSentinel to mute players. (Recommended: LiteBans/AdvancedBans)
87 | # Set to [] to disable this feature completely.
88 | punishments: []
89 |
90 | # Checks if player is chatting too fast.
91 | cooldown:
92 | enabled: true
93 |
94 | # Time in milliseconds.
95 | time:
96 | repeat-global: 1000
97 | repeat: 10000
98 | normal: 1000
99 | command: 400
100 |
101 | # Checks if player is using too many repeated characters.
102 | flood:
103 | enabled: true
104 |
105 | # If this is true it will replace the flood instead of cancelling it.
106 | # Example: Heloooooo would be converted to just Helloo
107 | replace: true
108 |
109 | # Regex pattern to do the checks and replacement.
110 | pattern: (\w)\1{5,}|(\w{28,})|([^\wñ]{20,})|(^.{220,}$)
111 |
112 | warn:
113 | # Amount of warns required to execute the commands.
114 | # Set to -1 to disable this feature completely.
115 | max: -1
116 |
117 | # Sends a notification to players with chatsentinel.notify permission.
118 | # Set to "" to disable this feature completely.
119 | notification: "&c&lCS: &e%player% &ffailed &6Flood &7(&c%message%&7)"
120 |
121 | # You need a mute plugin for ChatSentinel to mute players. (Recommended: LiteBans/AdvancedBans)
122 | # Set to [] to disable this feature completely.
123 | punishments: []
124 |
125 | # Checks if the player is using syntax.
126 | # Example: testplugin:testcommand
127 | syntax:
128 | # Do you want to enable this module?
129 | enabled: true
130 |
131 | # Syntax commands that will not be checked.
132 | # Set to {} to disable whitelist.
133 | whitelist:
134 | - "/strikepractice:"
135 |
136 | warn:
137 | # Amount of warns required to execute the commands.
138 | # Set to -1 to disable this feature completely.
139 | max: -1
140 |
141 | # Sends a notification to players with chatsentinel.notify permission.
142 | # Set to "" to disable this feature completely.
143 | notification: "&c&lCS: &e%player% &ffailed &6Syntax &7(&c%message%&7)"
144 |
145 | # You need a mute plugin for ChatSentinel to mute players. (Recommended: LiteBans/AdvancedBans)
146 | # Set to [] to disable this feature completely.
147 | punishments: []
148 |
--------------------------------------------------------------------------------
/src/main/resources/messages.yml:
--------------------------------------------------------------------------------
1 | # You can add as many languages as you want.
2 | # The language will change depending on the client language.
3 | # Supported Languages: https://minecraft.gamepedia.com/Language
4 | default: "en"
5 |
6 | # You can add as many languages as you want.
7 | langs:
8 | en:
9 | cleared: "&aThe chat was cleared by &b%player%&a!"
10 | reload: "&c&lCS: &aPlugin successfully reloaded!"
11 | help: |-
12 | &aChatSentinel commands:
13 | &e/chatsentinel help &7- &bShows this help message!
14 | &e/chatsentinel reload &7- &bReloads the plugin!
15 | unknown_command: "&cUnknown command. Use /chatsentinel help to see available commands!"
16 | no_permission: "&cYou dont have permission to use this command!"
17 | blacklist_warn_message: "&c&lCS: &cYou cant type '%message%'! (%warns%/%maxwarns%)"
18 | caps_warn_message: "&c&lCS: &cYou are using too many caps!"
19 | cooldown_warn_message: "&c&lCS: &cWait %cooldown%s before sending another message!"
20 | flood_warn_message: "&c&lCS: &cYou cant send too large messages!"
21 | syntax_warn_message: "&c&lCS: &cSyntax is disabled in this server!"
22 | filtered: "&c&lCS: &cYour message was filtered by ChatSentinel! (Characters not allowed)"
23 | notify-enabled: "&aChatSentinel notifications are now enabled!"
24 | notify-disabled: "&cChatSentinel notifications are now disabled!"
25 | es:
26 | cleared: "&aEl chat fue limpiado por &b%player%&a!"
27 | reload: "&c&lCS: &aPlugin recargado correctamente!"
28 | help: |-
29 | &aComandos de ChatSentinel:
30 | &e/chatsentinel help &7- &bMira este mensaje de ayuda!
31 | &e/chatsentinel reload &7- &bRecarga el plugin!
32 | unknown_command: "&cComando desconocido. Usa /chatsentinel help para ver comandos disponibles!"
33 | no_permission: "&cNo tienes permisos para usar este comando!"
34 | blacklist_warn_message: "&c&lCS: &cNo puedes escribir '%message%'! (%warns%/%maxwarns%)"
35 | caps_warn_message: "&c&lCS: &cEstas usando demasiadas mayusculas!"
36 | cooldown_warn_message: "&c&lCS: &cEspera %cooldown%s antes de enviar otro mensaje!"
37 | flood_warn_message: "&c&lCS: &cNo puedes enviar mensajes tan largos!"
38 | syntax_warn_message: "&c&lCS: &cLa sintaxis esta deshabilitada en este servidor!"
39 | filtered: "&c&lCS: &cTu mensaje fue filtrado por ChatSentinel! (Caracteres no permitidos)"
40 | notify-enabled: "&a¡Las notificaciones de ChatSentinel ahora están habilitadas!"
41 | notify-disabled: "&c¡Las notificaciones de ChatSentinel ahora están deshabilitadas!"
42 | pt-br:
43 | cleared: "&aO bate-papo foi limpo por &b%player%&a!"
44 | reload: "&c&lCS: &aPlugin recarregado com sucesso!"
45 | help: |-
46 | &aComandos do ChatSentinel:
47 | &e/chatsentinel help &7- &bMostra essa mensagem de ajuda!
48 | &e/chatsentinel reload &7- &bRecarrega o plugin!
49 | unknown_command: "&cComando desconhecido. Use /chatsentinel help para ver os comandos disponíveis!"
50 | no_permission: "&cVocê não tem permissão para executar este comando!"
51 | blacklist_warn_message: "&c&lCS: &cVocê não pode digitar '%message%'! (%warns%/%maxwarns%)"
52 | caps_warn_message: "&c&lCS: &cVocê está digitando muitas letras maiúsculas!"
53 | cooldown_warn_message: "&c&lCS: &cEspere %cooldown%s antes de enviar outra mensagem!"
54 | flood_warn_message: "&c&lCS: &cVocê não pode enviar mensagens muito grandes!"
55 | syntax_warn_message: "&c&lCS: &cA sintaxe está desativada neste servidor!"
56 | filtered: "&c&lCS: &cSua mensagem foi filtrada pelo ChatSentinel! (Caracteres não permitidos)"
57 | notify-enabled: "&aAs notificações do ChatSentinel agora estão ativadas!"
58 | notify-disabled: "&cAs notificações do ChatSentinel agora estão desativadas!"
59 |
--------------------------------------------------------------------------------
/src/main/resources/plugin.yml:
--------------------------------------------------------------------------------
1 | name: ${name}
2 | description: ${description}
3 | author: ${author}
4 | version: ${version}
5 | url: ${url}
6 | main: dev._2lstudios.chatsentinel.bukkit.ChatSentinel
7 | api: "1.13"
8 | api-version: "1.13"
9 | commands:
10 | chatsentinel:
11 | description: "Main command for ChatSentinel plugin"
--------------------------------------------------------------------------------
/src/main/resources/whitelist.yml:
--------------------------------------------------------------------------------
1 | # This plugin uses Regex for checking messages.
2 | # Set to [] to disable whitelist completely.
3 | expressions:
4 | # Server Domains
5 | - (yourserver)([.])(com)
6 | # Long Youtube Links
7 | - (youtube)([.])(com)(/watch)
8 |
--------------------------------------------------------------------------------