Skip to content

Commit

Permalink
列出实例与守护进程,部分实例操作
Browse files Browse the repository at this point in the history
  • Loading branch information
WhitrayHB committed Jul 31, 2023
1 parent 6db3969 commit d0027e0
Show file tree
Hide file tree
Showing 12 changed files with 328 additions and 119 deletions.
38 changes: 20 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,32 @@ Mirai to MCSM它来了!
> [NLR Dev](www.nlrdev.top)
## 使用方法

### 命令

|指令|作用|权限节点|
|:---:|:---:|:---:|
|`/queryStatus` <br>`/面板状态`|查看面板状态|`top.nlrdev.mirai2mcsm.queryStatus`|
|`/listRemotes` <br>`/守护进程列表`|列出守护进程列表|`top.nlrdev.mirai2mcsm.listRemotes`|
|`/listInstances <uuid> [page]`<br>`/实例列表 <守护进程uuid> [页数]`|列出实例列表|`top.nlrdev.mirai2mcsm.listInstances`|



### 必要配置
### 部署
- 部署[Mirai Console Loader](https://github.com/iTXTech/mirai-console-loader);
- 安装前置插件 [Chat Command](https://github.com/project-mirai/chat-command);
- 在 Releases 中下载最新的插件, 放入 MCL 根目录下的 `plugins` 文件夹中
- 参阅[权限说明文档](https://docs.mirai.mamoe.net/console/Permissions.html), 赋予相对应的权限
- 配置APIKey
- - 登录MCSM面板
- - 点击右上角账户 进入个人资料
- - 点击API接口密钥处的生成密钥并复制
- - 填入插件配置中的相应位置
- 开始使用吧!
### 命令

| 指令 | 描述 | 权限节点 |
|:-------------------------------------------------------------------------------------------------------------:|:----------------------------------:|:---------------------------------------:|
| `/queryStatus` <br>`/面板状态` | 查看面板状态 | `top.nlrdev.mirai2mcsm.queryStatus` |
| `/listRemotes`<br>`/listre`<br>`/守护进程列表` | 列出守护进程列表 | `top.nlrdev.mirai2mcsm.listRemotes` |
| `/listInstances <uuid> [page]`<br> 缩写:`/listinst`<br>`/实例列表 <守护进程uuid> [页数]` | 列出实例列表 | `top.nlrdev.mirai2mcsm.listInstances` |
| `/operateInstance <operation> <remote_uuid> <uuid>` <br> 缩写:`/opinst` <br> `/实例操作 <操作类型> <守护进程UUID> <实例UUID>` | 操作一个实例,操作类型:open stop restart kill | `top.nlrdev.mirai2mcsm.operateInstance` |


## 配置文件
### MCSMConfig.yml

### PluginConfig.yml

### 部署
- - 部署[Mirai Console Loader](https://github.com/iTXTech/mirai-console-loader);
- - 安装前置插件 [Chat Command](https://github.com/project-mirai/chat-command);
- - 在 Releases 中下载最新的插件, 放入 MCL 根目录下的 `plugins` 文件夹中
- - 参阅[权限说明文档](https://docs.mirai.mamoe.net/console/Permissions.html), 赋予相对应的权限
- - 开始使用吧!

## 更多
您可加入我们的 [QQ社群](https://join.nlrdev.top/) 了解更多
6 changes: 5 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ plugins {
kotlin("jvm") version kotlinVersion
kotlin("plugin.serialization") version kotlinVersion

id("net.mamoe.mirai-console") version "2.13.4"
id("net.mamoe.mirai-console") version "2.15.0"
}

group = "top.nlrdev"
Expand All @@ -19,4 +19,8 @@ repositories {
dependencies {
implementation("org.json:json:20230618")
compileOnly("net.mamoe:mirai-core-jvm:2.15.0")
}

mirai {
jvmTarget = JavaVersion.VERSION_17
}
107 changes: 91 additions & 16 deletions src/main/java/top/nlrdev/mirai2mcsm/Mirai2MCSM.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,43 @@
import net.mamoe.mirai.console.plugin.jvm.JavaPlugin;
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescriptionBuilder;
import net.mamoe.mirai.internal.deps.okhttp3.OkHttpClient;
import top.nlrdev.mirai2mcsm.commands.ListInstances;
import top.nlrdev.mirai2mcsm.commands.ListRemotes;
import top.nlrdev.mirai2mcsm.commands.ProtectedInstanceOperation;
import top.nlrdev.mirai2mcsm.commands.QueryPanelStatus;
import net.mamoe.mirai.utils.MiraiLogger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import top.nlrdev.mirai2mcsm.commands.*;
import top.nlrdev.mirai2mcsm.configs.MCSMConfig;
import top.nlrdev.mirai2mcsm.configs.PluginConfig;
import top.nlrdev.mirai2mcsm.utils.RequestHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public final class Mirai2MCSM extends JavaPlugin {

public static final Mirai2MCSM INSTANCE = new Mirai2MCSM();
public static final MiraiLogger logger = INSTANCE.getLogger();
public static final OkHttpClient globalHttpClient = new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS).build();
/**
* 守护进程的缓存,
* 存储值为< remark , uuid >
**/
public static final HashMap<String, String> remotesRemark = new HashMap<>();
/**
* 守护进程的缓存,
* 存储值为< uuid >
**/
public static final ArrayList<String> remotes = new ArrayList<>();
/**
* 实例的缓存,
* 存储值为< uuid , < nickName , uuid > >
**/
public static final ArrayList<String> instances = new ArrayList<>();
public static final HashMap<String, String> instancesRemark = new HashMap<>();

private Mirai2MCSM() {
super(new JvmPluginDescriptionBuilder("top.nlrdev.mirai2mcsm", "0.1.0")
Expand All @@ -32,30 +54,83 @@ private Mirai2MCSM() {

@Override
public void onEnable() {
getLogger().info("初始化插件中...");
logger.info("初始化插件中...");
initialize();
getLogger().info("初始化插件完毕");
logger.info("初始化插件完毕");
}

public void initialize() {
refreshInfo();
reloadConfigs();
refreshInfo();
registerCommands();
if(Objects.equals(MCSMConfig.INSTANCE.getApiKey.get(), "")){
getLogger().error("未填写APIKey!请在/config/top.nlrdev.mirai2mcsm/MCSMConfig.yml中填写!");

if (Objects.equals(MCSMConfig.INSTANCE.apiKey.get(), "")) {
logger.error("未填写 APIKey!请在 config/top.nlrdev.mirai2mcsm/MCSMConfig.yml 中填写!");
}
}
public void reloadConfigs(){

public void reloadConfigs() {
reloadPluginConfig(MCSMConfig.INSTANCE);
reloadPluginConfig(PluginConfig.INSTANCE);
}
public void registerCommands(){
CommandManager.INSTANCE.registerCommand(QueryPanelStatus.INSTANCE,true);
CommandManager.INSTANCE.registerCommand(ListInstances.INSTANCE,true);
CommandManager.INSTANCE.registerCommand(ListRemotes.INSTANCE,true);
CommandManager.INSTANCE.registerCommand(ProtectedInstanceOperation.INSTANCE,true);

public void registerCommands() {
CommandManager.INSTANCE.registerCommand(QueryPanelStatus.INSTANCE, true);
CommandManager.INSTANCE.registerCommand(ListInstances.INSTANCE, true);
CommandManager.INSTANCE.registerCommand(ListRemotes.INSTANCE, true);
CommandManager.INSTANCE.registerCommand(ProtectedInstanceOperation.INSTANCE, true);
CommandManager.INSTANCE.registerCommand(Refresh.INSTANCE, true);
}

public static void refreshInfo() {
try {
remotes.clear();
remotesRemark.clear();
instances.clear();
remotesRemark.clear();
refreshRemotesInfo();
refreshInstancesInfo();
}catch (Exception e){
logger.error("网络连接出错,获取JSON有误");
logger.info(e);
}
}
public void refreshInfo(){

public static void refreshRemotesInfo() {
JSONObject obj = RequestHandler.handleGetRequest("/service/remote_services_list", "");
JSONArray data = obj.getJSONArray("data");
for (Object object : data) {
JSONObject json = (JSONObject) object;
remotesRemark.put(json.getString("remarks"), json.getString("uuid"));
remotes.add(json.getString("uuid"));
}
}

public static void refreshInstancesInfo() {
JSONObject obj = RequestHandler.handleGetRequest("/service/remote_services", "");
JSONArray data = obj.getJSONArray("data");
for (Object object : data) {
JSONObject jsonObject = (JSONObject) object;
JSONArray instancesArray = jsonObject.getJSONArray("instances");
for (Object instance : instancesArray) {
JSONObject inst = (JSONObject) instance;
instancesRemark.put(inst.getJSONObject("config").getString("nickname"), inst.getString("instanceUuid"));
instances.add(inst.getString("instanceUuid"));
}
}
}

public static String getRemotesUUID(String arg) {
if (remotes.size() == 1) return remotes.get(0);
if (arg.matches("[0-9]+")) return remotes.get(Integer.getInteger(arg));
if (remotes.contains(arg)) return arg;
return remotesRemark.getOrDefault(arg, null);
}

public static String getInstancesUUID(String arg) {
if (remotes.size() == 1) return remotes.get(0);
else {
return null;
}
}
}
97 changes: 60 additions & 37 deletions src/main/java/top/nlrdev/mirai2mcsm/commands/ListInstances.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,77 +2,100 @@

import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.java.JRawCommand;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.data.ForwardMessageBuilder;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;
import top.nlrdev.mirai2mcsm.Mirai2MCSM;
import top.nlrdev.mirai2mcsm.configs.PluginConfig;
import top.nlrdev.mirai2mcsm.utils.MessageListener;
import top.nlrdev.mirai2mcsm.utils.RequestHandler;

import java.util.Objects;

public class ListInstances extends JRawCommand {
public static final ListInstances INSTANCE = new ListInstances();
String URL = "/service/remote_service_instances";
String REQUEST = "&page_size=20&remote_uuid=";
public static final String URL = "/service/remote_service_instances";

private ListInstances() {
super(Mirai2MCSM.INSTANCE, "listInstances","listinst","实例列表");
super(Mirai2MCSM.INSTANCE, "listInstances", "listinst", "实例列表");
setUsage("/实例列表");
setDescription("查询实例列表");
setPrefixOptional(false);
}

@Override
public void onCommand(@NotNull CommandSender sender, @NotNull MessageChain args) {
String uuid = args.get(0).contentToString();
if(uuid==null||uuid==""){
uuid = MessageListener.askForString(sender,"请问您要查找的uuid是?");
}
REQUEST += uuid;
try {
String page = args.get(1).contentToString();
if (page == null || page == "") {
REQUEST += "&page=1";
} else {
REQUEST += "&page="+page;
String uuid;
if (args.isEmpty()) {
if (Mirai2MCSM.remotes.size() != 1) {
MessageListener.askForString(sender, "您要查询的守护进程的 UUID 是?", id -> execute(sender, args, id));
return;
}
}catch (Exception ignored){}
JSONObject json = RequestHandler.handlePostRequest(URL,REQUEST);
switch (json.getInt("status")){
case 400:
sender.sendMessage("请求参数不正确,请检查UUID或页数是否正确");

uuid = Mirai2MCSM.remotes.get(0);
} else {
uuid = args.get(0).contentToString();
}

execute(sender, args, uuid);
}

public static void execute(CommandSender sender, MessageChain args, String uuid) {
String REQUEST = "&page_size=20&instance_name=&remote_uuid=" + uuid;
if (args.size() != 2) {
REQUEST += "&page=1";
} else {
REQUEST += "&page=" + args.get(1);
}

JSONObject json = RequestHandler.handleGetRequest(URL, REQUEST);
switch (json.getInt("status")) {
case 400 -> {
sender.sendMessage("请求参数不正确,请检查 UUID 或页数是否正确");
return;
case 403:
}

case 403 -> {
sender.sendMessage("您无权访问该守护进程");
return;
case 500:
}

case 500 -> {
sender.sendMessage("服务器内部错误,请重试或联系管理员");
return;
}
}

System.out.println(json);

JSONObject data = json.getJSONObject("data");
JSONArray instData = data.getJSONArray("data");
MessageChainBuilder messageChainBuilder = new MessageChainBuilder()
.append("---==实例列表==---\n")
.append("守护进程uuid:").append(uuid).append("\n");
for(Object object : instData){
for (Object object : instData) {
JSONObject obj = (JSONObject) object;
messageChainBuilder.append("实例名称:").append(obj.getJSONObject("config").getString("nickname")).append("\n")
.append(" 实例状态:");
switch (obj.getInt("status")){
case -1:
messageChainBuilder.append("未知\n");
case 0:
messageChainBuilder.append("已停止\n");
case 1:
messageChainBuilder.append("正在停止\n");
case 2:
messageChainBuilder.append("正在启动\n");
case 3:
messageChainBuilder.append("正在运行\n");
messageChainBuilder.append("实例名称:").append(obj.getJSONObject("config").getString("nickname")).append("")
.append(" 状态:");
switch (obj.getInt("status")) {
case -1 -> messageChainBuilder.append("未知\n");
case 0 -> messageChainBuilder.append("已停止\n");
case 1 -> messageChainBuilder.append("正在停止\n");
case 2 -> messageChainBuilder.append("正在启动\n");
case 3 -> messageChainBuilder.append("正在运行\n");
}
messageChainBuilder.append(" 实例UUID:").append(obj.getString("instanceUuid")).append("\n");
}
messageChainBuilder.append("实例总数:").append(String.valueOf(instData.length()));
sender.sendMessage(messageChainBuilder.build());

if (PluginConfig.INSTANCE.useForwardMessage.get() && sender.getSubject() != null && sender.getSubject() instanceof Group) {
ForwardMessageBuilder forwardMessageBuilder = new ForwardMessageBuilder(sender.getSubject()).add(Objects.requireNonNull(sender.getBot()).getId(), sender.getBot().getNick(), messageChainBuilder.build());
sender.sendMessage(forwardMessageBuilder.build());
} else {
sender.sendMessage(messageChainBuilder.build());
}
}
}
Loading

0 comments on commit d0027e0

Please sign in to comment.