mirror of
https://github.com/jie65535/gc-opencommand-plugin.git
synced 2025-12-15 19:31:35 +08:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 564f4d1e56 | |||
| 66fb25aa9b | |||
| c3c2ed08a7 | |||
| 82477321d1 | |||
| f19c4b8e77 | |||
| 3f1ecfe8a6 | |||
|
|
79564ff41c | ||
| ded44804d4 | |||
| 4b8eb490f5 | |||
| 70261df520 | |||
| 5c2be0e776 | |||
| 72948121d6 | |||
| 42c748ad2e | |||
| 1d03d3e476 | |||
| ef885af137 |
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
@@ -5,7 +5,7 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- "**.java"
|
- "**.java"
|
||||||
branches:
|
branches:
|
||||||
- "main"
|
- "master"
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- "**.java"
|
- "**.java"
|
||||||
|
|||||||
@@ -4,6 +4,12 @@
|
|||||||
|
|
||||||
一个为第三方客户端开放GC命令执行接口的插件
|
一个为第三方客户端开放GC命令执行接口的插件
|
||||||
|
|
||||||
|
## 使用本插件的应用
|
||||||
|
- [GrasscutterTools](https://github.com/jie65535/GrasscutterCommandGenerator) —— Windows 客户端工具
|
||||||
|
- [JGrasscutterCommand](https://github.com/jie65535/JGrasscutterCommand) —— [Mirai](https://github.com/mamoe/mirai) 插件,在QQ里执行命令
|
||||||
|
- [Yunzai-GrasscutterCommand](https://github.com/Zyy-boop/Yunzai-GrasscutterCommand) —— Yunzai-bot插件,在QQ里执行命令
|
||||||
|
- 待补充
|
||||||
|
|
||||||
## 服务端安装
|
## 服务端安装
|
||||||
|
|
||||||
1. 在 [Release](https://github.com/jie65535/gc-opencommand-plugin/releases) 下载 `jar`
|
1. 在 [Release](https://github.com/jie65535/gc-opencommand-plugin/releases) 下载 `jar`
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
|
|
||||||
A plugin that opens the GC command execution interface for third-party clients
|
A plugin that opens the GC command execution interface for third-party clients
|
||||||
|
|
||||||
|
## 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
|
||||||
|
- TODO
|
||||||
|
|
||||||
## Server installation
|
## Server installation
|
||||||
|
|
||||||
1. Download the `jar` in [Release](https://github.com/jie65535/gc-opencommand-plugin/releases)
|
1. Download the `jar` in [Release](https://github.com/jie65535/gc-opencommand-plugin/releases)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
group 'com.github.jie65535.opencommand'
|
group 'com.github.jie65535.opencommand'
|
||||||
version 'dev-1.4.0'
|
version '1.5.2'
|
||||||
|
|
||||||
sourceCompatibility = 17
|
sourceCompatibility = 17
|
||||||
targetCompatibility = 17
|
targetCompatibility = 17
|
||||||
|
|||||||
@@ -24,21 +24,54 @@ import emu.grasscutter.game.player.Player;
|
|||||||
import emu.grasscutter.server.event.game.ReceiveCommandFeedbackEvent;
|
import emu.grasscutter.server.event.game.ReceiveCommandFeedbackEvent;
|
||||||
import emu.grasscutter.server.event.player.PlayerJoinEvent;
|
import emu.grasscutter.server.event.player.PlayerJoinEvent;
|
||||||
import emu.grasscutter.server.event.player.PlayerQuitEvent;
|
import emu.grasscutter.server.event.player.PlayerQuitEvent;
|
||||||
import emu.grasscutter.utils.MessageHandler;
|
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||||
|
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
|
||||||
public final class EventListeners {
|
public final class EventListeners {
|
||||||
|
|
||||||
private static MessageHandler consoleMessageHandler;
|
private static StringBuilder consoleMessageHandler;
|
||||||
|
private static final Int2ObjectMap<StringBuilder> playerMessageHandlers = new Int2ObjectOpenHashMap<>();
|
||||||
|
|
||||||
public static void setConsoleMessageHandler(MessageHandler handler) {
|
public static void setConsoleMessageHandler(StringBuilder handler) {
|
||||||
consoleMessageHandler = handler;
|
consoleMessageHandler = handler;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取新的玩家消息处理类
|
||||||
|
* 获取时将创建或清空消息处理器并返回实例,**在执行命令前获取!**
|
||||||
|
* @param uid 玩家uid
|
||||||
|
* @return 新的玩家消息处理类
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 命令执行反馈事件处理
|
||||||
|
*/
|
||||||
public static void onCommandResponse(ReceiveCommandFeedbackEvent event) {
|
public static void onCommandResponse(ReceiveCommandFeedbackEvent event) {
|
||||||
if (consoleMessageHandler != null && event.getPlayer() == null) {
|
StringBuilder handler;
|
||||||
consoleMessageHandler.setMessage(event.getMessage());
|
if (event.getPlayer() == null) {
|
||||||
|
handler = consoleMessageHandler;
|
||||||
|
} else {
|
||||||
|
handler = playerMessageHandlers.get(event.getPlayer().getUid());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (handler != null) {
|
||||||
|
if (!handler.isEmpty()) {
|
||||||
|
// New line
|
||||||
|
handler.append(System.lineSeparator());
|
||||||
|
}
|
||||||
|
handler.append(event.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,6 +90,10 @@ public final class EventListeners {
|
|||||||
SocketClient.sendPacket(playerList);
|
SocketClient.sendPacket(playerList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅游戏模式下玩家离开事件处理方法
|
||||||
|
* 用于更新玩家列表
|
||||||
|
*/
|
||||||
public static void onPlayerQuit(PlayerQuitEvent playerQuitEvent) {
|
public static void onPlayerQuit(PlayerQuitEvent playerQuitEvent) {
|
||||||
PlayerList playerList = new PlayerList();
|
PlayerList playerList = new PlayerList();
|
||||||
playerList.player = Grasscutter.getGameServer().getPlayers().size();
|
playerList.player = Grasscutter.getGameServer().getPlayers().size();
|
||||||
@@ -70,4 +107,15 @@ public final class EventListeners {
|
|||||||
playerList.playerList = playerNames;
|
playerList.playerList = playerNames;
|
||||||
SocketClient.sendPacket(playerList);
|
SocketClient.sendPacket(playerList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 玩家离开事件处理 2
|
||||||
|
* 用于清理内存
|
||||||
|
*/
|
||||||
|
public static void onPlayerQuit2(PlayerQuitEvent playerQuitEvent) {
|
||||||
|
var uid = playerQuitEvent.getPlayer().getUid();
|
||||||
|
if (playerMessageHandlers.containsKey(uid)) {
|
||||||
|
playerMessageHandlers.remove(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.github.jie65535.opencommand;
|
||||||
|
|
||||||
|
import com.github.jie65535.opencommand.model.Client;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Vector;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 插件持久化数据
|
||||||
|
*/
|
||||||
|
public class OpenCommandData {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接的客户端列表
|
||||||
|
*/
|
||||||
|
public Vector<Client> clients = new Vector<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过令牌获取客户端
|
||||||
|
* @param token 令牌
|
||||||
|
* @return 客户端对象,若未找到返回null
|
||||||
|
*/
|
||||||
|
public Client getClientByToken(String token) {
|
||||||
|
for (var c : clients) {
|
||||||
|
if (c.token.equals(token))
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除所有过期的客户端
|
||||||
|
*/
|
||||||
|
public void removeExpiredClients() {
|
||||||
|
var now = new Date();
|
||||||
|
clients.removeIf(client -> client.tokenExpireTime.before(now));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addClient(Client client) {
|
||||||
|
clients.add(client);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,11 +19,11 @@ package com.github.jie65535.opencommand;
|
|||||||
|
|
||||||
import com.github.jie65535.opencommand.json.JsonRequest;
|
import com.github.jie65535.opencommand.json.JsonRequest;
|
||||||
import com.github.jie65535.opencommand.json.JsonResponse;
|
import com.github.jie65535.opencommand.json.JsonResponse;
|
||||||
|
import com.github.jie65535.opencommand.model.Client;
|
||||||
import com.github.jie65535.opencommand.socket.SocketData;
|
import com.github.jie65535.opencommand.socket.SocketData;
|
||||||
import emu.grasscutter.command.CommandMap;
|
import emu.grasscutter.command.CommandMap;
|
||||||
import emu.grasscutter.server.http.Router;
|
import emu.grasscutter.server.http.Router;
|
||||||
import emu.grasscutter.utils.Crypto;
|
import emu.grasscutter.utils.Crypto;
|
||||||
import emu.grasscutter.utils.MessageHandler;
|
|
||||||
import emu.grasscutter.utils.Utils;
|
import emu.grasscutter.utils.Utils;
|
||||||
import io.javalin.Javalin;
|
import io.javalin.Javalin;
|
||||||
import io.javalin.http.Context;
|
import io.javalin.http.Context;
|
||||||
@@ -42,17 +42,19 @@ public final class OpenCommandHandler implements Router {
|
|||||||
javalin.post("/opencommand/api", OpenCommandHandler::handle);
|
javalin.post("/opencommand/api", OpenCommandHandler::handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Map<String, Integer> clients = new HashMap<>();
|
|
||||||
private static final Map<String, Date> tokenExpireTime = new HashMap<>();
|
|
||||||
private static final Map<String, Integer> codes = new HashMap<>();
|
private static final Map<String, Integer> codes = new HashMap<>();
|
||||||
private static final Int2ObjectMap<Date> codeExpireTime = new Int2ObjectOpenHashMap<>();
|
private static final Int2ObjectMap<Date> codeExpireTime = new Int2ObjectOpenHashMap<>();
|
||||||
|
|
||||||
|
|
||||||
public static void handle(Context context) {
|
public static void handle(Context context) {
|
||||||
// Trigger cleanup action
|
|
||||||
cleanupExpiredData();
|
|
||||||
var plugin = OpenCommandPlugin.getInstance();
|
var plugin = OpenCommandPlugin.getInstance();
|
||||||
|
try {
|
||||||
var config = plugin.getConfig();
|
var config = plugin.getConfig();
|
||||||
|
var data = plugin.getData();
|
||||||
var now = new Date();
|
var now = new Date();
|
||||||
|
// Trigger cleanup action
|
||||||
|
cleanupExpiredCodes();
|
||||||
|
data.removeExpiredClients();
|
||||||
|
|
||||||
var req = context.bodyAsClass(JsonRequest.class);
|
var req = context.bodyAsClass(JsonRequest.class);
|
||||||
if (req.action.equals("sendCode")) {
|
if (req.action.equals("sendCode")) {
|
||||||
@@ -74,9 +76,8 @@ public final class OpenCommandHandler implements Router {
|
|||||||
token = Utils.bytesToHex(Crypto.createSessionKey(32));
|
token = Utils.bytesToHex(Crypto.createSessionKey(32));
|
||||||
int code = Utils.randomRange(1000, 9999);
|
int code = Utils.randomRange(1000, 9999);
|
||||||
codeExpireTime.put(playerId, new Date(now.getTime() + config.codeExpirationTime_S * 1000L));
|
codeExpireTime.put(playerId, new Date(now.getTime() + config.codeExpirationTime_S * 1000L));
|
||||||
tokenExpireTime.put(token, new Date(now.getTime() + config.tempTokenExpirationTime_S * 1000L));
|
|
||||||
codes.put(token, code);
|
codes.put(token, code);
|
||||||
clients.put(token, playerId);
|
data.addClient(new Client(token, playerId, new Date(now.getTime() + config.tempTokenExpirationTime_S * 1000L)));
|
||||||
player.dropMessage("[Open Command] Verification code: " + code);
|
player.dropMessage("[Open Command] Verification code: " + code);
|
||||||
context.json(new JsonResponse(token));
|
context.json(new JsonResponse(token));
|
||||||
}
|
}
|
||||||
@@ -97,7 +98,8 @@ public final class OpenCommandHandler implements Router {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var isConsole = req.token.equals(config.consoleToken);
|
var isConsole = req.token.equals(config.consoleToken);
|
||||||
if (!isConsole && !clients.containsKey(req.token)) {
|
var client = data.getClientByToken(req.token);
|
||||||
|
if (!isConsole && client == null) {
|
||||||
context.json(new JsonResponse(401, "Unauthorized"));
|
context.json(new JsonResponse(401, "Unauthorized"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -111,10 +113,10 @@ public final class OpenCommandHandler implements Router {
|
|||||||
synchronized (plugin) {
|
synchronized (plugin) {
|
||||||
try {
|
try {
|
||||||
plugin.getLogger().info(String.format("IP: %s run command in console > %s", context.ip(), req.data));
|
plugin.getLogger().info(String.format("IP: %s run command in console > %s", context.ip(), req.data));
|
||||||
var resultCollector = new MessageHandler();
|
var resultCollector = new StringBuilder();
|
||||||
EventListeners.setConsoleMessageHandler(resultCollector);
|
EventListeners.setConsoleMessageHandler(resultCollector);
|
||||||
CommandMap.getInstance().invoke(null, null, req.data.toString());
|
CommandMap.getInstance().invoke(null, null, req.data.toString());
|
||||||
context.json(new JsonResponse(resultCollector.getMessage()));
|
context.json(new JsonResponse(resultCollector.toString()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
plugin.getLogger().warn("Run command failed.", e);
|
plugin.getLogger().warn("Run command failed.", e);
|
||||||
EventListeners.setConsoleMessageHandler(null);
|
EventListeners.setConsoleMessageHandler(null);
|
||||||
@@ -131,9 +133,10 @@ public final class OpenCommandHandler implements Router {
|
|||||||
if (codes.get(req.token).equals(req.data)) {
|
if (codes.get(req.token).equals(req.data)) {
|
||||||
codes.remove(req.token);
|
codes.remove(req.token);
|
||||||
// update token expire time
|
// update token expire time
|
||||||
tokenExpireTime.put(req.token, new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L));
|
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);
|
||||||
context.json(new JsonResponse());
|
context.json(new JsonResponse());
|
||||||
plugin.getLogger().info(String.format("Player %d has passed the verification, ip: %s", clients.get(req.token), context.ip()));
|
plugin.getLogger().info(String.format("Player %d has passed the verification, ip: %s", client.playerId, context.ip()));
|
||||||
|
plugin.saveData();
|
||||||
} else {
|
} else {
|
||||||
context.json(new JsonResponse(400, "Verification failed"));
|
context.json(new JsonResponse(400, "Verification failed"));
|
||||||
}
|
}
|
||||||
@@ -142,47 +145,38 @@ public final class OpenCommandHandler implements Router {
|
|||||||
} else {
|
} else {
|
||||||
if (req.action.equals("command")) {
|
if (req.action.equals("command")) {
|
||||||
// update token expire time
|
// update token expire time
|
||||||
tokenExpireTime.put(req.token, new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L));
|
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);
|
||||||
var playerId = clients.get(req.token);
|
var player = plugin.getServer().getPlayerByUid(client.playerId);
|
||||||
var player = plugin.getServer().getPlayerByUid(playerId);
|
|
||||||
var command = req.data.toString();
|
var command = req.data.toString();
|
||||||
if (player == null) {
|
if (player == null) {
|
||||||
context.json(new JsonResponse(404, "Player not found"));
|
context.json(new JsonResponse(404, "Player not found"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Player MessageHandler do not support concurrency
|
|
||||||
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
||||||
synchronized (player) {
|
synchronized (player) {
|
||||||
|
// Player MessageHandler do not support concurrency
|
||||||
|
var handler = EventListeners.getPlayerNewMessageHandler(player.getUid());
|
||||||
try {
|
try {
|
||||||
var resultCollector = new MessageHandler();
|
|
||||||
player.setMessageHandler(resultCollector);
|
|
||||||
CommandMap.getInstance().invoke(player, player, command);
|
CommandMap.getInstance().invoke(player, player, command);
|
||||||
context.json(new JsonResponse(resultCollector.getMessage()));
|
context.json(new JsonResponse(handler.toString()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
plugin.getLogger().warn("Run command failed.", e);
|
plugin.getLogger().warn("Run command failed.", e);
|
||||||
context.json(new JsonResponse(500, "error", e.getLocalizedMessage()));
|
context.json(new JsonResponse(500, "error", e.getLocalizedMessage()));
|
||||||
} finally {
|
|
||||||
player.setMessageHandler(null);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
context.json(new JsonResponse(403, "forbidden"));
|
context.json(new JsonResponse(403, "forbidden"));
|
||||||
|
} catch (Throwable ex) {
|
||||||
|
plugin.getLogger().error("[OpenCommand] handler error.", ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void cleanupExpiredData() {
|
private static void cleanupExpiredCodes() {
|
||||||
var now = new Date();
|
var now = new Date();
|
||||||
codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now));
|
codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now));
|
||||||
|
if (codeExpireTime.isEmpty())
|
||||||
var it = tokenExpireTime.entrySet().iterator();
|
codes.clear();
|
||||||
while (it.hasNext()) {
|
|
||||||
var entry = it.next();
|
|
||||||
if (entry.getValue().before(now)) {
|
|
||||||
it.remove();
|
|
||||||
// remove expired token
|
|
||||||
clients.remove(entry.getKey());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ package com.github.jie65535.opencommand;
|
|||||||
|
|
||||||
import com.github.jie65535.opencommand.json.JsonRequest;
|
import com.github.jie65535.opencommand.json.JsonRequest;
|
||||||
import com.github.jie65535.opencommand.json.JsonResponse;
|
import com.github.jie65535.opencommand.json.JsonResponse;
|
||||||
|
import com.github.jie65535.opencommand.model.Client;
|
||||||
import com.github.jie65535.opencommand.socket.SocketData;
|
import com.github.jie65535.opencommand.socket.SocketData;
|
||||||
import com.github.jie65535.opencommand.socket.SocketDataWait;
|
import com.github.jie65535.opencommand.socket.SocketDataWait;
|
||||||
import com.github.jie65535.opencommand.socket.SocketServer;
|
import com.github.jie65535.opencommand.socket.SocketServer;
|
||||||
@@ -45,17 +46,18 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
javalin.post("/opencommand/api", OpenCommandOnlyHttpHandler::handle);
|
javalin.post("/opencommand/api", OpenCommandOnlyHttpHandler::handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Map<String, Integer> clients = new HashMap<>();
|
|
||||||
private static final Map<String, Date> tokenExpireTime = new HashMap<>();
|
|
||||||
private static final Map<String, Integer> codes = new HashMap<>();
|
private static final Map<String, Integer> codes = new HashMap<>();
|
||||||
private static final Int2ObjectMap<Date> codeExpireTime = new Int2ObjectOpenHashMap<>();
|
private static final Int2ObjectMap<Date> codeExpireTime = new Int2ObjectOpenHashMap<>();
|
||||||
|
|
||||||
public static void handle(Context context) {
|
public static void handle(Context context) {
|
||||||
// Trigger cleanup action
|
|
||||||
cleanupExpiredData();
|
|
||||||
var plugin = OpenCommandPlugin.getInstance();
|
var plugin = OpenCommandPlugin.getInstance();
|
||||||
|
try {
|
||||||
var config = plugin.getConfig();
|
var config = plugin.getConfig();
|
||||||
|
var data = plugin.getData();
|
||||||
var now = new Date();
|
var now = new Date();
|
||||||
|
// Trigger cleanup action
|
||||||
|
cleanupExpiredCodes();
|
||||||
|
data.removeExpiredClients();
|
||||||
|
|
||||||
var req = context.bodyAsClass(JsonRequest.class);
|
var req = context.bodyAsClass(JsonRequest.class);
|
||||||
if (req.action.equals("sendCode")) {
|
if (req.action.equals("sendCode")) {
|
||||||
@@ -77,9 +79,8 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
token = Utils.bytesToHex(Crypto.createSessionKey(32));
|
token = Utils.bytesToHex(Crypto.createSessionKey(32));
|
||||||
int code = Utils.randomRange(1000, 9999);
|
int code = Utils.randomRange(1000, 9999);
|
||||||
codeExpireTime.put(playerId, new Date(now.getTime() + config.codeExpirationTime_S * 1000L));
|
codeExpireTime.put(playerId, new Date(now.getTime() + config.codeExpirationTime_S * 1000L));
|
||||||
tokenExpireTime.put(token, new Date(now.getTime() + config.tempTokenExpirationTime_S * 1000L));
|
|
||||||
codes.put(token, code);
|
codes.put(token, code);
|
||||||
clients.put(token, playerId);
|
data.addClient(new Client(token, playerId, new Date(now.getTime() + config.tempTokenExpirationTime_S * 1000L)));
|
||||||
Player.dropMessage(playerId, "[Open Command] Verification code: " + code);
|
Player.dropMessage(playerId, "[Open Command] Verification code: " + code);
|
||||||
context.json(new JsonResponse(token));
|
context.json(new JsonResponse(token));
|
||||||
}
|
}
|
||||||
@@ -98,7 +99,8 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var isConsole = req.token.equals(config.consoleToken);
|
var isConsole = req.token.equals(config.consoleToken);
|
||||||
if (!isConsole && !clients.containsKey(req.token)) {
|
var client = data.getClientByToken(req.token);
|
||||||
|
if (!isConsole && client == null) {
|
||||||
context.json(new JsonResponse(401, "Unauthorized"));
|
context.json(new JsonResponse(401, "Unauthorized"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -130,12 +132,12 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
};
|
};
|
||||||
|
|
||||||
SocketServer.sendPacketAndWait(server.ip, new RunConsoleCommand(req.data.toString()), wait);
|
SocketServer.sendPacketAndWait(server.ip, new RunConsoleCommand(req.data.toString()), wait);
|
||||||
var data = wait.getData();
|
var packet = wait.getData();
|
||||||
if (data == null) {
|
if (packet == null) {
|
||||||
context.json(new JsonResponse(408, "Timeout"));
|
context.json(new JsonResponse(408, "Timeout"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
context.json(new JsonResponse(data.code, data.message, data.data));
|
context.json(new JsonResponse(packet.code, packet.message, packet.data));
|
||||||
return;
|
return;
|
||||||
} else if (req.action.equals("server")) {
|
} else if (req.action.equals("server")) {
|
||||||
context.json(new JsonResponse(200, "Success", SocketServer.getOnlineClient()));
|
context.json(new JsonResponse(200, "Success", SocketServer.getOnlineClient()));
|
||||||
@@ -149,9 +151,10 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
if (codes.get(req.token).equals(req.data)) {
|
if (codes.get(req.token).equals(req.data)) {
|
||||||
codes.remove(req.token);
|
codes.remove(req.token);
|
||||||
// update token expire time
|
// update token expire time
|
||||||
tokenExpireTime.put(req.token, new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L));
|
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);
|
||||||
context.json(new JsonResponse());
|
context.json(new JsonResponse());
|
||||||
plugin.getLogger().info(String.format("Player %d has passed the verification, ip: %s", clients.get(req.token), context.ip()));
|
plugin.getLogger().info(String.format("Player %d has passed the verification, ip: %s", client.playerId, context.ip()));
|
||||||
|
plugin.saveData();
|
||||||
} else {
|
} else {
|
||||||
context.json(new JsonResponse(400, "Verification failed"));
|
context.json(new JsonResponse(400, "Verification failed"));
|
||||||
}
|
}
|
||||||
@@ -175,15 +178,14 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// update token expire time
|
// update token expire time
|
||||||
tokenExpireTime.put(req.token, new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L));
|
client.tokenExpireTime = new Date(now.getTime() + config.tokenLastUseExpirationTime_H * 60L * 60L * 1000L);
|
||||||
var playerId = clients.get(req.token);
|
|
||||||
var command = req.data.toString();
|
var command = req.data.toString();
|
||||||
var player = new Player();
|
var player = new Player();
|
||||||
player.uid = playerId;
|
player.uid = client.playerId;
|
||||||
player.type = PlayerEnum.RunCommand;
|
player.type = PlayerEnum.RunCommand;
|
||||||
player.data = command;
|
player.data = command;
|
||||||
|
|
||||||
if (!SocketServer.sendUidPacketAndWait(playerId, player, socketDataWait)) {
|
if (!SocketServer.sendUidPacketAndWait(client.playerId, player, socketDataWait)) {
|
||||||
context.json(new JsonResponse(404, "Player Not Found."));
|
context.json(new JsonResponse(404, "Player Not Found."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -199,20 +201,15 @@ public final class OpenCommandOnlyHttpHandler implements Router {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
context.json(new JsonResponse(403, "forbidden"));
|
context.json(new JsonResponse(403, "forbidden"));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
plugin.getLogger().error("[OpenCommand] handler error.", ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void cleanupExpiredData() {
|
private static void cleanupExpiredCodes() {
|
||||||
var now = new Date();
|
var now = new Date();
|
||||||
codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now));
|
codeExpireTime.int2ObjectEntrySet().removeIf(entry -> entry.getValue().before(now));
|
||||||
|
if (codeExpireTime.isEmpty())
|
||||||
var it = tokenExpireTime.entrySet().iterator();
|
codes.clear();
|
||||||
while (it.hasNext()) {
|
|
||||||
var entry = it.next();
|
|
||||||
if (entry.getValue().before(now)) {
|
|
||||||
it.remove();
|
|
||||||
// remove expired token
|
|
||||||
clients.remove(entry.getKey());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ import emu.grasscutter.server.event.player.PlayerQuitEvent;
|
|||||||
import emu.grasscutter.utils.JsonUtils;
|
import emu.grasscutter.utils.JsonUtils;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
|
||||||
public final class OpenCommandPlugin extends Plugin {
|
public final class OpenCommandPlugin extends Plugin {
|
||||||
|
|
||||||
@@ -40,6 +42,8 @@ public final class OpenCommandPlugin extends Plugin {
|
|||||||
|
|
||||||
private OpenCommandConfig config;
|
private OpenCommandConfig config;
|
||||||
|
|
||||||
|
private OpenCommandData data;
|
||||||
|
|
||||||
private Grasscutter.ServerRunMode runMode = Grasscutter.ServerRunMode.HYBRID;
|
private Grasscutter.ServerRunMode runMode = Grasscutter.ServerRunMode.HYBRID;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -47,16 +51,24 @@ public final class OpenCommandPlugin extends Plugin {
|
|||||||
instance = this;
|
instance = this;
|
||||||
// 加载配置
|
// 加载配置
|
||||||
loadConfig();
|
loadConfig();
|
||||||
|
// 加载数据
|
||||||
|
loadData();
|
||||||
// 启动Socket
|
// 启动Socket
|
||||||
startSocket();
|
startSocket();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onEnable() {
|
public void onEnable() {
|
||||||
|
// 监听命令执行反馈
|
||||||
new EventHandler<>(ReceiveCommandFeedbackEvent.class)
|
new EventHandler<>(ReceiveCommandFeedbackEvent.class)
|
||||||
.priority(HandlerPriority.HIGH)
|
.priority(HandlerPriority.HIGH)
|
||||||
.listener(EventListeners::onCommandResponse)
|
.listener(EventListeners::onCommandResponse)
|
||||||
.register(this);
|
.register(this);
|
||||||
|
// 监听玩家离开事件
|
||||||
|
new EventHandler<>(PlayerQuitEvent.class)
|
||||||
|
.priority(HandlerPriority.NORMAL)
|
||||||
|
.listener(EventListeners::onPlayerQuit2)
|
||||||
|
.register(this);
|
||||||
if (runMode == Grasscutter.ServerRunMode.GAME_ONLY) {
|
if (runMode == Grasscutter.ServerRunMode.GAME_ONLY) {
|
||||||
// 仅运行游戏服务器时注册玩家加入和离开事件
|
// 仅运行游戏服务器时注册玩家加入和离开事件
|
||||||
new EventHandler<>(PlayerJoinEvent.class)
|
new EventHandler<>(PlayerJoinEvent.class)
|
||||||
@@ -72,11 +84,12 @@ public final class OpenCommandPlugin extends Plugin {
|
|||||||
} else {
|
} else {
|
||||||
getHandle().addRouter(OpenCommandHandler.class);
|
getHandle().addRouter(OpenCommandHandler.class);
|
||||||
}
|
}
|
||||||
getLogger().info("[OpenCommand] Enabled");
|
getLogger().info("[OpenCommand] Enabled. https://github.com/jie65535/gc-opencommand-plugin");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onDisable() {
|
public void onDisable() {
|
||||||
|
saveData();
|
||||||
getLogger().info("[OpenCommand] Disabled");
|
getLogger().info("[OpenCommand] Disabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +97,10 @@ public final class OpenCommandPlugin extends Plugin {
|
|||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public OpenCommandData getData() {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
private void loadConfig() {
|
private void loadConfig() {
|
||||||
var configFile = new File(getDataFolder(), "config.json");
|
var configFile = new File(getDataFolder(), "config.json");
|
||||||
if (!configFile.exists()) {
|
if (!configFile.exists()) {
|
||||||
@@ -97,11 +114,14 @@ public final class OpenCommandPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
config = JsonUtils.loadToClass(configFile.getAbsolutePath(), OpenCommandConfig.class);
|
config = JsonUtils.decode(Files.readString(configFile.toPath(), StandardCharsets.UTF_8),
|
||||||
|
OpenCommandConfig.class);
|
||||||
} catch (Exception exception) {
|
} 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.");
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
runMode = Grasscutter.getConfig().server.runMode;
|
runMode = Grasscutter.getConfig().server.runMode;
|
||||||
@@ -110,6 +130,34 @@ public final class OpenCommandPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void loadData() {
|
||||||
|
var dataFile = new File(getDataFolder(), "data.json");
|
||||||
|
if (!dataFile.exists()) {
|
||||||
|
data = new OpenCommandData();
|
||||||
|
saveData();
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
data = JsonUtils.decode(Files.readString(dataFile.toPath(), StandardCharsets.UTF_8),
|
||||||
|
OpenCommandData.class);
|
||||||
|
} catch (Exception exception) {
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
if (data == null) {
|
||||||
|
data = new OpenCommandData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void saveData() {
|
||||||
|
try (var file = new FileWriter(new File(getDataFolder(), "data.json"))) {
|
||||||
|
file.write(JsonUtils.encode(data));
|
||||||
|
} catch (IOException e) {
|
||||||
|
getLogger().error("[OpenCommand] Unable to write to data file.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
getLogger().error("[OpenCommand] Unable to save data file.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void startSocket() {
|
private void startSocket() {
|
||||||
if (runMode == Grasscutter.ServerRunMode.GAME_ONLY) {
|
if (runMode == Grasscutter.ServerRunMode.GAME_ONLY) {
|
||||||
getLogger().info("[OpenCommand] Starting socket client...");
|
getLogger().info("[OpenCommand] Starting socket client...");
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.github.jie65535.opencommand.model;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public final class Client {
|
||||||
|
|
||||||
|
public String token;
|
||||||
|
public Integer playerId;
|
||||||
|
public Date tokenExpireTime;
|
||||||
|
|
||||||
|
public Client(String token, Integer playerId, Date tokenExpireTime) {
|
||||||
|
this.token = token;
|
||||||
|
this.playerId = playerId;
|
||||||
|
this.tokenExpireTime = tokenExpireTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,6 @@ import com.github.jie65535.opencommand.socket.packet.player.PlayerList;
|
|||||||
import emu.grasscutter.Grasscutter;
|
import emu.grasscutter.Grasscutter;
|
||||||
import emu.grasscutter.command.CommandMap;
|
import emu.grasscutter.command.CommandMap;
|
||||||
import emu.grasscutter.utils.JsonUtils;
|
import emu.grasscutter.utils.JsonUtils;
|
||||||
import emu.grasscutter.utils.MessageHandler;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -160,19 +159,16 @@ public class SocketClient {
|
|||||||
sendPacket(new HttpPacket(404, "Player not found."), packet.packetID);
|
sendPacket(new HttpPacket(404, "Player not found."), packet.packetID);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Player MessageHandler do not support concurrency
|
|
||||||
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
||||||
synchronized (playerData) {
|
synchronized (playerData) {
|
||||||
|
// Player MessageHandler do not support concurrency
|
||||||
|
var handler = EventListeners.getPlayerNewMessageHandler(playerData.getUid());
|
||||||
try {
|
try {
|
||||||
var resultCollector = new MessageHandler();
|
|
||||||
playerData.setMessageHandler(resultCollector);
|
|
||||||
CommandMap.getInstance().invoke(playerData, playerData, command);
|
CommandMap.getInstance().invoke(playerData, playerData, command);
|
||||||
sendPacket(new HttpPacket(200, resultCollector.getMessage()), packet.packetID);
|
sendPacket(new HttpPacket(200, handler.toString()), packet.packetID);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
OpenCommandPlugin.getInstance().getLogger().warn("[OpenCommand] Run command failed.", e);
|
OpenCommandPlugin.getInstance().getLogger().warn("[OpenCommand] Run command failed.", e);
|
||||||
sendPacket(new HttpPacket(500, "error", e.getLocalizedMessage()), packet.packetID);
|
sendPacket(new HttpPacket(500, "error", e.getLocalizedMessage()), packet.packetID);
|
||||||
} finally {
|
|
||||||
playerData.setMessageHandler(null);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -192,10 +188,10 @@ public class SocketClient {
|
|||||||
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
||||||
synchronized (plugin) {
|
synchronized (plugin) {
|
||||||
try {
|
try {
|
||||||
var resultCollector = new MessageHandler();
|
var resultCollector = new StringBuilder();
|
||||||
EventListeners.setConsoleMessageHandler(resultCollector);
|
EventListeners.setConsoleMessageHandler(resultCollector);
|
||||||
CommandMap.getInstance().invoke(null, null, consoleCommand.command);
|
CommandMap.getInstance().invoke(null, null, consoleCommand.command);
|
||||||
sendPacket(new HttpPacket(resultCollector.getMessage()), packet.packetID);
|
sendPacket(new HttpPacket(resultCollector.toString()), packet.packetID);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
mLogger.warn("[OpenCommand] Run command failed.", e);
|
mLogger.warn("[OpenCommand] Run command failed.", e);
|
||||||
EventListeners.setConsoleMessageHandler(null);
|
EventListeners.setConsoleMessageHandler(null);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "opencommand-plugin",
|
"name": "opencommand-plugin",
|
||||||
"description": "Open command interface for third-party clients",
|
"description": "Open command interface for third-party clients",
|
||||||
"version": "dev-1.4.0",
|
"version": "dev-1.5.2",
|
||||||
"mainClass": "com.github.jie65535.opencommand.OpenCommandPlugin",
|
"mainClass": "com.github.jie65535.opencommand.OpenCommandPlugin",
|
||||||
"authors": ["jie65535", "方块君"]
|
"authors": ["jie65535", "方块君"]
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user