重写底层基础代码

This commit is contained in:
zhangyuheng 2024-05-19 20:22:57 +08:00
parent ceafff572b
commit ff2e5c7a2f
25 changed files with 248 additions and 1808 deletions

15
pom.xml
View File

@ -62,6 +62,10 @@
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<repository>
<id>lunadeer-repo</id>
<url>https://ssl.lunadeer.cn:14454/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
@ -72,14 +76,9 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.6.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.6.0</version>
<groupId>cn.lunadeer</groupId>
<artifactId>MinecraftPluginUtils</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
</project>

View File

@ -1,6 +1,5 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
@ -28,7 +27,7 @@ public class Color {
this.g = 0;
this.b = 0;
this.hex = "#000000";
XLogger.err("Invalid color: " + r + ", " + g + ", " + b);
MiniPlayerTitle.logger.err("Invalid color: " + r + ", " + g + ", " + b);
}
}
@ -43,7 +42,7 @@ public class Color {
this.g = 0;
this.b = 0;
this.hex = "#000000";
XLogger.err("Invalid color: " + hex);
MiniPlayerTitle.logger.err("Invalid color: " + hex);
}
}

View File

@ -1,12 +1,10 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.minecraftpluginutils.stui.View;
import cn.lunadeer.minecraftpluginutils.stui.ViewStyles;
import cn.lunadeer.minecraftpluginutils.stui.components.Button;
import cn.lunadeer.minecraftpluginutils.stui.components.Line;
import cn.lunadeer.miniplayertitle.commands.AdminCommands;
import cn.lunadeer.miniplayertitle.utils.Notification;
import cn.lunadeer.miniplayertitle.utils.STUI.Button;
import cn.lunadeer.miniplayertitle.utils.STUI.Line;
import cn.lunadeer.miniplayertitle.utils.STUI.View;
import cn.lunadeer.miniplayertitle.utils.STUI.ViewStyles;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import org.bukkit.command.Command;
@ -111,13 +109,13 @@ public class Commands implements TabExecutor {
private static void printHelp(@NotNull CommandSender sender) {
if (sender instanceof Player) {
Player player = (Player) sender;
Notification.warn(player, "用法: /mplt <use|list|shop|buy|custom|custominfo>");
MiniPlayerTitle.notification.warn(player, "用法: /mplt <use|list|shop|buy|custom|custominfo>");
if (player.isOp()) {
Notification.warn(player, "用法: /mplt <create|delete|setdesc|setname|addshop|removeshop|setprice|setamount|setendat|listall>");
MiniPlayerTitle.notification.warn(player, "用法: /mplt <create|delete|setdesc|setname|addshop|removeshop|setprice|setamount|setendat|listall>");
}
} else {
XLogger.info("用法: /mplt <use|list|shop|buy|custom>");
XLogger.info("用法: /mplt <create|delete|setdesc|setname|addshop|removeshop|setprice|setamount|setendat|listall>");
MiniPlayerTitle.logger.info("用法: /mplt <use|list|shop|buy|custom>");
MiniPlayerTitle.logger.info("用法: /mplt <create|delete|setdesc|setname|addshop|removeshop|setprice|setamount|setendat|listall>");
}
}
@ -134,9 +132,9 @@ public class Commands implements TabExecutor {
Line line_2 = Line.create();
line_2.append(Component.text("帮助文档:"));
line_2.append(Component.text("[点击在浏览器中打开]").clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, "https://ssl.lunadeer.cn:14446/zhangyuheng/MiniPlayerTitle")));
Component backpack = Button.create("称号背包", "/mplt list");
Component shop = Button.create("称号商店", "/mplt shop");
Component custom = Button.create("自定义称号", "/mplt custominfo");
Component backpack = Button.create("称号背包").setExecuteCommand("/mplt list").build();
Component shop = Button.create("称号商店").setExecuteCommand("/mplt shop").build();
Component custom = Button.create("自定义称号").setExecuteCommand("/mplt custominfo").build();
Line line = Line.create();
line.append(backpack).append(shop).append(custom);
view.actionBar(line).addLine(line_1).addLine(line_2);

View File

@ -1,6 +1,5 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.Notification;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;

View File

@ -1,863 +0,0 @@
package cn.lunadeer.miniplayertitle;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
public class Metrics {
private final Plugin plugin;
private final MetricsBase metricsBase;
/**
* Creates a new Metrics instance.
*
* @param plugin Your plugin instance.
* @param serviceId The id of the service. It can be found at <a
* href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(JavaPlugin plugin, int serviceId) {
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
if (!config.isSet("serverUuid")) {
config.addDefault("enabled", true);
config.addDefault("serverUuid", UUID.randomUUID().toString());
config.addDefault("logFailedRequests", false);
config.addDefault("logSentData", false);
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config
.options()
.header(
"bStats (https://bStats.org) collects some basic information for plugin authors, like how\n"
+ "many people use their plugin and their total player count. It's recommended to keep bStats\n"
+ "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n"
+ "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n"
+ "anonymous.")
.copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) {
}
}
// Load the data
boolean enabled = config.getBoolean("enabled", true);
String serverUUID = config.getString("serverUuid");
boolean logErrors = config.getBoolean("logFailedRequests", false);
boolean logSentData = config.getBoolean("logSentData", false);
boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false);
metricsBase =
new MetricsBase(
"bukkit",
serverUUID,
serviceId,
enabled,
this::appendPlatformData,
this::appendServiceData,
null,
//submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),
plugin::isEnabled,
(message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),
(message) -> this.plugin.getLogger().log(Level.INFO, message),
logErrors,
logSentData,
logResponseStatusText);
}
/**
* Shuts down the underlying scheduler service.
*/
public void shutdown() {
metricsBase.shutdown();
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
metricsBase.addCustomChart(chart);
}
private void appendPlatformData(JsonObjectBuilder builder) {
builder.appendField("playerAmount", getPlayerAmount());
builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0);
builder.appendField("bukkitVersion", Bukkit.getVersion());
builder.appendField("bukkitName", Bukkit.getName());
builder.appendField("javaVersion", System.getProperty("java.version"));
builder.appendField("osName", System.getProperty("os.name"));
builder.appendField("osArch", System.getProperty("os.arch"));
builder.appendField("osVersion", System.getProperty("os.version"));
builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
}
private void appendServiceData(JsonObjectBuilder builder) {
builder.appendField("pluginVersion", plugin.getDescription().getVersion());
}
private int getPlayerAmount() {
try {
// Around MC 1.8 the return type was changed from an array to a collection,
// This fixes java.lang.NoSuchMethodError:
// org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
return onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
// Just use the new method if the reflection failed
return Bukkit.getOnlinePlayers().size();
}
}
public static class MetricsBase {
/**
* The version of the Metrics class.
*/
public static final String METRICS_VERSION = "3.0.2";
private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
private final ScheduledExecutorService scheduler;
private final String platform;
private final String serverUuid;
private final int serviceId;
private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;
private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;
private final Consumer<Runnable> submitTaskConsumer;
private final Supplier<Boolean> checkServiceEnabledSupplier;
private final BiConsumer<String, Throwable> errorLogger;
private final Consumer<String> infoLogger;
private final boolean logErrors;
private final boolean logSentData;
private final boolean logResponseStatusText;
private final Set<CustomChart> customCharts = new HashSet<>();
private final boolean enabled;
/**
* Creates a new MetricsBase class instance.
*
* @param platform The platform of the service.
* @param serviceId The id of the service.
* @param serverUuid The server uuid.
* @param enabled Whether or not data sending is enabled.
* @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
* appends all platform-specific data.
* @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
* appends all service-specific data.
* @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be
* used to delegate the data collection to a another thread to prevent errors caused by
* concurrency. Can be {@code null}.
* @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.
* @param errorLogger A consumer that accepts log message and an error.
* @param infoLogger A consumer that accepts info log messages.
* @param logErrors Whether or not errors should be logged.
* @param logSentData Whether or not the sent data should be logged.
* @param logResponseStatusText Whether or not the response status text should be logged.
*/
public MetricsBase(
String platform,
String serverUuid,
int serviceId,
boolean enabled,
Consumer<JsonObjectBuilder> appendPlatformDataConsumer,
Consumer<JsonObjectBuilder> appendServiceDataConsumer,
Consumer<Runnable> submitTaskConsumer,
Supplier<Boolean> checkServiceEnabledSupplier,
BiConsumer<String, Throwable> errorLogger,
Consumer<String> infoLogger,
boolean logErrors,
boolean logSentData,
boolean logResponseStatusText) {
ScheduledThreadPoolExecutor scheduler =
new ScheduledThreadPoolExecutor(1, task -> new Thread(task, "bStats-Metrics"));
// We want delayed tasks (non-periodic) that will execute in the future to be
// cancelled when the scheduler is shutdown.
// Otherwise, we risk preventing the server from shutting down even when
// MetricsBase#shutdown() is called
scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.scheduler = scheduler;
this.platform = platform;
this.serverUuid = serverUuid;
this.serviceId = serviceId;
this.enabled = enabled;
this.appendPlatformDataConsumer = appendPlatformDataConsumer;
this.appendServiceDataConsumer = appendServiceDataConsumer;
this.submitTaskConsumer = submitTaskConsumer;
this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;
this.errorLogger = errorLogger;
this.infoLogger = infoLogger;
this.logErrors = logErrors;
this.logSentData = logSentData;
this.logResponseStatusText = logResponseStatusText;
checkRelocation();
if (enabled) {
// WARNING: Removing the option to opt-out will get your plugin banned from
// bStats
startSubmitting();
}
}
public void addCustomChart(CustomChart chart) {
this.customCharts.add(chart);
}
public void shutdown() {
scheduler.shutdown();
}
private void startSubmitting() {
final Runnable submitTask =
() -> {
if (!enabled || !checkServiceEnabledSupplier.get()) {
// Submitting data or service is disabled
scheduler.shutdown();
return;
}
if (submitTaskConsumer != null) {
submitTaskConsumer.accept(this::submitData);
} else {
this.submitData();
}
};
// Many servers tend to restart at a fixed time at xx:00 which causes an uneven
// distribution of requests on the
// bStats backend. To circumvent this problem, we introduce some randomness into
// the initial and second delay.
// WARNING: You must not modify and part of this Metrics class, including the
// submit delay or frequency!
// WARNING: Modifying this code will get your plugin banned on bStats. Just
// don't do it!
long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);
scheduler.scheduleAtFixedRate(
submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
}
private void submitData() {
final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();
appendPlatformDataConsumer.accept(baseJsonBuilder);
final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();
appendServiceDataConsumer.accept(serviceJsonBuilder);
JsonObjectBuilder.JsonObject[] chartData =
customCharts.stream()
.map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))
.filter(Objects::nonNull)
.toArray(JsonObjectBuilder.JsonObject[]::new);
serviceJsonBuilder.appendField("id", serviceId);
serviceJsonBuilder.appendField("customCharts", chartData);
baseJsonBuilder.appendField("service", serviceJsonBuilder.build());
baseJsonBuilder.appendField("serverUUID", serverUuid);
baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION);
JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();
scheduler.execute(
() -> {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logErrors) {
errorLogger.accept("Could not submit bStats metrics data", e);
}
}
});
}
private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
if (logSentData) {
infoLogger.accept("Sent bStats metrics data: " + data.toString());
}
String url = String.format(REPORT_URL, platform);
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("User-Agent", "Metrics-Service/1");
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData);
}
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
if (logResponseStatusText) {
infoLogger.accept("Sent data to bStats and received response: " + builder);
}
}
/**
* Checks that the class was properly relocated.
*/
private void checkRelocation() {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null
|| !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this
// little "trick" ... :D
final String defaultPackage =
new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
final String examplePackage =
new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure no one just copy & pastes the example and uses the wrong
// package names
if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)
|| MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
/**
* Gzips the given string.
*
* @param str The string to gzip.
* @return The gzipped string.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return outputStream.toByteArray();
}
}
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("value", value).build();
}
}
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()});
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public abstract static class CustomChart {
private final String chartId;
protected CustomChart(String chartId) {
if (chartId == null) {
throw new IllegalArgumentException("chartId must not be null");
}
this.chartId = chartId;
}
public JsonObjectBuilder.JsonObject getRequestJsonObject(
BiConsumer<String, Throwable> errorLogger, boolean logErrors) {
JsonObjectBuilder builder = new JsonObjectBuilder();
builder.appendField("chartId", chartId);
try {
JsonObjectBuilder.JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
builder.appendField("data", data);
} catch (Throwable t) {
if (logErrors) {
errorLogger.accept("Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return builder.build();
}
protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;
}
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("value", value).build();
}
}
/**
* An extremely simple JSON builder.
*
* <p>While this class is neither feature-rich nor the most performant one, it's sufficient enough
* for its use-case.
*/
public static class JsonObjectBuilder {
private StringBuilder builder = new StringBuilder();
private boolean hasAtLeastOneField = false;
public JsonObjectBuilder() {
builder.append("{");
}
/**
* Appends a null field to the JSON.
*
* @param key The key of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendNull(String key) {
appendFieldUnescaped(key, "null");
return this;
}
/**
* Appends a string field to the JSON.
*
* @param key The key of the field.
* @param value The value of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, String value) {
if (value == null) {
throw new IllegalArgumentException("JSON value must not be null");
}
appendFieldUnescaped(key, "\"" + escape(value) + "\"");
return this;
}
/**
* Appends an integer field to the JSON.
*
* @param key The key of the field.
* @param value The value of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, int value) {
appendFieldUnescaped(key, String.valueOf(value));
return this;
}
/**
* Appends an object to the JSON.
*
* @param key The key of the field.
* @param object The object.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, JsonObject object) {
if (object == null) {
throw new IllegalArgumentException("JSON object must not be null");
}
appendFieldUnescaped(key, object.toString());
return this;
}
/**
* Appends a string array to the JSON.
*
* @param key The key of the field.
* @param values The string array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, String[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values)
.map(value -> "\"" + escape(value) + "\"")
.collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends an integer array to the JSON.
*
* @param key The key of the field.
* @param values The integer array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, int[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends an object array to the JSON.
*
* @param key The key of the field.
* @param values The integer array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, JsonObject[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends a field to the object.
*
* @param key The key of the field.
* @param escapedValue The escaped value of the field.
*/
private void appendFieldUnescaped(String key, String escapedValue) {
if (builder == null) {
throw new IllegalStateException("JSON has already been built");
}
if (key == null) {
throw new IllegalArgumentException("JSON key must not be null");
}
if (hasAtLeastOneField) {
builder.append(",");
}
builder.append("\"").append(escape(key)).append("\":").append(escapedValue);
hasAtLeastOneField = true;
}
/**
* Builds the JSON string and invalidates this builder.
*
* @return The built JSON string.
*/
public JsonObject build() {
if (builder == null) {
throw new IllegalStateException("JSON has already been built");
}
JsonObject object = new JsonObject(builder.append("}").toString());
builder = null;
return object;
}
/**
* Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
*
* <p>This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'.
* Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n").
*
* @param value The value to escape.
* @return The escaped value.
*/
private static String escape(String value) {
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '"') {
builder.append("\\\"");
} else if (c == '\\') {
builder.append("\\\\");
} else if (c <= '\u000F') {
builder.append("\\u000").append(Integer.toHexString(c));
} else if (c <= '\u001F') {
builder.append("\\u00").append(Integer.toHexString(c));
} else {
builder.append(c);
}
}
return builder.toString();
}
/**
* A super simple representation of a JSON object.
*
* <p>This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not
* allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,
* JsonObject)}.
*/
public static class JsonObject {
private final String value;
private JsonObject(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
}
}

View File

@ -1,13 +1,11 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.minecraftpluginutils.*;
import cn.lunadeer.miniplayertitle.utils.ConfigManager;
import cn.lunadeer.miniplayertitle.utils.Database;
import cn.lunadeer.miniplayertitle.utils.GiteaReleaseCheck;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import cn.lunadeer.miniplayertitle.utils.DatabaseTables;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.Connection;
import java.util.Objects;
public final class MiniPlayerTitle extends JavaPlugin {
@ -16,15 +14,24 @@ public final class MiniPlayerTitle extends JavaPlugin {
public void onEnable() {
// Plugin startup logic
instance = this;
notification = new Notification(this);
logger = new XLogger(instance);
config = new ConfigManager(instance);
dbConnection = Database.createConnection();
Database.migrate();
logger.setDebug(config.isDebug());
database = new DatabaseManager(this,
config.getDbType().equals("pgsql") ? DatabaseManager.TYPE.POSTGRESQL : DatabaseManager.TYPE.SQLITE,
config.getDbHost(),
config.getDbPort(),
config.getDbName(),
config.getDbUser(),
config.getDbPass());
DatabaseTables.migrate();
Bukkit.getPluginManager().registerEvents(new Events(), this);
Objects.requireNonNull(Bukkit.getPluginCommand("MiniPlayerTitle")).setExecutor(new Commands());
Objects.requireNonNull(Bukkit.getPluginCommand("MiniPlayerTitle")).setTabCompleter(new Commands());
Metrics metrics = new Metrics(this, 21444);
bStatsMetrics metrics = new bStatsMetrics(this, 21444);
if (config.isCheckUpdate()) {
giteaReleaseCheck = new GiteaReleaseCheck(this,
"https://ssl.lunadeer.cn:14446",
@ -32,17 +39,17 @@ public final class MiniPlayerTitle extends JavaPlugin {
"MiniPlayerTitle");
}
XLogger.info("称号插件已加载");
XLogger.info("版本: " + getPluginMeta().getVersion());
logger.info("称号插件已加载");
logger.info("版本: " + getPluginMeta().getVersion());
// http://patorjk.com/software/taag/#p=display&f=Big&t=MiniPlayerTitle
XLogger.info(" __ __ _ _ _____ _ _______ _ _ _");
XLogger.info(" | \\/ (_) (_) __ \\| | |__ __(_) | | |");
XLogger.info(" | \\ / |_ _ __ _| |__) | | __ _ _ _ ___ _ __| | _| |_| | ___");
XLogger.info(" | |\\/| | | '_ \\| | ___/| |/ _` | | | |/ _ \\ '__| | | | __| |/ _ \\");
XLogger.info(" | | | | | | | | | | | | (_| | |_| | __/ | | | | | |_| | __/");
XLogger.info(" |_| |_|_|_| |_|_|_| |_|\\__,_|\\__, |\\___|_| |_| |_|\\__|_|\\___|");
XLogger.info(" __/ |");
XLogger.info(" |___/");
logger.info(" __ __ _ _ _____ _ _______ _ _ _");
logger.info(" | \\/ (_) (_) __ \\| | |__ __(_) | | |");
logger.info(" | \\ / |_ _ __ _| |__) | | __ _ _ _ ___ _ __| | _| |_| | ___");
logger.info(" | |\\/| | | '_ \\| | ___/| |/ _` | | | |/ _ \\ '__| | | | __| |/ _ \\");
logger.info(" | | | | | | | | | | | | (_| | |_| | __/ | | | | | |_| | __/");
logger.info(" |_| |_|_|_| |_|_|_| |_|\\__,_|\\__, |\\___|_| |_| |_|\\__|_|\\___|");
logger.info(" __/ |");
logger.info(" |___/");
}
@Override
@ -52,6 +59,8 @@ public final class MiniPlayerTitle extends JavaPlugin {
public static MiniPlayerTitle instance;
public static ConfigManager config;
public static Connection dbConnection;
public static DatabaseManager database;
public static XLogger logger;
public static Notification notification;
private GiteaReleaseCheck giteaReleaseCheck;
}

View File

@ -1,6 +1,5 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.Database;
import cn.lunadeer.miniplayertitle.utils.Time;
import java.sql.ResultSet;
@ -21,12 +20,12 @@ public class PlayerTitle extends Title {
sql += "INSERT INTO mplt_player_title (title_id, player_uuid, expire_at) ";
sql += "VALUES (" + title_id + ", '" + player_uuid.toString() + "', " + System.currentTimeMillis() + ") ";
sql += "RETURNING id;";
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
if (rs != null && rs.next()) {
return new PlayerTitle(title_id, player_uuid, -1L);
}
} catch (Exception e) {
cn.lunadeer.miniplayertitle.utils.XLogger.err("PlayerTitle create failed: " + e.getMessage());
MiniPlayerTitle.logger.err("PlayerTitle create failed: " + e.getMessage());
}
return null;
}
@ -61,6 +60,6 @@ public class PlayerTitle extends Title {
sql += "updated_at = CURRENT_TIMESTAMP ";
sql += "WHERE player_uuid = '" + _player_uuid.toString() + "' ";
sql += "AND title_id = " + this._id + ";";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
}

View File

@ -1,9 +1,7 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.Database;
import cn.lunadeer.miniplayertitle.utils.Time;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import java.sql.ResultSet;
@ -29,13 +27,13 @@ public class SaleTitle extends Title {
sql += "INSERT INTO mplt_title_shop (title_id, price, days, amount, sale_end_at) ";
sql += "VALUES (" + title_id + ", 0, 0, 0, -1) ";
sql += "RETURNING id;";
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
if (rs != null && rs.next()) {
Integer id = rs.getInt("id");
return new SaleTitle(id, title_id, 0, 0, 0, -1L);
}
} catch (Exception e) {
XLogger.err("SaleTitle create failed: " + e.getMessage());
MiniPlayerTitle.logger.err("SaleTitle create failed: " + e.getMessage());
}
return null;
}
@ -110,7 +108,7 @@ public class SaleTitle extends Title {
}
}
public Integer getSaleId(){
public Integer getSaleId() {
return this._sale_id;
}
@ -125,6 +123,6 @@ public class SaleTitle extends Title {
sql += "updated_at = CURRENT_TIMESTAMP ";
sql += "WHERE id = " + this._sale_id + ";";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
}

View File

@ -1,11 +1,8 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.Database;
import cn.lunadeer.miniplayertitle.utils.Notification;
import cn.lunadeer.miniplayertitle.utils.STUI.Button;
import cn.lunadeer.miniplayertitle.utils.STUI.Line;
import cn.lunadeer.miniplayertitle.utils.STUI.ListView;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import cn.lunadeer.minecraftpluginutils.stui.ListView;
import cn.lunadeer.minecraftpluginutils.stui.components.Button;
import cn.lunadeer.minecraftpluginutils.stui.components.Line;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.command.CommandSender;
@ -21,7 +18,7 @@ public class Shop {
if (!(sender instanceof Player)) {
for (SaleTitle title : titles.values()) {
Component idx = Component.text("[" + title.getSaleId() + "] ");
Notification.info(sender, idx.append(title.getTitle()));
MiniPlayerTitle.notification.info(sender, idx.append(title.getTitle()));
}
return;
}
@ -34,7 +31,7 @@ public class Shop {
TextComponent idx = Component.text("[" + title_sale_id + "] ");
SaleTitle title = entry.getValue();
Line line = Line.create();
Component button = Button.create("购买", "/mplt buy " + title_sale_id);
Component button = Button.create("购买").setExecuteCommand("/mplt buy " + title_sale_id).build();
line.append(idx)
.append(title.getTitle())
.append("价格:" + title.getPrice() + " 有效期:" + (title.getDays() == -1 ? "永久" : title.getDays() + ""))
@ -49,7 +46,7 @@ public class Shop {
public static void deleteTitle(Integer id) {
String sql = "";
sql += "DELETE FROM mplt_title_shop WHERE id = " + id + ";";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
public static Map<Integer, SaleTitle> getSaleTitles() {
@ -63,7 +60,7 @@ public class Shop {
sql += "sale_end_at ";
sql += "FROM mplt_title_shop;";
Map<Integer, SaleTitle> titles = new HashMap<>();
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
while (rs != null && rs.next()) {
Integer id = rs.getInt("id");
Integer title_id = rs.getInt("title_id");
@ -75,7 +72,7 @@ public class Shop {
titles.put(id, title);
}
} catch (Exception e) {
XLogger.err("XPlayer getTitles failed: " + e.getMessage());
MiniPlayerTitle.logger.err("XPlayer getTitles failed: " + e.getMessage());
}
return titles;
}

View File

@ -1,10 +1,7 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.Database;
import cn.lunadeer.miniplayertitle.utils.Notification;
import cn.lunadeer.miniplayertitle.utils.STUI.Line;
import cn.lunadeer.miniplayertitle.utils.STUI.ListView;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import cn.lunadeer.minecraftpluginutils.stui.ListView;
import cn.lunadeer.minecraftpluginutils.stui.components.Line;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.HoverEvent;
@ -28,13 +25,13 @@ public class Title {
sql += "'" + description + "', ";
sql += "true ";
sql += ") RETURNING id;";
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
if (rs != null && rs.next()) {
int titleId = rs.getInt("id");
return new Title(titleId);
}
} catch (Exception e) {
XLogger.err("Title create failed: " + e.getMessage());
MiniPlayerTitle.logger.err("Title create failed: " + e.getMessage());
}
return null;
}
@ -43,7 +40,7 @@ public class Title {
List<Title> titles = new ArrayList<>();
String sql = "";
sql += "SELECT id FROM mplt_title;";
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
if (rs != null) {
while (rs.next()) {
Integer id = rs.getInt("id");
@ -51,7 +48,7 @@ public class Title {
}
}
} catch (Exception e) {
XLogger.err("Title all failed: " + e.getMessage());
MiniPlayerTitle.logger.err("Title all failed: " + e.getMessage());
}
return titles;
}
@ -61,7 +58,7 @@ public class Title {
if (!(sender instanceof Player)) {
for (Title title : titles) {
Component idx = Component.text("[" + title.getId() + "]");
Notification.info(sender, idx.append(title.getTitle()));
MiniPlayerTitle.notification.info(sender, idx.append(title.getTitle()));
}
return;
}
@ -83,21 +80,21 @@ public class Title {
sql += "SELECT id, title, description, enabled ";
sql += "FROM mplt_title ";
sql += "WHERE id = " + id + ";";
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
if (rs != null && rs.next()) {
this._title = rs.getString("title");
this._description = rs.getString("description");
this._enabled = rs.getBoolean("enabled");
}
} catch (Exception e) {
XLogger.err("Title load failed: " + e.getMessage());
MiniPlayerTitle.logger.err("Title load failed: " + e.getMessage());
}
}
public static void delete(Integer id) {
String sql = "";
sql += "DELETE FROM mplt_title WHERE id = " + id + ";";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
private void save() {
@ -116,7 +113,7 @@ public class Title {
sql += "updated_at = CURRENT_TIMESTAMP ";
sql += "WHERE id = " + this._id + ";";
}
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
public Integer getId() {

View File

@ -1,12 +1,9 @@
package cn.lunadeer.miniplayertitle;
import cn.lunadeer.miniplayertitle.utils.Database;
import cn.lunadeer.miniplayertitle.utils.Notification;
import cn.lunadeer.miniplayertitle.utils.STUI.Button;
import cn.lunadeer.miniplayertitle.utils.STUI.Line;
import cn.lunadeer.miniplayertitle.utils.STUI.ListView;
import cn.lunadeer.minecraftpluginutils.stui.ListView;
import cn.lunadeer.minecraftpluginutils.stui.components.Button;
import cn.lunadeer.minecraftpluginutils.stui.components.Line;
import cn.lunadeer.miniplayertitle.utils.Time;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.entity.Player;
@ -43,7 +40,7 @@ public class XPlayer {
TextComponent idx = Component.text("[" + title_id + "] ");
Line line = Line.create();
boolean is_using = Objects.equals(title.getId(), _current_title_id);
Component button = Button.create(is_using ? "卸下" : "使用", "/mplt use " + (is_using ? -1 : title.getId()));
Component button = Button.create(is_using ? "卸下" : "使用").setExecuteCommand("/mplt use " + (is_using ? -1 : title.getId())).build();
line.append(idx)
.append(title.getTitle())
.append(Component.text("有效期至:" + title.getExpireAtStr()))
@ -61,13 +58,13 @@ public class XPlayer {
sql += "SET using_title_id = " + _current_title_id + ", ";
sql += "updated_at = CURRENT_TIMESTAMP ";
sql += "WHERE uuid = '" + _player.getUniqueId() + "';";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
updateName();
if (_current_title_id == -1) {
Notification.info(_player, "成功卸下称号");
MiniPlayerTitle.notification.info(_player, "成功卸下称号");
return;
}
Notification.info(_player, Component.text("成功使用称号: ").append(_titles.get(_current_title_id).getTitle()));
MiniPlayerTitle.notification.info(_player, Component.text("成功使用称号: ").append(_titles.get(_current_title_id).getTitle()));
}
private void checkTitleValid() {
@ -75,13 +72,13 @@ public class XPlayer {
return;
}
if (!_titles.containsKey(_current_title_id)) {
Notification.error(_player, "称号 " + _current_title_id + " 不存在");
MiniPlayerTitle.notification.error(_player, "称号 " + _current_title_id + " 不存在");
_current_title_id = -1;
return;
}
PlayerTitle title = _titles.get(_current_title_id);
if (title.isExpired()) {
Notification.error(_player, title.getTitle().append(Component.text(" 称号已过期")));
MiniPlayerTitle.notification.error(_player, title.getTitle().append(Component.text(" 称号已过期")));
_current_title_id = -1;
}
}
@ -93,7 +90,7 @@ public class XPlayer {
sql += "SET coin = " + coin + ", ";
sql += "updated_at = CURRENT_TIMESTAMP ";
sql += "WHERE uuid = '" + _player.getUniqueId().toString() + "';";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
public void add_coin(Integer coin) {
@ -116,7 +113,7 @@ public class XPlayer {
sql += "FROM mplt_player_title ";
sql += "WHERE player_uuid = '" + uuid.toString() + "';";
Map<Integer, PlayerTitle> titles = new HashMap<>();
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
while (rs != null && rs.next()) {
Integer title_id = rs.getInt("title_id");
Long expire_at = rs.getLong("expire_at");
@ -124,7 +121,7 @@ public class XPlayer {
titles.put(title_id, title);
}
} catch (Exception e) {
XLogger.err("XPlayer getTitles failed: " + e.getMessage());
MiniPlayerTitle.logger.err("XPlayer getTitles failed: " + e.getMessage());
}
return titles;
}
@ -137,7 +134,7 @@ public class XPlayer {
sql += "WHERE uuid = '" + uuid.toString() + "';";
this._coin = MiniPlayerTitle.config.getDefaultCoin();
this._current_title_id = -1;
try (ResultSet rs = Database.query(sql)) {
try (ResultSet rs = MiniPlayerTitle.database.query(sql)) {
if (rs != null && rs.next()) {
this._coin = rs.getInt("coin");
this._current_title_id = rs.getInt("using_title_id");
@ -147,30 +144,30 @@ public class XPlayer {
sql += "'" + uuid + "', ";
sql += this._coin + ", ";
sql += this._current_title_id + ");";
Database.query(sql);
MiniPlayerTitle.database.query(sql);
}
} catch (Exception e) {
XLogger.err("XPlayer getInfo failed: " + e.getMessage());
MiniPlayerTitle.logger.err("XPlayer getInfo failed: " + e.getMessage());
}
}
public void buyTitle(SaleTitle title) {
if (title.isSaleExpired() || title.getDays() == 0) {
Notification.error(_player, "此称号已停止销售");
MiniPlayerTitle.notification.error(_player, "此称号已停止销售");
return;
}
if (title.getAmount() != -1 && title.getAmount() <= 0) {
Notification.error(_player, "此称号已售罄");
MiniPlayerTitle.notification.error(_player, "此称号已售罄");
return;
}
if (title.getPrice() > _coin) {
Notification.error(_player, "你的余额不足");
MiniPlayerTitle.notification.error(_player, "你的余额不足");
return;
}
PlayerTitle title_bought = null;
if (_titles.containsKey(title.getId())) {
if (!_titles.get(title.getId()).isExpired()) {
Notification.warn(_player, "你已经拥有此称号");
MiniPlayerTitle.notification.warn(_player, "你已经拥有此称号");
return;
}
title_bought = _titles.get(title.getId());
@ -178,15 +175,15 @@ public class XPlayer {
title_bought = PlayerTitle.create(title.getId(), _player.getUniqueId());
}
if (title_bought == null) {
Notification.error(_player, "购买失败");
MiniPlayerTitle.notification.error(_player, "购买失败");
return;
}
set_coin(_coin - title.getPrice());
if (title.getAmount() > 0) {
SaleTitle.setAmount(title.getId(), title.getAmount() - 1);
}
Notification.info(_player, Component.text("成功购买称号: ").append(title.getTitle()));
Notification.info(_player, "花费: " + title.getPrice() + "称号币,余额: " + _coin + "称号币");
MiniPlayerTitle.notification.info(_player, Component.text("成功购买称号: ").append(title.getTitle()));
MiniPlayerTitle.notification.info(_player, "花费: " + title.getPrice() + "称号币,余额: " + _coin + "称号币");
if (title.getDays() == -1) {
title_bought.setExpireAt(-1L);
@ -194,12 +191,12 @@ public class XPlayer {
Long timestamp = System.currentTimeMillis() + title.getDays() * 24 * 60 * 60 * 1000L;
title_bought.setExpireAt((long) Time.getFromTimestamp(timestamp));
}
Notification.info(_player, title.getTitle().append(Component.text(" 已购买至 " + title_bought.getExpireAtStr())));
MiniPlayerTitle.notification.info(_player, title.getTitle().append(Component.text(" 已购买至 " + title_bought.getExpireAtStr())));
}
public void custom(String title_str) {
if (this.get_coin() < MiniPlayerTitle.config.getCustomCost()) {
Notification.error(this._player, "称号币不足");
MiniPlayerTitle.notification.error(this._player, "称号币不足");
return;
}
List<String> exist_titles = new ArrayList<>();
@ -208,29 +205,29 @@ public class XPlayer {
}
Title title = Title.create(title_str, this._player.getName() + "的自定义称号");
if (title == null) {
Notification.error(this._player, "创建称号失败");
MiniPlayerTitle.notification.error(this._player, "创建称号失败");
return;
}
if (title.getTitleContent().length() > MiniPlayerTitle.config.getMaxLength()) {
Notification.error(this._player, "称号长度超过限制,最大字符长度(不含颜色代码): " + MiniPlayerTitle.config.getMaxLength());
MiniPlayerTitle.notification.error(this._player, "称号长度超过限制,最大字符长度(不含颜色代码): " + MiniPlayerTitle.config.getMaxLength());
Title.delete(title.getId());
return;
}
if (exist_titles.contains(title.getTitleContent())) {
Notification.error(this._player, "已存在同名称号");
MiniPlayerTitle.notification.error(this._player, "已存在同名称号");
Title.delete(title.getId());
return;
}
PlayerTitle playerTitle = PlayerTitle.create(title.getId(), this._player.getUniqueId());
if (playerTitle == null) {
Notification.error(this._player, "创建称号失败");
MiniPlayerTitle.notification.error(this._player, "创建称号失败");
Title.delete(title.getId());
return;
}
playerTitle.setExpireAt(-1L);
this.set_coin(this.get_coin() - MiniPlayerTitle.config.getCustomCost());
Notification.info(this._player, Component.text("成功创建自定义称号: ").append(title.getTitle()));
Notification.info(this._player, "花费: " + MiniPlayerTitle.config.getCustomCost() + "称号币,余额: " + this.get_coin() + "称号币");
MiniPlayerTitle.notification.info(this._player, Component.text("成功创建自定义称号: ").append(title.getTitle()));
MiniPlayerTitle.notification.info(this._player, "花费: " + MiniPlayerTitle.config.getCustomCost() + "称号币,余额: " + this.get_coin() + "称号币");
}
public void updateName() {

View File

@ -1,10 +1,9 @@
package cn.lunadeer.miniplayertitle.commands;
import cn.lunadeer.miniplayertitle.MiniPlayerTitle;
import cn.lunadeer.miniplayertitle.SaleTitle;
import cn.lunadeer.miniplayertitle.Title;
import cn.lunadeer.miniplayertitle.XPlayer;
import cn.lunadeer.miniplayertitle.utils.Notification;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -14,19 +13,19 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt create <称号名称> <称号描述>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt create <称号名称> <称号描述>");
return;
}
Title title = Title.create(args[1], args[2]);
if (title != null) {
Notification.info(sender, Component.text("成功创建称号: [" + title.getId() + "]").append(title.getTitle()));
MiniPlayerTitle.notification.info(sender, Component.text("成功创建称号: [" + title.getId() + "]").append(title.getTitle()));
} else {
Notification.error(sender, "创建称号失败");
MiniPlayerTitle.notification.error(sender, "创建称号失败");
}
}
@ -35,18 +34,18 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 2) {
Notification.warn(sender, "用法: /mplt delete <称号ID>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt delete <称号ID>");
return;
}
Title.delete(Integer.parseInt(args[1]));
Notification.info(sender, "已删除称号");
MiniPlayerTitle.notification.info(sender, "已删除称号");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -55,7 +54,7 @@ public class AdminCommands {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
@ -64,13 +63,13 @@ public class AdminCommands {
try {
page = Integer.parseInt(args[1]);
} catch (Exception e) {
Notification.error(sender, "页数格式错误");
MiniPlayerTitle.notification.error(sender, "页数格式错误");
return;
}
}
Title.listAllTitle(sender, page);
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -79,19 +78,19 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt setdesc <称号ID> <称号描述>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt setdesc <称号ID> <称号描述>");
return;
}
Title title = new Title(Integer.parseInt(args[1]));
title.setDescription(args[2]);
Notification.info(sender, "已设置称号描述");
MiniPlayerTitle.notification.info(sender, "已设置称号描述");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -100,19 +99,19 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt setname <称号ID> <称号名称>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt setname <称号ID> <称号名称>");
return;
}
Title title = new Title(Integer.parseInt(args[1]));
title.setTitle(args[2]);
Notification.info(sender, "已设置称号名称");
MiniPlayerTitle.notification.info(sender, "已设置称号名称");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -121,23 +120,23 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 2) {
Notification.warn(sender, "用法: /mplt addshop <称号ID>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt addshop <称号ID>");
return;
}
SaleTitle title = SaleTitle.create(Integer.parseInt(args[1]));
if (title == null) {
Notification.error(sender, "添加商品失败");
MiniPlayerTitle.notification.error(sender, "添加商品失败");
} else {
Notification.info(sender, "已添加称号到商店, 商品ID: " + title.getSaleId());
Notification.info(sender, title.getTitle());
MiniPlayerTitle.notification.info(sender, "已添加称号到商店, 商品ID: " + title.getSaleId());
MiniPlayerTitle.notification.info(sender, title.getTitle());
}
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -146,18 +145,18 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 2) {
Notification.warn(sender, "用法: /mplt removeshop <商品ID>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt removeshop <商品ID>");
return;
}
SaleTitle.delete(Integer.parseInt(args[1]));
Notification.info(sender, "已从商店移除商品");
MiniPlayerTitle.notification.info(sender, "已从商店移除商品");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -166,12 +165,12 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 4) {
Notification.warn(sender, "用法: /mplt setprice <商品ID> <价格> <天数>(-1为永久)");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt setprice <商品ID> <价格> <天数>(-1为永久)");
return;
}
int price;
@ -182,18 +181,18 @@ public class AdminCommands {
days = Integer.parseInt(args[3]);
id = Integer.parseInt(args[1]);
} catch (Exception e) {
Notification.error(sender, "价格或天数格式错误");
MiniPlayerTitle.notification.error(sender, "价格或天数格式错误");
return;
}
if (price < 0 || days < -1) {
Notification.error(sender, "价格或天数格式错误");
MiniPlayerTitle.notification.error(sender, "价格或天数格式错误");
return;
}
SaleTitle.setPrice(id, price);
SaleTitle.setDays(id, days);
Notification.info(sender, "已设置商品价格");
MiniPlayerTitle.notification.info(sender, "已设置商品价格");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -202,12 +201,12 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt setamount <商品ID> <数量>(-1为无限)");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt setamount <商品ID> <数量>(-1为无限)");
return;
}
int amount;
@ -216,13 +215,13 @@ public class AdminCommands {
amount = Integer.parseInt(args[2]);
id = Integer.parseInt(args[1]);
} catch (Exception e) {
Notification.error(sender, "数量格式错误");
MiniPlayerTitle.notification.error(sender, "数量格式错误");
return;
}
SaleTitle.setAmount(id, amount);
Notification.info(sender, "已设置商品数量");
MiniPlayerTitle.notification.info(sender, "已设置商品数量");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -231,26 +230,26 @@ public class AdminCommands {
if (sender instanceof org.bukkit.entity.Player) {
Player player = (org.bukkit.entity.Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt setendat <商品ID> <时间YYYYMMDD>(-1为永久)");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt setendat <商品ID> <时间YYYYMMDD>(-1为永久)");
return;
}
long time_stamp;
try {
time_stamp = Long.parseLong(args[2]);
} catch (Exception e) {
Notification.error(sender, "时间格式错误");
MiniPlayerTitle.notification.error(sender, "时间格式错误");
return;
}
SaleTitle.setSaleEndAt(Integer.parseInt(args[1]), time_stamp);
Notification.info(sender, "已设置商品结束时间");
MiniPlayerTitle.notification.info(sender, "已设置商品结束时间");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -259,30 +258,30 @@ public class AdminCommands {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt addcoin <玩家> <数量>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt addcoin <玩家> <数量>");
return;
}
Player target = sender.getServer().getPlayer(args[1]);
if (target == null) {
Notification.error(sender, "玩家不在线");
MiniPlayerTitle.notification.error(sender, "玩家不在线");
return;
}
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception e) {
Notification.error(sender, "数量格式错误");
MiniPlayerTitle.notification.error(sender, "数量格式错误");
return;
}
new XPlayer(target).add_coin(amount);
Notification.info(sender, "已给予玩家 " + target.getName() + " " + amount + " 称号币");
MiniPlayerTitle.notification.info(sender, "已给予玩家 " + target.getName() + " " + amount + " 称号币");
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
@ -291,30 +290,30 @@ public class AdminCommands {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!player.isOp()) {
XLogger.warn(player, "你没有权限执行该命令");
MiniPlayerTitle.notification.warn(player, "你没有权限执行该命令");
return;
}
}
if (args.length != 3) {
Notification.warn(sender, "用法: /mplt setcoin <玩家> <数量>");
MiniPlayerTitle.notification.warn(sender, "用法: /mplt setcoin <玩家> <数量>");
return;
}
Player target = sender.getServer().getPlayer(args[1]);
if (target == null) {
Notification.error(sender, "玩家不在线");
MiniPlayerTitle.notification.error(sender, "玩家不在线");
return;
}
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception e) {
Notification.error(sender, "数量格式错误");
MiniPlayerTitle.notification.error(sender, "数量格式错误");
return;
}
new XPlayer(target).set_coin(amount);
Notification.info(sender, "已设置玩家 " + target.getName() + " 称号币为 " + amount);
MiniPlayerTitle.notification.info(sender, "已设置玩家 " + target.getName() + " 称号币为 " + amount);
} catch (Exception e) {
Notification.error(sender, e.getMessage());
MiniPlayerTitle.notification.error(sender, e.getMessage());
}
}
}

View File

@ -4,20 +4,18 @@ import cn.lunadeer.miniplayertitle.MiniPlayerTitle;
import cn.lunadeer.miniplayertitle.SaleTitle;
import cn.lunadeer.miniplayertitle.Shop;
import cn.lunadeer.miniplayertitle.XPlayer;
import cn.lunadeer.miniplayertitle.utils.Notification;
import cn.lunadeer.miniplayertitle.utils.XLogger;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class PlayerCommands {
public static void use(CommandSender sender, String[] args) {
if (!(sender instanceof org.bukkit.entity.Player)) {
XLogger.warn("该命令只能由玩家执行");
MiniPlayerTitle.logger.warn("该命令只能由玩家执行");
return;
}
org.bukkit.entity.Player player = (org.bukkit.entity.Player) sender;
if (args.length != 2) {
Notification.warn(player, "用法: /mplt use <称号ID>");
MiniPlayerTitle.notification.warn(player, "用法: /mplt use <称号ID>");
return;
}
@ -28,7 +26,7 @@ public class PlayerCommands {
public static void list(CommandSender sender, String[] args) {
if (!(sender instanceof org.bukkit.entity.Player)) {
XLogger.warn("该命令只能由玩家执行");
MiniPlayerTitle.logger.warn("该命令只能由玩家执行");
return;
}
org.bukkit.entity.Player player = (org.bukkit.entity.Player) sender;
@ -37,7 +35,7 @@ public class PlayerCommands {
try {
page = Integer.parseInt(args[1]);
} catch (Exception e) {
Notification.error(player, "页数格式错误");
MiniPlayerTitle.notification.error(player, "页数格式错误");
return;
}
}
@ -58,19 +56,19 @@ public class PlayerCommands {
public static void buy(CommandSender sender, String[] args) {
if (!(sender instanceof org.bukkit.entity.Player)) {
XLogger.warn("该命令只能由玩家执行");
MiniPlayerTitle.logger.warn("该命令只能由玩家执行");
return;
}
org.bukkit.entity.Player player = (org.bukkit.entity.Player) sender;
if (args.length != 2) {
Notification.warn(player, "用法: /mplt buy <称号ID>");
MiniPlayerTitle.notification.warn(player, "用法: /mplt buy <称号ID>");
return;
}
XPlayer xPlayer = new XPlayer(player);
Integer sale_id = Integer.parseInt(args[1]);
SaleTitle saleTitle = Shop.getSaleTitles().get(sale_id);
if (saleTitle == null) {
Notification.error(player, "该称号不存在");
MiniPlayerTitle.notification.error(player, "该称号不存在");
return;
}
xPlayer.buyTitle(saleTitle);
@ -78,16 +76,16 @@ public class PlayerCommands {
public static void custom(CommandSender sender, String[] args) {
if (!(sender instanceof org.bukkit.entity.Player)) {
XLogger.warn("该命令只能由玩家执行");
MiniPlayerTitle.logger.warn("该命令只能由玩家执行");
return;
}
Player player = (Player) sender;
if (args.length != 2) {
Notification.warn(player, "用法: /mplt custom <称号>");
MiniPlayerTitle.notification.warn(player, "用法: /mplt custom <称号>");
return;
}
if (!MiniPlayerTitle.config.isEnableCustom()) {
Notification.error(player, "自定义称号功能已关闭");
MiniPlayerTitle.notification.error(player, "自定义称号功能已关闭");
return;
}
XPlayer xPlayer = new XPlayer(player);

View File

@ -17,7 +17,7 @@ public class ConfigManager {
_debug = _file.getBoolean("Debug", false);
_db_type = _file.getString("Database.Type", "sqlite");
if (!_db_type.equals("pgsql") && !_db_type.equals("sqlite")) {
XLogger.err("当前数据库只支持 pgsql 或 sqlite已重置为 sqlite");
MiniPlayerTitle.logger.err("当前数据库只支持 pgsql 或 sqlite已重置为 sqlite");
setDbType("sqlite");
}
_db_host = _file.getString("Database.Host", "localhost");

View File

@ -1,158 +0,0 @@
package cn.lunadeer.miniplayertitle.utils;
import cn.lunadeer.miniplayertitle.MiniPlayerTitle;
import java.sql.*;
public class Database {
public static Connection createConnection() {
try {
String connectionUrl;
if (MiniPlayerTitle.config.getDbType().equals("pgsql")) {
XLogger.info("正在连接到 PostgreSQL 数据库");
Class.forName("org.postgresql.Driver");
connectionUrl = "jdbc:postgresql://" + MiniPlayerTitle.config.getDbHost() + ":" + MiniPlayerTitle.config.getDbPort();
connectionUrl += "/" + MiniPlayerTitle.config.getDbName();
return DriverManager.getConnection(connectionUrl, MiniPlayerTitle.config.getDbUser(), MiniPlayerTitle.config.getDbPass());
} else if (MiniPlayerTitle.config.getDbType().equals("sqlite")) {
XLogger.info("正在连接到 SQLite 数据库");
Class.forName("org.sqlite.JDBC");
connectionUrl = "jdbc:sqlite:" + MiniPlayerTitle.instance.getDataFolder() + "/" + MiniPlayerTitle.config.getDbName() + ".db";
return DriverManager.getConnection(connectionUrl);
} else {
XLogger.err("=== 严重错误 ===");
XLogger.err("数据库类型错误,只能为 pgsql 或 sqlite");
XLogger.err("===============");
return null;
}
} catch (ClassNotFoundException | SQLException e) {
XLogger.err("=== 严重错误 ===");
XLogger.err("Database connection failed: " + e.getMessage());
XLogger.err("===============");
return null;
}
}
public static ResultSet query(String sql) {
Connection conn = MiniPlayerTitle.dbConnection;
if (conn == null) {
return null;
}
try {
Statement stmt = conn.createStatement();
if (sql.contains("SERIAL PRIMARY KEY") && MiniPlayerTitle.config.getDbType().equals("sqlite")) {
sql = sql.replace("SERIAL PRIMARY KEY", "INTEGER PRIMARY KEY AUTOINCREMENT");
}
// if query with no result return null
if (stmt.execute(sql)) {
return stmt.getResultSet();
}
} catch (SQLException e) {
handleDatabaseError("Database query failed: ", e, sql);
}
return null;
}
private static void handleDatabaseError(String errorMessage, SQLException e, String sql) {
XLogger.err("=== 严重错误 ===");
XLogger.err(errorMessage + e.getMessage());
XLogger.err("SQL: " + sql);
XLogger.err("===============");
}
private static void addColumnIfNotExists(String tableName, String columnName, String columnDefinition) {
if (MiniPlayerTitle.config.getDbType().equals("pgsql")) {
String sql = "ALTER TABLE " + tableName + " ADD COLUMN IF NOT EXISTS " + columnName + " " + columnDefinition + ";";
query(sql);
} else if (MiniPlayerTitle.config.getDbType().equals("sqlite")) {
try {
ResultSet rs = query("PRAGMA table_info(" + tableName + ");");
boolean columnExists = false;
if (rs != null) {
while (rs.next()) {
if (columnName.equals(rs.getString("name"))) {
columnExists = true;
break;
}
}
}
if (!columnExists) {
query("ALTER TABLE " + tableName + " ADD COLUMN " + columnName + " " + columnDefinition + ";");
}
} catch (SQLException e) {
handleDatabaseError("Database operation failed: ", e, "");
}
}
}
public static void migrate() {
String sql = "";
// title table
sql = "CREATE TABLE IF NOT EXISTS mplt_title (" +
" id SERIAL PRIMARY KEY," +
" title TEXT NOT NULL UNIQUE," +
" description TEXT NOT NULL," +
" enabled BOOLEAN NOT NULL DEFAULT TRUE," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP" +
");";
query(sql);
// title shop table
sql = "CREATE TABLE IF NOT EXISTS mplt_title_shop (" +
" id SERIAL PRIMARY KEY," +
" title_id INTEGER NOT NULL," +
" price INTEGER NOT NULL DEFAULT 0," +
" days INTEGER NOT NULL DEFAULT 0," +
" amount INTEGER NOT NULL DEFAULT -1," +
" sale_end_at BIGINT NOT NULL DEFAULT -1," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" FOREIGN KEY (title_id) REFERENCES mplt_title(id) ON DELETE CASCADE" +
");";
query(sql);
// player title info table
sql = "CREATE TABLE IF NOT EXISTS mplt_player_info (" +
" uuid UUID PRIMARY KEY," +
" coin INTEGER NOT NULL DEFAULT 0," +
" using_title_id INTEGER NOT NULL DEFAULT -1," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" FOREIGN KEY (using_title_id) REFERENCES mplt_title(id) ON DELETE CASCADE" +
");";
query(sql);
// player title table
sql = "CREATE TABLE IF NOT EXISTS mplt_player_title (" +
" id SERIAL PRIMARY KEY," +
" player_uuid UUID NOT NULL," +
" title_id INTEGER NOT NULL," +
" expire_at BIGINT NOT NULL DEFAULT -1," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" FOREIGN KEY (title_id) REFERENCES mplt_title(id) ON DELETE CASCADE," +
" FOREIGN KEY (player_uuid) REFERENCES mplt_player_info(uuid) ON DELETE CASCADE" +
");";
query(sql);
sql = "INSERT INTO mplt_title (" +
"id, " +
"title, " +
"description," +
"enabled, " +
"created_at, " +
"updated_at " +
") VALUES (" +
"-1, " +
"'default', " +
"'default', " +
"TRUE, " +
"CURRENT_TIMESTAMP, " +
"CURRENT_TIMESTAMP " +
") ON CONFLICT (id) DO NOTHING;";
query(sql);
}
}

View File

@ -0,0 +1,76 @@
package cn.lunadeer.miniplayertitle.utils;
import cn.lunadeer.miniplayertitle.MiniPlayerTitle;
public class DatabaseTables {
public static void migrate() {
String sql = "";
// title table
sql = "CREATE TABLE IF NOT EXISTS mplt_title (" +
" id SERIAL PRIMARY KEY," +
" title TEXT NOT NULL UNIQUE," +
" description TEXT NOT NULL," +
" enabled BOOLEAN NOT NULL DEFAULT TRUE," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP" +
");";
MiniPlayerTitle.database.query(sql);
// title shop table
sql = "CREATE TABLE IF NOT EXISTS mplt_title_shop (" +
" id SERIAL PRIMARY KEY," +
" title_id INTEGER NOT NULL," +
" price INTEGER NOT NULL DEFAULT 0," +
" days INTEGER NOT NULL DEFAULT 0," +
" amount INTEGER NOT NULL DEFAULT -1," +
" sale_end_at BIGINT NOT NULL DEFAULT -1," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" FOREIGN KEY (title_id) REFERENCES mplt_title(id) ON DELETE CASCADE" +
");";
MiniPlayerTitle.database.query(sql);
// player title info table
sql = "CREATE TABLE IF NOT EXISTS mplt_player_info (" +
" uuid UUID PRIMARY KEY," +
" coin INTEGER NOT NULL DEFAULT 0," +
" using_title_id INTEGER NOT NULL DEFAULT -1," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" FOREIGN KEY (using_title_id) REFERENCES mplt_title(id) ON DELETE CASCADE" +
");";
MiniPlayerTitle.database.query(sql);
// player title table
sql = "CREATE TABLE IF NOT EXISTS mplt_player_title (" +
" id SERIAL PRIMARY KEY," +
" player_uuid UUID NOT NULL," +
" title_id INTEGER NOT NULL," +
" expire_at BIGINT NOT NULL DEFAULT -1," +
" created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
" FOREIGN KEY (title_id) REFERENCES mplt_title(id) ON DELETE CASCADE," +
" FOREIGN KEY (player_uuid) REFERENCES mplt_player_info(uuid) ON DELETE CASCADE" +
");";
MiniPlayerTitle.database.query(sql);
sql = "INSERT INTO mplt_title (" +
"id, " +
"title, " +
"description," +
"enabled, " +
"created_at, " +
"updated_at " +
") VALUES (" +
"-1, " +
"'default', " +
"'default', " +
"TRUE, " +
"CURRENT_TIMESTAMP, " +
"CURRENT_TIMESTAMP " +
") ON CONFLICT (id) DO NOTHING;";
MiniPlayerTitle.database.query(sql);
}
}

View File

@ -1,199 +0,0 @@
package cn.lunadeer.miniplayertitle.utils;
import org.bukkit.plugin.java.JavaPlugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;
import java.util.concurrent.TimeUnit;
public class GiteaReleaseCheck {
private static class GiteaRelease {
public String tag_name;
public String message;
public String html_url;
public String download_url;
}
public GiteaReleaseCheck(JavaPlugin plugin, String giteaServer, String owner, String repo) {
this.gitea_server = giteaServer;
this.owner = owner;
this.repo = repo;
this.plugin = plugin;
this.current_version = plugin.getPluginMeta().getVersion();
// 异步每12小时检查一次更新
plugin.getServer().getAsyncScheduler().runAtFixedRate(plugin, (instance) -> {
getLatestRelease();
if (auto_update) {
downloadUpdate();
}
}, 10, 60 * 60 * 12, TimeUnit.SECONDS);
}
public void enableAutoUpdate() {
auto_update = true;
}
private String repoReleases() {
return gitea_server + "/api/v1/repos/" + owner + "/" + repo + "/releases";
}
private String tag(String tagName) {
return gitea_server + "/api/v1/repos/" + owner + "/" + repo + "/tags/" + tagName;
}
private void getLatestRelease() {
XLogger.info("================================");
XLogger.info("正在检查更新...");
// send get request to repoReleases()
try {
// 发送 GET 请求
HttpsURLConnection connection = (HttpsURLConnection) new URL(repoReleases()).openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// 获取响应
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
JSONArray releaseList = (JSONArray) new JSONParser().parse(builder.toString());
JSONObject latestRelease = (JSONObject) releaseList.get(0);
GiteaRelease release = new GiteaRelease();
release.tag_name = (String) latestRelease.get("tag_name");
release.message = (String) latestRelease.get("body");
release.html_url = (String) latestRelease.get("html_url");
JSONArray assets = (JSONArray) latestRelease.get("assets");
if (assets.size() > 0) {
JSONObject asset = (JSONObject) assets.get(0);
release.download_url = (String) asset.get("browser_download_url");
}
latest_release = release;
XLogger.debug("Latest release: " + latest_release.tag_name);
XLogger.debug("Message: " + latest_release.message);
XLogger.debug("Download URL: " + latest_release.download_url);
XLogger.debug("HTML URL: " + latest_release.html_url);
if (isNewVersion(current_version, latest_release.tag_name)) {
XLogger.info("发现新版本:" + latest_release.tag_name);
XLogger.info("版本信息:");
String[] message = latest_release.message.split("\n");
for (String line : message) {
XLogger.info("\t" + line);
}
XLogger.info("下载页面:" + latest_release.html_url);
} else {
XLogger.info("当前已是最新版本:" + current_version);
}
XLogger.info("================================");
} catch (Exception e) {
XLogger.err("Failed to get latest release: " + e.getMessage());
}
}
private String getTagMessage(String tagName) {
try {
// 发送 GET 请求
HttpsURLConnection connection = (HttpsURLConnection) new URL(tag(tagName)).openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// 获取响应
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
JSONObject tag = (JSONObject) new JSONParser().parse(builder.toString());
return (String) tag.get("message");
} catch (Exception e) {
XLogger.debug("Failed to get tag message: " + e.getMessage());
return "null";
}
}
private void downloadUpdate() {
if (latest_release == null) {
getLatestRelease();
if (latest_release == null)
return;
}
if (!isNewVersion(current_version, latest_release.tag_name)) {
XLogger.info("当前已是最新版本");
return;
}
if (latest_release.download_url == null) {
XLogger.err("下载地址不可用");
return;
}
try {
XLogger.info("================================");
XLogger.info("正在下载更新...");
File pluginsFolder = plugin.getDataFolder().getParentFile();
File newJarFile = new File(pluginsFolder, latest_release.download_url.substring(latest_release.download_url.lastIndexOf("/") + 1));
// send get request to download_url
HttpsURLConnection connection = (HttpsURLConnection) new URL(latest_release.download_url).openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// 获取响应写入文件到 newJarFile
try (DataOutputStream outputStream = new DataOutputStream(Files.newOutputStream(newJarFile.toPath()))) {
byte[] buffer = new byte[1024];
int length;
while ((length = connection.getInputStream().read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
XLogger.info("更新下载完成");
XLogger.info("新版本:" + latest_release.tag_name);
XLogger.info("请删除旧版本插件,然后重启服务器。");
XLogger.info("================================");
} catch (Exception e) {
XLogger.err("Failed to auto update: " + e.getMessage());
}
}
private String gitea_server;
private String owner;
private String repo;
private JavaPlugin plugin;
private String current_version;
private GiteaRelease latest_release = null;
private boolean auto_update = false;
private boolean isNewVersion(String current, String in_coming) {
// 只保留数字和点号
current = current.replaceAll("[^0-9.]", "");
in_coming = in_coming.replaceAll("[^0-9.]", "");
XLogger.debug("Current version: " + current);
XLogger.debug("In-coming version: " + in_coming);
String[] current_version = current.split("\\.");
String[] in_coming_version = in_coming.split("\\.");
for (int i = 0; i < Math.min(current_version.length, in_coming_version.length); i++) {
int current_v = Integer.parseInt(current_version[i]);
int in_coming_v = Integer.parseInt(in_coming_version[i]);
if (current_v < in_coming_v) {
return true;
} else if (current_v > in_coming_v) {
return false;
}
}
return current_version.length < in_coming_version.length;
}
}

View File

@ -1,63 +0,0 @@
package cn.lunadeer.miniplayertitle.utils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Notification {
private static final Style i_style = Style.style(TextColor.color(139, 255, 123));
private static final Style w_style = Style.style(TextColor.color(255, 185, 69));
private static final Style e_style = Style.style(TextColor.color(255, 96, 72));
private static final String prefix = "[MiniPlayerTitle] ";
public static void info(Player player, String msg) {
player.sendMessage(Component.text(prefix + msg, i_style));
}
public static void warn(Player player, String msg) {
player.sendMessage(Component.text(prefix + msg, w_style));
}
public static void error(Player player, String msg) {
player.sendMessage(Component.text(prefix + msg, e_style));
}
public static void info(CommandSender sender, String msg) {
sender.sendMessage(Component.text(prefix + msg, i_style));
}
public static void warn(CommandSender sender, String msg) {
sender.sendMessage(Component.text(prefix + msg, w_style));
}
public static void error(CommandSender sender, String msg) {
sender.sendMessage(Component.text(prefix + msg, e_style));
}
public static void info(Player player, Component msg) {
player.sendMessage(Component.text(prefix, i_style).append(msg));
}
public static void warn(Player player, Component msg) {
player.sendMessage(Component.text(prefix, w_style).append(msg));
}
public static void error(Player player, Component msg) {
player.sendMessage(Component.text(prefix, e_style).append(msg));
}
public static void info(CommandSender player, Component msg) {
player.sendMessage(Component.text(prefix, i_style).append(msg));
}
public static void warn(CommandSender player, Component msg) {
player.sendMessage(Component.text(prefix, w_style).append(msg));
}
public static void error(CommandSender player, Component msg) {
player.sendMessage(Component.text(prefix, e_style).append(msg));
}
}

View File

@ -1,12 +0,0 @@
package cn.lunadeer.miniplayertitle.utils.STUI;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
public class Button {
public static TextComponent create(String text, String command) {
return Component.text("[" + text + "]", ViewStyles.action_color)
.clickEvent(net.kyori.adventure.text.event.ClickEvent.clickEvent(net.kyori.adventure.text.event.ClickEvent.Action.RUN_COMMAND, command));
}
}

View File

@ -1,48 +0,0 @@
package cn.lunadeer.miniplayertitle.utils.STUI;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.ArrayList;
import java.util.List;
public class Line {
private final List<Component> elements = new ArrayList<>();
private final TextComponent divider = Component.text(" - ", ViewStyles.sub_color);
public Line() {
}
public TextComponent build() {
TextComponent.Builder builder = Component.text();
for (int i = 0; i < elements.size(); i++) {
builder.append(elements.get(i));
if (i != elements.size() - 1) {
builder.append(divider);
}
}
return builder.build();
}
public static Line create() {
return new Line();
}
public Line append(TextComponent component) {
elements.add(component);
return this;
}
public Line append(Component component) {
elements.add(component);
return this;
}
public Line append(String component) {
elements.add(Component.text(component));
return this;
}
}

View File

@ -1,71 +0,0 @@
package cn.lunadeer.miniplayertitle.utils.STUI;
import cn.lunadeer.miniplayertitle.utils.Notification;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class ListView {
private final Integer page_size;
private final List<Line> lines = new ArrayList<>();
private String command = "";
private final View view = View.create();
public ListView(int page_size, String command) {
super();
this.page_size = page_size;
this.command = command;
}
public static ListView create(int page_size, String command) {
return new ListView(page_size, command);
}
public ListView title(String title) {
view.title(title);
return this;
}
public ListView title(String title, String subtitle) {
view.title(title);
view.subtitle(subtitle);
return this;
}
public ListView subtitle(String subtitle) {
view.subtitle(subtitle);
return this;
}
public ListView add(Line line) {
lines.add(line);
return this;
}
public ListView addLines(List<Line> lines) {
this.lines.addAll(lines);
return this;
}
public void showOn(Player player, Integer page) {
int offset = (page - 1) * page_size;
if (lines.isEmpty()) {
Notification.warn(player, "没有数据");
return;
}
if (offset >= lines.size() || offset < 0) {
Notification.error(player, "页数超出范围");
return;
}
for (int i = offset; i < offset + page_size; i++) {
if (i >= lines.size()) {
break;
}
view.addLine(lines.get(i));
}
view.actionBar(Pagination.create(page, lines.size(), this.command));
view.showOn(player);
}
}

View File

@ -1,38 +0,0 @@
package cn.lunadeer.miniplayertitle.utils.STUI;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.ArrayList;
import java.util.List;
import static cn.lunadeer.miniplayertitle.utils.STUI.ViewStyles.main_color;
import static cn.lunadeer.miniplayertitle.utils.STUI.ViewStyles.sub_color;
public class Pagination {
public static TextComponent create(int page, int item_size, String command) {
// x/y [上一页] [下一页]
int page_size = 4;
int page_count = (int) Math.ceil((double) item_size / page_size);
if (page_count == 0) {
page_count = 1;
}
List<Component> componentList = new ArrayList<>();
componentList.add(Component.text("", main_color));
componentList.add(Component.text(page, sub_color));
componentList.add(Component.text("/", main_color));
componentList.add(Component.text(page_count, sub_color));
componentList.add(Component.text("", main_color));
if (page > 1) {
componentList.add(Button.create("上一页", command + " " + (page - 1)));
}
if (page < page_count) {
componentList.add(Button.create("下一页", command + " " + (page + 1)));
}
TextComponent.Builder builder = Component.text();
for (Component component : componentList) {
builder.append(component);
}
return builder.build();
}
}

View File

@ -1,106 +0,0 @@
package cn.lunadeer.miniplayertitle.utils.STUI;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import static cn.lunadeer.miniplayertitle.utils.STUI.ViewStyles.main_color;
public class View {
protected TextComponent title_decorate = Component.text("", main_color);
protected TextComponent space = Component.text(" ");
protected TextComponent sub_title_decorate = Component.text("- ", main_color);
protected TextComponent line_decorate = Component.text("", main_color);
protected TextComponent action_decorate = Component.text("", main_color);
protected TextComponent title = Component.text(" ");
protected TextComponent subtitle = Component.text("");
protected List<TextComponent> content_lines = new ArrayList<>();
protected TextComponent actionbar = Component.text(" ");
protected TextComponent edge = Component.text("━━━━━━━━━━━━━━━━━━━━━━━━━━━━", main_color);
protected TextComponent divide_line = Component.text("━━━━━━━━━━━━━━━━━━━━━━━━━━━━", main_color);
public void showOn(Player player) {
player.sendMessage(edge);
TextComponent.Builder builder = Component.text();
int title_length = title.content().length();
int title_width = title_length * 2 + 2;
int decorate_count = divide_line.content().length() - title_width;
for (int i = 0; i < decorate_count / 2; i++) {
builder.append(title_decorate);
}
builder.append(space).append(title).append(space);
for (int i = 0; i < decorate_count / 2; i++) {
builder.append(title_decorate);
}
player.sendMessage(builder.build());
if (subtitle.content().length() > 0) {
player.sendMessage(divide_line);
player.sendMessage(Component.text().append(sub_title_decorate).append(subtitle).build());
}
player.sendMessage(divide_line);
for (TextComponent content_line : content_lines) {
player.sendMessage(Component.text().append(line_decorate).append(content_line).build());
}
player.sendMessage(divide_line);
player.sendMessage(Component.text().append(action_decorate).append(actionbar).build());
player.sendMessage(edge);
player.sendMessage(Component.text(" "));
}
public static View create() {
return new View();
}
public View title(String title) {
this.title = Component.text(title);
return this;
}
public View title(TextComponent title) {
this.title = title;
return this;
}
public View subtitle(String subtitle) {
this.subtitle = Component.text(subtitle);
return this;
}
public View subtitle(TextComponent subtitle) {
this.subtitle = subtitle;
return this;
}
public View actionBar(TextComponent actionbar) {
this.actionbar = actionbar;
return this;
}
public View actionBar(String actionbar) {
this.actionbar = Component.text(actionbar);
return this;
}
public View actionBar(Line actionbar) {
this.actionbar = actionbar.build();
return this;
}
public View addLine(TextComponent component) {
this.content_lines.add(component);
return this;
}
public View addLine(String component) {
this.content_lines.add(Component.text(component));
return this;
}
public View addLine(Line component) {
this.content_lines.add(component.build());
return this;
}
}

View File

@ -1,11 +0,0 @@
package cn.lunadeer.miniplayertitle.utils.STUI;
import net.kyori.adventure.text.format.TextColor;
public class ViewStyles {
public static TextColor main_color = TextColor.color(0, 148, 213);
public static TextColor sub_color = TextColor.color(122, 122, 122);
public static TextColor action_color = TextColor.color(251, 255, 139);
public static TextColor error_color = TextColor.color(255, 96, 72);
public static TextColor success_color = TextColor.color(139, 255, 123);
}

View File

@ -1,56 +0,0 @@
package cn.lunadeer.miniplayertitle.utils;
import cn.lunadeer.miniplayertitle.MiniPlayerTitle;
import org.bukkit.entity.Player;
import java.util.logging.Logger;
public class XLogger {
private static final MiniPlayerTitle _plugin = MiniPlayerTitle.instance;
private static final Logger _logger = _plugin.getLogger();
private static final String prefix = "[MiniPlayerTitle] ";
public static void info(Player player, String message) {
Notification.info(player, prefix + "I | " + message);
if (MiniPlayerTitle.config.isDebug())
debug("来自玩家[ " + player.getName() + " ] 的信息 | " + message);
}
public static void info(String message) {
_logger.info(" I | " + message);
}
public static void warn(Player player, String message) {
Notification.warn(player, prefix + "W | " + message);
if (MiniPlayerTitle.config.isDebug())
debug("来自玩家[ " + player.getName() + " ] 的警告 | " + message);
}
public static void warn(String message) {
_logger.warning(" W | " + message);
}
public static void err(Player player, String message) {
Notification.error(player, prefix + "E | " + message);
if (MiniPlayerTitle.config.isDebug())
debug("来自玩家[ " + player.getName() + " ] 的报错 | " + message);
}
public static void err(String message) {
_logger.severe(" E | " + message);
}
public static void debug(Player player, String message) {
if (!MiniPlayerTitle.config.isDebug()) return;
if (player.isOp())
Notification.info(player, prefix + "D | " + message);
else
debug("来自玩家[ " + player.getName() + " ] 的调试 | " + message);
}
public static void debug(String message) {
if (!MiniPlayerTitle.config.isDebug()) return;
_logger.info(" D | " + message);
}
}