Repository navigation
Expand file tree
/
Copy pathmain.java
More file actions
477 lines (404 loc) · 16.8 KB
/
Copy pathmain.java
File metadata and controls
477 lines (404 loc) · 16.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package com.nauticalproxy.plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.CommandExecutor;
import org.bukkit.entity.Player;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
public class NauticalProxyPlugin extends JavaPlugin implements Listener, CommandExecutor {
private static final String PROXY_API_URL = "http://localhost:8080/api/v1";
private String serverId;
private String serverName;
private String proxyHost;
private int proxyPort;
private BukkitTask heartbeatTask;
private Gson gson;
@Override
public void onEnable() {
// Initialize Gson
gson = new GsonBuilder().setPrettyPrinting().create();
// Save default config
saveDefaultConfig();
// Load configuration
loadConfiguration();
// Register events
getServer().getPluginManager().registerEvents(this, this);
// Register commands
getCommand("nautical").setExecutor(this);
// Start heartbeat task
startHeartbeat();
// Register with proxy
registerWithProxy();
getLogger().info("Nautical Proxy Plugin enabled!");
}
@Override
public void onDisable() {
// Cancel heartbeat task
if (heartbeatTask != null) {
heartbeatTask.cancel();
}
// Unregister from proxy
unregisterFromProxy();
getLogger().info("Nautical Proxy Plugin disabled!");
}
private void loadConfiguration() {
serverId = getConfig().getString("server.id", "server-" + System.currentTimeMillis());
serverName = getConfig().getString("server.name", "Minecraft Server");
proxyHost = getConfig().getString("proxy.host", "localhost");
proxyPort = getConfig().getInt("proxy.port", 8080);
// Save the generated server ID back to config
getConfig().set("server.id", serverId);
saveConfig();
}
private void startHeartbeat() {
heartbeatTask = getServer().getScheduler().runTaskTimerAsynchronously(this, () -> {
sendHeartbeat();
}, 0L, 20L * 30); // Every 30 seconds
}
private void registerWithProxy() {
getServer().getScheduler().runTaskAsynchronously(this, () -> {
try {
ServerInfo serverInfo = createServerInfo();
String jsonData = gson.toJson(serverInfo);
// First try to update existing server
if (!updateServer(jsonData)) {
// If update fails, try to add new server
addServer(jsonData);
}
getLogger().info("Successfully registered with proxy as server: " + serverId);
} catch (Exception e) {
getLogger().log(Level.WARNING, "Failed to register with proxy: " + e.getMessage());
}
});
}
private void unregisterFromProxy() {
try {
URL url = new URL(PROXY_API_URL + "/servers/" + serverId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setRequestProperty("Content-Type", "application/json");
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
getLogger().info("Successfully unregistered from proxy");
}
} catch (Exception e) {
getLogger().log(Level.WARNING, "Failed to unregister from proxy: " + e.getMessage());
}
}
private boolean updateServer(String jsonData) {
try {
URL url = new URL(PROXY_API_URL + "/servers/" + serverId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonData.getBytes("utf-8");
os.write(input, 0, input.length);
}
return conn.getResponseCode() == 200;
} catch (Exception e) {
return false;
}
}
private boolean addServer(String jsonData) {
try {
URL url = new URL(PROXY_API_URL + "/servers");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonData.getBytes("utf-8");
os.write(input, 0, input.length);
}
return conn.getResponseCode() == 201;
} catch (Exception e) {
getLogger().log(Level.WARNING, "Failed to add server to proxy: " + e.getMessage());
return false;
}
}
private void sendHeartbeat() {
try {
ServerInfo serverInfo = createServerInfo();
String jsonData = gson.toJson(serverInfo);
updateServer(jsonData);
} catch (Exception e) {
getLogger().log(Level.WARNING, "Failed to send heartbeat: " + e.getMessage());
}
}
private ServerInfo createServerInfo() {
ServerInfo info = new ServerInfo();
info.id = serverId;
info.name = serverName;
info.address = getConfig().getString("server.address", "localhost");
info.port = getServer().getPort();
info.status = "online";
info.player_count = getServer().getOnlinePlayers().size();
info.max_players = getServer().getMaxPlayers();
info.motd = getServer().getMotd();
info.version = getServer().getVersion();
info.last_ping = System.currentTimeMillis();
info.priority = getConfig().getInt("server.priority", 1);
// Add custom metadata
info.metadata = new HashMap<>();
info.metadata.put("world", getServer().getWorlds().get(0).getName());
info.metadata.put("difficulty", getServer().getWorlds().get(0).getDifficulty().name());
info.metadata.put("gamemode", getServer().getDefaultGameMode().name());
info.metadata.put("tps", String.valueOf(getServer().getTPS()[0]));
info.metadata.put("plugin_version", getDescription().getVersion());
return info;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
// Send player join notification to proxy
getServer().getScheduler().runTaskAsynchronously(this, () -> {
sendPlayerEvent("join", event.getPlayer());
});
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
// Send player quit notification to proxy
getServer().getScheduler().runTaskAsynchronously(this, () -> {
sendPlayerEvent("quit", event.getPlayer());
});
}
private void sendPlayerEvent(String eventType, Player player) {
try {
Map<String, Object> eventData = new HashMap<>();
eventData.put("server_id", serverId);
eventData.put("event_type", eventType);
eventData.put("player_name", player.getName());
eventData.put("player_uuid", player.getUniqueId().toString());
eventData.put("timestamp", System.currentTimeMillis());
String jsonData = gson.toJson(eventData);
URL url = new URL(PROXY_API_URL + "/events");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonData.getBytes("utf-8");
os.write(input, 0, input.length);
}
} catch (Exception e) {
getLogger().log(Level.WARNING, "Failed to send player event: " + e.getMessage());
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!command.getName().equalsIgnoreCase("nautical")) {
return false;
}
if (args.length == 0) {
sender.sendMessage("§6Nautical Proxy Plugin v" + getDescription().getVersion());
sender.sendMessage("§7Server ID: §f" + serverId);
sender.sendMessage("§7Proxy: §f" + proxyHost + ":" + proxyPort);
sender.sendMessage("§7Commands: §f/nautical [reload|status|test]");
return true;
}
switch (args[0].toLowerCase()) {
case "reload":
if (!sender.hasPermission("nautical.admin")) {
sender.sendMessage("§cYou don't have permission to use this command.");
return true;
}
reloadConfig();
loadConfiguration();
sender.sendMessage("§aConfiguration reloaded!");
return true;
case "status":
sender.sendMessage("§6Proxy Connection Status:");
sender.sendMessage("§7Server ID: §f" + serverId);
sender.sendMessage("§7Server Name: §f" + serverName);
sender.sendMessage("§7Proxy Host: §f" + proxyHost + ":" + proxyPort);
sender.sendMessage("§7Heartbeat: §a" + (heartbeatTask != null ? "Active" : "Inactive"));
return true;
case "test":
if (!sender.hasPermission("nautical.admin")) {
sender.sendMessage("§cYou don't have permission to use this command.");
return true;
}
sender.sendMessage("§7Testing proxy connection...");
getServer().getScheduler().runTaskAsynchronously(this, () -> {
try {
testProxyConnection();
sender.sendMessage("§aProxy connection test successful!");
} catch (Exception e) {
sender.sendMessage("§cProxy connection test failed: " + e.getMessage());
}
});
return true;
default:
sender.sendMessage("§cUnknown command. Use /nautical for help.");
return true;
}
}
private void testProxyConnection() throws Exception {
URL url = new URL(PROXY_API_URL + "/health");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new Exception("Proxy returned status code: " + responseCode);
}
// Read response
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// Parse JSON response to verify it's valid
gson.fromJson(response.toString(), Map.class);
}
}
// Inner class for server information
public static class ServerInfo {
public String id;
public String name;
public String address;
public int port;
public String status;
public int player_count;
public int max_players;
public String motd;
public String version;
public long last_ping;
public int priority;
public Map<String, String> metadata;
}
}
// plugin.yml content (create as separate file)
/*
name: NauticalProxy
version: 1.0.0
description: Nautical Proxy Plugin for Minecraft servers
author: NauticalProxy
main: com.nauticalproxy.plugin.NauticalProxyPlugin
api-version: 1.19
softdepend: []
commands:
nautical:
description: Nautical Proxy commands
usage: /nautical [reload|status|test]
permission: nautical.use
permission-message: You don't have permission to use this command.
permissions:
nautical.use:
description: Allows use of basic nautical commands
default: true
nautical.admin:
description: Allows use of admin nautical commands
default: op
*/
// config.yml content (create as separate file)
/*
# Nautical Proxy Plugin Configuration
server:
# Unique identifier for this server (auto-generated if not set)
id: ""
# Display name for this server
name: "Minecraft Server"
# Server address (IP/hostname) that the proxy should connect to
address: "localhost"
# Priority for load balancing (higher = more preferred)
priority: 1
proxy:
# Proxy API host
host: "localhost"
# Proxy API port
port: 8080
# API key for authentication (optional)
api_key: ""
# Additional server metadata
metadata:
server_type: "survival"
description: "A Minecraft server"
*/
// pom.xml for Maven build (create as separate file)
/*
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nauticalproxy</groupId>
<artifactId>nautical-proxy-plugin</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.19.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>com.google.gson</pattern>
<shadedPattern>com.nauticalproxy.plugin.gson</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
*/