├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── README_en-US.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main ├── java └── com │ └── github │ └── jie65535 │ └── opencommand │ ├── EventListeners.java │ ├── OpenCommandConfig.java │ ├── OpenCommandData.java │ ├── OpenCommandHandler.java │ ├── OpenCommandOnlyHttpHandler.java │ ├── OpenCommandPlugin.java │ ├── json │ ├── JsonRequest.java │ └── JsonResponse.java │ ├── model │ └── Client.java │ └── socket │ ├── ClientInfo.java │ ├── SocketClient.java │ ├── SocketData.java │ ├── SocketDataWait.java │ ├── SocketServer.java │ ├── SocketUtils.java │ └── packet │ ├── AuthPacket.java │ ├── BasePacket.java │ ├── HeartBeat.java │ ├── HttpPacket.java │ ├── Packet.java │ ├── PacketEnum.java │ ├── RunConsoleCommand.java │ └── player │ ├── Player.java │ ├── PlayerEnum.java │ └── PlayerList.java └── resources └── plugin.json /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: "Build" 2 | on: 3 | workflow_dispatch: ~ 4 | push: 5 | paths: 6 | - "**.java" 7 | branches: 8 | - "master" 9 | pull_request: 10 | paths: 11 | - "**.java" 12 | types: 13 | - opened 14 | - synchronize 15 | - reopened 16 | jobs: 17 | Build-Jar: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@v2 22 | - name: Setup Java 23 | uses: actions/setup-java@v3 24 | with: 25 | distribution: temurin 26 | java-version: '17' 27 | - name: Cache gradle files 28 | uses: actions/cache@v2 29 | with: 30 | path: | 31 | ~/.gradle/caches 32 | ~/.gradle/wrapper 33 | ./.gradle/loom-cache 34 | key: ${{ runner.os }}-gradle-${{ hashFiles('*.gradle', 'gradle.properties', '**/*.accesswidener') }} 35 | restore-keys: | 36 | ${{ runner.os }}-gradle- 37 | - name: Download latest grasscutter jar 38 | run: wget https://nightly.link/Grasscutters/Grasscutter/workflows/build/development/Grasscutter.zip && mkdir lib && unzip Grasscutter.zip -d lib 39 | 40 | - name: Change permission 41 | run: chmod +x gradlew 42 | 43 | - name: Run Gradle 44 | run: ./gradlew jar 45 | 46 | - name: Upload build 47 | uses: actions/upload-artifact@v3 48 | with: 49 | name: opencommand 50 | path: opencommand*.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | /lib/ 26 | .gradle 27 | .idea 28 | /build -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gc-opencommand-plugin 2 | 3 | 中文 | [English](README_en-US.md) 4 | 5 | 一个为第三方客户端开放GC命令执行接口的插件 6 | 7 | 自 `1.7.0` 起可以通过 `|` 或者换行来分隔多条命令,例如: 8 | ```shell 9 | /a 1 | /a 2 10 | /a 3 11 | ``` 12 | 13 | 调用 `ping` 响应数据将包含插件版本号。 14 | 15 | ## 使用本插件的应用 16 | - [GrasscutterTools](https://github.com/jie65535/GrasscutterCommandGenerator) —— Windows 客户端工具 17 | - [JGrasscutterCommand](https://github.com/jie65535/JGrasscutterCommand) —— [Mirai](https://github.com/mamoe/mirai) 插件,在QQ里执行命令 18 | - [Yunzai-GrasscutterCommand](https://github.com/Zyy-boop/Yunzai-GrasscutterCommand) —— Yunzai-bot插件,在QQ里执行命令 19 | - 待补充 20 | 21 | ## 服务端安装 22 | 23 | 1. 在 [Release](https://github.com/jie65535/gc-opencommand-plugin/releases) 下载 `jar` 24 | 2. 放入 `grasscutter/plugins` 文件夹 25 | 3. 重启 `grasscutter` 即可生效 26 | 27 | ## 玩家使用流程 28 | 29 | 1. 在远程工具中填写服务地址,查询插件状态 30 | 2. 填写UID,发送验证码(需要在线) 31 | 3. 将游戏内收到的**4位整数验证码**填入工具校验 32 | 4. 享受便利! 33 | 34 | ## 控制台连接 35 | 36 | 1. 首次启动时,会在 `plugins` 目录下生成一个 `opencommand-plugin` 目录,打开并编辑 `config.json` 37 | 2. 设置 `consoleToken` 的值为你的连接秘钥,建议使用至少32字符的长随机字符串。(检测到为空时会自动生成,生成时会在控制台中输出) 38 | 3. 重新启动服务端即可生效配置 39 | 4. 在工具中选择控制台身份,并填写你的 `consoleToken` 即可以控制台身份运行指令 40 | 41 | --- 42 | 43 | ## 客户端请求流程 44 | 45 | 1. `ping` 确认是否支持 `opencommand` 插件 46 | 2. `sendCode` 向指定玩家发送验证码(1分钟内不允许重发),保存返回的 `token` 47 | 3. 使用 `token` 和**4位整数验证码**发送 `verify` 校验 48 | 4. 如果验证通过,可以使用该 `token` 执行 `command` 动作 49 | 50 | ## 插件构建说明 51 | 52 | 1. 克隆仓库 53 | 2. 在目录下新建 `lib` 目录 54 | 3. 将 `grasscutter.jar` 放入 `lib` 目录 55 | 4. 执行 `gradle build` 56 | 57 | ## 多服务器 58 | ### 主服务器 (Dispatch) 59 | 1. 在 `opencommand-plugin` 目录下打开 `config.json` 60 | 2. 修改 `socketPort` 值为一个未被使用的端口 61 | 3. 设置 `socketToken` 多服务器通信密钥,建议使用至少32字符的长随机字符串。 62 | 4. 重新启动服务端即可生效配置 63 | 64 | ### 子服务器 (Game) 65 | 1. 在 `opencommand-plugin` 目录下打开 `config.json` 66 | 2. 修改 `socketHost` 和 `socketPort` 值为主服务器的地址和端口 67 | 3. 设置 `socketToken` 和主服务器相同的值 68 | 4. 设置 `socketDisplayName` 值为你的服务器名称 (用途请见[下方](https://github.com/jie65535/gc-opencommand-plugin#%E8%8E%B7%E5%8F%96%E5%A4%9A%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%88%97%E8%A1%A8)) 69 | 5. 重新启动服务端即可生效配置 70 | 71 | --- 72 | 73 | ## `config.json` 74 | 75 | ```json5 76 | { 77 | // 控制台连接令牌(检测到空时会自动生成) 78 | "consoleToken": "", 79 | // 验证码过期时间(秒) 80 | "codeExpirationTime_S": 60, 81 | // 临时令牌过期时间(秒) 82 | "tempTokenExpirationTime_S": 300, 83 | // 授权令牌最后使用过期时间(小时) 84 | "tokenLastUseExpirationTime_H": 48, 85 | // 多服务器通信端口 86 | "socketPort": 5746, 87 | // 多服务器通信密钥 88 | "socketToken": "", 89 | // 多服务器Dispatch服务器地址 90 | "socketHost": "127.0.0.1", 91 | // 多服务器显示名称 92 | "socketDisplayName": "" 93 | } 94 | ``` 95 | 96 | ## API `/opencommand/api` 97 | 98 | 示例 99 | 100 | ``` 101 | https://127.0.0.1/opencommand/api 102 | ``` 103 | 104 | ### Request 请求 105 | 106 | ```java 107 | public final class JsonRequest { 108 | public String token = ""; 109 | public String action = ""; 110 | public String server = ""; 111 | public Object data = null; 112 | } 113 | ``` 114 | 115 | ### Response 响应 116 | 117 | ```java 118 | public final class JsonResponse { 119 | public int retcode = 200; 120 | public String message = "Success"; 121 | public Object data; 122 | } 123 | ``` 124 | 125 | ### Actions 动作 126 | 127 | #### `测试连接` 128 | 129 | ##### Request 130 | 131 | | 请求参数 | 请求数据 | 类型 | 132 | |--------|--------|----------| 133 | | action | `ping` | `String` | 134 | 135 | ##### Response 136 | 137 | | 返回参数 | 返回数据 | 类型 | 138 | |---------|-----------|----------| 139 | | retcode | `200` | `Int` | 140 | | message | `Success` | `String` | 141 | | data | `null` | `null` | 142 | 143 | #### `获取在线玩家` 144 | 145 | ##### Request 146 | 147 | | 请求参数 | 请求数据 | 类型 | 148 | |--------|----------|----------| 149 | | action | `online` | `String` | 150 | 151 | ##### Response 152 | 153 | | 返回参数 | 返回数据 | 类型 | 154 | |---------|---------------------------------|--------------| 155 | | retcode | `200` | `Int` | 156 | | message | `Success` | `String` | 157 | | data | `{"count": 0, playerList": []}` | `JsonObject` | 158 | 159 | #### `发送验证码` 160 | 161 | ##### Request 162 | 163 | | 请求参数 | 请求数据 | 类型 | 164 | |--------|------------|----------| 165 | | action | `sendCode` | `String` | 166 | | data | `uid` | `Int` | 167 | 168 | ##### Response 169 | 170 | | 返回参数 | 返回数据 | 类型 | 171 | |---------|-----------|----------| 172 | | retcode | `200` | `Int` | 173 | | message | `Success` | `String` | 174 | | data | `token` | `String` | 175 | 176 | #### `验证验证码` 177 | 178 | ##### Request 179 | 180 | | 请求参数 | 请求数据 | 类型 | 181 | |--------|----------|----------| 182 | | action | `verify` | `String` | 183 | | token | `token` | `String` | 184 | | data | `code` | `Int` | 185 | 186 | ##### Response 187 | 188 | 成功 189 | 190 | | 返回参数 | 返回数据 | 类型 | 191 | |---------|-----------|----------| 192 | | retcode | `200` | `Int` | 193 | | message | `Success` | `String` | 194 | | data | `null` | `null` | 195 | 196 | 失败 197 | 198 | | 返回参数 | 返回数据 | 类型 | 199 | |---------|-----------------------|----------| 200 | | retcode | `400` | `Int` | 201 | | message | `Verification failed` | `String` | 202 | | data | `null` | `null` | 203 | 204 | #### `执行命令` 205 | 206 | ##### Request 207 | 208 | | 请求参数 | 请求数据 | 类型 | 209 | |--------|-----------|----------| 210 | | action | `command` | `String` | 211 | | token | `token` | `String` | 212 | | data | `command` | `String` | 213 | 214 | ##### Response 215 | 216 | 成功 217 | 218 | | 返回参数 | 返回数据 | 类型 | 219 | |---------|------------------|----------| 220 | | retcode | `200` | `Int` | 221 | | message | `Success` | `String` | 222 | | data | `Command return` | `String` | 223 | 224 | ### 执行控制台命令 225 | 226 | #### `获取运行模式` 227 | 228 | ##### Request 229 | 230 | | 请求参数 | 请求数据 | 类型 | 231 | |--------|-----------|----------| 232 | | action | `runmode` | `String` | 233 | | token | `token` | `String` | 234 | 235 | ##### Response 236 | 237 | 成功 238 | 239 | | 返回参数 | 返回数据 | 类型 | 240 | |---------|-----------------------|----------| 241 | | retcode | `200` | `Int` | 242 | | message | `Success` | `String` | 243 | | data | `1 (多服务器) / 0 (单服务器)` | `Int` | 244 | 245 | #### `获取多服务器列表` 246 | 247 | ##### Request 248 | 249 | | 请求参数 | 请求数据 | 类型 | 250 | |--------|----------|----------| 251 | | action | `server` | `String` | 252 | | token | `token` | `String` | 253 | 254 | ##### Response 255 | 256 | 成功 257 | 258 | | 返回参数 | 返回数据 | 类型 | 259 | |---------|-----------|--------------| 260 | | retcode | `200` | `Int` | 261 | | message | `Success` | `String` | 262 | | data | `{}` | `JsonObject` | 263 | 264 | ```json5 265 | { 266 | "retcode": 200, 267 | "message": "success", 268 | "data": { 269 | // 服务器 UUID 270 | "13d82d0d-c7d9-47dd-830c-76588006ef6e": "2.8.0 服务器", 271 | "e6b83224-a761-4023-be57-e054c5bb823a": "2.8.0 开发服务器" 272 | } 273 | } 274 | ``` 275 | 276 | #### `执行命令` 277 | 278 | ##### Request 279 | 280 | > 如果为单服务器则无需填写服务器 UUID 281 | 282 | | 请求参数 | 请求数据 | 类型 | 283 | |--------|-----------|----------| 284 | | action | `command` | `String` | 285 | | token | `token` | `String` | 286 | | server | `UUID` | `String` | 287 | | data | `command` | `String` | 288 | 289 | ##### Response 290 | 291 | 成功 292 | 293 | | 返回参数 | 返回数据 | 类型 | 294 | |---------|------------------|----------| 295 | | retcode | `200` | `Int` | 296 | | message | `Success` | `String` | 297 | | data | `Command return` | `String` | 298 | -------------------------------------------------------------------------------- /README_en-US.md: -------------------------------------------------------------------------------- 1 | # gc-opencommand-plugin 2 | 3 | [中文](README.md) | English 4 | 5 | A plugin that opens the GC command execution interface for third-party clients 6 | 7 | Since `1.7.0`, multiple commands can be separated by `|` or newline, for example: 8 | ```shell 9 | /a 1 | /a 2 10 | /a 3 11 | ``` 12 | 13 | Invoking `ping` the response data will contain the plugin version. 14 | 15 | ## Applications using this plug-in 16 | - [GrasscutterTools](https://github.com/jie65535/GrasscutterCommandGenerator) —— Windows Client Tools 17 | - [JGrasscutterCommand](https://github.com/jie65535/JGrasscutterCommand) —— [Mirai](https://github.com/mamoe/mirai) Plugin, run commands in QQ 18 | - [Yunzai-GrasscutterCommand](https://github.com/Zyy-boop/Yunzai-GrasscutterCommand) —— Yunzai-bot plugin, execute commands in QQ 19 | - More... 20 | 21 | ## Server installation 22 | 23 | 1. Download the `jar` in [Release](https://github.com/jie65535/gc-opencommand-plugin/releases) 24 | 2. Put it in the `grasscutter/plugins` folder 25 | 3. Restart `grasscutter` server 26 | 27 | ## Player 28 | 29 | 1. Fill in the service address in the Tool to check plugin status 30 | 2. Fill in the UID and send the verification code 31 | 3. Fill in the **4-digit integer verification code** received in the game into the Tool verification 32 | 4. Enjoy the convenience! 33 | 34 | ## Console connection 35 | 36 | 1. When starting for the first time, a `opencommand-plugin` directory will be generated under the `plugins` directory, 37 | open and edit `config.json` 38 | 2. Set the value of `consoleToken` to your connection key. It is recommended to use a long random string of at least 32 39 | characters. (automatically generated when empty is detected) 40 | 3. Restart the server to take effect 41 | 4. Select the console identity in the client, and fill in your `consoleToken` to run the command as the console identity 42 | 43 | --- 44 | 45 | ## Client request 46 | 47 | 1. `ping` to confirm whether the `opencommand` plugin is supported 48 | 2. `sendCode` sends a verification code to the specified player (re-send is not allowed within 1 minute), and save the 49 | returned `token` 50 | 3. Send `verify` check using `token` and **4-digit integer verification code** 51 | 4. If the verification is passed, you can use the `token` to execute the `command` action 52 | 53 | ## Build 54 | 55 | 1. `git clone https://github.com/jie65535/gc-opencommand-plugin` 56 | 2. `cd gc-opencommand-plugin` 57 | 3. `mkdir lib` 58 | 4. `mv path/to/grasscutter-1.x.x-dev.jar ./lib` 59 | 5. `gradle build` 60 | 61 | ## Multi server 62 | ### Master server (Dispatch) 63 | 1. Open `config.json` in the `opencommand-plugin` directory 64 | 2. Modify the `socketPort` value to an unused port 65 | 3. Set `sockettoken` multi server communication key. It is recommended to use a long random string of at least 32 characters. 66 | 4. Restart the server to make the configuration effective 67 | 68 | ### Sub server (Game) 69 | 1. Open `config.json` in the `opencommand-plugin` directory 70 | 2. Modify the `sockethost` and `socketport` values to the address and port of the primary server 71 | 3. Set the same value of `sockettoken` and the primary server 72 | 4. Set the `socketDisplayName` value to your server name (See below for usage [Jump](https://github.com/jie65535/gc-opencommand-plugin/blob/master/README_en-US.md#get-mulit-server-list)) 73 | 5. Restart the server to make the configuration effective 74 | 75 | --- 76 | 77 | ## `config.json` 78 | 79 | ```json5 80 | { 81 | // console connection token (automatically generated when empty is detected) 82 | "consoleToken": "", 83 | // Verification code expiration time (seconds) 84 | "codeExpirationTime_S": 60, 85 | // Temporary token expiration time (seconds) 86 | "tempTokenExpirationTime_S": 300, 87 | // Authorization token last used expiration time (hours) 88 | "tokenLastUseExpirationTime_H": 48, 89 | // Multi-server communication port 90 | "socketPort": 5746, 91 | // Multi-server communication key 92 | "socketToken": "", 93 | // Multi-server Dispatch server address 94 | "socketHost": "127.0.0.1", 95 | // multi-server display name 96 | "socketDisplayName": "" 97 | } 98 | ``` 99 | 100 | ## API `/opencommand/api` 101 | 102 | Example 103 | 104 | ``` 105 | https://127.0.0.1/opencommand/api 106 | ``` 107 | 108 | ## Request 109 | 110 | ```java 111 | public final class JsonRequest { 112 | public String token = ""; 113 | public String action = ""; 114 | public Seting server = ""; 115 | public Object data = null; 116 | } 117 | ``` 118 | 119 | ## Response 120 | 121 | ```java 122 | public final class JsonResponse { 123 | public int retcode = 200; 124 | public String message = "Success"; 125 | public Object data; 126 | } 127 | ``` 128 | 129 | ### Actions 130 | 131 | #### `Test connect` 132 | 133 | ##### Request 134 | 135 | | Request | Request data | type | 136 | |---------|--------------|----------| 137 | | action | `ping` | `String` | 138 | 139 | ##### Response 140 | 141 | | Response | Response data | type | 142 | |----------|---------------|----------| 143 | | retcode | `200` | `String` | 144 | | message | `Success` | `String` | 145 | | data | `null` | `null` | 146 | 147 | #### `Get online players` 148 | 149 | ##### Request 150 | 151 | | Request | Request data | type | 152 | |---------|--------------|----------| 153 | | action | `online` | `String` | 154 | 155 | ##### Response 156 | 157 | | Response | Response data | type | 158 | |----------|---------------------------------|--------------| 159 | | retcode | `200` | `String` | 160 | | message | `Success` | `String` | 161 | | data | `{"count": 0, playerList": []}` | `JsonObject` | 162 | 163 | #### `Send code` 164 | 165 | ##### Request 166 | 167 | | Request | Request data | type | 168 | |---------|--------------|----------| 169 | | action | `sendCode` | `String` | 170 | | data | `uid` | `Int` | 171 | 172 | ##### Response 173 | 174 | | Response | Response data | type | 175 | |----------|---------------|----------| 176 | | retcode | `200` | `String` | 177 | | message | `Success` | `String` | 178 | | data | `token` | `String` | 179 | 180 | #### `Verify code` 181 | 182 | ##### Request 183 | 184 | | Request | Request data | type | 185 | |---------|--------------|----------| 186 | | action | `verify` | `String` | 187 | | token | `token` | `String` | 188 | | data | `code` | `Int` | 189 | 190 | ##### Response 191 | 192 | Success 193 | 194 | | Response | Response data | type | 195 | |----------|---------------|----------| 196 | | retcode | `200` | `String` | 197 | | message | `Success` | `String` | 198 | | data | `null` | `null` | 199 | 200 | Failed 201 | 202 | | Response | Response data | type | 203 | |----------|-----------------------|----------| 204 | | retcode | `400` | `String` | 205 | | message | `Verification failed` | `String` | 206 | | data | `null` | `null` | 207 | 208 | #### `Run command` 209 | 210 | ##### Request 211 | 212 | | Request | Request data | type | 213 | |---------|--------------|----------| 214 | | action | `command` | `String` | 215 | | token | `token` | `String` | 216 | | data | `command` | `String` | 217 | 218 | ##### Response 219 | 220 | Success 221 | 222 | | Response | Response data | type | 223 | |----------|------------------|----------| 224 | | retcode | `200` | `String` | 225 | | message | `Success` | `String` | 226 | | data | `Command return` | `String` | 227 | 228 | ### Run console command 229 | 230 | #### `Get run mode` 231 | 232 | ##### Request 233 | 234 | | Request | Request data | Type | 235 | |---------|--------------|----------| 236 | | action | `runmode` | `String` | 237 | | token | `token` | `String` | 238 | 239 | ##### Response 240 | 241 | Success 242 | 243 | | Request | Response data | Type | 244 | |---------|----------------------------------------|----------| 245 | | retcode | `200` | `Int` | 246 | | message | `Success` | `String` | 247 | | data | `1 (Multi server) / 0 (Single server)` | `Int` | 248 | 249 | #### `Get mulit server list` 250 | 251 | ##### Request 252 | 253 | | Request | Request data | Type | 254 | |---------|--------------|----------| 255 | | action | `server` | `String` | 256 | | token | `token` | `String` | 257 | 258 | ##### Response 259 | 260 | Success 261 | 262 | | Request | Response data | Type | 263 | |---------|---------------|--------------| 264 | | retcode | `200` | `Int` | 265 | | message | `Success` | `String` | 266 | | data | `{}` | `JsonObject` | 267 | 268 | ```json5 269 | { 270 | "retcode": 200, 271 | "message": "success", 272 | "data": { 273 | // Server UUID 274 | "13d82d0d-c7d9-47dd-830c-76588006ef6e": "2.8.0 Server", 275 | "e6b83224-a761-4023-be57-e054c5bb823a": "2.8.0 Dev server" 276 | } 277 | } 278 | ``` 279 | 280 | #### `Run command` 281 | 282 | ##### Request 283 | 284 | > If it is a single server, there is no need to fill in server UUID. 285 | 286 | | Request | Request data | Type | 287 | |---------|--------------|----------| 288 | | action | `command` | `String` | 289 | | token | `token` | `String` | 290 | | server | `UUID` | `String` | 291 | | data | `command` | `String` | 292 | 293 | ##### Response 294 | 295 | Success 296 | 297 | | Request | Response data | Type | 298 | |---------|------------------|----------| 299 | | retcode | `200` | `Int` | 300 | | message | `Success` | `String` | 301 | | data | `Command return` | `String` | 302 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'idea' 4 | } 5 | 6 | group 'com.github.jie65535.opencommand' 7 | version '1.7.0' 8 | 9 | sourceCompatibility = 17 10 | targetCompatibility = 17 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation fileTree(dir: 'lib', include: ['*.jar']) 18 | } 19 | 20 | jar { 21 | jar.baseName = 'opencommand' 22 | 23 | destinationDir = file(".") 24 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jie65535/gc-opencommand-plugin/896b802bff96248990d37dbcf11ee2fe99efbfa2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'gc-opencommand' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/EventListeners.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand; 19 | 20 | import com.github.jie65535.opencommand.socket.SocketClient; 21 | import com.github.jie65535.opencommand.socket.packet.player.PlayerList; 22 | import emu.grasscutter.Grasscutter; 23 | import emu.grasscutter.game.player.Player; 24 | import emu.grasscutter.server.event.game.ReceiveCommandFeedbackEvent; 25 | import emu.grasscutter.server.event.player.PlayerJoinEvent; 26 | import emu.grasscutter.server.event.player.PlayerQuitEvent; 27 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap; 28 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; 29 | 30 | import java.util.ArrayList; 31 | 32 | public final class EventListeners { 33 | 34 | private static StringBuilder consoleMessageHandler; 35 | private static final Int2ObjectMap playerMessageHandlers = new Int2ObjectOpenHashMap<>(); 36 | 37 | public static void setConsoleMessageHandler(StringBuilder handler) { 38 | consoleMessageHandler = handler; 39 | } 40 | 41 | /** 42 | * 获取新的玩家消息处理类 43 | * 获取时将创建或清空消息处理器并返回实例,**在执行命令前获取!** 44 | * @param uid 玩家uid 45 | * @return 新的玩家消息处理类 46 | */ 47 | public static StringBuilder getPlayerMessageHandler(int uid) { 48 | var handler = playerMessageHandlers.get(uid); 49 | if (handler == null) { 50 | handler = new StringBuilder(); 51 | playerMessageHandlers.put(uid, handler); 52 | } 53 | return handler; 54 | } 55 | 56 | /** 57 | * 命令执行反馈事件处理 58 | */ 59 | public static void onCommandResponse(ReceiveCommandFeedbackEvent event) { 60 | StringBuilder handler; 61 | if (event.getPlayer() == null) { 62 | handler = consoleMessageHandler; 63 | } else { 64 | handler = playerMessageHandlers.get(event.getPlayer().getUid()); 65 | } 66 | 67 | if (handler != null) { 68 | if (!handler.isEmpty()) { 69 | // New line 70 | handler.append(System.lineSeparator()); 71 | } 72 | handler.append(event.getMessage()); 73 | } 74 | } 75 | 76 | public static void onPlayerJoin(PlayerJoinEvent playerJoinEvent) { 77 | PlayerList playerList = new PlayerList(); 78 | playerList.player = Grasscutter.getGameServer().getPlayers().size(); 79 | ArrayList playerNames = new ArrayList<>(); 80 | playerNames.add(playerJoinEvent.getPlayer().getNickname()); 81 | playerList.playerMap.put(playerJoinEvent.getPlayer().getUid(), playerJoinEvent.getPlayer().getNickname()); 82 | for (Player player : Grasscutter.getGameServer().getPlayers().values()) { 83 | playerNames.add(player.getNickname()); 84 | playerList.playerMap.put(player.getUid(), player.getNickname()); 85 | } 86 | playerList.playerList = playerNames; 87 | 88 | SocketClient.sendPacket(playerList); 89 | } 90 | 91 | /** 92 | * 仅游戏模式下玩家离开事件处理方法 93 | * 用于更新玩家列表 94 | */ 95 | public static void onPlayerQuit(PlayerQuitEvent playerQuitEvent) { 96 | PlayerList playerList = new PlayerList(); 97 | playerList.player = Grasscutter.getGameServer().getPlayers().size(); 98 | ArrayList playerNames = new ArrayList<>(); 99 | for (Player player : Grasscutter.getGameServer().getPlayers().values()) { 100 | playerNames.add(player.getNickname()); 101 | playerList.playerMap.put(player.getUid(), player.getNickname()); 102 | } 103 | playerList.playerMap.remove(playerQuitEvent.getPlayer().getUid()); 104 | playerNames.remove(playerQuitEvent.getPlayer().getNickname()); 105 | playerList.playerList = playerNames; 106 | SocketClient.sendPacket(playerList); 107 | } 108 | 109 | /** 110 | * 玩家离开事件处理 2 111 | * 用于清理内存 112 | */ 113 | public static void onPlayerQuit2(PlayerQuitEvent playerQuitEvent) { 114 | var uid = playerQuitEvent.getPlayer().getUid(); 115 | if (playerMessageHandlers.containsKey(uid)) { 116 | playerMessageHandlers.remove(uid); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/OpenCommandConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand; 19 | 20 | public class OpenCommandConfig { 21 | /** 22 | * 控制台 Token 23 | */ 24 | public String consoleToken = ""; 25 | 26 | /** 27 | * 验证码过期时间(单位秒) 28 | */ 29 | public int codeExpirationTime_S = 60; 30 | 31 | /** 32 | * 临时Token过期时间(单位秒) 33 | */ 34 | public int tempTokenExpirationTime_S = 300; 35 | 36 | /** 37 | * Token 最后使用过期时间(单位小时) 38 | */ 39 | public int tokenLastUseExpirationTime_H = 48; 40 | 41 | /** 42 | * Socket 端口 43 | */ 44 | public int socketPort = 5746; 45 | 46 | /** 47 | * Socket Token 48 | */ 49 | public String socketToken = ""; 50 | 51 | /** 52 | * Socket 主机地址 53 | */ 54 | public String socketHost = "127.0.0.1"; 55 | 56 | /** 57 | * Socket 显示名称 58 | */ 59 | public String socketDisplayName = ""; 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/OpenCommandData.java: -------------------------------------------------------------------------------- 1 | package com.github.jie65535.opencommand; 2 | 3 | import com.github.jie65535.opencommand.model.Client; 4 | 5 | import java.util.Date; 6 | import java.util.Vector; 7 | 8 | /** 9 | * 插件持久化数据 10 | */ 11 | public class OpenCommandData { 12 | 13 | /** 14 | * 连接的客户端列表 15 | */ 16 | public Vector clients = new Vector<>(); 17 | 18 | /** 19 | * 通过令牌获取客户端 20 | * @param token 令牌 21 | * @return 客户端对象,若未找到返回null 22 | */ 23 | public Client getClientByToken(String token) { 24 | for (var c : clients) { 25 | if (c.token.equals(token)) 26 | return c; 27 | } 28 | return null; 29 | } 30 | 31 | /** 32 | * 移除所有过期的客户端 33 | */ 34 | public void removeExpiredClients() { 35 | var now = new Date(); 36 | clients.removeIf(client -> client.tokenExpireTime.before(now)); 37 | } 38 | 39 | public void addClient(Client client) { 40 | clients.add(client); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/OpenCommandHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand; 19 | 20 | import com.github.jie65535.opencommand.json.JsonRequest; 21 | import com.github.jie65535.opencommand.json.JsonResponse; 22 | import com.github.jie65535.opencommand.model.Client; 23 | import com.github.jie65535.opencommand.socket.SocketData; 24 | import emu.grasscutter.command.CommandMap; 25 | import emu.grasscutter.game.player.Player; 26 | import emu.grasscutter.server.http.Router; 27 | import emu.grasscutter.utils.Crypto; 28 | import emu.grasscutter.utils.Utils; 29 | import io.javalin.Javalin; 30 | import io.javalin.http.Context; 31 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap; 32 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; 33 | 34 | import java.util.ArrayList; 35 | import java.util.Date; 36 | import java.util.HashMap; 37 | import java.util.Map; 38 | 39 | public final class OpenCommandHandler implements Router { 40 | 41 | @Override 42 | public void applyRoutes(Javalin javalin) { 43 | javalin.post("/opencommand/api", OpenCommandHandler::handle); 44 | } 45 | 46 | private static final Map codes = new HashMap<>(); 47 | private static final Int2ObjectMap codeExpireTime = new Int2ObjectOpenHashMap<>(); 48 | 49 | 50 | public static void handle(Context context) { 51 | var plugin = OpenCommandPlugin.getInstance(); 52 | try { 53 | var config = plugin.getConfig(); 54 | var data = plugin.getData(); 55 | var now = new Date(); 56 | // Trigger cleanup action 57 | cleanupExpiredCodes(); 58 | data.removeExpiredClients(); 59 | 60 | var req = context.bodyAsClass(JsonRequest.class); 61 | if (req.action.equals("sendCode")) { 62 | int playerId = (int)Double.parseDouble(req.data.toString()); 63 | var player = plugin.getServer().getPlayerByUid(playerId); 64 | if (player == null) { 65 | context.json(new JsonResponse(404, "Player Not Found.")); 66 | } else { 67 | if (codeExpireTime.containsKey(playerId)) { 68 | var expireTime = codeExpireTime.get(playerId); 69 | if (now.before(expireTime)) { 70 | context.json(new JsonResponse(403, "Requests are too frequent")); 71 | return; 72 | } 73 | } 74 | 75 | String token = req.token; 76 | if (token == null || token.isEmpty()) 77 | token = Utils.bytesToHex(Crypto.createSessionKey(32)); 78 | int code = Utils.randomRange(1000, 9999); 79 | codeExpireTime.put(playerId, new Date(now.getTime() + config.codeExpirationTime_S * 1000L)); 80 | codes.put(token, code); 81 | data.addClient(new Client(token, playerId, new Date(now.getTime() + config.tempTokenExpirationTime_S * 1000L))); 82 | player.dropMessage("[Open Command] Verification code: " + code); 83 | context.json(new JsonResponse(token)); 84 | } 85 | return; 86 | } else if (req.action.equals("ping")) { 87 | context.json(new JsonResponse(plugin.getVersion())); 88 | return; 89 | } else if (req.action.equals("online")) { 90 | var p = new ArrayList(); 91 | plugin.getServer().getPlayers().forEach((uid, player) -> p.add(player.getNickname())); 92 | context.json(new JsonResponse(200, "Success", new SocketData.OnlinePlayer(p))); 93 | return; 94 | } 95 | 96 | // token is required 97 | if (req.token == null || req.token.isEmpty()) { 98 | context.json(new JsonResponse(401, "Unauthorized")); 99 | return; 100 | } 101 | var isConsole = req.token.equals(config.consoleToken); 102 | var client = data.getClientByToken(req.token); 103 | if (!isConsole && client == null) { 104 | context.json(new JsonResponse(401, "Unauthorized")); 105 | return; 106 | } 107 | 108 | if (isConsole) { 109 | if (req.action.equals("verify")) { 110 | context.json(new JsonResponse()); 111 | return; 112 | } else if (req.action.equals("command")) { 113 | //noinspection SynchronizationOnLocalVariableOrMethodParameter 114 | synchronized (plugin) { 115 | try { 116 | plugin.getLogger().info(String.format("IP: %s run command in console > %s", context.ip(), req.data)); 117 | var resultCollector = new StringBuilder(); 118 | EventListeners.setConsoleMessageHandler(resultCollector); 119 | tryInvokeCommand(null, null, req.data.toString()); 120 | context.json(new JsonResponse(resultCollector.toString())); 121 | } catch (Exception e) { 122 | plugin.getLogger().warn("Run command failed.", e); 123 | EventListeners.setConsoleMessageHandler(null); 124 | context.json(new JsonResponse(500, "error", e.getLocalizedMessage())); 125 | } 126 | } 127 | return; 128 | } else if (req.action.equals("runmode")) { 129 | context.json(new JsonResponse(200, "Success", 0)); 130 | return; 131 | } 132 | } else if (codes.containsKey(req.token)) { 133 | if (req.action.equals("verify")) { 134 | if (codes.get(req.token) == (int)Double.parseDouble(req.data.toString())) { 135 | codes.remove(req.token); 136 | // update token expire time 137 | client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L); 138 | context.json(new JsonResponse()); 139 | plugin.getLogger().info(String.format("Player %d has passed the verification, ip: %s", client.playerId, context.ip())); 140 | plugin.saveData(); 141 | } else { 142 | context.json(new JsonResponse(400, "Verification failed")); 143 | } 144 | return; 145 | } 146 | } else { 147 | if (req.action.equals("command")) { 148 | // update token expire time 149 | client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L); 150 | var player = plugin.getServer().getPlayerByUid(client.playerId); 151 | if (player == null) { 152 | context.json(new JsonResponse(404, "Player not found")); 153 | return; 154 | } 155 | // Player MessageHandler do not support concurrency 156 | var handler = EventListeners.getPlayerMessageHandler(player.getUid()); 157 | //noinspection SynchronizationOnLocalVariableOrMethodParameter 158 | synchronized (handler) { 159 | try { 160 | handler.setLength(0); 161 | tryInvokeCommand(player, player, req.data.toString()); 162 | context.json(new JsonResponse(handler.toString())); 163 | } catch (Exception e) { 164 | plugin.getLogger().warn("Run command failed.", e); 165 | context.json(new JsonResponse(500, "error", e.getLocalizedMessage())); 166 | } 167 | } 168 | return; 169 | } 170 | } 171 | context.json(new JsonResponse(403, "forbidden")); 172 | } catch (Throwable ex) { 173 | plugin.getLogger().error("[OpenCommand] handler error.", ex); 174 | } 175 | } 176 | 177 | private static void tryInvokeCommand(Player sender, Player target, String rawMessage) { 178 | for (var command : rawMessage.split("\n[/!]|\\|")) { 179 | command = command.trim(); 180 | if (command.isEmpty()) continue; 181 | if (command.charAt(0) == '/' || command.charAt(0) == '!') { 182 | command = command.substring(1); 183 | } 184 | CommandMap.getInstance().invoke(sender, target, command); 185 | } 186 | } 187 | 188 | private static void cleanupExpiredCodes() { 189 | var now = new Date(); 190 | codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now)); 191 | if (codeExpireTime.isEmpty()) 192 | codes.clear(); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/OpenCommandOnlyHttpHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand; 19 | 20 | import com.github.jie65535.opencommand.json.JsonRequest; 21 | import com.github.jie65535.opencommand.json.JsonResponse; 22 | import com.github.jie65535.opencommand.model.Client; 23 | import com.github.jie65535.opencommand.socket.SocketData; 24 | import com.github.jie65535.opencommand.socket.SocketDataWait; 25 | import com.github.jie65535.opencommand.socket.SocketServer; 26 | import com.github.jie65535.opencommand.socket.packet.HttpPacket; 27 | import com.github.jie65535.opencommand.socket.packet.RunConsoleCommand; 28 | import com.github.jie65535.opencommand.socket.packet.player.Player; 29 | import com.github.jie65535.opencommand.socket.packet.player.PlayerEnum; 30 | import emu.grasscutter.server.http.Router; 31 | import emu.grasscutter.utils.Crypto; 32 | import emu.grasscutter.utils.Utils; 33 | import io.javalin.Javalin; 34 | import io.javalin.http.Context; 35 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap; 36 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; 37 | 38 | import java.util.Date; 39 | import java.util.HashMap; 40 | import java.util.Map; 41 | 42 | public final class OpenCommandOnlyHttpHandler implements Router { 43 | 44 | @Override 45 | public void applyRoutes(Javalin javalin) { 46 | javalin.post("/opencommand/api", OpenCommandOnlyHttpHandler::handle); 47 | } 48 | 49 | private static final Map codes = new HashMap<>(); 50 | private static final Int2ObjectMap codeExpireTime = new Int2ObjectOpenHashMap<>(); 51 | 52 | public static void handle(Context context) { 53 | var plugin = OpenCommandPlugin.getInstance(); 54 | try { 55 | var config = plugin.getConfig(); 56 | var data = plugin.getData(); 57 | var now = new Date(); 58 | // Trigger cleanup action 59 | cleanupExpiredCodes(); 60 | data.removeExpiredClients(); 61 | 62 | var req = context.bodyAsClass(JsonRequest.class); 63 | if (req.action.equals("sendCode")) { 64 | int playerId = (int)Double.parseDouble(req.data.toString()); 65 | var player = SocketData.getPlayer(playerId); 66 | if (player == null) { 67 | context.json(new JsonResponse(404, "Player Not Found.")); 68 | } else { 69 | if (codeExpireTime.containsKey(playerId)) { 70 | var expireTime = codeExpireTime.get(playerId); 71 | if (now.before(expireTime)) { 72 | context.json(new JsonResponse(403, "Requests are too frequent")); 73 | return; 74 | } 75 | } 76 | 77 | String token = req.token; 78 | if (token == null || token.isEmpty()) 79 | token = Utils.bytesToHex(Crypto.createSessionKey(32)); 80 | int code = Utils.randomRange(1000, 9999); 81 | codeExpireTime.put(playerId, new Date(now.getTime() + config.codeExpirationTime_S * 1000L)); 82 | codes.put(token, code); 83 | data.addClient(new Client(token, playerId, new Date(now.getTime() + config.tempTokenExpirationTime_S * 1000L))); 84 | Player.dropMessage(playerId, "[Open Command] Verification code: " + code); 85 | context.json(new JsonResponse(token)); 86 | } 87 | return; 88 | } else if (req.action.equals("ping")) { 89 | context.json(new JsonResponse()); 90 | return; 91 | } else if (req.action.equals("online")) { 92 | context.json(new JsonResponse(200, "Success", SocketData.getOnlinePlayer())); 93 | return; 94 | } 95 | 96 | // token is required 97 | if (req.token == null || req.token.isEmpty()) { 98 | context.json(new JsonResponse(401, "Unauthorized")); 99 | return; 100 | } 101 | var isConsole = req.token.equals(config.consoleToken); 102 | var client = data.getClientByToken(req.token); 103 | if (!isConsole && client == null) { 104 | context.json(new JsonResponse(401, "Unauthorized")); 105 | return; 106 | } 107 | 108 | if (isConsole) { 109 | if (req.action.equals("verify")) { 110 | context.json(new JsonResponse()); 111 | return; 112 | } else if (req.action.equals("command")) { 113 | var server = SocketServer.getClientInfoByUuid(req.server); 114 | if (server == null) { 115 | context.json(new JsonResponse(404, "Server Not Found.")); 116 | return; 117 | } 118 | plugin.getLogger().info(String.format("IP: %s run command in console > %s", context.ip(), req.data)); 119 | var wait = new SocketDataWait(2000L) { 120 | @Override 121 | public void run() { 122 | } 123 | 124 | @Override 125 | public HttpPacket initData(HttpPacket data) { 126 | return data; 127 | } 128 | 129 | @Override 130 | public void timeout() { 131 | } 132 | }; 133 | 134 | SocketServer.sendPacketAndWait(server.ip, new RunConsoleCommand(req.data.toString()), wait); 135 | var packet = wait.getData(); 136 | if (packet == null) { 137 | context.json(new JsonResponse(408, "Timeout")); 138 | return; 139 | } 140 | context.json(new JsonResponse(packet.code, packet.message, packet.data)); 141 | return; 142 | } else if (req.action.equals("server")) { 143 | context.json(new JsonResponse(200, "Success", SocketServer.getOnlineClient())); 144 | return; 145 | } else if (req.action.equals("runmode")) { 146 | context.json(new JsonResponse(200, "Success", 1)); 147 | return; 148 | } 149 | } else if (codes.containsKey(req.token)) { 150 | if (req.action.equals("verify")) { 151 | if (codes.get(req.token) == (int)Double.parseDouble(req.data.toString())) { 152 | codes.remove(req.token); 153 | // update token expire time 154 | client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L); 155 | context.json(new JsonResponse()); 156 | plugin.getLogger().info(String.format("Player %d has passed the verification, ip: %s", client.playerId, context.ip())); 157 | plugin.saveData(); 158 | } else { 159 | context.json(new JsonResponse(400, "Verification failed")); 160 | } 161 | return; 162 | } 163 | } else { 164 | if (req.action.equals("command")) { 165 | SocketDataWait socketDataWait = new SocketDataWait<>(1000L * 10L) { 166 | @Override 167 | public void run() { 168 | } 169 | 170 | @Override 171 | public HttpPacket initData(HttpPacket data) { 172 | return data; 173 | } 174 | 175 | @Override 176 | public void timeout() { 177 | } 178 | }; 179 | 180 | // update token expire time 181 | client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L); 182 | var command = req.data.toString(); 183 | var player = new Player(); 184 | player.uid = client.playerId; 185 | player.type = PlayerEnum.RunCommand; 186 | player.data = command; 187 | 188 | if (!SocketServer.sendUidPacketAndWait(client.playerId, player, socketDataWait)) { 189 | context.json(new JsonResponse(404, "Player Not Found.")); 190 | return; 191 | } 192 | 193 | 194 | HttpPacket httpPacket = socketDataWait.getData(); 195 | if (httpPacket == null) { 196 | context.json(new JsonResponse(500, "error", "Wait timeout")); 197 | return; 198 | } 199 | context.json(new JsonResponse(httpPacket.code, httpPacket.message)); 200 | return; 201 | } 202 | } 203 | context.json(new JsonResponse(403, "forbidden")); 204 | } catch (Exception ex) { 205 | plugin.getLogger().error("[OpenCommand] handler error.", ex); 206 | } 207 | } 208 | 209 | private static void cleanupExpiredCodes() { 210 | var now = new Date(); 211 | codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now)); 212 | if (codeExpireTime.isEmpty()) 213 | codes.clear(); 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/OpenCommandPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand; 19 | 20 | import com.github.jie65535.opencommand.socket.SocketClient; 21 | import com.github.jie65535.opencommand.socket.SocketServer; 22 | import emu.grasscutter.Grasscutter; 23 | import emu.grasscutter.plugin.Plugin; 24 | import emu.grasscutter.server.event.EventHandler; 25 | import emu.grasscutter.server.event.HandlerPriority; 26 | import emu.grasscutter.server.event.game.ReceiveCommandFeedbackEvent; 27 | import emu.grasscutter.server.event.player.PlayerJoinEvent; 28 | import emu.grasscutter.server.event.player.PlayerQuitEvent; 29 | import emu.grasscutter.utils.Crypto; 30 | import emu.grasscutter.utils.JsonUtils; 31 | import emu.grasscutter.utils.Utils; 32 | 33 | import java.io.*; 34 | import java.nio.charset.StandardCharsets; 35 | import java.nio.file.Files; 36 | 37 | public final class OpenCommandPlugin extends Plugin { 38 | 39 | private static OpenCommandPlugin instance; 40 | 41 | public static OpenCommandPlugin getInstance() { 42 | return instance; 43 | } 44 | 45 | private OpenCommandConfig config; 46 | 47 | private OpenCommandData data; 48 | 49 | private Grasscutter.ServerRunMode runMode = Grasscutter.ServerRunMode.HYBRID; 50 | 51 | @Override 52 | public void onLoad() { 53 | instance = this; 54 | // 加载配置 55 | loadConfig(); 56 | // 加载数据 57 | loadData(); 58 | // 启动Socket 59 | startSocket(); 60 | } 61 | 62 | @Override 63 | public void onEnable() { 64 | // 监听命令执行反馈 65 | new EventHandler<>(ReceiveCommandFeedbackEvent.class) 66 | .priority(HandlerPriority.HIGH) 67 | .listener(EventListeners::onCommandResponse) 68 | .register(this); 69 | // 监听玩家离开事件 70 | new EventHandler<>(PlayerQuitEvent.class) 71 | .priority(HandlerPriority.NORMAL) 72 | .listener(EventListeners::onPlayerQuit2) 73 | .register(this); 74 | if (runMode == Grasscutter.ServerRunMode.GAME_ONLY) { 75 | // 仅运行游戏服务器时注册玩家加入和离开事件 76 | new EventHandler<>(PlayerJoinEvent.class) 77 | .priority(HandlerPriority.HIGH) 78 | .listener(EventListeners::onPlayerJoin) 79 | .register(this); 80 | new EventHandler<>(PlayerQuitEvent.class) 81 | .priority(HandlerPriority.HIGH) 82 | .listener(EventListeners::onPlayerQuit) 83 | .register(this); 84 | } else if (runMode == Grasscutter.ServerRunMode.DISPATCH_ONLY) { 85 | getHandle().addRouter(OpenCommandOnlyHttpHandler.class); 86 | } else { 87 | getHandle().addRouter(OpenCommandHandler.class); 88 | } 89 | getLogger().info("[OpenCommand] Enabled. https://github.com/jie65535/gc-opencommand-plugin"); 90 | } 91 | 92 | @Override 93 | public void onDisable() { 94 | saveData(); 95 | getLogger().info("[OpenCommand] Disabled"); 96 | } 97 | 98 | public OpenCommandConfig getConfig() { 99 | return config; 100 | } 101 | 102 | public OpenCommandData getData() { 103 | return data; 104 | } 105 | 106 | private void loadConfig() { 107 | var configFile = new File(getDataFolder(), "config.json"); 108 | if (!configFile.exists()) { 109 | config = new OpenCommandConfig(); 110 | saveConfig(); 111 | } else { 112 | try { 113 | config = JsonUtils.decode(Files.readString(configFile.toPath(), StandardCharsets.UTF_8), 114 | OpenCommandConfig.class); 115 | } catch (Exception exception) { 116 | config = new OpenCommandConfig(); 117 | getLogger().error("[OpenCommand] There was an error while trying to load the configuration from config.json. Please make sure that there are no syntax errors. If you want to start with a default configuration, delete your existing config.json."); 118 | } 119 | } 120 | 121 | // 检查控制台Token 122 | if (config.consoleToken == null || config.consoleToken.isEmpty()) { 123 | config.consoleToken = Utils.base64Encode(Crypto.createSessionKey(24)); 124 | saveConfig(); 125 | getLogger().warn("Detected that consoleToken is empty, automatically generated Token for you as follows: {}", config.consoleToken); 126 | } 127 | 128 | try { 129 | runMode = Grasscutter.getConfig().server.runMode; 130 | } catch (Exception ex) { 131 | getLogger().warn("[OpenCommand] Failed to load server configuration, default HYBRID mode is being used."); 132 | } 133 | } 134 | 135 | private void saveConfig() { 136 | var configFile = new File(getDataFolder(), "config.json"); 137 | try (var file = new FileWriter(configFile)) { 138 | file.write(JsonUtils.encode(config)); 139 | } catch (IOException e) { 140 | getLogger().error("[OpenCommand] Unable to write to config file."); 141 | } catch (Exception e) { 142 | getLogger().error("[OpenCommand] Unable to save config file."); 143 | } 144 | } 145 | 146 | private void loadData() { 147 | var dataFile = new File(getDataFolder(), "data.json"); 148 | if (!dataFile.exists()) { 149 | data = new OpenCommandData(); 150 | saveData(); 151 | } else { 152 | try { 153 | data = JsonUtils.decode(Files.readString(dataFile.toPath(), StandardCharsets.UTF_8), 154 | OpenCommandData.class); 155 | } catch (Exception exception) { 156 | getLogger().error("[OpenCommand] There was an error while trying to load the data from data.json. Please make sure that there are no syntax errors. If you want to start with a default data, delete your existing data.json."); 157 | } 158 | if (data == null) { 159 | data = new OpenCommandData(); 160 | } 161 | } 162 | } 163 | 164 | public void saveData() { 165 | try (var file = new FileWriter(new File(getDataFolder(), "data.json"))) { 166 | file.write(JsonUtils.encode(data)); 167 | } catch (IOException e) { 168 | getLogger().error("[OpenCommand] Unable to write to data file."); 169 | } catch (Exception e) { 170 | getLogger().error("[OpenCommand] Unable to save data file."); 171 | } 172 | } 173 | 174 | private void startSocket() { 175 | if (runMode == Grasscutter.ServerRunMode.GAME_ONLY) { 176 | getLogger().info("[OpenCommand] Starting socket client..."); 177 | SocketClient.connectServer(); 178 | } else if (runMode == Grasscutter.ServerRunMode.DISPATCH_ONLY) { 179 | getLogger().info("[OpenCommand] Starting socket server..."); 180 | try { 181 | SocketServer.startServer(); 182 | } catch (IOException e) { 183 | getLogger().error("[OpenCommand] Unable to start socket server.", e); 184 | } 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/json/JsonRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.json; 19 | 20 | public final class JsonRequest { 21 | public String token = ""; 22 | public String action = ""; 23 | public String server = ""; 24 | public Object data = null; 25 | } -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/json/JsonResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.json; 19 | 20 | public final class JsonResponse { 21 | public int retcode = 200; 22 | public String message = "Success"; 23 | public Object data; 24 | 25 | public JsonResponse() { 26 | 27 | } 28 | 29 | public JsonResponse(int code, String message) { 30 | this.retcode = code; 31 | this.message = message; 32 | } 33 | 34 | public JsonResponse(int code, String message, Object data) { 35 | this.retcode = code; 36 | this.message = message; 37 | this.data = data; 38 | } 39 | 40 | public JsonResponse(Object data) { 41 | this.data = data; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/model/Client.java: -------------------------------------------------------------------------------- 1 | package com.github.jie65535.opencommand.model; 2 | 3 | import java.util.Date; 4 | 5 | public final class Client { 6 | 7 | public String token; 8 | public Integer playerId; 9 | public Date tokenExpireTime; 10 | 11 | public Client(String token, Integer playerId, Date tokenExpireTime) { 12 | this.token = token; 13 | this.playerId = playerId; 14 | this.tokenExpireTime = tokenExpireTime; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/ClientInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket; 19 | 20 | public class ClientInfo { 21 | 22 | public final String uuid; 23 | public final SocketServer.ClientThread clientThread; 24 | public final String ip; 25 | 26 | public ClientInfo(String uuid, String ip, SocketServer.ClientThread clientThread) { 27 | this.uuid = uuid; 28 | this.clientThread = clientThread; 29 | this.ip = ip; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/SocketClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket; 19 | 20 | import com.github.jie65535.opencommand.EventListeners; 21 | import com.github.jie65535.opencommand.OpenCommandConfig; 22 | import com.github.jie65535.opencommand.OpenCommandPlugin; 23 | import com.github.jie65535.opencommand.socket.packet.*; 24 | import com.github.jie65535.opencommand.socket.packet.player.Player; 25 | import com.github.jie65535.opencommand.socket.packet.player.PlayerList; 26 | import emu.grasscutter.Grasscutter; 27 | import emu.grasscutter.command.CommandMap; 28 | import emu.grasscutter.utils.JsonUtils; 29 | import org.slf4j.Logger; 30 | 31 | import java.io.IOException; 32 | import java.io.InputStream; 33 | import java.io.OutputStream; 34 | import java.net.Socket; 35 | import java.util.ArrayList; 36 | import java.util.Timer; 37 | import java.util.TimerTask; 38 | 39 | // Socket 客户端 40 | public class SocketClient { 41 | public static ClientThread clientThread; 42 | 43 | public static Logger mLogger; 44 | 45 | public static Timer timer; 46 | 47 | public static boolean connect = false; 48 | 49 | public static ReceiveThread receiveThread; 50 | 51 | // 连接服务器 52 | public static void connectServer() { 53 | if (connect) return; 54 | if (clientThread != null) { 55 | mLogger.warn("[OpenCommand] Retry connecting to the server after 15 seconds"); 56 | try { 57 | Thread.sleep(15000); 58 | } catch (InterruptedException ex) { 59 | throw new RuntimeException(ex); 60 | } 61 | } 62 | OpenCommandConfig config = OpenCommandPlugin.getInstance().getConfig(); 63 | mLogger = OpenCommandPlugin.getInstance().getLogger(); 64 | clientThread = new ClientThread(config.socketHost, config.socketPort); 65 | 66 | if (timer != null) { 67 | timer.cancel(); 68 | } 69 | timer = new Timer(); 70 | timer.schedule(new SendHeartBeatPacket(), 500); 71 | timer.schedule(new SendPlayerListPacket(), 1000); 72 | } 73 | 74 | // 发送数据包 75 | public static boolean sendPacket(BasePacket packet) { 76 | var p = SocketUtils.getPacket(packet); 77 | if (!clientThread.sendPacket(p)) { 78 | mLogger.warn("[OpenCommand] Send packet to server failed"); 79 | mLogger.info("[OpenCommand] Reconnect to server"); 80 | connect = false; 81 | connectServer(); 82 | return false; 83 | } 84 | return true; 85 | } 86 | 87 | // 发送数据包带数据包ID 88 | public static boolean sendPacket(BasePacket packet, String packetID) { 89 | if (!clientThread.sendPacket(SocketUtils.getPacketAndPackID(packet, packetID))) { 90 | mLogger.warn("[OpenCommand] Send packet to server failed"); 91 | mLogger.info("[OpenCommand] Reconnect to server"); 92 | connect = false; 93 | connectServer(); 94 | return false; 95 | } 96 | return true; 97 | } 98 | 99 | // 心跳包发送 100 | private static class SendHeartBeatPacket extends TimerTask { 101 | @Override 102 | public void run() { 103 | if (connect) { 104 | sendPacket(new HeartBeat("Pong")); 105 | } 106 | } 107 | } 108 | 109 | private static class SendPlayerListPacket extends TimerTask { 110 | @Override 111 | public void run() { 112 | if (connect) { 113 | PlayerList playerList = new PlayerList(); 114 | playerList.player = Grasscutter.getGameServer().getPlayers().size(); 115 | ArrayList playerNames = new ArrayList<>(); 116 | for (emu.grasscutter.game.player.Player player : Grasscutter.getGameServer().getPlayers().values()) { 117 | playerNames.add(player.getNickname()); 118 | playerList.playerMap.put(player.getUid(), player.getNickname()); 119 | } 120 | playerList.playerList = playerNames; 121 | sendPacket(playerList); 122 | } 123 | } 124 | } 125 | 126 | // 数据包接收 127 | private static class ReceiveThread extends Thread { 128 | private InputStream is; 129 | private boolean exit = false; 130 | 131 | public ReceiveThread(Socket socket) { 132 | try { 133 | is = socket.getInputStream(); 134 | } catch (IOException e) { 135 | e.printStackTrace(); 136 | } 137 | start(); 138 | } 139 | 140 | @Override 141 | public void run() { 142 | while (true) { 143 | try { 144 | if (exit) { 145 | return; 146 | } 147 | String data = SocketUtils.readString(is); 148 | Packet packet = JsonUtils.decode(data, Packet.class); 149 | switch (packet.type) { 150 | // 玩家类 151 | case Player: 152 | var player = JsonUtils.decode(packet.data, Player.class); 153 | switch (player.type) { 154 | // 运行命令 155 | case RunCommand -> { 156 | var command = player.data; 157 | var playerData = OpenCommandPlugin.getInstance().getServer().getPlayerByUid(player.uid); 158 | if (playerData == null) { 159 | sendPacket(new HttpPacket(404, "Player not found."), packet.packetID); 160 | return; 161 | } 162 | // Player MessageHandler do not support concurrency 163 | var handler = EventListeners.getPlayerMessageHandler(playerData.getUid()); 164 | //noinspection SynchronizationOnLocalVariableOrMethodParameter 165 | synchronized (handler) { 166 | try { 167 | handler.setLength(0); 168 | CommandMap.getInstance().invoke(playerData, playerData, command); 169 | sendPacket(new HttpPacket(200, handler.toString()), packet.packetID); 170 | } catch (Exception e) { 171 | OpenCommandPlugin.getInstance().getLogger().warn("[OpenCommand] Run command failed.", e); 172 | sendPacket(new HttpPacket(500, "error", e.getLocalizedMessage()), packet.packetID); 173 | } 174 | } 175 | } 176 | // 发送信息 177 | case DropMessage -> { 178 | var playerData = OpenCommandPlugin.getInstance().getServer().getPlayerByUid(player.uid); 179 | if (playerData == null) { 180 | return; 181 | } 182 | playerData.dropMessage(player.data); 183 | } 184 | } 185 | break; 186 | case RunConsoleCommand: 187 | var consoleCommand = JsonUtils.decode(packet.data, RunConsoleCommand.class); 188 | var plugin = OpenCommandPlugin.getInstance(); 189 | //noinspection SynchronizationOnLocalVariableOrMethodParameter 190 | synchronized (plugin) { 191 | try { 192 | var resultCollector = new StringBuilder(); 193 | EventListeners.setConsoleMessageHandler(resultCollector); 194 | CommandMap.getInstance().invoke(null, null, consoleCommand.command); 195 | sendPacket(new HttpPacket(resultCollector.toString()), packet.packetID); 196 | } catch (Exception e) { 197 | mLogger.warn("[OpenCommand] Run command failed.", e); 198 | EventListeners.setConsoleMessageHandler(null); 199 | sendPacket(new HttpPacket(500, "error", e.getLocalizedMessage()), packet.packetID); 200 | } finally { 201 | EventListeners.setConsoleMessageHandler(null); 202 | } 203 | } 204 | } 205 | } catch (Throwable e) { 206 | e.printStackTrace(); 207 | if (!sendPacket(new HeartBeat("Pong"))) { 208 | return; 209 | } 210 | } 211 | } 212 | } 213 | 214 | public void exit() { 215 | exit = true; 216 | } 217 | } 218 | 219 | // 客户端连接线程 220 | private static class ClientThread extends Thread { 221 | private final String ip; 222 | private final int port; 223 | private Socket socket; 224 | private OutputStream os; 225 | 226 | public ClientThread(String ip, int port) { 227 | this.ip = ip; 228 | this.port = port; 229 | start(); 230 | } 231 | 232 | public Socket getSocket() { 233 | return socket; 234 | } 235 | 236 | public boolean sendPacket(String string) { 237 | return SocketUtils.writeString(os, string); 238 | } 239 | 240 | @Override 241 | public void run() { 242 | try { 243 | connect = true; 244 | if (receiveThread != null) { 245 | receiveThread.exit(); 246 | } 247 | 248 | socket = new Socket(ip, port); 249 | os = socket.getOutputStream(); 250 | mLogger.info("[OpenCommand] Connect to server: " + ip + ":" + port); 251 | SocketClient.sendPacket(new AuthPacket(OpenCommandPlugin.getInstance().getConfig().socketToken, OpenCommandPlugin.getInstance().getConfig().socketDisplayName)); 252 | receiveThread = new ReceiveThread(socket); 253 | } catch (IOException e) { 254 | connect = false; 255 | mLogger.warn("[OpenCommand] Connect to server failed: " + ip + ":" + port); 256 | connectServer(); 257 | } 258 | } 259 | } 260 | } 261 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/SocketData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket; 19 | 20 | import com.github.jie65535.opencommand.socket.packet.player.PlayerList; 21 | 22 | import java.util.ArrayList; 23 | import java.util.HashMap; 24 | import java.util.concurrent.atomic.AtomicReference; 25 | 26 | // Socket 数据保存 27 | public class SocketData { 28 | public static HashMap playerList = new HashMap<>(); 29 | 30 | public static String getPlayer(int uid) { 31 | for (PlayerList player : playerList.values()) { 32 | if (player.playerMap.get(uid) != null) { 33 | return player.playerMap.get(uid); 34 | } 35 | } 36 | return null; 37 | } 38 | 39 | public static String getPlayerInServer(int uid) { 40 | AtomicReference ret = new AtomicReference<>(); 41 | playerList.forEach((key, value) -> { 42 | if (value.playerMap.get(uid) != null) { 43 | ret.set(key); 44 | } 45 | }); 46 | return ret.get(); 47 | } 48 | 49 | public static OnlinePlayer getOnlinePlayer() { 50 | ArrayList player = new ArrayList<>(); 51 | playerList.forEach((address, playerMap) -> playerMap.playerMap.forEach((uid, name) -> player.add(name))); 52 | return new OnlinePlayer(player); 53 | } 54 | 55 | public static class OnlinePlayer { 56 | public int count; 57 | public ArrayList playerList; 58 | 59 | public OnlinePlayer(ArrayList playerList) { 60 | this.playerList = playerList; 61 | this.count = playerList.size(); 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/SocketDataWait.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket; 19 | 20 | // 异步等待数据返回 21 | public abstract class SocketDataWait extends Thread { 22 | public T data; 23 | public long timeout; 24 | public long time; 25 | public String uid; 26 | 27 | /** 28 | * 异步等待数据返回 29 | * @param timeout 超时时间 30 | */ 31 | public SocketDataWait(long timeout) { 32 | this.timeout = timeout; 33 | start(); 34 | } 35 | 36 | public abstract void run(); 37 | 38 | /** 39 | * 数据处理 40 | * @param data 数据 41 | * @return 处理后的数据 42 | */ 43 | public abstract T initData(T data); 44 | 45 | /** 46 | * 超时回调 47 | */ 48 | public abstract void timeout(); 49 | 50 | /** 51 | * 异步设置数据 52 | * @param data 数据 53 | */ 54 | public void setData(Object data) { 55 | this.data = initData((T) data); 56 | } 57 | 58 | /** 59 | * 获取异步数据(此操作会一直堵塞直到获取到数据) 60 | * @return 数据 61 | */ 62 | public T getData() { 63 | while (data == null) { 64 | try { 65 | time += 100; 66 | Thread.sleep(100); 67 | } catch (InterruptedException e) { 68 | e.printStackTrace(); 69 | } 70 | if (time > timeout) { 71 | timeout(); 72 | return null; 73 | } 74 | } 75 | return data; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/SocketServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket; 19 | 20 | import com.github.jie65535.opencommand.OpenCommandPlugin; 21 | import com.github.jie65535.opencommand.socket.packet.*; 22 | import com.github.jie65535.opencommand.socket.packet.player.PlayerList; 23 | import emu.grasscutter.utils.JsonUtils; 24 | import org.slf4j.Logger; 25 | 26 | import java.io.IOException; 27 | import java.io.InputStream; 28 | import java.io.OutputStream; 29 | import java.net.ServerSocket; 30 | import java.net.Socket; 31 | import java.util.HashMap; 32 | import java.util.Timer; 33 | import java.util.TimerTask; 34 | import java.util.UUID; 35 | 36 | // Socket 服务器 37 | public class SocketServer { 38 | // 客户端超时时间 39 | private static final int TIMEOUT = 5000; 40 | private static final HashMap clientList = new HashMap<>(); 41 | 42 | private static final HashMap clientTimeout = new HashMap<>(); 43 | private static Logger mLogger; 44 | 45 | public static HashMap getOnlineClient() { 46 | HashMap onlineClient = new HashMap<>(); 47 | for (var key : clientList.entrySet()) { 48 | onlineClient.put(key.getValue().uuid, key.getValue().clientThread.getDisplayName()); 49 | } 50 | return onlineClient; 51 | } 52 | 53 | public static ClientInfo getClientInfoByUuid(String uuid) { 54 | for (var key : clientList.entrySet()) { 55 | if (key.getValue().uuid.equals(uuid)) { 56 | return key.getValue(); 57 | } 58 | } 59 | return null; 60 | } 61 | 62 | public static void startServer() throws IOException { 63 | int port = OpenCommandPlugin.getInstance().getConfig().socketPort; 64 | mLogger = OpenCommandPlugin.getInstance().getLogger(); 65 | new Timer().schedule(new SocketClientCheck(), 500); 66 | new WaitClientConnect(port); 67 | } 68 | 69 | // 向全部客户端发送数据 70 | public static boolean sendAllPacket(BasePacket packet) { 71 | var p = SocketUtils.getPacket(packet); 72 | HashMap old = (HashMap) clientList.clone(); 73 | for (var client : old.entrySet()) { 74 | if (!client.getValue().clientThread.sendPacket(p)) { 75 | mLogger.warn("[OpenCommand] Send packet to client {} failed", client.getKey()); 76 | clientList.remove(client.getKey()); 77 | } 78 | } 79 | return false; 80 | } 81 | 82 | // 根据地址发送到相应的客户端 83 | public static boolean sendPacket(String address, BasePacket packet) { 84 | var p = SocketUtils.getPacket(packet); 85 | var client = clientList.get(address); 86 | if (client != null) { 87 | if (client.clientThread.sendPacket(p)) { 88 | return true; 89 | } 90 | mLogger.warn("[OpenCommand] Send packet to client {} failed", address); 91 | clientList.remove(address); 92 | } 93 | return false; 94 | } 95 | 96 | public static boolean sendPacketAndWait(String address, BasePacket packet, SocketDataWait wait) { 97 | var p = SocketUtils.getPacketAndPackID(packet); 98 | var client = clientList.get(address); 99 | if (client != null) { 100 | wait.uid = p.get(0); 101 | if (client.clientThread.sendPacket(p.get(1), wait)) { 102 | return true; 103 | } 104 | mLogger.warn("[OpenCommand] Send packet to client {} failed", address); 105 | clientList.remove(address); 106 | } 107 | return false; 108 | } 109 | 110 | public static boolean sendUidPacket(Integer playerId, BasePacket player) { 111 | var p = SocketUtils.getPacket(player); 112 | var clientID = SocketData.getPlayerInServer(playerId); 113 | if (clientID == null) return false; 114 | var client = clientList.get(clientID); 115 | if (client != null) { 116 | if (!client.clientThread.sendPacket(p)) { 117 | mLogger.warn("[OpenCommand] Send packet to client {} failed", clientID); 118 | clientList.remove(clientID); 119 | return false; 120 | } 121 | return true; 122 | } 123 | return false; 124 | } 125 | 126 | // 根据Uid发送到相应的客户端异步返回数据 127 | public static boolean sendUidPacketAndWait(Integer playerId, BasePacket player, SocketDataWait socketDataWait) { 128 | var p = SocketUtils.getPacketAndPackID(player); 129 | var clientID = SocketData.getPlayerInServer(playerId); 130 | if (clientID == null) return false; 131 | var client = clientList.get(clientID); 132 | if (client != null) { 133 | socketDataWait.uid = p.get(0); 134 | if (!client.clientThread.sendPacket(p.get(1), socketDataWait)) { 135 | mLogger.warn("[OpenCommand] Send packet to client {} failed", clientID); 136 | clientList.remove(clientID); 137 | return false; 138 | } 139 | return true; 140 | } 141 | return false; 142 | } 143 | 144 | // 客户端超时检测 145 | private static class SocketClientCheck extends TimerTask { 146 | @Override 147 | public void run() { 148 | HashMap old = (HashMap) clientTimeout.clone(); 149 | for (var client : old.entrySet()) { 150 | var clientID = client.getKey(); 151 | var clientTime = client.getValue(); 152 | if (clientTime > TIMEOUT) { 153 | mLogger.info("[OpenCommand] Client {} timeout, disconnect.", clientID); 154 | clientList.remove(clientID); 155 | clientTimeout.remove(clientID); 156 | SocketData.playerList.remove(clientID); 157 | } else { 158 | clientTimeout.put(clientID, clientTime + 500); 159 | } 160 | } 161 | } 162 | } 163 | 164 | // 客户端数据包处理 165 | static class ClientThread extends Thread { 166 | private final Socket socket; 167 | private InputStream is; 168 | private OutputStream os; 169 | private final String address; 170 | private final String token; 171 | private boolean auth = false; 172 | private String displayName = ""; 173 | 174 | private final HashMap> socketDataWaitList = new HashMap<>(); 175 | 176 | public ClientThread(Socket accept) { 177 | socket = accept; 178 | address = socket.getInetAddress() + ":" + socket.getPort(); 179 | token = OpenCommandPlugin.getInstance().getConfig().socketToken; 180 | try { 181 | is = accept.getInputStream(); 182 | os = accept.getOutputStream(); 183 | } catch (IOException e) { 184 | e.printStackTrace(); 185 | } 186 | start(); 187 | } 188 | 189 | public Socket getSocket() { 190 | return socket; 191 | } 192 | 193 | // 发送数据包 194 | public boolean sendPacket(String packet) { 195 | return SocketUtils.writeString(os, packet); 196 | } 197 | 198 | // 发送异步数据包 199 | public boolean sendPacket(String packet, SocketDataWait socketDataWait) { 200 | if (SocketUtils.writeString(os, packet)) { 201 | socketDataWaitList.put(socketDataWait.uid, socketDataWait); 202 | return true; 203 | } else { 204 | return false; 205 | } 206 | } 207 | 208 | @Override 209 | public void run() { 210 | while (true) { 211 | try { 212 | String data = SocketUtils.readString(is); 213 | Packet packet = JsonUtils.decode(data, Packet.class); 214 | if (packet.type == PacketEnum.AuthPacket) { 215 | AuthPacket authPacket = JsonUtils.decode(packet.data, AuthPacket.class); 216 | if (authPacket.token.equals(token)) { 217 | auth = true; 218 | displayName = authPacket.displayName; 219 | mLogger.info("[OpenCommand] Client {} auth success, name: {}", address, displayName); 220 | clientList.put(address, new ClientInfo(UUID.randomUUID().toString(), address, this)); 221 | clientTimeout.put(address, 0); 222 | } else { 223 | mLogger.warn("[OpenCommand] Client {} auth failed", address); 224 | socket.close(); 225 | return; 226 | } 227 | } 228 | if (!auth) { 229 | mLogger.warn("[OpenCommand] Client {} auth failed", address); 230 | socket.close(); 231 | return; 232 | } 233 | switch (packet.type) { 234 | // 缓存玩家列表 235 | case PlayerList -> { 236 | PlayerList playerList = JsonUtils.decode(packet.data, PlayerList.class); 237 | SocketData.playerList.put(address, playerList); 238 | } 239 | // Http信息返回 240 | case HttpPacket -> { 241 | HttpPacket httpPacket = JsonUtils.decode(packet.data, HttpPacket.class); 242 | var socketWait = socketDataWaitList.get(packet.packetID); 243 | if (socketWait == null) { 244 | mLogger.error("[OpenCommand] HttpPacket: " + packet.packetID + " not found"); 245 | return; 246 | } 247 | socketWait.setData(httpPacket); 248 | socketDataWaitList.remove(packet.packetID); 249 | } 250 | // 心跳包 251 | case HeartBeat -> clientTimeout.put(address, 0); 252 | } 253 | } catch (Throwable e) { 254 | e.printStackTrace(); 255 | mLogger.error("[OpenCommand] Client {} disconnect.", address); 256 | clientList.remove(address); 257 | clientTimeout.remove(address); 258 | SocketData.playerList.remove(address); 259 | break; 260 | } 261 | } 262 | } 263 | 264 | public String getDisplayName() { 265 | return displayName; 266 | } 267 | } 268 | 269 | // 等待客户端连接 270 | private static class WaitClientConnect extends Thread { 271 | ServerSocket socketServer; 272 | 273 | public WaitClientConnect(int port) throws IOException { 274 | socketServer = new ServerSocket(port); 275 | start(); 276 | } 277 | 278 | @Override 279 | public void run() { 280 | mLogger.info("[OpenCommand] Start socket server on port " + socketServer.getLocalPort()); 281 | // noinspection InfiniteLoopStatement 282 | while (true) { 283 | try { 284 | Socket accept = socketServer.accept(); 285 | String address = accept.getInetAddress() + ":" + accept.getPort(); 286 | mLogger.info("[OpenCommand] Client connect: " + address); 287 | new ClientThread(accept); 288 | } catch (IOException e) { 289 | e.printStackTrace(); 290 | } 291 | } 292 | } 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/SocketUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket; 19 | 20 | import com.github.jie65535.opencommand.socket.packet.BasePacket; 21 | import com.github.jie65535.opencommand.socket.packet.Packet; 22 | import emu.grasscutter.utils.JsonUtils; 23 | 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.OutputStream; 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | import java.util.UUID; 30 | 31 | // Socket 工具类 32 | public class SocketUtils { 33 | 34 | /** 35 | * 获取打包后的数据包 36 | * 37 | * @param bPacket 数据包 38 | * @return 打包后的数据包 39 | */ 40 | public static String getPacket(BasePacket bPacket) { 41 | Packet packet = new Packet(); 42 | packet.type = bPacket.getType(); 43 | packet.data = bPacket.getPacket(); 44 | packet.packetID = UUID.randomUUID().toString(); 45 | return JsonUtils.encode(packet); 46 | } 47 | 48 | /** 49 | * 获取打包后的数据包 50 | * 51 | * @param bPacket BasePacket 52 | * @return list[0] 是包ID, list[1] 是数据包 53 | */ 54 | public static List getPacketAndPackID(BasePacket bPacket) { 55 | Packet packet = new Packet(); 56 | packet.type = bPacket.getType(); 57 | packet.data = bPacket.getPacket(); 58 | packet.packetID = UUID.randomUUID().toString(); 59 | 60 | List list = new ArrayList<>(); 61 | list.add(packet.packetID); 62 | list.add(JsonUtils.encode(packet)); 63 | return list; 64 | } 65 | 66 | /** 67 | * 获取打包后的数据包 68 | * 69 | * @param bPacket 数据包 70 | * @param packetID 数据包ID 71 | * @return 打包后的数据包 72 | */ 73 | public static String getPacketAndPackID(BasePacket bPacket, String packetID) { 74 | Packet packet = new Packet(); 75 | packet.type = bPacket.getType(); 76 | packet.data = bPacket.getPacket(); 77 | packet.packetID = packetID; 78 | return JsonUtils.encode(packet); 79 | } 80 | 81 | /** 82 | * 读整数 83 | * 84 | * @param is 输入流 85 | * @return 整数 86 | */ 87 | public static int readInt(InputStream is) { 88 | int[] values = new int[4]; 89 | try { 90 | for (int i = 0; i < 4; i++) { 91 | values[i] = is.read(); 92 | } 93 | } catch (IOException e) { 94 | e.printStackTrace(); 95 | } 96 | 97 | return values[0] << 24 | values[1] << 16 | values[2] << 8 | values[3]; 98 | } 99 | 100 | /** 101 | * 写整数 102 | * 103 | * @param os 输出流 104 | * @param value 整数 105 | */ 106 | public static void writeInt(OutputStream os, int value) { 107 | int[] values = new int[4]; 108 | values[0] = (value >> 24) & 0xFF; 109 | values[1] = (value >> 16) & 0xFF; 110 | values[2] = (value >> 8) & 0xFF; 111 | values[3] = (value) & 0xFF; 112 | 113 | try { 114 | for (int i = 0; i < 4; i++) { 115 | os.write(values[i]); 116 | } 117 | } catch (IOException e) { 118 | e.printStackTrace(); 119 | } 120 | } 121 | 122 | /** 123 | * 读字符串 124 | * 125 | * @param is 输入流 126 | * @return 字符串 127 | */ 128 | public static String readString(InputStream is) { 129 | int len = readInt(is); 130 | byte[] sByte = new byte[len]; 131 | try { 132 | is.read(sByte); 133 | } catch (IOException e) { 134 | e.printStackTrace(); 135 | } 136 | return new String(sByte); 137 | } 138 | 139 | /** 140 | * 写字符串 141 | * 142 | * @param os 输出流 143 | * @param s 字符串 144 | * @return 是否成功 145 | */ 146 | public static boolean writeString(OutputStream os, String s) { 147 | try { 148 | byte[] bytes = s.getBytes(); 149 | int len = bytes.length; 150 | writeInt(os, len); 151 | os.write(bytes); 152 | return true; 153 | } catch (IOException e) { 154 | e.printStackTrace(); 155 | } 156 | return false; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/AuthPacket.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | import emu.grasscutter.utils.JsonUtils; 21 | 22 | public class AuthPacket extends BasePacket { 23 | public String token; 24 | public String displayName; 25 | 26 | public AuthPacket(String token, String displayName) { 27 | this.displayName = displayName; 28 | this.token = token; 29 | } 30 | 31 | @Override 32 | public String getPacket() { 33 | return JsonUtils.encode(this); 34 | } 35 | 36 | @Override 37 | public PacketEnum getType() { 38 | return PacketEnum.AuthPacket; 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return "AuthPacket [token=" + token + ", displayName=" + displayName + "]"; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/BasePacket.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | // 基本数据包 21 | public abstract class BasePacket { 22 | public abstract String getPacket(); 23 | 24 | public abstract PacketEnum getType(); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/HeartBeat.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | import emu.grasscutter.utils.JsonUtils; 21 | 22 | // 心跳包 23 | public class HeartBeat extends BasePacket { 24 | public String ping; 25 | 26 | public HeartBeat(String ping) { 27 | this.ping = ping; 28 | } 29 | 30 | @Override 31 | public String getPacket() { 32 | return JsonUtils.encode(this); 33 | } 34 | 35 | @Override 36 | public PacketEnum getType() { 37 | return PacketEnum.HeartBeat; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/HttpPacket.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | import emu.grasscutter.utils.JsonUtils; 21 | 22 | // http返回数据 23 | public class HttpPacket extends BasePacket { 24 | public int code = 200; 25 | public String message = "Success"; 26 | public String data; 27 | 28 | public HttpPacket(int code, String message, String data) { 29 | this.code = code; 30 | this.message = message; 31 | this.data = data; 32 | } 33 | 34 | public HttpPacket(int code, String message) { 35 | this.code = code; 36 | this.message = message; 37 | } 38 | public HttpPacket(String data) { 39 | this.data = data; 40 | } 41 | 42 | @Override 43 | public String getPacket() { 44 | return JsonUtils.encode(this); 45 | } 46 | 47 | @Override 48 | public PacketEnum getType() { 49 | return PacketEnum.HttpPacket; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "HttpPacket [code=" + code + ", message=" + message + ", data=" + data + "]"; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/Packet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | // 数据包结构 21 | public class Packet { 22 | public PacketEnum type; 23 | public String data; 24 | public String packetID; 25 | 26 | @Override 27 | public String toString() { 28 | return "Packet [type=" + type + ", data=" + data + ", packetID=" + packetID + "]"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/PacketEnum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | // 数据包类型列表 21 | public enum PacketEnum { 22 | PlayerList, 23 | Player, 24 | HttpPacket, 25 | AuthPacket, 26 | RunConsoleCommand, 27 | HeartBeat 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/RunConsoleCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet; 19 | 20 | import emu.grasscutter.utils.JsonUtils; 21 | 22 | public class RunConsoleCommand extends BasePacket { 23 | public String command; 24 | 25 | public RunConsoleCommand(String command) { 26 | this.command = command; 27 | } 28 | 29 | @Override 30 | public String getPacket() { 31 | return JsonUtils.encode(this); 32 | } 33 | 34 | @Override 35 | public PacketEnum getType() { 36 | return PacketEnum.RunConsoleCommand; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/player/Player.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet.player; 19 | 20 | import com.github.jie65535.opencommand.socket.SocketServer; 21 | import com.github.jie65535.opencommand.socket.packet.BasePacket; 22 | import com.github.jie65535.opencommand.socket.packet.PacketEnum; 23 | import emu.grasscutter.utils.JsonUtils; 24 | 25 | // 玩家操作类 26 | public class Player extends BasePacket { 27 | public PlayerEnum type; 28 | public int uid; 29 | public String data; 30 | 31 | @Override 32 | public String getPacket() { 33 | return JsonUtils.encode(this); 34 | } 35 | 36 | @Override 37 | public PacketEnum getType() { 38 | return PacketEnum.Player; 39 | } 40 | 41 | public static void dropMessage(int uid, String str) { 42 | Player p = new Player(); 43 | p.type = PlayerEnum.DropMessage; 44 | p.uid = uid; 45 | p.data = str; 46 | SocketServer.sendUidPacket(uid, p); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/player/PlayerEnum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet.player; 19 | 20 | // 玩家操作列表 21 | public enum PlayerEnum { 22 | DropMessage, 23 | RunCommand 24 | } -------------------------------------------------------------------------------- /src/main/java/com/github/jie65535/opencommand/socket/packet/player/PlayerList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * gc-opencommand 3 | * Copyright (C) 2022 jie65535 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published 7 | * by the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.github.jie65535.opencommand.socket.packet.player; 19 | 20 | import com.github.jie65535.opencommand.socket.packet.BasePacket; 21 | import com.github.jie65535.opencommand.socket.packet.PacketEnum; 22 | import emu.grasscutter.utils.JsonUtils; 23 | 24 | import java.util.ArrayList; 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | // 玩家列表信息 30 | public class PlayerList extends BasePacket { 31 | public int player = -1; 32 | public List playerList = new ArrayList<>(); 33 | public Map playerMap = new HashMap<>(); 34 | 35 | @Override 36 | public String getPacket() { 37 | return JsonUtils.encode(this); 38 | } 39 | 40 | @Override 41 | public PacketEnum getType() { 42 | return PacketEnum.PlayerList; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/resources/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opencommand-plugin", 3 | "description": "Open command interface for third-party clients", 4 | "version": "1.7.0", 5 | "mainClass": "com.github.jie65535.opencommand.OpenCommandPlugin", 6 | "authors": ["jie65535", "方块君"], 7 | "api": 2 8 | } --------------------------------------------------------------------------------