forked from Shweit/MinecraftServerAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerAPI.java
More file actions
411 lines (336 loc) · 17.8 KB
/
ServerAPI.java
File metadata and controls
411 lines (336 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package com.shweit.serverapi.endpoints.v1;
import com.shweit.serverapi.MinecraftServerAPI;
import com.shweit.serverapi.handlers.CommandOutputCapture;
import com.shweit.serverapi.handlers.LogHandler;
import com.shweit.serverapi.listeners.ChatListener;
import com.shweit.serverapi.utils.Helper;
import com.shweit.serverapi.utils.Logger;
import fi.iki.elonen.NanoHTTPD;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.*;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.shweit.serverapi.utils.Helper.formatSize;
public final class ServerAPI {
private final ChatListener chatListener;
private final LogHandler logHandler;
public ServerAPI() {
chatListener = new ChatListener();
Bukkit.getPluginManager().registerEvents(chatListener, MinecraftServerAPI.getInstance());
logHandler = new LogHandler();
Logger.getLogger().addHandler(logHandler);
}
public NanoHTTPD.Response ping(final Map<String, String> ignoredParams) {
return NanoHTTPD.newFixedLengthResponse("pong");
}
public NanoHTTPD.Response serverInfo(final Map<String, String> ignoredParams) {
JSONObject serverInfo = new JSONObject();
serverInfo.put("name", Bukkit.getServer().getName());
serverInfo.put("motd", Bukkit.getServer().getMotd());
serverInfo.put("version", Bukkit.getServer().getVersion());
serverInfo.put("bukkitVersion", Bukkit.getServer().getBukkitVersion());
serverInfo.put("ip", Bukkit.getServer().getIp());
serverInfo.put("port", Bukkit.getServer().getPort());
serverInfo.put("maxPlayers", Bukkit.getServer().getMaxPlayers());
serverInfo.put("onlinePlayers", Bukkit.getServer().getOnlinePlayers().size());
serverInfo.put("whitelisted", Bukkit.getServer().hasWhitelist());
serverInfo.put("viewDistance", Bukkit.getServer().getViewDistance());
serverInfo.put("simulationDistance", Bukkit.getServer().getSimulationDistance());
serverInfo.put("spawnRadius", Bukkit.getServer().getSpawnRadius());
serverInfo.put("worldType", Bukkit.getServer().getWorldType());
JSONObject plugins = new JSONObject();
for (Plugin key : Bukkit.getServer().getPluginManager().getPlugins()) {
plugins.put(key.getName(), key.getDescription().getVersion());
}
serverInfo.put("plugins", plugins);
JSONObject worlds = new JSONObject();
for (World world : Bukkit.getServer().getWorlds()) {
worlds.put(world.getName(), world.getEnvironment().name());
}
serverInfo.put("worlds", worlds);
serverInfo.put("defaultGameMode", Bukkit.getServer().getDefaultGameMode().name());
serverInfo.put("allowEnd", Bukkit.getServer().getAllowEnd());
serverInfo.put("allowNether", Bukkit.getServer().getAllowNether());
serverInfo.put("allowFlight", Bukkit.getServer().getAllowFlight());
serverInfo.put("generateStructures", Bukkit.getServer().getGenerateStructures());
serverInfo.put("hardcore", Bukkit.getServer().isHardcore());
File serverIconFile = new File("server-icon.png");
try {
byte[] iconBytes = Files.readAllBytes(serverIconFile.toPath());
String base64Icon = Base64.getEncoder().encodeToString(iconBytes);
serverInfo.put("icon", "data:image/png;base64," + base64Icon);
} catch (IOException e) {
serverInfo.put("icon", "No server icon found");
}
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", serverInfo.toString());
}
public NanoHTTPD.Response getServerHealth(final Map<String, String> ignoredParams) {
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
JSONObject healthJson = new JSONObject();
// System Memory Usage
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long usedMemory = totalMemory - freeMemory;
healthJson.put("totalMemory", formatSize(totalMemory));
healthJson.put("usedMemory", formatSize(usedMemory));
healthJson.put("freeMemory", formatSize(freeMemory));
// JVM Memory Usage
MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();
MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
healthJson.put("jvmHeapMemoryUsed", formatSize(heapMemoryUsage.getUsed()));
healthJson.put("jvmHeapMemoryMax", formatSize(heapMemoryUsage.getMax()));
healthJson.put("jvmNonHeapMemoryUsed", formatSize(nonHeapMemoryUsage.getUsed()));
healthJson.put("jvmNonHeapMemoryMax", formatSize(nonHeapMemoryUsage.getMax()));
// CPU Information
healthJson.put("availableProcessors", osBean.getAvailableProcessors());
healthJson.put("systemLoadAverage", osBean.getSystemLoadAverage());
// Disk Usage
JSONObject diskUsageJson = new JSONObject();
for (FileStore store : FileSystems.getDefault().getFileStores()) {
try {
long totalSpace = store.getTotalSpace();
long usableSpace = store.getUsableSpace();
long usedSpace = totalSpace - usableSpace;
JSONObject diskJson = new JSONObject();
diskJson.put("total", formatSize(totalSpace));
diskJson.put("used", formatSize(usedSpace));
diskJson.put("available", formatSize(usableSpace));
diskUsageJson.put(store.name(), diskJson);
} catch (IOException e) {
Logger.error("Error getting disk usage for " + store.name());
}
}
healthJson.put("diskUsage", diskUsageJson);
// Thread Information
healthJson.put("threadCount", threadBean.getThreadCount());
healthJson.put("peakThreadCount", threadBean.getPeakThreadCount());
healthJson.put("totalStartedThreadCount", threadBean.getTotalStartedThreadCount());
healthJson.put("deadlockedThreads", threadBean.findDeadlockedThreads() != null);
// Uptime
healthJson.put("uptime", formatUpTime(runtimeBean.getUptime()));
healthJson.put("tps", Helper.calculateTPS());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", healthJson.toString());
}
public NanoHTTPD.Response tps(final Map<String, String> ignoredParams) {
JSONObject tpsJson = new JSONObject();
tpsJson.put("tps", Helper.calculateTPS());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", tpsJson.toString());
}
public NanoHTTPD.Response uptime(final Map<String, String> ignoredParams) {
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
JSONObject uptimeJson = new JSONObject();
uptimeJson.put("uptime", formatUpTime(runtimeBean.getUptime()));
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", uptimeJson.toString());
}
public NanoHTTPD.Response getServerProperties(final Map<String, String> ignoredParams) {
Properties properties = new Properties();
File propertiesFile = new File(Bukkit.getServer().getWorldContainer(), "server.properties");
try (InputStream input = new FileInputStream(propertiesFile)) {
properties.load(input);
JSONObject jsonResponse = new JSONObject();
for (String key : properties.stringPropertyNames()) {
jsonResponse.put(key, properties.getProperty(key));
}
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", jsonResponse.toString());
} catch (IOException e) {
Logger.error(e.getMessage());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, "application/json", "{\"error\":\"Could not load properties.\"}");
}
}
public NanoHTTPD.Response updateServerProperties(final Map<String, String> params) {
String key = params.get("key");
String value = params.get("value");
if (key == null || value == null) {
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "application/json", "{\"error\":\"Missing key or value.\"}");
}
Properties properties = new Properties();
File propertiesFile = new File(Bukkit.getServer().getWorldContainer(), "server.properties");
try (InputStream input = new FileInputStream(propertiesFile)) {
properties.load(input);
} catch (IOException e) {
Logger.error(e.getMessage());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, "application/json", "{\"error\":\"Could not load properties.\"}");
}
try (FileOutputStream output = new FileOutputStream(propertiesFile)) {
properties.setProperty(key, value);
properties.store(output, null);
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", "{\"message\":\"Property updated successfully.\"}");
} catch (IOException e) {
Logger.error(e.getMessage());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, "application/json", "{\"error\":\"Could not save properties.\"}");
}
}
public NanoHTTPD.Response execCommand(final Map<String, String> params) {
String command = params.get("command");
if (command == null) {
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "application/json", "{\"error\":\"Invalid Command.\"}");
}
AtomicBoolean success = new AtomicBoolean(false);
CommandOutputCapture outputCapture = new CommandOutputCapture();
BukkitTask t1 = Bukkit.getScheduler().runTask(MinecraftServerAPI.getInstance(), () -> {
success.set(Bukkit.getServer().dispatchCommand(outputCapture, command));
});
while (Bukkit.getScheduler().isCurrentlyRunning(t1.getTaskId()) || Bukkit.getScheduler().isQueued(t1.getTaskId())) {
try {
Logger.debug("Waiting for command to finish...");
final int sleepTime = 100;
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Logger.error(e.getMessage());
Thread.currentThread().interrupt();
}
}
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("success", success.get());
jsonResponse.put("output", outputCapture.getOutputMessages());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", jsonResponse.toString());
}
public NanoHTTPD.Response execMultipleCommands(final Map<String, String> params) {
String commandsParam = params.get("commands");
if (commandsParam == null) {
return NanoHTTPD.newFixedLengthResponse(
NanoHTTPD.Response.Status.BAD_REQUEST,
"application/json",
"{\"error\":\"Missing 'commands' parameter\"}"
);
}
JSONArray commandsJsonArray;
try {
commandsJsonArray = new JSONArray(commandsParam);
} catch (Exception e) {
Logger.error("Error parsing 'commands' array: " + e.getMessage());
return NanoHTTPD.newFixedLengthResponse(
NanoHTTPD.Response.Status.BAD_REQUEST,
"application/json",
"{\"error\":\"'commands' parameter must be a valid JSON array\"}"
);
}
JSONArray resultsArray = new JSONArray();
for (int i = 0; i < commandsJsonArray.length(); i++) {
String command = commandsJsonArray.optString(i);
if (command == null || command.trim().isEmpty()) {
JSONObject result = new JSONObject();
result.put("command", JSONObject.NULL);
result.put("success", false);
result.put("output", "Empty command string provided.");
resultsArray.put(result);
continue;
}
AtomicBoolean success = new AtomicBoolean(false);
CommandOutputCapture outputCapture = new CommandOutputCapture();
JSONObject result = new JSONObject();
result.put("command", command);
try {
BukkitTask task = Bukkit.getScheduler().runTask(MinecraftServerAPI.getInstance(), () -> {
success.set(Bukkit.getServer().dispatchCommand(outputCapture, command));
});
while (!task.isCancelled() && (Bukkit.getScheduler().isCurrentlyRunning(task.getTaskId()) || Bukkit.getScheduler().isQueued(task.getTaskId()))) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Logger.error("Command execution interrupted: " + command);
result.put("success", false);
result.put("output", "Command execution was interrupted.");
break;
}
}
if (Thread.currentThread().isInterrupted()){
Logger.error("Command execution interrupted: " + command);
result.put("success", false);
result.put("output", "Command execution was interrupted.");
}
} catch (Exception e) {
Logger.error("Error executing command '" + command + "': " + e.getMessage());
result.put("success", false);
result.put("output", "Error executing command: " + e.getMessage());
}
if (!result.has("success")) {
result.put("success", success.get());
result.put("output", outputCapture.getOutputMessages());
}
resultsArray.put(result);
}
JSONObject responseJson = new JSONObject();
responseJson.put("results", resultsArray);
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", responseJson.toString());
}
public NanoHTTPD.Response reload(final Map<String, String> ignoredParams) {
NanoHTTPD.Response response = NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", "{}");
final long delay = 20L;
new BukkitRunnable() {
@Override
public void run() {
Bukkit.reload();
}
}.runTaskLater(MinecraftServerAPI.getInstance(), delay);
return response;
}
public NanoHTTPD.Response reboot(final Map<String, String> ignoredParams) {
NanoHTTPD.Response response = NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", "{}");
final long delay = 20L;
new BukkitRunnable() {
@Override
public void run() {
Bukkit.spigot().restart();
}
}.runTaskLater(MinecraftServerAPI.getInstance(), delay);
return response;
}
public NanoHTTPD.Response shutdown(final Map<String, String> ignoredParams) {
NanoHTTPD.Response response = NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", "{}");
final long delay = 20L;
new BukkitRunnable() {
@Override
public void run() {
Bukkit.shutdown();
}
}.runTaskLater(MinecraftServerAPI.getInstance(), delay);
return response;
}
public NanoHTTPD.Response broadcast(final Map<String, String> params) {
String message = params.get("message");
if (message == null) {
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "application/json", "{\"error\":\"Invalid Message.\"}");
}
Bukkit.broadcastMessage(message);
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", "{}");
}
public NanoHTTPD.Response getChat(final Map<String, String> ignoredParams) {
JSONObject chatJson = new JSONObject();
chatJson.put("messages", chatListener.getMessages());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", chatJson.toString());
}
public NanoHTTPD.Response getLog(final Map<String, String> ignoredParams) {
JSONObject logJson = new JSONObject();
logJson.put("log", logHandler.getLog());
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", logJson.toString());
}
private String formatUpTime(final long uptime) {
long uptimeSeconds = uptime / 1000;
long uptimeMinutes = uptimeSeconds / 60;
long uptimeHours = uptimeMinutes / 60;
long uptimeDays = uptimeHours / 24;
return String.format("%d days, %d hours, %d minutes, %d seconds", uptimeDays, uptimeHours % 24, uptimeMinutes % 60, uptimeSeconds % 60);
}
}