refactor: refactor code

This commit is contained in:
itqop 2025-11-09 02:41:10 +03:00
parent 1f02781d07
commit 0c70a4696d
3 changed files with 97 additions and 8 deletions

View File

@ -63,7 +63,17 @@ public class WhitelistApiClient {
if (addedBy != null && !addedBy.isBlank()) body.addProperty("added_by", addedBy); if (addedBy != null && !addedBy.isBlank()) body.addProperty("added_by", addedBy);
if (addedAtIso != null && !addedAtIso.isBlank()) body.addProperty("added_at", addedAtIso); if (addedAtIso != null && !addedAtIso.isBlank()) body.addProperty("added_at", addedAtIso);
return makeRequest("POST", "/add", HttpRequest.BodyPublishers.ofString(GSON.toJson(body))) return makeRequest("POST", "/add", HttpRequest.BodyPublishers.ofString(GSON.toJson(body)))
.thenApply(resp -> resp != null && resp.statusCode() == 201); .thenApply(resp -> {
if (resp == null) return false;
int code = resp.statusCode();
if (code == 201) return true;
logHttpError("POST /add", code, resp.body());
return false;
})
.exceptionally(ex -> {
LOGGER.error("Failed to add player '{}': {}", playerName, ex.getMessage(), ex);
return false;
});
} }
public CompletableFuture<WhitelistEntry> addPlayer(String playerName, public CompletableFuture<WhitelistEntry> addPlayer(String playerName,
@ -82,13 +92,23 @@ public class WhitelistApiClient {
if (reason != null && !reason.isBlank()) body.addProperty("reason", reason); if (reason != null && !reason.isBlank()) body.addProperty("reason", reason);
return makeRequest("POST", "/add", HttpRequest.BodyPublishers.ofString(GSON.toJson(body))) return makeRequest("POST", "/add", HttpRequest.BodyPublishers.ofString(GSON.toJson(body)))
.thenApply(resp -> { .thenApply(resp -> {
if (resp == null || resp.statusCode() != 201) return null; if (resp == null) return null;
int code = resp.statusCode();
if (code != 201) {
logHttpError("POST /add", code, resp.body());
return null;
}
try { try {
JsonObject json = JsonParser.parseString(resp.body()).getAsJsonObject(); JsonObject json = JsonParser.parseString(resp.body()).getAsJsonObject();
return WhitelistEntry.fromJson(json); return WhitelistEntry.fromJson(json);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Failed to parse addPlayer response for '{}': {}", playerName, e.getMessage(), e);
return null; return null;
} }
})
.exceptionally(ex -> {
LOGGER.error("Failed to add player '{}': {}", playerName, ex.getMessage(), ex);
return null;
}); });
} }
@ -97,7 +117,17 @@ public class WhitelistApiClient {
JsonObject body = new JsonObject(); JsonObject body = new JsonObject();
body.addProperty("player_name", playerName); body.addProperty("player_name", playerName);
return makeRequest("POST", "/remove", HttpRequest.BodyPublishers.ofString(GSON.toJson(body))) return makeRequest("POST", "/remove", HttpRequest.BodyPublishers.ofString(GSON.toJson(body)))
.thenApply(resp -> resp != null && resp.statusCode() == 204); .thenApply(resp -> {
if (resp == null) return false;
int code = resp.statusCode();
if (code == 204) return true;
logHttpError("POST /remove", code, resp.body());
return false;
})
.exceptionally(ex -> {
LOGGER.error("Failed to remove player '{}': {}", playerName, ex.getMessage(), ex);
return false;
});
} }
public CompletableFuture<CheckResponse> checkPlayer(String playerName) { public CompletableFuture<CheckResponse> checkPlayer(String playerName) {
@ -109,21 +139,33 @@ public class WhitelistApiClient {
if (response == null) return new CheckResponse(false, false); if (response == null) return new CheckResponse(false, false);
try { try {
int code = response.statusCode(); int code = response.statusCode();
if (code < 200 || code >= 300) return new CheckResponse(false, false); if (code < 200 || code >= 300) {
logHttpError("POST /check", code, response.body());
return new CheckResponse(false, false);
}
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject(); JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
boolean isWhitelisted = json.has("is_whitelisted") && json.get("is_whitelisted").getAsBoolean(); boolean isWhitelisted = json.has("is_whitelisted") && json.get("is_whitelisted").getAsBoolean();
return new CheckResponse(true, isWhitelisted); return new CheckResponse(true, isWhitelisted);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Failed to parse checkPlayer response for '{}': {}", playerName, e.getMessage(), e);
return new CheckResponse(false, false); return new CheckResponse(false, false);
} }
}) })
.exceptionally(ex -> new CheckResponse(false, false)); .exceptionally(ex -> {
LOGGER.error("Failed to check player '{}': {}", playerName, ex.getMessage(), ex);
return new CheckResponse(false, false);
});
} }
public CompletableFuture<WhitelistListResponse> listAll() { public CompletableFuture<WhitelistListResponse> listAll() {
return makeRequest("GET", "/", HttpRequest.BodyPublishers.noBody()) return makeRequest("GET", "/", HttpRequest.BodyPublishers.noBody())
.thenApply(resp -> { .thenApply(resp -> {
if (resp == null) return null; if (resp == null) return null;
int code = resp.statusCode();
if (code < 200 || code >= 300) {
logHttpError("GET /", code, resp.body());
return null;
}
try { try {
JsonObject json = JsonParser.parseString(resp.body()).getAsJsonObject(); JsonObject json = JsonParser.parseString(resp.body()).getAsJsonObject();
JsonArray arr = json.getAsJsonArray("entries"); JsonArray arr = json.getAsJsonArray("entries");
@ -134,8 +176,13 @@ public class WhitelistApiClient {
} }
return new WhitelistListResponse(List.of(entries), total); return new WhitelistListResponse(List.of(entries), total);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Failed to parse listAll response: {}", e.getMessage(), e);
return null; return null;
} }
})
.exceptionally(ex -> {
LOGGER.error("Failed to list whitelist entries: {}", ex.getMessage(), ex);
return null;
}); });
} }
@ -143,12 +190,22 @@ public class WhitelistApiClient {
return makeRequest("GET", "/count", HttpRequest.BodyPublishers.noBody()) return makeRequest("GET", "/count", HttpRequest.BodyPublishers.noBody())
.thenApply(resp -> { .thenApply(resp -> {
if (resp == null) return null; if (resp == null) return null;
int code = resp.statusCode();
if (code < 200 || code >= 300) {
logHttpError("GET /count", code, resp.body());
return null;
}
try { try {
JsonObject json = JsonParser.parseString(resp.body()).getAsJsonObject(); JsonObject json = JsonParser.parseString(resp.body()).getAsJsonObject();
return json.has("total") ? json.get("total").getAsInt() : 0; return json.has("total") ? json.get("total").getAsInt() : 0;
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Failed to parse count response: {}", e.getMessage(), e);
return null; return null;
} }
})
.exceptionally(ex -> {
LOGGER.error("Failed to get whitelist count: {}", ex.getMessage(), ex);
return null;
}); });
} }
@ -161,6 +218,14 @@ public class WhitelistApiClient {
return http.sendAsync(b.build(), HttpResponse.BodyHandlers.ofString()); return http.sendAsync(b.build(), HttpResponse.BodyHandlers.ofString());
} }
private void logHttpError(String endpoint, int statusCode, String responseBody) {
if (Config.enableLogging) {
LOGGER.error("API request failed: {} returned {} - Response: {}", endpoint, statusCode, responseBody);
} else {
LOGGER.error("API request failed: {} returned {}", endpoint, statusCode);
}
}
public static final class CheckResponse { public static final class CheckResponse {
private final boolean success; private final boolean success;
private final boolean isWhitelisted; private final boolean isWhitelisted;

View File

@ -114,7 +114,13 @@ public class WhitelistCommands {
Component.literal("Failed to add " + player)); Component.literal("Failed to add " + player));
} }
}) })
); ).exceptionally(ex -> {
dispatchBack(ctx, () ->
ctx.getSource().sendFailure(
Component.literal("Error adding player: " + ex.getMessage()))
);
return null;
});
return 1; return 1;
} }
@ -143,7 +149,13 @@ public class WhitelistCommands {
Component.literal("Failed to remove " + player)); Component.literal("Failed to remove " + player));
} }
}) })
); ).exceptionally(ex -> {
dispatchBack(ctx, () ->
ctx.getSource().sendFailure(
Component.literal("Error removing player: " + ex.getMessage()))
);
return null;
});
return 1; return 1;
} }
@ -162,7 +174,13 @@ public class WhitelistCommands {
Component.literal("Check failed for " + player)); Component.literal("Check failed for " + player));
} }
}) })
); ).exceptionally(ex -> {
dispatchBack(ctx, () ->
ctx.getSource().sendFailure(
Component.literal("Error checking player: " + ex.getMessage()))
);
return null;
});
return 1; return 1;
} }

View File

@ -25,7 +25,13 @@ public class WhitelistEventHandler {
String name = sp.getGameProfile().getName(); String name = sp.getGameProfile().getName();
WhitelistApiClient.get().checkPlayer(name).thenAccept(resp -> { WhitelistApiClient.get().checkPlayer(name).thenAccept(resp -> {
if (resp != null && resp.isSuccess() && !resp.isWhitelisted()) { if (resp != null && resp.isSuccess() && !resp.isWhitelisted()) {
// Check if server is still available (player might have disconnected)
if (sp.server == null) return;
sp.server.execute(() -> { sp.server.execute(() -> {
// Double-check connection is still valid
if (sp.connection == null) return;
Component link = Component.literal("https://hubmc.org/shop") Component link = Component.literal("https://hubmc.org/shop")
.withStyle(style -> style .withStyle(style -> style
.withUnderlined(true) .withUnderlined(true)