Files
src
pom.xml
Code
3 216
src/main/java/pl/kodari/velocitylicense/VelocityLicensePlugin.java
package pl.kodari.velocitylicense;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import net.kyori.adventure.text.Component;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Properties;
import java.util.regex.Pattern;
@Plugin(id = "velocitylicense", name = "VelocityLicense", version = "1.0.0")
public final class VelocityLicensePlugin {
private static final Pattern VALID_RESPONSE = Pattern.compile("\\\"valid\\\"\\s*:\\s*true");
private final ProxyServer server;
private final Logger logger;
private final Path dataDirectory;
private final HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
private volatile boolean licenseValid;
private boolean licenseRequired;
private int maxAdvertisedPlayers = 100;
private String licenseApiUrl = "";
private String licenseKey = "";
private String licenseProduct = "velocitylicense";
@Inject
public VelocityLicensePlugin(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) {
this.server = server;
this.logger = logger;
this.dataDirectory = dataDirectory;
}
@Subscribe
public void onProxyInitialize(ProxyInitializeEvent event) {
try {
loadConfiguration();
} catch (IOException exception) {
logger.error("Nie można wczytać konfiguracji VelocityLicense.", exception);
return;
}
if (!licenseRequired) {
licenseValid = true;
logger.info("Weryfikacja licencji jest wyłączona w config.properties.");
return;
}
validateLicense();
server.getScheduler().buildTask(this, this::validateLicense)
.repeat(Duration.ofMinutes(5))
.schedule();
}
@Subscribe
public void onProxyPing(ProxyPingEvent event) {
event.setPing(event.getPing().asBuilder()
.maximumPlayers(maxAdvertisedPlayers)
.build());
}
@Subscribe
public void onPreLogin(PreLoginEvent event) {
if (licenseRequired && !licenseValid) {
event.setResult(PreLoginEvent.PreLoginComponentResult.denied(
Component.text("Licencja serwera jest nieprawidłowa lub niedostępna.")));
}
}
private void loadConfiguration() throws IOException {
Files.createDirectories(dataDirectory);
Path configPath = dataDirectory.resolve("config.properties");
if (Files.notExists(configPath)) {
try (InputStream input = getClass().getResourceAsStream("/config.properties")) {
if (input == null) {
throw new IOException("Brak domyślnego pliku config.properties w pluginie.");
}
Files.copy(input, configPath);
}
}
Properties properties = new Properties();
try (InputStream input = Files.newInputStream(configPath)) {
properties.load(input);
}
try {
maxAdvertisedPlayers = Math.max(1,
Integer.parseInt(properties.getProperty("max-advertised-players", "500").trim()));
} catch (NumberFormatException exception) {
maxAdvertisedPlayers = 500;
logger.warn("Nieprawidłowa wartość max-advertised-players; ustawiono 500.");
}
licenseRequired = Boolean.parseBoolean(properties.getProperty("license-required", "false").trim());
licenseApiUrl = properties.getProperty("license-api-url", "").trim();
licenseKey = properties.getProperty("license-key", "").trim();
licenseProduct = properties.getProperty("license-product", "velocitylicense").trim();
}
private void validateLicense() {
if (licenseApiUrl.isBlank() || licenseKey.isBlank()) {
licenseValid = false;
logger.warn("Licencja jest wymagana, ale license-api-url lub license-key nie jest ustawione.");
return;
}
String body = "{\"licenseKey\":\"" + escapeJson(licenseKey)
+ "\",\"product\":\"" + escapeJson(licenseProduct) + "\"}";
HttpRequest request;
try {
request = HttpRequest.newBuilder(URI.create(licenseApiUrl))
.timeout(Duration.ofSeconds(10))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
.build();
} catch (IllegalArgumentException exception) {
licenseValid = false;
logger.error("Nieprawidłowy adres license-api-url.", exception);
return;
}
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> response.statusCode() == 200
&& VALID_RESPONSE.matcher(response.body()).find())
.whenComplete((valid, error) -> {
licenseValid = error == null && Boolean.TRUE.equals(valid);
if (error != null) {
logger.warn("Nie udało się sprawdzić licencji: {}", error.getMessage());
} else if (!licenseValid) {
logger.warn("API odrzuciło licencję lub zwróciło nieprawidłową odpowiedź.");
} else {
logger.info("Licencja serwera została potwierdzona.");
}
});
}
private String escapeJson(String value) {
return value.replace("\\", "\\\\").replace("\"", "\\\"");
}
}