-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlayerCoordsAPIClient.java
More file actions
186 lines (161 loc) · 6.97 KB
/
PlayerCoordsAPIClient.java
File metadata and controls
186 lines (161 loc) · 6.97 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
package fr.sukikui.playercoordsapi;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientWorldEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.world.biome.Biome;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.Executors;
public class PlayerCoordsAPIClient implements ClientModInitializer {
private HttpServer server;
private boolean serverStarted = false;
private volatile PlayerSnapshot latestSnapshot;
// Hardcoded port value - no longer in config
private static final int PORT = 25565;
@Override
public void onInitializeClient() {
// Start server on init if enabled
if (PlayerCoordsAPI.getConfig().enabled) {
startServer();
}
// Register tick event to constantly check config status
ClientTickEvents.END_CLIENT_TICK.register(client -> {
updateSnapshot(client);
boolean configEnabled = PlayerCoordsAPI.getConfig().enabled;
// If enabled and server not started, start server
if (configEnabled && !serverStarted) {
startServer();
}
// If disabled and server is running, stop server
if (!configEnabled && serverStarted) {
stopServer();
}
});
ClientWorldEvents.AFTER_CLIENT_WORLD_CHANGE.register((client, world) -> updateSnapshot(client));
ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> clearSnapshot());
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> {
clearSnapshot();
stopServer();
});
PlayerCoordsAPI.LOGGER.info("Registered config monitor");
}
private void updateSnapshot(MinecraftClient client) {
PlayerEntity player = client.player;
ClientWorld worldObj = client.world;
if (player == null || worldObj == null) {
latestSnapshot = null;
return;
}
RegistryEntry<Biome> biomeEntry = worldObj.getBiome(player.getBlockPos());
String biome = biomeEntry.getKey()
.map(key -> key.getValue().toString())
.orElse("unknown");
latestSnapshot = new PlayerSnapshot(
player.getX(),
player.getY(),
player.getZ(),
player.getYaw(),
player.getPitch(),
worldObj.getRegistryKey().getValue().toString(),
biome,
player.getUuid().toString(),
player.getName().getString()
);
}
private void clearSnapshot() {
latestSnapshot = null;
}
private void startServer() {
if (serverStarted) return;
try {
PlayerCoordsAPI.LOGGER.info("Starting PlayerCoordsAPI HTTP server on port " + PORT);
server = HttpServer.create(new InetSocketAddress(PORT), 0);
server.createContext("/api/coords", this::handleCoordsRequest);
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
serverStarted = true;
PlayerCoordsAPI.LOGGER.info("PlayerCoordsAPI HTTP server started successfully");
} catch (IOException e) {
PlayerCoordsAPI.LOGGER.error("Failed to start PlayerCoordsAPI HTTP server", e);
}
}
private void stopServer() {
if (server != null) {
PlayerCoordsAPI.LOGGER.info("Stopping PlayerCoordsAPI HTTP server");
// Create a separate thread to stop the server to prevent blocking
final HttpServer serverToStop = server; // Create a final reference for the thread
Thread stopThread = new Thread(() -> {
serverToStop.stop(0); // Stop with no delay
PlayerCoordsAPI.LOGGER.info("PlayerCoordsAPI HTTP server stopped successfully");
});
stopThread.setDaemon(true);
stopThread.start();
// Set variables immediately so we know the server is being stopped
server = null;
serverStarted = false;
}
}
private void handleCoordsRequest(HttpExchange exchange) throws IOException {
// Handle CORS preflight request
if (exchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
sendResponse(exchange, 204, null);
return;
}
// Check if the client is allowed to access (only localhost)
String remoteAddress = exchange.getRemoteAddress().getAddress().getHostAddress();
if (!remoteAddress.equals("127.0.0.1") && !remoteAddress.equals("0:0:0:0:0:0:0:1")) {
sendResponse(exchange, 403, "{\"error\": \"Access denied\"}");
return;
}
PlayerSnapshot snapshot = latestSnapshot;
if (snapshot != null) {
sendResponse(exchange, 200, snapshot.toJson());
} else {
sendResponse(exchange, 404, "{\"error\": \"Player not in world\"}");
}
}
private void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException {
// Add CORS headers
exchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
exchange.getResponseHeaders().set("Access-Control-Allow-Methods", "GET, OPTIONS");
exchange.getResponseHeaders().set("Access-Control-Allow-Headers", "Content-Type, Authorization");
// Set content type if response is not null
if (response != null) {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(statusCode, response.length());
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
}
} else {
exchange.sendResponseHeaders(statusCode, -1); // No response body
}
}
private record PlayerSnapshot(
double x,
double y,
double z,
float yaw,
float pitch,
String world,
String biome,
String uuid,
String username
) {
private String toJson() {
return String.format(Locale.US,
"{\"x\": %.2f, \"y\": %.2f, \"z\": %.2f, \"yaw\": %.2f, \"pitch\": %.2f, \"world\": \"%s\", \"biome\": \"%s\", \"uuid\": \"%s\", \"username\": \"%s\"}",
x, y, z, yaw, pitch, world, biome, uuid, username
);
}
}
}