Compare commits

..

6 Commits

Author SHA1 Message Date
d64238a9e9 Fix CI branch 2023-05-21 21:13:59 +08:00
c3667a8206 Add unstable description 2023-05-21 21:10:52 +08:00
c62d777037 Add url to enable log
(cherry picked from commit 66fb25aa9b)
2023-05-21 21:04:41 +08:00
5019b6548a Update player command response handler 2023-05-21 20:50:34 +08:00
1c8d448a7b Update baseName to opencommand-for-unstable 2023-05-21 20:38:22 +08:00
99f914b952 Update CI gc path 2023-05-21 20:01:11 +08:00
10 changed files with 100 additions and 140 deletions

View File

@ -5,7 +5,7 @@ on:
paths:
- "**.java"
branches:
- "master"
- "for-unstable"
pull_request:
paths:
- "**.java"
@ -35,7 +35,7 @@ jobs:
restore-keys: |
${{ runner.os }}-gradle-
- name: Download latest grasscutter jar
run: wget https://nightly.link/Grasscutters/Grasscutter/workflows/build/development/Grasscutter.zip && mkdir lib && unzip Grasscutter.zip -d lib
run: wget https://nightly.link/Grasscutters/Grasscutter/workflows/build/unstable/Grasscutter.zip && mkdir lib && unzip Grasscutter.zip -d lib
- name: Change permission
run: chmod +x gradlew

View File

@ -4,13 +4,9 @@
一个为第三方客户端开放GC命令执行接口的插件
`1.7.0` 起可以通过 `|` 或者换行来分隔多条命令,例如:
```shell
/a 1 | /a 2
/a 3
```
## 分支说明
调用 `ping` 响应数据将包含插件版本号。
本分支目的在于兼容 GC 的 `unstable` 分支
## 使用本插件的应用
- [GrasscutterTools](https://github.com/jie65535/GrasscutterCommandGenerator) —— Windows 客户端工具
@ -21,38 +17,23 @@
## 服务端安装
1. 在 [Release](https://github.com/jie65535/gc-opencommand-plugin/releases) 下载 `jar`
2. 放入 `grasscutter/plugins` 文件夹
3. 重启 `grasscutter` 即可生效
2. 放入 `plugins` 文件夹即可
## 玩家使用流程
1. 在远程工具中填写服务地址,查询插件状态
2. 填写UID发送验证码需要在线
3. 将游戏内收到的**4位整数验证码**填入工具校验
4. 享受便利!
> 注意,如果出现以下错误:
> ```log
> INFO:PluginManager Enabling plugin: opencommand-plugin
> Exception in thread "main" java.lang.NoSuchMethodError: 'void emu.grasscutter.server.event.EventHandler.register(emu.grasscutter.plugin.Plugin)'
> at com.github.jie65535.opencommand.OpenCommandPlugin.onEnable(OpenCommandPlugin.java:49)
> at emu.grasscutter.plugin.PluginManager.lambda$enablePlugins$3(PluginManager.java:131)
> ```
> 请使用v1.2.1版本插件,因为该报错表示你的服务端是旧版!
## 控制台连接
1. 首次启动时,会在 `plugins` 目录下生成一个 `opencommand-plugin` 目录,打开并编辑 `config.json`
2. 设置 `consoleToken` 的值为你的连接秘钥建议使用至少32字符的长随机字符串。(检测到为空时会自动生成,生成时会在控制台中输出)
2. 设置 `consoleToken` 的值为你的连接秘钥建议使用至少32字符的长随机字符串。
3. 重新启动服务端即可生效配置
4. 在工具中选择控制台身份,并填写你的 `consoleToken` 即可以控制台身份运行指令
---
## 客户端请求流程
1. `ping` 确认是否支持 `opencommand` 插件
2. `sendCode` 向指定玩家发送验证码1分钟内不允许重发保存返回的 `token`
3. 使用 `token` 和**4位整数验证码**发送 `verify` 校验
4. 如果验证通过,可以使用该 `token` 执行 `command` 动作
## 插件构建说明
1. 克隆仓库
2. 在目录下新建 `lib` 目录
3. 将 `grasscutter.jar` 放入 `lib` 目录
4. 执行 `gradle build`
4. 在客户端中选择控制台身份,并填写你的 `consoleToken` 即可以控制台身份运行指令
## 多服务器
### 主服务器 (Dispatch)
@ -68,13 +49,34 @@
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))
5. 重新启动服务端即可生效配置
## 构建说明
1. 克隆仓库
2. 在目录下新建 `lib` 目录
3. 将 `grasscutter-1.1.x-dev.jar` 放入 `lib` 目录
4. `gradle build`
## 玩家使用流程
1. 在客户端中填写服务地址,确认是否支持
2. 填写UID发送验证码
3. 将游戏内收到的**4位整数验证码**填入客户端校验
4. 享受便利!
## 客户端请求流程
1. `ping` 确认是否支持 `opencommand` 插件
2. `sendCode` 向指定玩家发送验证码1分钟内不允许重发保存返回的 `token`
3. 使用 `token` 和**4位整数验证码**发送 `verify` 校验
4. 如果验证通过,可以使用该 `token` 执行 `command` 动作
---
## `config.json`
```json5
{
// 控制台连接令牌(检测到空时会自动生成)
// 控制台连接令牌
"consoleToken": "",
// 验证码过期时间(秒)
"codeExpirationTime_S": 60,

View File

@ -4,60 +4,29 @@
A plugin that opens the GC command execution interface for third-party clients
Since `1.7.0`, multiple commands can be separated by `|` or newline, for example:
```shell
/a 1 | /a 2
/a 3
```
## Branch Description
Invoking `ping` the response data will contain the plugin version.
The purpose of this branch is to be compatible with the 'unstable' branch of GC
## Applications using this plug-in
- [GrasscutterTools](https://github.com/jie65535/GrasscutterCommandGenerator) —— Windows Client Tools
- [JGrasscutterCommand](https://github.com/jie65535/JGrasscutterCommand) —— [Mirai](https://github.com/mamoe/mirai) Plugin, run commands in QQ
- [Yunzai-GrasscutterCommand](https://github.com/Zyy-boop/Yunzai-GrasscutterCommand) —— Yunzai-bot plugin, execute commands in QQ
- More...
- TODO
## Server installation
1. Download the `jar` in [Release](https://github.com/jie65535/gc-opencommand-plugin/releases)
2. Put it in the `grasscutter/plugins` folder
3. Restart `grasscutter` server
## Player
1. Fill in the service address in the Tool to check plugin status
2. Fill in the UID and send the verification code
3. Fill in the **4-digit integer verification code** received in the game into the Tool verification
4. Enjoy the convenience!
2. Put it in the `plugins` folder
## Console connection
1. When starting for the first time, a `opencommand-plugin` directory will be generated under the `plugins` directory,
open and edit `config.json`
2. Set the value of `consoleToken` to your connection key. It is recommended to use a long random string of at least 32
characters. (automatically generated when empty is detected)
characters.
3. Restart the server to take effect
4. Select the console identity in the client, and fill in your `consoleToken` to run the command as the console identity
---
## Client request
1. `ping` to confirm whether the `opencommand` plugin is supported
2. `sendCode` sends a verification code to the specified player (re-send is not allowed within 1 minute), and save the
returned `token`
3. Send `verify` check using `token` and **4-digit integer verification code**
4. If the verification is passed, you can use the `token` to execute the `command` action
## Build
1. `git clone https://github.com/jie65535/gc-opencommand-plugin`
2. `cd gc-opencommand-plugin`
3. `mkdir lib`
4. `mv path/to/grasscutter-1.x.x-dev.jar ./lib`
5. `gradle build`
## Multi server
### Master server (Dispatch)
1. Open `config.json` in the `opencommand-plugin` directory
@ -72,28 +41,42 @@ Invoking `ping` the response data will contain the plugin version.
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))
5. Restart the server to make the configuration effective
## Build
1. `git clone https://github.com/jie65535/gc-opencommand-plugin`
2. `cd gc-opencommand-plugin`
3. `mkdir lib`
4. `mv path/to/grasscutter-1.x.x-dev.jar ./lib`
5. `gradle build`
## Player
1. Fill in the service address in the client to confirm whether it supports
2. Fill in the UID and send the verification code
3. Fill in the **4-digit integer verification code** received in the game into the client verification
4. Enjoy the convenience!
## Client request
1. `ping` to confirm whether the `opencommand` plugin is supported
2. `sendCode` sends a verification code to the specified player (re-send is not allowed within 1 minute), and save the
returned `token`
3. Send `verify` check using `token` and **4-digit integer verification code**
4. If the verification is passed, you can use the `token` to execute the `command` action
---
## `config.json`
```json5
```json
{
// console connection token (automatically generated when empty is detected)
"consoleToken": "",
// Verification code expiration time (seconds)
"codeExpirationTime_S": 60,
// Temporary token expiration time (seconds)
"tempTokenExpirationTime_S": 300,
// Authorization token last used expiration time (hours)
"tokenLastUseExpirationTime_H": 48,
// Multi-server communication port
"socketPort": 5746,
// Multi-server communication key
"socketToken": "",
// Multi-server Dispatch server address
"socketHost": "127.0.0.1",
// multi-server display name
"socketDisplayName": ""
"socketPort": 5746,
"socketToken": "",
"socketHost": "127.0.0.1"
}
```

View File

@ -4,7 +4,7 @@ plugins {
}
group 'com.github.jie65535.opencommand'
version '1.7.0'
version '1.5.2'
sourceCompatibility = 17
targetCompatibility = 17
@ -18,7 +18,7 @@ dependencies {
}
jar {
jar.baseName = 'opencommand'
jar.baseName = 'opencommand-for-unstable'
destinationDir = file(".")
}

View File

@ -44,11 +44,13 @@ public final class EventListeners {
* @param uid 玩家uid
* @return 新的玩家消息处理类
*/
public static StringBuilder getPlayerMessageHandler(int uid) {
public static StringBuilder getPlayerNewMessageHandler(int uid) {
var handler = playerMessageHandlers.get(uid);
if (handler == null) {
handler = new StringBuilder();
playerMessageHandlers.put(uid, handler);
} else {
handler.setLength(0);
}
return handler;
}

View File

@ -22,7 +22,6 @@ import com.github.jie65535.opencommand.json.JsonResponse;
import com.github.jie65535.opencommand.model.Client;
import com.github.jie65535.opencommand.socket.SocketData;
import emu.grasscutter.command.CommandMap;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.http.Router;
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.Utils;
@ -59,7 +58,7 @@ public final class OpenCommandHandler implements Router {
var req = context.bodyAsClass(JsonRequest.class);
if (req.action.equals("sendCode")) {
int playerId = (int)Double.parseDouble(req.data.toString());
int playerId = (int) req.data;
var player = plugin.getServer().getPlayerByUid(playerId);
if (player == null) {
context.json(new JsonResponse(404, "Player Not Found."));
@ -84,7 +83,7 @@ public final class OpenCommandHandler implements Router {
}
return;
} else if (req.action.equals("ping")) {
context.json(new JsonResponse(plugin.getVersion()));
context.json(new JsonResponse());
return;
} else if (req.action.equals("online")) {
var p = new ArrayList<String>();
@ -116,7 +115,7 @@ public final class OpenCommandHandler implements Router {
plugin.getLogger().info(String.format("IP: %s run command in console > %s", context.ip(), req.data));
var resultCollector = new StringBuilder();
EventListeners.setConsoleMessageHandler(resultCollector);
tryInvokeCommand(null, null, req.data.toString());
CommandMap.getInstance().invoke(null, null, req.data.toString());
context.json(new JsonResponse(resultCollector.toString()));
} catch (Exception e) {
plugin.getLogger().warn("Run command failed.", e);
@ -131,7 +130,7 @@ public final class OpenCommandHandler implements Router {
}
} else if (codes.containsKey(req.token)) {
if (req.action.equals("verify")) {
if (codes.get(req.token) == (int)Double.parseDouble(req.data.toString())) {
if (codes.get(req.token).equals(req.data)) {
codes.remove(req.token);
// update token expire time
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);
@ -148,17 +147,17 @@ public final class OpenCommandHandler implements Router {
// update token expire time
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);
var player = plugin.getServer().getPlayerByUid(client.playerId);
var command = req.data.toString();
if (player == null) {
context.json(new JsonResponse(404, "Player not found"));
return;
}
// Player MessageHandler do not support concurrency
var handler = EventListeners.getPlayerMessageHandler(player.getUid());
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (handler) {
synchronized (player) {
// Player MessageHandler do not support concurrency
var handler = EventListeners.getPlayerNewMessageHandler(player.getUid());
try {
handler.setLength(0);
tryInvokeCommand(player, player, req.data.toString());
CommandMap.getInstance().invoke(player, player, command);
context.json(new JsonResponse(handler.toString()));
} catch (Exception e) {
plugin.getLogger().warn("Run command failed.", e);
@ -174,17 +173,6 @@ public final class OpenCommandHandler implements Router {
}
}
private static void tryInvokeCommand(Player sender, Player target, String rawMessage) {
for (var command : rawMessage.split("\n[/!]|\\|")) {
command = command.trim();
if (command.isEmpty()) continue;
if (command.charAt(0) == '/' || command.charAt(0) == '!') {
command = command.substring(1);
}
CommandMap.getInstance().invoke(sender, target, command);
}
}
private static void cleanupExpiredCodes() {
var now = new Date();
codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now));

View File

@ -61,7 +61,7 @@ public final class OpenCommandOnlyHttpHandler implements Router {
var req = context.bodyAsClass(JsonRequest.class);
if (req.action.equals("sendCode")) {
int playerId = (int)Double.parseDouble(req.data.toString());
int playerId = (int) req.data;
var player = SocketData.getPlayer(playerId);
if (player == null) {
context.json(new JsonResponse(404, "Player Not Found."));
@ -148,7 +148,7 @@ public final class OpenCommandOnlyHttpHandler implements Router {
}
} else if (codes.containsKey(req.token)) {
if (req.action.equals("verify")) {
if (codes.get(req.token) == (int)Double.parseDouble(req.data.toString())) {
if (codes.get(req.token).equals(req.data)) {
codes.remove(req.token);
// update token expire time
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);

View File

@ -26,9 +26,7 @@ import emu.grasscutter.server.event.HandlerPriority;
import emu.grasscutter.server.event.game.ReceiveCommandFeedbackEvent;
import emu.grasscutter.server.event.player.PlayerJoinEvent;
import emu.grasscutter.server.event.player.PlayerQuitEvent;
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.JsonUtils;
import emu.grasscutter.utils.Utils;
import java.io.*;
import java.nio.charset.StandardCharsets;
@ -107,24 +105,24 @@ public final class OpenCommandPlugin extends Plugin {
var configFile = new File(getDataFolder(), "config.json");
if (!configFile.exists()) {
config = new OpenCommandConfig();
saveConfig();
try (var file = new FileWriter(configFile)) {
file.write(JsonUtils.encode(config));
} catch (IOException e) {
getLogger().error("[OpenCommand] Unable to write to config file.");
} catch (Exception e) {
getLogger().error("[OpenCommand] Unable to save config file.");
}
} else {
try {
config = JsonUtils.decode(Files.readString(configFile.toPath(), StandardCharsets.UTF_8),
OpenCommandConfig.class);
} catch (Exception exception) {
config = new OpenCommandConfig();
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.");
}
if (config == null) {
config = new OpenCommandConfig();
}
}
// 检查控制台Token
if (config.consoleToken == null || config.consoleToken.isEmpty()) {
config.consoleToken = Utils.base64Encode(Crypto.createSessionKey(24));
saveConfig();
getLogger().warn("Detected that consoleToken is empty, automatically generated Token for you as follows: {}", config.consoleToken);
}
try {
runMode = Grasscutter.getConfig().server.runMode;
} catch (Exception ex) {
@ -132,17 +130,6 @@ public final class OpenCommandPlugin extends Plugin {
}
}
private void saveConfig() {
var configFile = new File(getDataFolder(), "config.json");
try (var file = new FileWriter(configFile)) {
file.write(JsonUtils.encode(config));
} catch (IOException e) {
getLogger().error("[OpenCommand] Unable to write to config file.");
} catch (Exception e) {
getLogger().error("[OpenCommand] Unable to save config file.");
}
}
private void loadData() {
var dataFile = new File(getDataFolder(), "data.json");
if (!dataFile.exists()) {

View File

@ -159,12 +159,11 @@ public class SocketClient {
sendPacket(new HttpPacket(404, "Player not found."), packet.packetID);
return;
}
// Player MessageHandler do not support concurrency
var handler = EventListeners.getPlayerMessageHandler(playerData.getUid());
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (handler) {
synchronized (playerData) {
// Player MessageHandler do not support concurrency
var handler = EventListeners.getPlayerNewMessageHandler(playerData.getUid());
try {
handler.setLength(0);
CommandMap.getInstance().invoke(playerData, playerData, command);
sendPacket(new HttpPacket(200, handler.toString()), packet.packetID);
} catch (Exception e) {

View File

@ -1,8 +1,7 @@
{
"name": "opencommand-plugin",
"description": "Open command interface for third-party clients",
"version": "1.7.0",
"version": "dev-1.5.2",
"mainClass": "com.github.jie65535.opencommand.OpenCommandPlugin",
"authors": ["jie65535", "方块君"],
"api": 2
"authors": ["jie65535", "方块君"]
}