From 7b2f3f55a5f7402731226975055845a876ec60ff Mon Sep 17 00:00:00 2001 From: AndrewR3K <10902965+AndrewR3K@users.noreply.github.com> Date: Wed, 20 Nov 2024 20:28:54 -0800 Subject: [PATCH] first commit --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++ README.md | 71 ++++ client/client.lua | 512 +++++++++++++++++++++++++++ client/clientAimandKill.lua | 350 +++++++++++++++++++ config.lua | 17 + fxmanifest.lua | 26 ++ languages/en_lang.lua | 55 +++ languages/ro_lang.lua | 55 +++ locale.lua | 45 +++ server/server.lua | 600 ++++++++++++++++++++++++++++++++ server/txAdminhandlers.lua | 88 +++++ version | 2 + 12 files changed, 2495 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 client/client.lua create mode 100644 client/clientAimandKill.lua create mode 100644 config.lua create mode 100644 fxmanifest.lua create mode 100644 languages/en_lang.lua create mode 100644 languages/ro_lang.lua create mode 100644 locale.lua create mode 100644 server/server.lua create mode 100644 server/txAdminhandlers.lua create mode 100644 version diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8a04e53 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# bcc-userlog + +> This script provides an in-depth and immersive user logging system for tracking player activity! With features like total playtime tracking, session times, leaderboards, and more, this script offers a quality experience for both players and administrators. + +## Features + +- **Playtime Tracking**: Accurately tracks total playtime and session durations for each player. +- **Leaderboards**: Provides daily, weekly, and monthly leaderboards to showcase the most active players. +- **Automatic Resets**: Leaderboards reset automatically at the end of each day, week, and month. +- **Historical Data**: Stores historical leaderboard data for administrative review. +- **Player Commands**: + - `/ore` – Shows your total accumulated playtime. + - `/ultimasesiune` – Displays details about your last game session. + - `/clasament` – Opens the leaderboard menu to view top players. +- **Admin Commands**: + - `/userlog` – Opens the user log system with detailed player information (admin access only). +- **Player Details**: Administrators can view detailed information about players, including identifiers, playtime, and account status. +- **Localization**: Easy to translate with support for multiple languages (English and Romanian included). +- **Discord Integration**: In-depth webhooks for player connection and disconnection notifications. +- **Version Checking**: Helps you keep the script up to date with automatic version checks. + +## How It Works + +- **Playtime Accumulation**: The script tracks when players connect and disconnect, calculating their session durations and adding them to their total playtime. +- **Leaderboards**: Players' playtimes are compiled into daily, weekly, and monthly leaderboards, which reset automatically at specified intervals. +- **Data Storage**: All player data and leaderboard histories are stored in the database, ensuring persistence and accuracy. +- **Admin Interface**: Administrators can access a dedicated menu to view player logs and leaderboard histories, manage player data, and more. +- **Player Interaction**: Players can use in-game commands to check their own playtime stats and view leaderboards to see how they rank among others. + +## How to Install + +1. **Download and Install Dependencies**: Ensure all required scripts and dependencies are installed and running. +2. **Add the Script**: Place the `bcc-userlog` script into your server's resources folder. +3. **Configure the Script**: + - Edit the `config.lua` file to adjust settings such as command names, permissions, and other options. + - Customize localization files if needed. +4. **Start the Script**: + - Add `ensure bcc-userlog` to your server configuration file (`server.cfg`). +5. **Database Setup**: + - The script will automatically create the necessary database tables upon first launch. + - If required, run any provided SQL files to set up the database schema. +6. **Restart the Server**: Restart your server to load the new script and apply all changes. + +## Commands + +- **Player Commands**: + - `/playtime` – Displays your total playtime on the server. + - `/lastsession` – Shows information about your last game session, including duration. + - `/leaderboard` – Opens the leaderboard menu to view daily, weekly, and monthly top players. +- **Admin Commands** (restricted to authorized staff): + - `/userlog` – Accesses the user log system with detailed player information and leaderboard history. + +## Requirements + +- vorp_core +- vorp_character +- feather-menu +- bcc-utils +- MySQL database + +## Side Notes + +- **Feedback and Support**: This is a comprehensive project, and we welcome any suggestions or bug reports. Please share your feedback to help us improve! +- **Leaderboard History**: Currently, only administrators can view the leaderboard history to monitor player activity over time. +- **Data Privacy**: Ensure you handle player data responsibly and comply with any applicable privacy regulations. +- **Customization**: The script is designed to be easily customizable and translatable. Adjust settings and localization files to fit your server's needs. +- **Join Our Community**: Need assistance or want to stay updated? Join the BCC Discord community: [Discord Link](https://discord.gg/VrZEEpBgZJ) + +--- + +Thank you for choosing `bcc-userlog`! We hope this script enhances your server's player engagement and management capabilities. diff --git a/client/client.lua b/client/client.lua new file mode 100644 index 0000000..d0a8029 --- /dev/null +++ b/client/client.lua @@ -0,0 +1,512 @@ +Core = exports.vorp_core:GetCore() +local FeatherMenu = exports["feather-menu"].initiate() + +BCCUserLogMenu = FeatherMenu:RegisterMenu("bcc:bcc-userlog:mainmenu", + { + top = '3%', + left = '3%', + ['720width'] = '400px', + ['1080width'] = '500px', + ['2kwidth'] = '600px', + ['4kwidth'] = '800px', + style = {}, + contentslot = { + style = { + ['height'] = '350px', + ['min-height'] = '250px' + } + }, + draggable = true, + canclose = true + }, + { + opened = function() + DisplayRadar(false) + end, + closed = function() + DisplayRadar(true) + end + } +) + +local AdminAllowed, userListRequested, currentUsersList = false, false, {} + +-- Helper function for debugging in DevMode +if Config.devMode then + function devPrint(message) + print("^1[DEV MODE] ^4" .. message) + end +else + function devPrint(message) end -- No-op if DevMode is disabled +end + +RegisterNetEvent('vorp:SelectedCharacter') +AddEventHandler('vorp:SelectedCharacter', function() + TriggerServerEvent('bcc-userlog:AdminCheck') +end) + +Citizen.CreateThread(function() + while not NetworkIsPlayerActive(PlayerId()) do + Citizen.Wait(1000) + end + devPrint("Player fully loaded, triggering server event.") + TriggerServerEvent('playerFullyLoaded') + + if Config.devMode then + TriggerServerEvent('bcc-userlog:AdminCheck') + end +end) + +RegisterNetEvent('bcc-userlog:sendUserList') +AddEventHandler('bcc-userlog:sendUserList', function(users) + devPrint("Received user list from server.") + currentUsersList = users + openUserLogMenu() + userListRequested = false -- Reset flag after receiving the user list +end) + +RegisterNetEvent('bcc-userlog:sendUserDetails') +AddEventHandler('bcc-userlog:sendUserDetails', function(userDetails) + devPrint("Received user details for user: " .. (userDetails.players_displayName or _U("unknown_user"))) + openUserDetailsMenu(userDetails) -- Open detailed view with the received data +end) + +RegisterNetEvent('bcc-userlog:AdminClientCheck') +AddEventHandler('bcc-userlog:AdminClientCheck', function(isAdmin) + AdminAllowed = isAdmin + devPrint("AdminAllowed set to: " .. tostring(AdminAllowed)) +end) + +RegisterCommand(Config.AdminManagementMenuCommand, function() + devPrint("AdminAllowed: " .. tostring(AdminAllowed)) + devPrint("userListRequested: " .. tostring(userListRequested)) + + if AdminAllowed then + if not userListRequested then + devPrint("Requesting user list from server...") + userListRequested = true + TriggerServerEvent('bcc-userlog:fetchUsers') + else + devPrint("Opening user log menu directly.") + openUserLogMenu() + end + else + devPrint("User does not have admin permissions.") + end +end) + +function formatPlaytime(playTimeMinutes) + local days = math.floor(playTimeMinutes / 1440) + local remainingMinutesAfterDays = playTimeMinutes % 1440 + local hours = math.floor(remainingMinutesAfterDays / 60) + local minutes = remainingMinutesAfterDays % 60 + return string.format("%d" .. _U("totalDays") .. "%d" .. _U("totalHours") .. "%d" .. _U("totalMintutes"), days, hours, minutes) +end + +function openUserLogMenu() + devPrint("Opening user log main menu.") + + local userLogMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:MainPage") + + -- Set up header + userLogMenu:RegisterElement('header', { + value = _U("user_log_system"), + slot = 'header', + style = {} + }) + + userLogMenu:RegisterElement('line', { + style = {}, + slot = 'header' + }) + + -- Button to open Leaderboard History + userLogMenu:RegisterElement('button', { + label = _U('leaderboardHistory'), + style = {}, + }, function() + openLeaderboardHistoryMenu() -- Opens the leaderboard history menu + end) + + -- Button to open Player List + userLogMenu:RegisterElement('button', { + label = _U('playerList'), + style = {}, + }, function() + openPlayerListMenu() -- Opens the player list menu + end) + + -- Footer instructions + userLogMenu:RegisterElement('bottomline', { + style = {}, + slot = "footer" + }) + + TextDisplay = userLogMenu:RegisterElement('textdisplay', { + value = _U('selectAnOption'), + style = { fontSize = '20px', textAlign = 'center', padding = '10px' }, + slot = "footer" + }) + + devPrint("Opening user log main menu.") + BCCUserLogMenu:Open({ startupPage = userLogMenu }) +end + +-- Function to open the Player List menu +function openPlayerListMenu() + devPrint("Opening player list menu.") + + local playerListMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:PlayerListPage") + + -- Header for Player List + playerListMenu:RegisterElement('header', { + value = _U('playerList'), + slot = 'header', + style = { fontSize = '24px', textAlign = 'center', color = '#FFD700' } + }) + + playerListMenu:RegisterElement('line', { + style = {}, + slot = 'header' + }) + + -- Add each player in the list + if #currentUsersList > 0 then + for _, user in ipairs(currentUsersList) do + local userName = user.name or _U("unknown_user") + local userID = user.id or _U("na") + + playerListMenu:RegisterElement('button', { + label = userName, + style = {}, + }, function() + devPrint("Fetching details for user ID: " .. userID) + TriggerServerEvent('bcc-userlog:fetchUserDetails', userID) + end) + end + else + playerListMenu:RegisterElement('textdisplay', { + value = _U('noUsersAvailable'), + style = { fontSize = '18px', textAlign = 'center', padding = '10px' } + }) + end + + -- Footer instructions + playerListMenu:RegisterElement('bottomline', { + style = {}, + slot = "footer" + }) + + TextDisplay = playerListMenu:RegisterElement('textdisplay', { + value = _U('selectAPlayer'), + style = { fontSize = '20px', textAlign = 'center', padding = '10px' }, + slot = "footer" + }) + + devPrint("Opening player list menu.") + BCCUserLogMenu:Open({ startupPage = playerListMenu }) +end + +-- Function to open the Leaderboard History menu +function openLeaderboardHistoryMenu() + devPrint("Opening leaderboard history menu.") + + local leaderboardHistoryMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:LeaderboardHistoryPage") + + -- Header for Leaderboard History + leaderboardHistoryMenu:RegisterElement('header', { + value = _U('leaderboardHistory'), + slot = 'header', + style = { fontSize = '24px', textAlign = 'center', color = '#FFD700' } + }) + + -- Buttons for Daily, Weekly, and Monthly Leaderboards + leaderboardHistoryMenu:RegisterElement('button', { + label = _U('yesterdayHistory'), + style = {}, + }, function() + TriggerServerEvent('bcc-userlog:fetchLeaderboardHistory', "daily") + end) + + leaderboardHistoryMenu:RegisterElement('button', { + label = _U('weeklyHistory'), + style = {}, + }, function() + TriggerServerEvent('bcc-userlog:fetchLeaderboardHistory', "weekly") + end) + + leaderboardHistoryMenu:RegisterElement('button', { + label = _U('monthlyHistory'), + style = {}, + }, function() + TriggerServerEvent('bcc-userlog:fetchLeaderboardHistory', "monthly") + end) + + -- Open the leaderboard history menu + BCCUserLogMenu:Open({ startupPage = leaderboardHistoryMenu }) +end + +RegisterNetEvent('bcc-userlog:displayLeaderboardHistory') +AddEventHandler('bcc-userlog:displayLeaderboardHistory', function(leaderboardData, title) + local leaderboardTitle = tostring(title or _U("leaderboardHistory")) + local leaderboardHTML = string.format([[

%s

]], leaderboardTitle) + + leaderboardHTML = leaderboardHTML .. [[ + + + + + + ]] + + -- Check if leaderboardData contains any records + if leaderboardData and #leaderboardData > 0 then + for i, player in ipairs(leaderboardData) do + local playerName = tostring(player.player_displayName or _U("unknown_user")) + local playTime = tonumber(player.playtime) or 0 + local hours = math.floor(playTime / 3600) + local minutes = math.floor((playTime % 3600) / 60) + local seconds = playTime % 60 + local formattedPlayTime = string.format("%02d:%02d:%02d", hours, minutes, seconds) + + -- Add each player's row to the table + leaderboardHTML = leaderboardHTML .. string.format([[]], i, playerName, formattedPlayTime) + end + else + -- Display a message if no data is available + leaderboardHTML = leaderboardHTML .. [[]] + end + + leaderboardHTML = leaderboardHTML .. "
]] .. _U("rank") .. [[]] .. _U("player") .. [[]] .. _U("playtime") .. [[
%d%s%s
]] .. _U("no_data_available") .. [[
" + + -- Display the leaderboard data in the menu + local leaderboardHistoryMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:LeaderboardHistoryPage") + leaderboardHistoryMenu:RegisterElement('html', { + value = leaderboardHTML, + slot = 'content', + style = {} + }) + + BCCUserLogMenu:Open({ startupPage = leaderboardHistoryMenu }) +end) + +function openUserDetailsMenu(user) + devPrint("User object received: " .. json.encode(user)) + local formattedPlaytime = formatPlaytime(user.players_playTime or 0) + local htmlContent = string.format([[ +
+
+
+

%s

+

%s: %s

+

%s: %s

+

%s: %s

+

%s: %s

+

%s: $%s

+

%s: %s

+
+
+
+

%s

+
    +
  • %s: %s
  • +
  • %s: %s
  • +
  • %s: %s
  • +
  • %s: %s
  • +
  • %s: %s
  • +
  • %s: %s
  • +
  • %s: %s
  • +
+
+
+ ]], + user.players_displayName or _U("unknown_user"), + _U("playtime"), formattedPlaytime, + _U("last_connection"), user.formattedLastConnection or _U("na"), + _U("joined"), user.formattedJoined or _U("na"), + _U("character_id"), user.characterDetails.charIdentifier or _U("na"), + _U("money"), user.characterDetails.money or "0.00", + _U("gold"), user.characterDetails.gold or "0.00", + _U("identifiers"), + _U("discord_id"), user.discord_id or _U("na"), + _U("license"), user.license or _U("na"), + _U("fivem_id"), user.fivem_id or _U("na"), + _U("license2"), user.license2 or _U("na"), + _U("steam_id"), user.steam_id or _U("na"), + _U("live_id"), user.live_id or _U("na"), + _U("xbl_id"), user.xbl_id or _U("na") + ) + + local detailsMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:DetailsPage") + + detailsMenu:RegisterElement('header', { + value = _U("user_details"), + slot = 'header', + style = {} + }) + + detailsMenu:RegisterElement("html", { + value = { htmlContent }, + slot = 'content', + style = {} + }) + + detailsMenu:RegisterElement('line', { + style = {}, + slot = "footer" + }) + + detailsMenu:RegisterElement('button', { + label = _U("back_to_users"), + slot = "footer", + style = {} + }, function() + devPrint("Returning to main user log menu.") + openUserLogMenu() + end) + + detailsMenu:RegisterElement('bottomline', { + style = {}, + slot = "footer" + }) + + TextDisplay = detailsMenu:RegisterElement('textdisplay', { + value = _U('detailed_user_information'), + style = { fontSize = '20px', textAlign = 'center', padding = '10px' }, + slot = "footer" + }) + + devPrint("Opening details menu for user: " .. (user.players_displayName or _U("unknown_user"))) + BCCUserLogMenu:Open({ startupPage = detailsMenu }) +end +RegisterNetEvent('bcc-userlog:displayLeaderboard') +AddEventHandler('bcc-userlog:displayLeaderboard', function(leaderboardData, leaderboardTitle) + displayLeaderboardMenu(leaderboardData, leaderboardTitle) +end) + +RegisterNetEvent('bcc-userlog:openMainLeaderboardMenu') +AddEventHandler('bcc-userlog:openMainLeaderboardMenu', function() + local mainLeaderboardMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:LeaderbordMainPage") + + -- Set the header/title for the menu + mainLeaderboardMenu:RegisterElement('header', { + value = _U("selectLeaderboardType"), + slot = 'header', + style = { fontSize = '24px', textAlign = 'center', color = '#FFD700' } + }) + + -- Daily leaderboard button + mainLeaderboardMenu:RegisterElement('button', { + label = _U("dailyLeaderboard"), + style = {} + }, function() + TriggerServerEvent('bcc-userlog:requestLeaderboardData', "daily") + end) + + -- Weekly leaderboard button + mainLeaderboardMenu:RegisterElement('button', { + label = _U("weeklyLeaderboard"), + style = {} + }, function() + TriggerServerEvent('bcc-userlog:requestLeaderboardData', "weekly") + end) + + -- Monthly leaderboard button + mainLeaderboardMenu:RegisterElement('button', { + label = _U("monthlyLeaderboard"), + style = {} + }, function() + TriggerServerEvent('bcc-userlog:requestLeaderboardData', "monthly") + end) + + -- Open the main leaderboard menu + BCCUserLogMenu:Open({ startupPage = mainLeaderboardMenu }) +end) + +function displayLeaderboardMenu(leaderboardData, leaderboardTitle) + local leaderboardMenu = BCCUserLogMenu:RegisterPage("bcc-userlog:leaderBoardMenu") + + -- Set the header/title for the menu + leaderboardMenu:RegisterElement('header', { + value = leaderboardTitle, + slot = 'header', + style = { fontSize = '24px', textAlign = 'center', color = '#FFD700' } + }) + + -- Define HTML content for the leaderboard + local leaderboardHTML = [[ +
+ + + + + + + ]] + + if #leaderboardData > 0 then + for i, player in ipairs(leaderboardData) do + local playerName = player.players_displayName or _U("unknown_user") + local playTime = player.players_dailyPlayTime or player.players_weeklyPlayTime or player.players_monthlyPlayTime or 0 + + -- Format playtime as hours, minutes, and seconds + local hours = math.floor(playTime / 3600) + local minutes = math.floor((playTime % 3600) / 60) + local seconds = playTime % 60 + local formattedPlayTime = string.format("%02d:%02d:%02d", hours, minutes, seconds) + + -- Alternate row colors with opacity + local rowColor = i % 2 == 0 and "rgba(249, 249, 249, 0.3)" or "rgba(239, 239, 239, 0.3)" + + -- Add each player's row to the table + leaderboardHTML = leaderboardHTML .. string.format([[ + + + + ]], rowColor, i, playerName, formattedPlayTime) + end + else + leaderboardHTML = leaderboardHTML .. [[ + + + + ]] + end + + -- Close the table and div + leaderboardHTML = leaderboardHTML .. "
]] .. _U("rank") .. [[]] .. _U("player") .. [[]] .. _U("playtime") .. [[
%d%s%s
]] .. _U("no_data_available") .. [[
" + + -- Register HTML content in Feather Menu + leaderboardMenu:RegisterElement("html", { + value = { leaderboardHTML }, + slot = 'content', + style = { padding = '10px' } + }) + leaderboardMenu:RegisterElement('line', { + style = {}, + slot = "footer" + }) + + -- Register the "Back to Leaderboard" button + leaderboardMenu:RegisterElement('button', { + label = _U("backToLeaderboard"), + slot = "footer", + style = {} + }, function() + TriggerEvent('bcc-userlog:openMainLeaderboardMenu') + end) + + leaderboardMenu:RegisterElement('bottomline', { + style = {}, + slot = "footer" + }) + + TextDisplay = leaderboardMenu:RegisterElement('textdisplay', { + value = _U("additionalInfo"), + style = { fontSize = '20px', textAlign = 'center', padding = '10px' }, + slot = "footer" + }) + + -- Open the leaderboard menu + BCCUserLogMenu:Open({ startupPage = leaderboardMenu }) +end diff --git a/client/clientAimandKill.lua b/client/clientAimandKill.lua new file mode 100644 index 0000000..909a35a --- /dev/null +++ b/client/clientAimandKill.lua @@ -0,0 +1,350 @@ + +Citizen.CreateThread(function() + instanceNumber = math.random(1, 100000 + tonumber(GetPlayerServerId(PlayerPedId()))) + Core.instancePlayers(tonumber(GetPlayerServerId(PlayerId())) + instanceNumber) +end) + +Citizen.CreateThread(function() + instanceNumber = math.random(1, 100000 + tonumber(GetPlayerServerId(PlayerPedId()))) + Core.instancePlayers(tonumber(GetPlayerServerId(PlayerId())) + instanceNumber) +end) + +local lastPedAimed = nil +Citizen.CreateThread(function() + while true do + Citizen.Wait(1000) + local playerPed = PlayerPedId() + local exists, playerWeapon = GetCurrentPedWeapon(playerPed) + + if DoesEntityExist(playerPed) and IsPedArmed(playerPed, 4) then + local isAiming, targetPed = GetEntityPlayerIsFreeAimingAt(PlayerId()) + + -- Ensure targetPed is the correct reference by checking its existence + if isAiming and DoesEntityExist(targetPed) and targetPed ~= lastPedAimed then + lastPedAimed = targetPed + local weaponName = WeaponNames[tostring(playerWeapon)] or "Unknown Weapon" + + print("Player is aiming with weapon:", weaponName) + + if IsEntityAPed(targetPed) then + local isPlayer = IsPedAPlayer(targetPed) + + if isPlayer then + -- If the target is a player + local targetId = NetworkGetPlayerIndexFromPed(targetPed) + if targetId then + local pedId = GetPlayerServerId(targetId) + if pedId and (pedId > 0) then + print("Triggering player aim log event for target ID:", pedId) + TriggerServerEvent('bcc-logs:aimlogs', pedId) + end + end + else + -- If the target is an NPC, check if they have a weapon equipped + local hasWeapon, npcWeapon = GetCurrentPedWeapon(targetPed, true) + + if hasWeapon and npcWeapon ~= `WEAPON_UNARMED` then + local npcWeaponName = WeaponNames[tostring(npcWeapon)] or "Unknown Weapon" + print("NPC is equipped with weapon:", npcWeaponName) + print("Triggering NPC aim log event for NPC weapon:", npcWeaponName) + TriggerServerEvent('bcc-logs:npcAimLogs', "NPC", npcWeaponName) + else + print("NPC does not have a weapon equipped or is unarmed.") + end + end + else + print("Aimed target is not a ped or entity does not exist.") + end + else + if not isAiming then + print("Player is not currently aiming.") + elseif targetPed == lastPedAimed then + print("Player is still aiming at the same target.") + end + end + else + print("Player is either not armed or player entity does not exist.") + end + end +end) + +Citizen.CreateThread(function() + local DeathReason, Killer, DeathCauseHash, Weapon + while true do + Citizen.Wait(1000) + local playerPed = PlayerPedId() + + if IsEntityDead(playerPed) then + Citizen.Wait(500) + local PedKiller = GetPedSourceOfDeath(playerPed) + DeathCauseHash = GetPedCauseOfDeath(playerPed) + Weapon = WeaponNames[DeathCauseHash] or "Unknown Weapon" + + if IsEntityAPed(PedKiller) then + if IsPedAPlayer(PedKiller) then + -- Player killer + Killer = NetworkGetPlayerIndexFromPed(PedKiller) + DeathReason = determineDeathReason(DeathCauseHash) + TriggerServerEvent('bcc-logs:killlogs', GetPlayerName(Killer) .. '['..GetPlayerServerId(Killer).. '] ' .. DeathReason .. ' ' .. GetPlayerName(PlayerId()) .. '['..GetPlayerServerId(PlayerId())..']', Weapon) + else + -- NPC killer + DeathReason = determineDeathReason(DeathCauseHash) + TriggerServerEvent('bcc-logs:killlogs', "Killed by NPC", DeathReason .. ' ' .. GetPlayerName(PlayerId()) .. '['..GetPlayerServerId(PlayerId())..']', Weapon) + end + elseif IsEntityAVehicle(PedKiller) and IsEntityAPed(GetPedInVehicleSeat(PedKiller, -1)) then + -- Death caused by a player or NPC in a vehicle + local vehicleKiller = GetPedInVehicleSeat(PedKiller, -1) + if IsPedAPlayer(vehicleKiller) then + Killer = NetworkGetPlayerIndexFromPed(vehicleKiller) + DeathReason = determineDeathReason(DeathCauseHash) + TriggerServerEvent('bcc-logs:killlogs', GetPlayerName(Killer) .. '['..GetPlayerServerId(Killer).. '] ' .. DeathReason .. ' ' .. GetPlayerName(PlayerId()) .. '['..GetPlayerServerId(PlayerId())..']', Weapon) + else + DeathReason = determineDeathReason(DeathCauseHash) + TriggerServerEvent('bcc-logs:killlogs', "Killed by NPC (Vehicle)", DeathReason .. ' ' .. GetPlayerName(PlayerId()) .. '['..GetPlayerServerId(PlayerId())..']', Weapon) + end + else + -- Self-inflicted or unknown cause + DeathReason = 'committed suicide' or 'died' + TriggerServerEvent('bcc-logs:killlogs', GetPlayerName(PlayerId()) .. ' ' .. DeathReason .. '.', Weapon) + end + + -- Reset variables after logging + Killer, DeathReason, DeathCauseHash, Weapon = nil, nil, nil, nil + end + + while IsEntityDead(playerPed) do + Citizen.Wait(0) + end + end +end) + +-- Updated helper function to determine death reason based on weapon hash +function determineDeathReason(weaponHash) + local readableWeaponName = getReadableWeaponName(weaponHash) + + if IsMelee(weaponHash) then + return 'murdered with a ' .. readableWeaponName + elseif IsPistol(weaponHash) or IsRepeater(weaponHash) or IsRevolver(weaponHash) or IsRifle(weaponHash) then + return 'shot with a ' .. readableWeaponName + elseif IsShotgun(weaponHash) then + return 'blasted with a ' .. readableWeaponName + elseif IsSniper(weaponHash) then + return 'sniped with a ' .. readableWeaponName + elseif IsThrown(weaponHash) then + return 'exploded by a ' .. readableWeaponName + elseif IsHeldWeapon(weaponHash) or IsBow(weaponHash) then + return 'struck with a ' .. readableWeaponName + elseif IsSpecialWeapon(weaponHash) then + return 'captured with a ' .. readableWeaponName + elseif IsUnarmed(weaponHash) then + return 'attacked by an animal' .. readableWeaponName + elseif IsEnvironmental(weaponHash) then + return 'killed by environment'.. readableWeaponName + else + return 'killed with a ' .. readableWeaponName + end +end + +-- Define melee weapons +function IsMelee(weaponHash) + local meleeWeapons = { + 'WEAPON_MELEE_HATCHET_MELEEONLY', 'WEAPON_MELEE_KNIFE_MINER', 'WEAPON_MELEE_KNIFE_JAWBONE', + 'WEAPON_MELEE_KNIFE_VAMPIRE', 'WEAPON_MELEE_KNIFE_JOHN', 'WEAPON_MELEE_MACHETE', + 'WEAPON_MELEE_KNIFE_BEAR', 'WEAPON_MELEE_KNIFE_DUTCH', 'WEAPON_MELEE_KNIFE_KIERAN', + 'WEAPON_MELEE_KNIFE_UNCLE', 'WEAPON_MELEE_KNIFE_SEAN', 'WEAPON_MELEE_TORCH', + 'WEAPON_MELEE_KNIFE_LENNY', 'WEAPON_MELEE_KNIFE_SADIE', 'WEAPON_MELEE_KNIFE_CHARLES', + 'WEAPON_MELEE_KNIFE_HOSEA', 'WEAPON_MELEE_TORCH_CROWD', 'WEAPON_MELEE_KNIFE_BILL', + 'WEAPON_MELEE_KNIFE_CIVIL_WAR', 'WEAPON_MELEE_KNIFE', 'WEAPON_MELEE_KNIFE_MICAH', + 'WEAPON_MELEE_BROKEN_SWORD', 'WEAPON_MELEE_KNIFE_JAVIER', 'WEAPON_MELEE_MACHETE_HORROR', + 'WEAPON_MELEE_KNIFE_TRADER', 'WEAPON_MELEE_MACHETE_COLLECTOR', 'WEAPON_MELEE_KNIFE_HORROR', + 'WEAPON_MELEE_KNIFE_RUSTIC' + } + return containsWeapon(weaponHash, meleeWeapons) +end + +-- Define pistol weapons +function IsPistol(weaponHash) + local pistolWeapons = { + 'WEAPON_PISTOL_VOLCANIC', 'WEAPON_PISTOL_MAUSER_DRUNK', 'WEAPON_PISTOL_M1899', + 'WEAPON_PISTOL_SEMIAUTO', 'WEAPON_PISTOL_MAUSER' + } + return containsWeapon(weaponHash, pistolWeapons) +end + +-- Define repeater weapons +function IsRepeater(weaponHash) + local repeaterWeapons = { + 'WEAPON_REPEATER_EVANS', 'WEAPON_REPEATER_CARBINE_SADIE', 'WEAPON_REPEATER_HENRY', + 'WEAPON_REPEATER_WINCHESTER', 'WEAPON_REPEATER_WINCHESTER_JOHN', 'WEAPON_REPEATER_CARBINE' + } + return containsWeapon(weaponHash, repeaterWeapons) +end + +-- Define revolver weapons +function IsRevolver(weaponHash) + local revolverWeapons = { + 'WEAPON_REVOLVER_DOUBLEACTION', 'WEAPON_REVOLVER_CATTLEMAN', 'WEAPON_REVOLVER_CATTLEMAN_MEXICAN', + 'WEAPON_REVOLVER_LeMAT', 'WEAPON_REVOLVER_SCHOFIELD', 'WEAPON_REVOLVER_DOUBLEACTION_GAMBLER', + 'WEAPON_REVOLVER_NAVY', 'WEAPON_REVOLVER_NAVY_CROSSOVER' + } + return containsWeapon(weaponHash, revolverWeapons) +end + +-- Define rifle weapons +function IsRifle(weaponHash) + local rifleWeapons = { + 'WEAPON_RIFLE_SPRINGFIELD', 'WEAPON_RIFLE_BOLTACTION', 'WEAPON_RIFLE_VARMiNT', 'WEAPON_RIFLE_ELEPHANT' + } + return containsWeapon(weaponHash, rifleWeapons) +end + +-- Define shotgun weapons +function IsShotgun(weaponHash) + local shotgunWeapons = { + 'WEAPON_SHOTGUN_SAWEDOFF', 'WEAPON_SHOTGUN_DOUBLEBARREL_EXOTIC', 'WEAPON_SHOTGUN_PUMP', + 'WEAPON_SHOTGUN_REPEATING', 'WEAPON_SHOTGUN_SEMIAUTO', 'WEAPON_SHOTGUN_DOUBLEBARREL' + } + return containsWeapon(weaponHash, shotgunWeapons) +end + +-- Define sniper weapons +function IsSniper(weaponHash) + local sniperWeapons = { + 'WEAPON_SNIPERRIFLE_CARCANO', 'WEAPON_SNIPERRIFLE_ROLLINGBLOCK' + } + return containsWeapon(weaponHash, sniperWeapons) +end + +-- Define thrown weapons +function IsThrown(weaponHash) + local thrownWeapons = { + 'WEAPON_THROWN_MOLOTOV', 'WEAPON_THROWN_TOMAHAWK_ANCIENT', 'WEAPON_THROWN_TOMAHAWK', + 'WEAPON_THROWN_DYNAMITE', 'WEAPON_THROWN_THROWING_KNIVES', 'WEAPON_THROWN_BOLAS', + 'WEAPON_THROWN_POISONBOTTLE', 'WEAPON_THROWN_BOLAS_HAWKMOTH', 'WEAPON_THROWN_BOLAS_IRONSPIKED', + 'WEAPON_THROWN_BOLAS_INTERTWINED' + } + return containsWeapon(weaponHash, thrownWeapons) +end + +-- Define held weapons/tools +function IsHeldWeapon(weaponHash) + local heldWeapons = { + 'WEAPON_MELEE_LANTERN', 'WEAPON_MELEE_DAVY_LANTERN', 'WEAPON_MELEE_LANTERN_ELECTRIC', + 'WEAPON_KIT_BINOCULARS', 'WEAPON_KIT_CAMERA', 'WEAPON_KIT_CAMERA_ADVANCED', 'WEAPON_KIT_METAL_DETECTOR', + 'WEAPON_MELEE_LANTERN_HALLOWEEN', 'WEAPON_KIT_BINOCULARS_IMPROVED' + } + return containsWeapon(weaponHash, heldWeapons) +end + +-- Define bow weapons +function IsBow(weaponHash) + local bowWeapons = { + 'WEAPON_BOW', 'WEAPON_BOW_IMPROVED', 'WEAPON_BOW_CHARLES' + } + return containsWeapon(weaponHash, bowWeapons) +end + +-- Define special tools/weapons +function IsSpecialWeapon(weaponHash) + local specialWeapons = { + 'WEAPON_FISHINGROD', 'WEAPON_LASSO', 'WEAPON_LASSO_REINFORCED' + } + return containsWeapon(weaponHash, specialWeapons) +end + +-- Define unarmed/nature-related weapons +function IsUnarmed(weaponHash) + local unarmedWeapons = { + 'WEAPON_WOLF', 'WEAPON_WOLF_MEDIUM', 'WEAPON_WOLF_SMALL', 'WEAPON_ALLIGATOR', 'WEAPON_ANIMAL', + 'WEAPON_BADGER', 'WEAPON_BEAR', 'WEAPON_BEAVER', 'WEAPON_COUGAR', 'WEAPON_COYOTE', 'WEAPON_DEER', + 'WEAPON_FOX', 'WEAPON_HORSE', 'WEAPON_MUSKRAT', 'WEAPON_RACCOON', 'WEAPON_SNAKE' + } + return containsWeapon(weaponHash, unarmedWeapons) +end + +-- Define environmental weapons +function IsEnvironmental(weaponHash) + local environmentalWeapons = { + 'WEAPON_FALL', 'WEAPON_FIRE', 'WEAPON_BLEEDING', 'WEAPON_DROWNING', 'WEAPON_DROWNING_IN_VEHICLE', + 'WEAPON_EXPLOSION', 'WEAPON_RAMMED_BY_CAR', 'WEAPON_RUN_OVER_BY_CAR' + } + return containsWeapon(weaponHash, environmentalWeapons) +end + +-- Utility function to check if a weapon hash is in a list of weapons +function containsWeapon(weaponHash, weaponList) + for _, weapon in ipairs(weaponList) do + if GetHashKey(weapon) == weaponHash then return true end + end + return false +end +-- Helper function to convert weapon hash to readable name +function getReadableWeaponName(weaponHash) + local weaponName = tostring(weaponHash) -- Convert the hash to a string + weaponName = weaponName:gsub("WEAPON_", "") -- Remove "WEAPON_" prefix + weaponName = weaponName:gsub("_", " "):lower() -- Replace underscores with spaces and convert to lowercase + return weaponName +end + +WeaponNames = { + -- Unarmed + [tostring(GetHashKey('WEAPON_UNARMED'))] = 'Unarmed', + + -- Melee Weapons + [tostring(GetHashKey('WEAPON_MELEE_KNIFE'))] = 'Knife', + [tostring(GetHashKey('WEAPON_MELEE_HATCHET'))] = 'Hatchet', + [tostring(GetHashKey('WEAPON_MELEE_CLEAVER'))] = 'Cleaver', + [tostring(GetHashKey('WEAPON_MELEE_MACHETE'))] = 'Machete', + [tostring(GetHashKey('WEAPON_MELEE_ANCIENT_HATCHET'))] = 'Ancient Hatchet', + [tostring(GetHashKey('WEAPON_MELEE_CROWBAR'))] = 'Crowbar', + [tostring(GetHashKey('WEAPON_MELEE_LANTERN'))] = 'Lantern', + + -- Revolvers + [tostring(GetHashKey('WEAPON_REVOLVER_CATTLEMAN'))] = 'Cattleman Revolver', + [tostring(GetHashKey('WEAPON_REVOLVER_DOUBLEACTION'))] = 'Double-Action Revolver', + [tostring(GetHashKey('WEAPON_REVOLVER_LEMAT'))] = 'LeMat Revolver', + [tostring(GetHashKey('WEAPON_REVOLVER_SCHOFIELD'))] = 'Schofield Revolver', + [tostring(GetHashKey('WEAPON_REVOLVER_NAVY'))] = 'Navy Revolver', + + -- Pistols + [tostring(GetHashKey('WEAPON_PISTOL_MAUSER'))] = 'Mauser Pistol', + [tostring(GetHashKey('WEAPON_PISTOL_SEMIAUTO'))] = 'Semi-Automatic Pistol', + [tostring(GetHashKey('WEAPON_PISTOL_VOLCANIC'))] = 'Volcanic Pistol', + + -- Rifles + [tostring(GetHashKey('WEAPON_RIFLE_BOLTACTION'))] = 'Bolt-Action Rifle', + [tostring(GetHashKey('WEAPON_RIFLE_SPRINGFIELD'))] = 'Springfield Rifle', + [tostring(GetHashKey('WEAPON_RIFLE_VARMINT'))] = 'Varmint Rifle', + [tostring(GetHashKey('WEAPON_RIFLE_CARCANO'))] = 'Carcano Rifle', + + -- Repeater Rifles + [tostring(GetHashKey('WEAPON_REPEATER_CARBINE'))] = 'Carbine Repeater', + [tostring(GetHashKey('WEAPON_REPEATER_HENRY'))] = 'Henry Repeater', + [tostring(GetHashKey('WEAPON_REPEATER_WINCHESTER'))] = 'Winchester Repeater', + + -- Shotguns + [tostring(GetHashKey('WEAPON_SHOTGUN_DOUBLEBARREL'))] = 'Double-Barrel Shotgun', + [tostring(GetHashKey('WEAPON_SHOTGUN_PUMP'))] = 'Pump-Action Shotgun', + [tostring(GetHashKey('WEAPON_SHOTGUN_REPEATING'))] = 'Repeating Shotgun', + [tostring(GetHashKey('WEAPON_SHOTGUN_SAWEDOFF'))] = 'Sawed-Off Shotgun', + [tostring(GetHashKey('WEAPON_SHOTGUN_SEMIAUTO'))] = 'Semi-Automatic Shotgun', + + -- Sniper Rifles + [tostring(GetHashKey('WEAPON_SNIPERRIFLE_CARCANO'))] = 'Carcano Sniper Rifle', + [tostring(GetHashKey('WEAPON_SNIPERRIFLE_ROLLINGBLOCK'))] = 'Rolling Block Rifle', + + -- Bows + [tostring(GetHashKey('WEAPON_BOW'))] = 'Bow', + [tostring(GetHashKey('WEAPON_THROWN_TOMAHAWK'))] = 'Tomahawk', + + -- Thrown Weapons + [tostring(GetHashKey('WEAPON_THROWN_THROWING_KNIVES'))] = 'Throwing Knives', + [tostring(GetHashKey('WEAPON_THROWN_DYNAMITE'))] = 'Dynamite', + [tostring(GetHashKey('WEAPON_THROWN_MOLOTOV'))] = 'Molotov', + + -- Miscellaneous + [tostring(GetHashKey('WEAPON_LASSO'))] = 'Lasso', + [tostring(GetHashKey('WEAPON_LASSO_REINFORCED'))] = 'Reinforced Lasso', + [tostring(GetHashKey('WEAPON_MELEE_TORCH'))] = 'Torch' +} + diff --git a/config.lua b/config.lua new file mode 100644 index 0000000..71290a7 --- /dev/null +++ b/config.lua @@ -0,0 +1,17 @@ +Config = { + defaultlang = 'en_lang', + devMode = false, + AdminManagementMenuCommand = 'userLog', + playTimeCommad = 'playtime', + lastSessioncommand = 'lastsession', + leaderboard = 'leaderboard', + -- Set your admin group here + adminGroup = 'admin', + UsePlayTimeTracking = true, + + -- webhooks to log all the user stuff to discord + Webhook ='', + WebhookTitle = 'BCC-UserSystemLog', + WebhookAvatar = '' + ----------------------------------------------------- +} diff --git a/fxmanifest.lua b/fxmanifest.lua new file mode 100644 index 0000000..05c12af --- /dev/null +++ b/fxmanifest.lua @@ -0,0 +1,26 @@ +fx_version 'adamant' +games { 'rdr3' } +rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.' + +author 'BCC Scripts @iseeyoucopy' +description 'An in-depth and immersive user logging system for tracking player activity' + +shared_scripts { + 'config.lua', + 'locale.lua', + 'languages/*.lua' + +} +-- Define server and client scripts +client_scripts { + 'client/client.lua', + --'client/clientAimandKill.lua' +} + +server_scripts { + '@oxmysql/lib/MySQL.lua', -- oxmysql dependency + 'server/server.lua', + 'server/txAdminhandlers.lua' +} + +version '1.0.0' \ No newline at end of file diff --git a/languages/en_lang.lua b/languages/en_lang.lua new file mode 100644 index 0000000..c32c836 --- /dev/null +++ b/languages/en_lang.lua @@ -0,0 +1,55 @@ +Locales['en_lang'] = { + yourTime = 'Your total played game: ', + formatted_playtime = " days, hours, minutes", + user_log_system = 'User Log System', + no_users_found = 'No users found in the current user list.', + no_users_available = 'No users available', + license = 'License', + playtime = 'Playtime', + last_connection = 'Last Connection', + joined = 'Joined', + character_id = 'Character ID', + money = 'Money', + gold = 'Gold', + identifiers = 'User Identifiers', + discord_id = 'Discord ID', + fivem_id = 'FiveM ID', + license2 = 'License2', + steam_id = 'Steam ID', + live_id = 'Live ID', + xbl_id = 'XBL ID', + unknown_user = 'Unknown User', + na = 'N/A', + user_details = 'User Details', + back_to_users = 'Back to Users', + total_playtime_message = "Your total playtime is: ", + totalDays = " days, ", + totalHours = " hours, ", + totalMintutes = " minutes", + playtime_not_found_message = "Could not find your playtime. Ensure you are registered in the database.", + select_user_description = "Select a user from the list to view detailed information.", + detailed_user_information = "Detailed information about the selected user, including identifiers, playtime, and account status.", + leaderboardHistory = 'Leaderboard History', + playerList = 'Player List', + selectAnOption = 'Select an option to proceed.', + noUsersAvailable = 'No users available', + selectAPlayer = 'Select a player to view details.', + yesterdayHistory = "Yesterday's Daily Leaderboard", + weeklyHistory = "Last Week's Weekly Leaderboard", + monthlyHistory = "Last Month's Monthly Leaderboard", + select_leaderboard_type = "Select Leaderboard Type", + daily_leaderboard = "Daily Leaderboard", + weekly_leaderboard = "Weekly Leaderboard", + monthly_leaderboard = "Monthly Leaderboard", + info_text = "Here will add some info", + selectLeaderboardType = "Select Leaderboard Type", + dailyLeaderboard = "Daily Leaderboard", + weeklyLeaderboard = "Weekly Leaderboard", + monthlyLeaderboard = "Monthly Leaderboard", + rank = "Rank", + player = "Player", + no_data_available = "No data available", + backToLeaderboard = "Back to Leaderboard", + additionalInfo = "Here will add some info", + +} diff --git a/languages/ro_lang.lua b/languages/ro_lang.lua new file mode 100644 index 0000000..2816c38 --- /dev/null +++ b/languages/ro_lang.lua @@ -0,0 +1,55 @@ +Locales['ro_lang'] = { + yourTime = 'Timpul total de joc: ', + formatted_playtime = " zile, ore, minute", + user_log_system = 'Sistem de Jurnal Utilizatori', + no_users_found = 'Niciun utilizator gasit in lista curenta.', + no_users_available = 'Niciun utilizator disponibil', + license = 'Licenta', + playtime = 'Timp de joc', + last_connection = 'Ultima Conexiune', + joined = 'Alaturat', + character_id = 'ID-ul Personajului', + money = 'Bani', + gold = 'Aur', + identifiers = 'Identificatori Utilizator', + discord_id = 'Discord ID', + fivem_id = 'FiveM ID', + license2 = 'Licenta2', + steam_id = 'Steam ID', + live_id = 'Live ID', + xbl_id = 'XBL ID', + unknown_user = 'Utilizator Necunoscut', + na = 'N/A', + user_details = 'Detalii Utilizator', + back_to_users = 'Inapoi la Utilizatori', + total_playtime_message = "Timpul total de joc este: ", + totalDays = " zile, ", + totalHours = " ore, ", + totalMintutes = " minute", + playtime_not_found_message = "Nu am putut gasi timpul tau de joc. Asigura-te ca esti inregistrat in baza de date.", + select_user_description = "Selecteaza un utilizator din lista pentru a vedea informatii detaliate.", + detailed_user_information = "Informatii detaliate despre utilizatorul selectat, inclusiv identificatori, timp de joc si statutul contului.", + leaderboardHistory = 'Istoric Clasament', + playerList = 'Lista Utilizatorilor', + selectAnOption = 'Selecteaza o optiune pentru a continua.', + noUsersAvailable = 'Niciun utilizator disponibil', + selectAPlayer = 'Selecteaza un utilizator pentru a vedea detalii.', + yesterdayHistory = 'Clasamentul Zilnic de Ieri', + weeklyHistory = 'Clasamentul Saptamanal al Saptamanii Trecute', + monthlyHistory = 'Clasamentul Lunar al Lunii Trecute', + select_leaderboard_type = 'Selecteaza Tipul de Clasament', + daily_leaderboard = 'Clasament Zilnic', + weekly_leaderboard = 'Clasament Saptamanal', + monthly_leaderboard = 'Clasament Lunar', + info_text = 'Aici va fi adaugata informatie', + selectLeaderboardType = 'Selecteaza Tipul de Clasament', + dailyLeaderboard = 'Clasament Zilnic', + weeklyLeaderboard = 'Clasament Saptamanal', + monthlyLeaderboard = 'Clasament Lunar', + rank = 'Rang', + player = 'Jucator', + no_data_available = 'Nicio informatie disponibila', + backToLeaderboard = 'Inapoi la Clasament', + additionalInfo = 'Aici va fi adaugata informatie', + +} diff --git a/locale.lua b/locale.lua new file mode 100644 index 0000000..53743ad --- /dev/null +++ b/locale.lua @@ -0,0 +1,45 @@ +Locales = {} + +local translationCache = {} -- Cache for translations + +function _(str, ...) -- Translate string + -- Check cache first + if translationCache[str] and select("#", ...) > 0 then + -- Use cached translation with formatting + return string.format(translationCache[str], ...) + elseif translationCache[str] then + -- Use cached translation without formatting + return translationCache[str] + end + + local lang = Config.defaultlang + local defaultLang = "en" -- Set your fallback language here (e.g., 'en') + + if Locales[lang] ~= nil then + if Locales[lang][str] ~= nil then + translationCache[str] = Locales[lang][str] -- Cache the translation for faster future access + if select("#", ...) > 0 then + return string.format(Locales[lang][str], ...) + else + return Locales[lang][str] + end + elseif Locales[defaultLang] ~= nil and Locales[defaultLang][str] ~= nil then + translationCache[str] = Locales[defaultLang][str] + if select("#", ...) > 0 then + return string.format(Locales[defaultLang][str], ...) + else + return Locales[defaultLang][str] + end + else + return 'Translation [' .. lang .. '][' .. str .. '] and fallback [' .. defaultLang .. '] do not exist' + end + else + return 'Locale [' .. lang .. '] does not exist' + end +end + +function _U(str, ...) -- Translate string with first character uppercase + -- Use cached translation if available + local translation = _(str, ...) + return translation:sub(1, 1):upper() .. translation:sub(2) +end diff --git a/server/server.lua b/server/server.lua new file mode 100644 index 0000000..cd6a494 --- /dev/null +++ b/server/server.lua @@ -0,0 +1,600 @@ +local Core = exports.vorp_core:GetCore() +BccUtils = exports['bcc-utils'].initiate() +discordWebhook = BccUtils.Discord.setup(Config.Webhook, Config.WebhookTitle, Config.WebhookAvatar) + +local playerSessionStart = {} + +-- Helper function for debugging in DevMode +if Config.devMode then + function devPrint(message) + print("^1[DEV MODE] ^4" .. tostring(message or "No message provided")) + end +else + function devPrint(message) end -- No-op if DevMode is disabled +end + +-- Helper function to get player identifiers +local function GetPlayerIdentifiersData(_source) + local identifiers = GetPlayerIdentifiers(_source) + local data = { license = nil, discord = nil, steam = nil, live = nil, xbl = nil, license2 = nil, fivem = nil } + + -- Iterate through player identifiers and extract specific ones + for _, id in ipairs(identifiers) do + if string.sub(id, 1, string.len("license:")) == "license:" then + data.license = string.gsub(id, "license:", "") + elseif string.sub(id, 1, string.len("discord:")) == "discord:" then + data.discord = string.gsub(id, "discord:", "") + elseif string.sub(id, 1, string.len("steam:")) == "steam:" then + data.steam = string.gsub(id, "steam:", "") + elseif string.sub(id, 1, string.len("live:")) == "live:" then + data.live = string.gsub(id, "live:", "") + elseif string.sub(id, 1, string.len("xbl:")) == "xbl:" then + data.xbl = string.gsub(id, "xbl:", "") + elseif string.sub(id, 1, string.len("license2:")) == "license2:" then + data.license2 = string.gsub(id, "license2:", "") + elseif string.sub(id, 1, string.len("fivem:")) == "fivem:" then + data.fivem = string.gsub(id, "fivem:", "") + end + end + + return data +end + +-- Update playtime for all connected players +function UpdateAllPlayerPlaytime() + for license, sessionData in pairs(playerSessionStart) do + local connectTime = sessionData.connectTime + local _source = sessionData.source + + if connectTime then + local currentTime = os.time() + local sessionPlayTimeMinutes = math.floor((currentTime - connectTime) / 60) + + if sessionPlayTimeMinutes > 0 then + -- Update the connect time for the next interval + playerSessionStart[license].connectTime = currentTime + + -- Fetch current playtime from the database for debugging + MySQL.query('SELECT players_playTime FROM bcc_player_connections WHERE license = ?', { license }, + function(result) + if result and #result > 0 then + local currentPlayTime = result[1].players_playTime + local newPlayTime = currentPlayTime + sessionPlayTimeMinutes + + devPrint("Successfully updated playtime for license: " .. license .. " Current: " .. currentPlayTime .. " New: " .. newPlayTime) + + -- Update the total playtime in the database + MySQL.update('UPDATE bcc_player_connections SET players_playTime = ? WHERE license = ?', + { newPlayTime, license }, function(affectedRows) + if affectedRows > 0 then + devPrint("Successfully updated total playtime for license: " .. license) + else + devPrint("Failed to update total playtime for license: " .. license) + end + end) + + -- Update daily, weekly, and monthly playtime + UpdateDailyPlaytime(license, sessionPlayTimeMinutes) + UpdateWeeklyPlaytime(license, sessionPlayTimeMinutes) + UpdateMonthlyPlaytime(license, sessionPlayTimeMinutes) + else + devPrint("No playtime record found for license: " .. license) + end + end) + else + devPrint("No new playtime to update for license: " .. license) + end + else + devPrint("No connect time found for license: " .. license) + end + end +end + +-- Initialize connected players on script start +function ReinitializePlayers() + devPrint("Reinitializing players on script start...") + for _, playerId in ipairs(GetPlayers()) do + local _source = tonumber(playerId) + local identifiers = GetPlayerIdentifiersData(_source) + if identifiers.license then + playerSessionStart[identifiers.license] = { connectTime = os.time(), source = _source } + devPrint("Initialized session for connected player with license: " .. identifiers.license) + end + end +end + +-- Event triggered every minute to update playtime +Citizen.CreateThread(function() + while true do + Citizen.Wait(60000) + UpdateAllPlayerPlaytime() + end +end) + +-- Update daily playtime for a specific license +function UpdateDailyPlaytime(license, playTime) + MySQL.update('UPDATE bcc_player_connections SET players_dailyPlayTime = players_dailyPlayTime + ? WHERE license = ?', + { playTime, license }, function(affectedRows) + if affectedRows > 0 then + devPrint("Successfully updated daily playtime for license: " .. license) + else + devPrint("Failed to update daily playtime for license: " .. license) + end + end) +end + +-- Update weekly playtime for a specific license +function UpdateWeeklyPlaytime(license, playTime) + MySQL.update('UPDATE bcc_player_connections SET players_weeklyPlayTime = players_weeklyPlayTime + ? WHERE license = ?', + { playTime, license }, function(affectedRows) + if affectedRows > 0 then + devPrint("Successfully updated weekly playtime for license: " .. license) + else + devPrint("Failed to update weekly playtime for license: " .. license) + end + end) +end + +-- Update monthly playtime for a specific license +function UpdateMonthlyPlaytime(license, playTime) + MySQL.update('UPDATE bcc_player_connections SET players_monthlyPlayTime = players_monthlyPlayTime + ? WHERE license = ?', + { playTime, license }, function(affectedRows) + if affectedRows > 0 then + devPrint("Successfully updated monthly playtime for license: " .. license) + else + devPrint("Failed to update monthly playtime for license: " .. license) + end + end) +end + +-- Handle player connecting and check database for existing record +AddEventHandler('playerConnecting', function(playerName, setKickReason, deferrals) + local _source = source + local playerName = GetPlayerName(_source) + local identifiers = GetPlayerIdentifiersData(_source) + local playerIp = GetPlayerEndpoint(_source) + local playerPing = GetPlayerPing(_source) + + if not identifiers.license then + local message23 = "❌ Unable to identify your license. Please restart your game." + setKickReason(message23) + discordWebhook:sendMessage("🚫 Player **" .. playerName .. "** was unable to connect: " .. message) + CancelEvent() + return + end + + -- Store the connection time for session tracking + playerSessionStart[identifiers.license] = { connectTime = os.time(), source = _source } + devPrint("Player added to session with license:" .. (identifiers.license or "N/A")) + + local identifierInfo = + "License: `" .. (identifiers.license or "N/A") .. "`\n" .. + "Discord: `" .. (identifiers.discord or "N/A") .. "`\n" .. + "Steam: `" .. (identifiers.steam or "N/A") .. "`\n" .. + "FiveM: `" .. (identifiers.fivem or "N/A") .. "`\n" .. + "IP: `" .. (playerIp or "N/A") .. "`\n" .. + "Ping: `" .. tostring(playerPing or 0) .. "ms`" + + -- Wrap sendMessage in pcall to catch any errors + local success, err = pcall(function() + discordWebhook:sendMessage("✅ Player **" .. playerName .. "** added to session.\n" .. identifierInfo) + end) + + if not success then + print("Failed to send Discord message: " .. tostring(err)) + end + + -- Optional: print to console for confirmation + devPrint("Player added to session with license:" .. (identifiers.license or "N/A")) + + MySQL.query('SELECT id FROM bcc_player_connections WHERE license = ?', { identifiers.license }, function(result) + local tsLastConnection = os.time() + + if result and #result > 0 then + MySQL.update('UPDATE bcc_player_connections SET players_tsLastConnection = ? WHERE id = ?', + { tsLastConnection, result[1].id }, function(affectedRows) + ---devPrint(message) + end) + else + local playTime, tsJoined = 0, os.time() + MySQL.insert('INSERT INTO bcc_player_connections (license, discord_id, steam_id, fivem_id, license2, live_id, xbl_id, players_displayName, players_playTime, players_tsJoined, players_tsLastConnection) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', + { + identifiers.license, identifiers.discord, identifiers.steam, identifiers.fivem, identifiers.license2, + identifiers.live, identifiers.xbl, playerName, playTime, tsJoined, tsLastConnection + }, function(id) + --devPrint(message) + end) + end + end) +end) + +AddEventHandler('playerDropped', function(reason) + local _source = source + local playerName = GetPlayerName(_source) + local identifiers = GetPlayerIdentifiersData(_source) + local playerIp = GetPlayerEndpoint(_source) + local playerPing = GetPlayerPing(_source) + + if identifiers.license and playerSessionStart[identifiers.license] then + -- Calculate session duration in seconds + local sessionStartTime = playerSessionStart[identifiers.license].connectTime + local sessionEndTime = os.time() + local sessionDuration = sessionEndTime - sessionStartTime + + -- Convert session duration to hours, minutes, and seconds for logging + local hours = math.floor(sessionDuration / 3600) + local minutes = math.floor((sessionDuration % 3600) / 60) + local seconds = sessionDuration % 60 + local sessionTime = string.format("%02d:%02d:%02d", hours, minutes, seconds) + + -- Update only the last session time and total playtime in the database + MySQL.update('UPDATE bcc_player_connections SET players_lastSessionTime = ?, players_playTime = players_playTime + ?, players_tsLastConnection = ? WHERE license = ?', + { sessionDuration, sessionDuration, sessionEndTime, identifiers.license }, + function(affectedRows) + if affectedRows > 0 then + devPrint("Successfully logged session time for license: " .. identifiers.license) + else + devPrint("Failed to log session time for license: " .. identifiers.license) + end + end) + + -- Prepare identifier info for Discord message + local identifierInfo = string.format( + "License: `%s`\nDiscord: `%s`\nSteam: `%s`\nFiveM: `%s`\nIP: `%s`\nPing: `%d`ms", + tostring(identifiers.license), + tostring(identifiers.discord), + tostring(identifiers.steam), + tostring(identifiers.fivem), + tostring(playerIp), + tonumber(playerPing) or 0) + + -- Construct and send the session end message to Discord + local message = string.format("👋 Player **%s** disconnected. Reason: %s\n%s\nSession Duration: `%s`", + playerName or "Unknown", reason, identifierInfo, sessionTime) + discordWebhook:sendMessage(message) + + -- Remove the player from session tracking + playerSessionStart[identifiers.license] = nil + end +end) + +-- Show player's playtime command +RegisterCommand(Config.playTimeCommad, function(source, args, rawCommand) + local _source = source + local identifiers = GetPlayerIdentifiersData(_source) + + MySQL.query('SELECT players_playTime FROM bcc_player_connections WHERE license = ?', { identifiers.license }, + function(result) + if result and #result > 0 then + local totalPlayTimeMinutes = result[1].players_playTime + + -- Calculate current session time if player is still connected + local sessionStart = playerSessionStart[identifiers.license] and + playerSessionStart[identifiers.license].connectTime + local currentSessionTime = 0 + + if sessionStart then + currentSessionTime = math.floor((os.time() - sessionStart) / 60) -- convert session time from seconds to minutes + end + + -- Add session time to the total playtime + local combinedPlayTime = totalPlayTimeMinutes + currentSessionTime + + -- Convert playtime to days, hours, and minutes + local days = math.floor(combinedPlayTime / 1440) + local hours = math.floor((combinedPlayTime % 1440) / 60) + local minutes = combinedPlayTime % 60 + + Core.NotifyObjective(_source, _U('total_playtime_message') .. days .. _U('totalDays') .. hours .. _U('totalHours').. minutes.. _U('totalMintutes'), 4000) + else + Core.NotifyObjective(_source, _U("playtime_not_found_message"), 4000) + end + end) +end, false) + +RegisterCommand(Config.lastSessioncommand, function(source, args, rawCommand) + local _source = source + local identifiers = GetPlayerIdentifiersData(_source) + + -- Query the last session time for the player + MySQL.query('SELECT players_lastSessionTime FROM bcc_player_connections WHERE license = ?', { identifiers.license }, function(result) + if result and #result > 0 then + local lastSessionTime = result[1].players_lastSessionTime or 0 + + -- Convert the session time from seconds to hours, minutes, and seconds + local hours = math.floor(lastSessionTime / 3600) + local minutes = math.floor((lastSessionTime % 3600) / 60) + local seconds = lastSessionTime % 60 + + local formattedTime = string.format("%02d:%02d:%02d", hours, minutes, seconds) + + -- Send the formatted session time to the player + Core.NotifyObjective(_source, "Your last session playtime was: " .. formattedTime, 4000) + else + Core.NotifyObjective(_source, "Could not retrieve your last session time. Please ensure you are registered in the database.", 4000) + end + end) +end, false) + +RegisterCommand(Config.leaderboard, function(source, args, rawCommand) + TriggerClientEvent('bcc-userlog:openMainLeaderboardMenu', source) +end, false) + +RegisterNetEvent('bcc-userlog:requestLeaderboardData') +AddEventHandler('bcc-userlog:requestLeaderboardData', function(leaderboardType) + local source = source + local query = "" + local title = "" + + if leaderboardType == "daily" then + query = 'SELECT players_displayName, players_dailyPlayTime FROM bcc_player_connections ORDER BY players_dailyPlayTime DESC LIMIT 10' + title = "Daily Leaderboard" + elseif leaderboardType == "weekly" then + query = 'SELECT players_displayName, players_weeklyPlayTime FROM bcc_player_connections ORDER BY players_weeklyPlayTime DESC LIMIT 10' + title = "Weekly Leaderboard" + elseif leaderboardType == "monthly" then + query = 'SELECT players_displayName, players_monthlyPlayTime FROM bcc_player_connections ORDER BY players_monthlyPlayTime DESC LIMIT 10' + title = "Monthly Leaderboard" + end + + -- Fetch and send leaderboard data to the client + MySQL.query(query, {}, function(result) + TriggerClientEvent('bcc-userlog:displayLeaderboard', source, result, title) + end) +end) + +RegisterNetEvent('bcc-userlog:fetchLeaderboardHistory') +AddEventHandler('bcc-userlog:fetchLeaderboardHistory', function(historyType) + local source = source + + -- Ensure historyType is valid + local query, title + if historyType == "daily" then + query = "SELECT player_displayName, playtime FROM bcc_leaderboard_history WHERE leaderboard_type = 'daily' AND DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY ORDER BY playtime DESC LIMIT 10" + title = "Yesterday's Daily Leaderboard" + elseif historyType == "weekly" then + query = "SELECT player_displayName, playtime FROM bcc_leaderboard_history WHERE leaderboard_type = 'weekly' AND recorded_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) ORDER BY playtime DESC LIMIT 10" + title = "Last Week's Weekly Leaderboard" + elseif historyType == "monthly" then + query = "SELECT player_displayName, playtime FROM bcc_leaderboard_history WHERE leaderboard_type = 'monthly' AND recorded_at >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ORDER BY playtime DESC LIMIT 10" + title = "Last Month's Monthly Leaderboard" + else + -- Log an error if historyType is not valid and return early + print("Invalid historyType received:", historyType) + TriggerClientEvent('bcc-userlog:displayLeaderboardHistory', source, {}, "Invalid Leaderboard History Type") + return + end + + -- Execute the query and send results to the client + MySQL.insert(query, {}, function(results) + if results and #results > 0 then + -- Log results for debugging + print("Sending leaderboard data to client:", json.encode(results)) + TriggerClientEvent('bcc-userlog:displayLeaderboardHistory', source, results, title) + else + print("No leaderboard data found for:", historyType) + TriggerClientEvent('bcc-userlog:displayLeaderboardHistory', source, {}, title) -- Send empty data if none found + end + end) +end) + +-- Daily Reset Thread +Citizen.CreateThread(function() + while true do + Citizen.Wait(86400000) -- 24-hour interval for daily reset + + -- Record daily leaderboard to history + MySQL.insert("INSERT INTO bcc_leaderboard_history (player_id, player_displayName, playtime, leaderboard_type) " .. + "SELECT id, players_displayName, players_dailyPlayTime, 'daily' FROM bcc_player_connections WHERE players_dailyPlayTime > 0") + + -- Reset daily playtime + MySQL.update("UPDATE bcc_player_connections SET players_dailyPlayTime = 0") + + print("Daily playtime reset and snapshot completed.") + end +end) + +-- Weekly Reset Thread +Citizen.CreateThread(function() + while true do + local currentDay = os.date("%A") + local waitTime + + -- Calculate time until next Monday + if currentDay == "Monday" then + waitTime = 86400000 -- If today is Monday, wait 24 hours + else + local daysUntilMonday = (8 - os.date("*t").wday) % 7 -- Days until next Monday + waitTime = daysUntilMonday * 86400000 -- Convert days to milliseconds + end + + Citizen.Wait(waitTime) -- Wait until the next Monday + + -- Record weekly leaderboard to history + MySQL.insert("INSERT INTO bcc_leaderboard_history (player_id, player_displayName, playtime, leaderboard_type) " .. + "SELECT id, players_displayName, players_weeklyPlayTime, 'weekly' FROM bcc_player_connections WHERE players_weeklyPlayTime > 0") + + -- Reset weekly playtime + MySQL.update("UPDATE bcc_player_connections SET players_weeklyPlayTime = 0") + + print("Weekly playtime reset and snapshot completed.") + end +end) + +-- Monthly Reset Thread +Citizen.CreateThread(function() + while true do + local currentDate = os.date("*t") + local nextMonthTime = os.time{year=currentDate.year, month=currentDate.month + 1, day=1, hour=0} + local waitTime = (nextMonthTime - os.time()) * 1000 -- Time until first day of the next month in milliseconds + + Citizen.Wait(waitTime) -- Wait until the first day of the next month + + -- Record monthly leaderboard to history + MySQL.insert("INSERT INTO bcc_leaderboard_history (player_id, player_displayName, playtime, leaderboard_type) " .. + "SELECT id, players_displayName, players_monthlyPlayTime, 'monthly' FROM bcc_player_connections WHERE players_monthlyPlayTime > 0") + + -- Reset monthly playtime + MySQL.update("UPDATE bcc_player_connections SET players_monthlyPlayTime = 0") + + print("Monthly playtime reset and snapshot completed.") + end +end) + +-- Event triggered on resource start +AddEventHandler('onResourceStart', function(resourceName) + if GetCurrentResourceName() == resourceName then + devPrint("Resource " .. resourceName .. " started.") + ReinitializePlayers() + end +end) + +-- Server: Event to handle fetching the full user list +RegisterNetEvent('bcc-userlog:fetchUsers') +AddEventHandler('bcc-userlog:fetchUsers', function() + local source = source + devPrint("Received fetchUsers request from player: " .. source) + + MySQL.query('SELECT id, players_displayName AS name FROM bcc_player_connections', {}, function(users) + if users and #users > 0 then + -- Send user list back to the client once + TriggerClientEvent('bcc-userlog:sendUserList', source, users) + devPrint("Sent user list to client for player: " .. source) + else + devPrint("No users found in the database.") + TriggerClientEvent('bcc-userlog:sendUserList', source, {}) -- Send empty list if no users found + end + end) +end) + +RegisterNetEvent('bcc-userlog:fetchUserDetails') +AddEventHandler('bcc-userlog:fetchUserDetails', function(userID) + local source = source + + -- Fetch user details from the database + MySQL.query('SELECT * FROM bcc_player_connections WHERE id = ?', { userID }, function(results) + if results and #results > 0 then + local user = results[1] + + -- Format dates on the server + user.formattedLastConnection = os.date('%Y-%m-%d %H:%M:%S', user.players_tsLastConnection or 0) + user.formattedJoined = os.date('%Y-%m-%d %H:%M:%S', user.players_tsJoined or 0) + + -- Add 'steam:' prefix to steam_id when querying characters table + local steamIdentifier = 'steam:' .. user.steam_id + + -- Fetch character details from the characters table based on the prefixed steam identifier + MySQL.query('SELECT * FROM characters WHERE identifier = ?', { steamIdentifier }, function(characterResults) + if characterResults and #characterResults > 0 then + local character = characterResults[1] + + -- Include character information with user details + user.characterDetails = { + charIdentifier = character.charidentifier, + steamName = character.steamname, + group = character.group, + money = character.money, + gold = character.gold, + job = character.job, + jobLabel = character.joblabel, + firstname = character.firstname, + lastname = character.lastname, + age = character.age, + gender = character.gender, + xp = character.xp, + health = { + outer = character.healthouter, + inner = character.healthinner + }, + stamina = { + outer = character.staminaouter, + inner = character.staminainner + }, + -- Add other fields as needed + } + + -- Send the user and character details to the client + TriggerClientEvent('bcc-userlog:sendUserDetails', source, user) + else + devPrint("Character not found in database for identifier: " .. steamIdentifier) + end + end) + else + devPrint("User not found in database.") + end + end) +end) + +AddEventHandler('chatMessage', function(source, author, message) + -- Check if the message is a command (starting with /) + if message:sub(1, 1) == "/" then + local command = message:sub(2) -- Get the command without the "/" + local playerName = GetPlayerName(source) or "Unknown" + local logMessage = ("💬 Command Used: **/%s** by **%s**"):format(command, playerName) + + -- Log the command to console for debugging + devPrint(logMessage) + + -- Send the command log to Discord + discordWebhook:sendMessage(logMessage) + end +end) + +RegisterServerEvent("bcc-userlog:AdminCheck", function() + local _source, admin = source, false + local character = Core.getUser(_source).getUsedCharacter + if character.group == Config.adminGroup then + TriggerClientEvent("bcc-userlog:AdminClientCheck", _source, true) + end + end) + +--This is a TO DO +-- Log aiming at another player +--[[RegisterServerEvent('bcc-userlog:aimlogs') +AddEventHandler('bcc-userlog:aimlogs', function(pedId) + -- Get player details + local playerName = GetPlayerName(source) + local playerId = source + local playerCharacter = Core.getUser(playerId).getUsedCharacter + local playerCharacterId = playerCharacter and playerCharacter.charIdentifier or "Unknown" + local playerFirstName = playerCharacter and playerCharacter.firstname or "Unknown" + local playerLastName = playerCharacter and playerCharacter.lastname or "Unknown" + + -- Get target details + local targetName = GetPlayerName(pedId) or "Unknown" + local targetCharacter = Core.getUser(pedId).getUsedCharacter + local targetCharacterId = targetCharacter and targetCharacter.charIdentifier or "Unknown" + local targetFirstName = targetCharacter and targetCharacter.firstname or "Unknown" + local targetLastName = targetCharacter and targetCharacter.lastname or "Unknown" + + -- Log message with character IDs and names + local logMessage = ("🎯 **Aim Logs**\nPlayer: %s `[ID: %s, Character ID: %s, Name: %s %s]`\nIs aiming at: %s `[ID: %s, Character ID: %s, Name: %s %s]`") + :format(playerName, playerId, playerCharacterId, playerFirstName, playerLastName, targetName, pedId, targetCharacterId, targetFirstName, targetLastName) + + -- Send message to Discord + discordWebhook:sendMessage(logMessage) +end) + +-- Log player kills +RegisterServerEvent('bcc-userlog:killlogs') +AddEventHandler('bcc-userlog:killlogs', function(message, weapon) + local time = os.date('*t') + local hour = (time.hour - 2) % 24 -- Adjust for time zone if needed + local minute = time.min + + local logMessage = ("💀 **Kill Logs**\n%s\nWeapon: %s\nTime: %02d:%02d"):format(message, weapon, hour, minute) + discordWebhook:sendMessage(logMessage) +end) + +-- Define the server event to log NPC aim actions +RegisterServerEvent('bcc-logs:npcAimLogs') +AddEventHandler('bcc-logs:npcAimLogs', function(npcType, weaponName) + local playerId = source -- Player who is being aimed at + local playerName = GetPlayerName(playerId) or "Unknown Player" + + -- Construct a log message + local logMessage = string.format("🔫 NPC Aiming Log: %s was aimed at by %s with weapon: %s", playerName, npcType, weaponName) + discordWebhook:sendMessage(logMessage) +end)]] -- + +BccUtils.Versioner.checkFile(GetCurrentResourceName(), 'https://github.com/BryceCanyonCounty/bcc-SystemUserLog') diff --git a/server/txAdminhandlers.lua b/server/txAdminhandlers.lua new file mode 100644 index 0000000..029e821 --- /dev/null +++ b/server/txAdminhandlers.lua @@ -0,0 +1,88 @@ +-- Cache player names every second +names = {} +CreateThread(function() + while true do + Wait(1000) + for k, v in pairs(GetPlayers()) do + names[v] = GetPlayerName(v) + end + end +end) + +-- Scheduled restart event +AddEventHandler('txAdmin:events:scheduledRestart', function(data) + local message = ("⏰ The server will restart in %s"):format(SecondsToClock(data.secondsRemaining)) + discordWebhook:sendMessage(message) +end) + +-- Skipped scheduled restart event +AddEventHandler('txAdmin:events:skippedNextScheduledRestart', function() + local message = "⚠️ The server skipped the scheduled restart." + discordWebhook:sendMessage(message) +end) + +-- Player kicked event +AddEventHandler('txAdmin:events:playerKicked', function(data) + local message = ("🚫 **%s** kicked **%s**\n📝 Reason: `%s`"):format(data.author, names[data.target] or "Unknown", data.reason) + discordWebhook:sendMessage(message) +end) + +-- Player warned event +AddEventHandler('txAdmin:events:playerWarned', function(data) + local message = ("⚠️ **%s** warned **%s**\n🔹 Action ID: `%s`\n📝 Reason: `%s`"):format(data.author, GetPlayerName(data.target) or "Unknown", data.actionId, data.reason) + discordWebhook:sendMessage(message) +end) + +-- Player banned event +AddEventHandler('txAdmin:events:playerBanned', function(data) + local expiration = data.expiration == false and "Permanent" or data.expiration + local message = ("⛔ **%s** banned **%s**\n🔹 Action ID: `%s`\n📝 Reason: `%s`\n🕒 Expiration: `%s`"):format(data.author, names[data.target] or "Unknown", data.actionId, data.reason, expiration) + discordWebhook:sendMessage(message) +end) + +-- Player whitelisted event +AddEventHandler('txAdmin:events:playerWhitelisted', function(data) + local message = ("✅ **%s** whitelisted `%s`\n🔹 Action ID: `%s`"):format(data.author, data.target, data.actionId) + discordWebhook:sendMessage(message) +end) + +-- Config changed event +AddEventHandler('txAdmin:event:configChanged', function() + local message = "⚙️ The `server.cfg` file has been updated." + discordWebhook:sendMessage(message) +end) + +-- Healed player event +AddEventHandler('txAdmin:events:healedPlayer', function(data) + local message + if data.id == -1 then + message = "🌍 The whole server was healed" + else + local playerName = GetPlayerName(data.id) or "Unknown Player" + message = "💉 " .. playerName .. " was healed by `txAdmin`" + end + discordWebhook:sendMessage(message) +end) + +-- Announcement event +AddEventHandler('txAdmin:events:announcement', function(data) + local message = ("📢 **%s** created an announcement:\n`%s`"):format(data.author, data.message) + discordWebhook:sendMessage(message) +end) + +-- Server shutting down event +AddEventHandler('txAdmin:events:serverShuttingDown', function(data) + local message = ("🔌 Server will shut down in `%s`\n🔹 Requested by: `%s`\n📜 Message: `%s`"):format(SecondsToClock(data.delay / 1000), data.author, data.message) + discordWebhook:sendMessage(message) +end) + +-- Utility function to format seconds into minutes and seconds +function SecondsToClock(sec) + local minutes = math.floor(sec / 60) + local seconds = sec - minutes * 60 + if minutes == 0 then + return string.format("%d seconds", seconds) + else + return string.format("%d minutes, %d seconds", minutes, seconds) + end +end diff --git a/version b/version new file mode 100644 index 0000000..7db3f6e --- /dev/null +++ b/version @@ -0,0 +1,2 @@ +<1.0.0> +See GitHub for details!