This commit is contained in:
JaTiTV 2022-11-15 23:44:45 +01:00
parent 3051d68de4
commit 60edfc7dc1
20 changed files with 130 additions and 1076 deletions

View File

@ -6,7 +6,7 @@
<groupId>net.t2code</groupId> <groupId>net.t2code</groupId>
<artifactId>AutoResponse</artifactId> <artifactId>AutoResponse</artifactId>
<version>0.2.0</version> <version>0.2.2</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>T2C-AutoResponse</name> <name>T2C-AutoResponse</name>
@ -65,6 +65,7 @@
</repositories> </repositories>
<dependencies> <dependencies>
<!-- repo.t2code / T2Code -->
<dependency> <dependency>
<groupId>net.t2code.minecraft.1_8.r1</groupId> <groupId>net.t2code.minecraft.1_8.r1</groupId>
<artifactId>spigot</artifactId> <artifactId>spigot</artifactId>
@ -73,7 +74,7 @@
<dependency> <dependency>
<groupId>net.t2code</groupId> <groupId>net.t2code</groupId>
<artifactId>T2CodeLib</artifactId> <artifactId>T2CodeLib</artifactId>
<version>12.5</version> <version>13.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.t2code</groupId> <groupId>net.t2code</groupId>

View File

@ -1,40 +0,0 @@
package net.t2code.autoresponse.Bungee;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import net.t2code.autoresponse.Bungee.system.BLoad;
import net.t2code.autoresponse.Util;
import net.t2code.lib.Bungee.Lib.messages.BT2CodeTemplate;
import java.util.logging.Level;
public final class BMain extends Plugin {
private static Plugin plugin;
private static String version;
private static String autor;
@Override
public void onEnable() {
// Plugin startup logic
plugin = this;
version = plugin.getDescription().getVersion();
autor = plugin.getDescription().getAuthor();
if (ProxyServer.getInstance().getPluginManager().getPlugin("T2CodeLib") == null) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
ProxyServer.getInstance().getConsole().sendMessage(Util.getPrefix() + " §eT2CodeLib §4could not be found. Please download it here: " +
"§6https://www.spigotmc.org/resources/t2codelib.96388/ §4to be able to use this plugin.");
getProxy().getPluginManager().getPlugin(plugin.getDescription().getName()).onDisable();
return;
}
BLoad.onLoad(plugin, Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord(), Util.getSpigotID(), Util.getBstatsID());
}
@Override
public void onDisable() {
// Plugin shutdown logic
if (ProxyServer.getInstance().getPluginManager().getPlugin("T2CodeLib") == null) return;
BT2CodeTemplate.onDisable(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord());
}
}

View File

@ -1,48 +0,0 @@
package net.t2code.autoresponse.Bungee.system;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.t2code.lib.Bungee.Lib.messages.Bsend;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class BListener implements Listener {
@EventHandler
public void onPluginmessage(PluginMessageEvent event) {
if (event.getTag().equalsIgnoreCase("t2car:bungee")) {
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(event.getData()));
event.setCancelled(true);
try {
String channel = stream.readUTF();
String input = stream.readUTF();
switch (channel) {
case "ConC":
ProxyServer.getInstance().getConsole().sendMessage("Command Console: " + input);
ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), input);
break;
case "ALLPMSG":
for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) {
Bsend.player(player, input);
}
break;
default:
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(channel);
if (player != null) {
ProxyServer.getInstance().getConsole().sendMessage("Command " + player + ": " + input);
ProxyServer.getInstance().getPluginManager().dispatchCommand(player, input);
}
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -1,24 +0,0 @@
package net.t2code.autoresponse.Bungee.system;
import net.md_5.bungee.api.plugin.Plugin;
import net.t2code.lib.Bungee.Lib.messages.BT2CodeTemplate;
import net.t2code.lib.Bungee.Lib.messages.Bsend;
import net.t2code.lib.Bungee.Lib.update.BUpdateAPI;
public class BLoad {
public static void onLoad(Plugin plugin, String prefix, String autor, String version, String spigot, String discord, Integer spigotID, Integer bstatsID) {
Long long_ = BT2CodeTemplate.onLoadHeader(prefix,autor,version,spigot,discord);
plugin.getProxy().registerChannel("t2car:bungee");
Bsend.console(prefix + " registerChannel(t2car:bungee)");
plugin.getProxy().getPluginManager().registerListener(plugin, new BListener());
BMetrics metrics = new BMetrics(plugin, bstatsID);
BUpdateAPI.onUpdateCheckTimer(plugin, prefix, spigot, discord, spigotID);
BT2CodeTemplate.onLoadFooter(prefix, long_);
}
}

View File

@ -1,846 +0,0 @@
package net.t2code.autoresponse.Bungee.system;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
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 BMetrics {
private final Plugin plugin;
private final MetricsBase metricsBase;
private boolean enabled;
private String serverUUID;
private boolean logErrors = false;
private boolean logSentData;
private boolean logResponseStatusText;
/**
* 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 BMetrics(Plugin plugin, int serviceId) {
this.plugin = plugin;
try {
loadConfig();
} catch (IOException e) {
// Failed to load configuration
plugin.getLogger().log(Level.WARNING, "Failed to load bStats config!", e);
metricsBase = null;
return;
}
metricsBase =
new MetricsBase(
"bungeecord",
serverUUID,
serviceId,
enabled,
this::appendPlatformData,
this::appendServiceData,
null,
() -> true,
(message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),
(message) -> this.plugin.getLogger().log(Level.INFO, message),
logErrors,
logSentData,
logResponseStatusText);
}
/** Loads the bStats configuration. */
private void loadConfig() throws IOException {
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
bStatsFolder.mkdirs();
File configFile = new File(bStatsFolder, "config.yml");
if (!configFile.exists()) {
writeFile(
configFile,
"# bStats (https://bStats.org) collects some basic information for plugin authors, like how",
"# many people use their plugin and their total player count. It's recommended to keep bStats",
"# enabled, but if you're not comfortable with this, you can turn this setting off. There is no",
"# performance penalty associated with having metrics enabled, and data sent to bStats is fully",
"# anonymous.",
"enabled: true",
"serverUuid: \"" + UUID.randomUUID() + "\"",
"logFailedRequests: false",
"logSentData: false",
"logResponseStatusText: false");
}
Configuration configuration =
ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
// Load configuration
enabled = configuration.getBoolean("enabled", true);
serverUUID = configuration.getString("serverUuid");
logErrors = configuration.getBoolean("logFailedRequests", false);
logSentData = configuration.getBoolean("logSentData", false);
logResponseStatusText = configuration.getBoolean("logResponseStatusText", false);
}
private void writeFile(File file, String... lines) throws IOException {
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {
for (String line : lines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
}
}
/**
* 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", plugin.getProxy().getOnlineCount());
builder.appendField("managedServers", plugin.getProxy().getServers().size());
builder.appendField("onlineMode", plugin.getProxy().getConfig().isOnlineMode() ? 1 : 0);
builder.appendField("bungeecordVersion", plugin.getProxy().getVersion());
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());
}
public static class MetricsBase {
/** The version of the Metrics class. */
public static final String METRICS_VERSION = "2.2.1";
private static final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics"));
private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
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) {
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) {
startSubmitting();
}
}
public void addCustomChart(CustomChart chart) {
this.customCharts.add(chart);
}
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 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 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 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 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();
}
}
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 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();
}
}
/**
* 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

@ -3,7 +3,7 @@ package net.t2code.autoresponse.Spigot;
import net.t2code.autoresponse.Spigot.objects.ResponsesObject; import net.t2code.autoresponse.Spigot.objects.ResponsesObject;
import net.t2code.autoresponse.Spigot.system.Load; import net.t2code.autoresponse.Spigot.system.Load;
import net.t2code.autoresponse.Util; import net.t2code.autoresponse.Util;
import net.t2code.lib.Spigot.Lib.messages.T2CodeTemplate; import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -42,7 +42,7 @@ public final class Main extends JavaPlugin {
// Plugin shutdown logic // Plugin shutdown logic
allResponses.clear(); allResponses.clear();
if (Bukkit.getPluginManager().getPlugin("T2CodeLib") == null) return; if (Bukkit.getPluginManager().getPlugin("T2CodeLib") == null) return;
T2CodeTemplate.onDisable(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord()); T2Ctemplate.onDisable(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord());
} }
public static Boolean pluginNotFound(String pl, Integer spigotID, String ver) { public static Boolean pluginNotFound(String pl, Integer spigotID, String ver) {

View File

@ -2,7 +2,7 @@ package net.t2code.autoresponse.Spigot.cmdManagement;
import net.t2code.autoresponse.Spigot.config.languages.SelectMessages; import net.t2code.autoresponse.Spigot.config.languages.SelectMessages;
import net.t2code.autoresponse.Spigot.system.Permissions; import net.t2code.autoresponse.Spigot.system.Permissions;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -26,7 +26,7 @@ public class CmdExecuter implements CommandExecutor, TabCompleter {
case "rl": case "rl":
if (sender.hasPermission(Permissions.admin) || sender.isOp()) { if (sender.hasPermission(Permissions.admin) || sender.isOp()) {
Commands.reload(sender); Commands.reload(sender);
} else send.sender(sender, SelectMessages.NoPermissionForCommand.replace("[cmd]", "/t2code-autoresponse reload") } else T2Csend.sender(sender, SelectMessages.NoPermissionForCommand.replace("[cmd]", "/t2code-autoresponse reload")
.replace("[perm]", Permissions.admin)); .replace("[perm]", Permissions.admin));
break; break;
case "info": case "info":
@ -34,7 +34,7 @@ public class CmdExecuter implements CommandExecutor, TabCompleter {
case "version": case "version":
if (sender.hasPermission(Permissions.info)) { if (sender.hasPermission(Permissions.info)) {
Commands.info(sender); Commands.info(sender);
} else send.sender(sender, SelectMessages.NoPermissionForCommand.replace("[cmd]", "/t2code-autoresponse info") } else T2Csend.sender(sender, SelectMessages.NoPermissionForCommand.replace("[cmd]", "/t2code-autoresponse info")
.replace("[perm]", Permissions.info)); .replace("[perm]", Permissions.info));
break; break;

View File

@ -4,26 +4,25 @@ import net.t2code.autoresponse.Util;
import net.t2code.autoresponse.Spigot.config.languages.SelectMessages; import net.t2code.autoresponse.Spigot.config.languages.SelectMessages;
import net.t2code.autoresponse.Spigot.system.Load; import net.t2code.autoresponse.Spigot.system.Load;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.lib.Spigot.Lib.messages.T2CodeTemplate; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import net.t2code.lib.Spigot.Lib.update.UpdateAPI;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class Commands { public class Commands {
public static void info(CommandSender sender) { public static void info(CommandSender sender) {
T2CodeTemplate.sendInfo(sender, Util.getPrefix(),Util.getSpigot(),Util.getDiscord(), Main.getAutor(),Main.getVersion(), UpdateAPI.PluginVersionen.get(Main.getPlugin().getName()).publicVersion); T2Ctemplate.sendInfo(sender,Main.getPlugin(),Util.getSpigotID(),Util.getDiscord(),Util.getInfoText());
} }
public static void reload(CommandSender sender) { public static void reload(CommandSender sender) {
if (sender instanceof Player) sender.sendMessage(SelectMessages.ReloadStart); if (sender instanceof Player) sender.sendMessage(SelectMessages.ReloadStart);
send.console(Util.getPrefix() + "§8-------------------------------"); T2Csend.console(Util.getPrefix() + "§8-------------------------------");
send.console(Util.getPrefix() + " §6Plugin reload..."); T2Csend.console(Util.getPrefix() + " §6Plugin reload...");
send.console(Util.getPrefix() + "§8-------------------------------"); T2Csend.console(Util.getPrefix() + "§8-------------------------------");
Load.loadReload(); Load.loadReload();
if (sender instanceof Player) sender.sendMessage(SelectMessages.ReloadEnd); if (sender instanceof Player) sender.sendMessage(SelectMessages.ReloadEnd);
send.console(Util.getPrefix() + "§8-------------------------------"); T2Csend.console(Util.getPrefix() + "§8-------------------------------");
send.console(Util.getPrefix() + " §2Plugin successfully reloaded."); T2Csend.console(Util.getPrefix() + " §2Plugin successfully reloaded.");
send.console(Util.getPrefix() + "§8-------------------------------"); T2Csend.console(Util.getPrefix() + "§8-------------------------------");
} }
} }

View File

@ -2,8 +2,8 @@ package net.t2code.autoresponse.Spigot.config.config;
import net.t2code.autoresponse.Util; import net.t2code.autoresponse.Util;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.yamlConfiguration.Config; import net.t2code.t2codelib.SPIGOT.api.yaml.T2Cconfig;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
@ -15,16 +15,20 @@ public class CreateConfig {
File config = new File(Main.getPath(), "config.yml"); File config = new File(Main.getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config); YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
Config.set("Plugin.language", "english", yamlConfiguration); T2Cconfig.set("Plugin.language", "english", yamlConfiguration);
Config.set("BungeeCord.Enable", false, yamlConfiguration); T2Cconfig.set("Plugin.updateCheck.onJoin", true, yamlConfiguration);
T2Cconfig.set("Plugin.updateCheck.seePreReleaseUpdates", true, yamlConfiguration);
T2Cconfig.set("Plugin.updateCheck.timeInterval", 60, yamlConfiguration);
Config.set("Log.Console.Enable", true, yamlConfiguration); T2Cconfig.set("BungeeCord.Enable", false, yamlConfiguration);
T2Cconfig.set("Log.Console.Enable", true, yamlConfiguration);
try { try {
yamlConfiguration.save(config); yamlConfiguration.save(config);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
send.console(Util.getPrefix() + " §2config.yml were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_) + "ms"); T2Csend.console(Util.getPrefix() + " §2config.yml were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_) + "ms");
} }
} }

View File

@ -7,6 +7,9 @@ import java.io.File;
public class SelectConfig { public class SelectConfig {
public static String language; public static String language;
public static Boolean updateCheckOnJoin;
public static Boolean updateCheckSeePreReleaseUpdates;
public static Integer updateCheckTimeInterval;
public static Boolean bungee; public static Boolean bungee;
public static Boolean logConsole; public static Boolean logConsole;
@ -15,6 +18,13 @@ public class SelectConfig {
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config); YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
language = yamlConfiguration.getString("Plugin.language"); language = yamlConfiguration.getString("Plugin.language");
updateCheckOnJoin = yamlConfiguration.getBoolean("Plugin.updateCheck.onJoin");
updateCheckSeePreReleaseUpdates = yamlConfiguration.getBoolean("Plugin.updateCheck.seePreReleaseUpdates");
updateCheckTimeInterval = yamlConfiguration.getInt("Plugin.updateCheck.timeInterval");
bungee = yamlConfiguration.getBoolean("BungeeCord.Enable"); bungee = yamlConfiguration.getBoolean("BungeeCord.Enable");
logConsole = yamlConfiguration.getBoolean("Log.Console.Enable"); logConsole = yamlConfiguration.getBoolean("Log.Console.Enable");
} }

View File

@ -2,8 +2,8 @@ package net.t2code.autoresponse.Spigot.config.languages;
import net.t2code.autoresponse.Util; import net.t2code.autoresponse.Util;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.yamlConfiguration.Config; import net.t2code.t2codelib.SPIGOT.api.yaml.T2Cconfig;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
@ -14,7 +14,7 @@ public class CreateMessages {
private static Plugin plugin = Main.getPlugin(); private static Plugin plugin = Main.getPlugin();
public static void langCreate() { public static void langCreate() {
send.debug(plugin,"§4Language files are created / updated..."); T2Csend.debug(plugin,"§4Language files are created / updated...");
Long long_ = Long.valueOf(System.currentTimeMillis()); Long long_ = Long.valueOf(System.currentTimeMillis());
/** /**
@ -26,14 +26,14 @@ public class CreateMessages {
File messagesEN = new File(Main.getPath(), "languages/english_messages.yml"); File messagesEN = new File(Main.getPath(), "languages/english_messages.yml");
YamlConfiguration yamlConfigurationEN = YamlConfiguration.loadConfiguration(messagesEN); YamlConfiguration yamlConfigurationEN = YamlConfiguration.loadConfiguration(messagesEN);
Config.set("Plugin.Reload.Start", MSG.EN_ReloadStart, yamlConfigurationEN); T2Cconfig.set("Plugin.Reload.Start", MSG.EN_ReloadStart, yamlConfigurationEN);
Config.set("Plugin.Reload.End", MSG.EN_ReloadEnd, yamlConfigurationEN); T2Cconfig.set("Plugin.Reload.End", MSG.EN_ReloadEnd, yamlConfigurationEN);
Config.set("Plugin.ForCommand", MSG.EN_NoPermissionForCommand, yamlConfigurationEN); T2Cconfig.set("Plugin.ForCommand", MSG.EN_NoPermissionForCommand, yamlConfigurationEN);
try { try {
yamlConfigurationEN.save(messagesEN); yamlConfigurationEN.save(messagesEN);
} catch (IOException e) { } catch (IOException e) {
send.warning(plugin,e.getMessage()); T2Csend.warning(plugin,e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
@ -47,17 +47,17 @@ public class CreateMessages {
File messagesDE = new File(Main.getPath(), "languages/german_messages.yml"); File messagesDE = new File(Main.getPath(), "languages/german_messages.yml");
YamlConfiguration yamlConfigurationDE = YamlConfiguration.loadConfiguration(messagesDE); YamlConfiguration yamlConfigurationDE = YamlConfiguration.loadConfiguration(messagesDE);
Config.set("Plugin.Reload.Start", MSG.DE_ReloadStart, yamlConfigurationDE); T2Cconfig.set("Plugin.Reload.Start", MSG.DE_ReloadStart, yamlConfigurationDE);
Config.set("Plugin.Reload.End", MSG.DE_ReloadEnd, yamlConfigurationDE); T2Cconfig.set("Plugin.Reload.End", MSG.DE_ReloadEnd, yamlConfigurationDE);
Config.set("Plugin.ForCommand", MSG.DE_NoPermissionForCommand, yamlConfigurationDE); T2Cconfig.set("Plugin.ForCommand", MSG.DE_NoPermissionForCommand, yamlConfigurationDE);
try { try {
yamlConfigurationDE.save(messagesDE); yamlConfigurationDE.save(messagesDE);
} catch (IOException e) { } catch (IOException e) {
send.warning(plugin,e.getMessage()); T2Csend.warning(plugin,e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
send.console(Util.getPrefix() + " §2Language files were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_.longValue()) + "ms"); T2Csend.console(Util.getPrefix() + " §2Language files were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_.longValue()) + "ms");
} }
} }

View File

@ -3,8 +3,8 @@ package net.t2code.autoresponse.Spigot.config.languages;
import net.t2code.autoresponse.Util; import net.t2code.autoresponse.Util;
import net.t2code.autoresponse.Spigot.config.config.SelectConfig; import net.t2code.autoresponse.Spigot.config.config.SelectConfig;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.yamlConfiguration.Config; import net.t2code.t2codelib.SPIGOT.api.yaml.T2Cconfig;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
@ -24,28 +24,28 @@ public class SelectMessages {
public static void onSelect(String Prefix) { public static void onSelect(String Prefix) {
send.debug(Main.getPlugin(), "§4Select language..."); T2Csend.debug(Main.getPlugin(), "§4Select language...");
long long_ = System.currentTimeMillis(); long long_ = System.currentTimeMillis();
File msg; File msg;
msg = new File(Main.getPath(), "languages/" + SelectConfig.language + "_messages.yml"); msg = new File(Main.getPath(), "languages/" + SelectConfig.language + "_messages.yml");
if (!msg.isFile()) { if (!msg.isFile()) {
send.console(Prefix); T2Csend.console(Prefix);
send.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); T2Csend.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
send.console(Prefix + " §4The selected §c" + SelectConfig.language + " §4language file was not found."); T2Csend.console(Prefix + " §4The selected §c" + SelectConfig.language + " §4language file was not found.");
send.console(Prefix + " §6The default language §eEnglish §6is used!"); T2Csend.console(Prefix + " §6The default language §eEnglish §6is used!");
send.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); T2Csend.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
send.console(Prefix); T2Csend.console(Prefix);
msg = new File(Main.getPath(), "languages/" + "english_messages.yml"); msg = new File(Main.getPath(), "languages/" + "english_messages.yml");
selectMSG = "english"; selectMSG = "english";
} else selectMSG = SelectConfig.language; } else selectMSG = SelectConfig.language;
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(msg); YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(msg);
ReloadStart = Config.select(prefix, "Plugin.Reload.Start", yamlConfiguration); ReloadStart = T2Cconfig.select(prefix, "Plugin.Reload.Start", yamlConfiguration);
ReloadEnd = Config.select(prefix, "Plugin.Reload.End", yamlConfiguration); ReloadEnd = T2Cconfig.select(prefix, "Plugin.Reload.End", yamlConfiguration);
NoPermissionForCommand = Config.select(prefix, "Plugin.ForCommand", yamlConfiguration); NoPermissionForCommand = T2Cconfig.select(prefix, "Plugin.ForCommand", yamlConfiguration);
send.console(Prefix + " §2Language successfully selected to: §6" + selectMSG + " §7- §e" + (System.currentTimeMillis() - long_) + "ms"); T2Csend.console(Prefix + " §2Language successfully selected to: §6" + selectMSG + " §7- §e" + (System.currentTimeMillis() - long_) + "ms");
} }
} }

View File

@ -2,8 +2,8 @@ package net.t2code.autoresponse.Spigot.config.response;
import net.t2code.autoresponse.Util; import net.t2code.autoresponse.Util;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.yamlConfiguration.Config; import net.t2code.t2codelib.SPIGOT.api.yaml.T2Cconfig;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
@ -16,42 +16,42 @@ public class CreateExampleResponse {
public static void configCreate() { public static void configCreate() {
long long_ = System.currentTimeMillis(); long long_ = System.currentTimeMillis();
if (new File(Main.getPath(), "config.yml").exists()) { if (new File(Main.getPath(), "config.yml").exists()) {
if (Main.getPlugin().getConfig().getBoolean("Plugin.Debug")) send.console(Util.getPrefix() + " §5DEBUG: §6" + " §4config.yml are created / updated..."); if (Main.getPlugin().getConfig().getBoolean("Plugin.Debug")) T2Csend.console(Util.getPrefix() + " §5DEBUG: §6" + " §4config.yml are created / updated...");
} else send.console(Util.getPrefix() + " §4config.yml are created..."); } else T2Csend.console(Util.getPrefix() + " §4config.yml are created...");
File config = new File(Main.getPath(), "Responses/responseexample.yml"); File config = new File(Main.getPath(), "Responses/responseexample.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config); YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
Config.set("Response.Enable", true, yamlConfiguration); T2Cconfig.set("Response.Enable", true, yamlConfiguration);
Config.set("Response.ResponseKeys", Collections.singletonList(".example"), yamlConfiguration); T2Cconfig.set("Response.ResponseKeys", Collections.singletonList(".example"), yamlConfiguration);
Config.set("Response.Contains", false, yamlConfiguration); T2Cconfig.set("Response.Contains", false, yamlConfiguration);
Config.set("Response.BlockKeyMessage", true, yamlConfiguration); T2Cconfig.set("Response.BlockKeyMessage", true, yamlConfiguration);
Config.set("Response.Permission.Necessary", true, yamlConfiguration); T2Cconfig.set("Response.Permission.Necessary", true, yamlConfiguration);
Config.set("Response.Permission.Permission", "t2c-autoresponse.response.example", yamlConfiguration); T2Cconfig.set("Response.Permission.Permission", "t2c-autoresponse.response.example", yamlConfiguration);
Config.set("Response.Command.Enable", false, yamlConfiguration); T2Cconfig.set("Response.Command.Enable", false, yamlConfiguration);
Config.set("Response.Command.CommandAsConsole", false, yamlConfiguration); T2Cconfig.set("Response.Command.CommandAsConsole", false, yamlConfiguration);
Config.set("Response.Command.BungeeCommand", false, yamlConfiguration); T2Cconfig.set("Response.Command.BungeeCommand", false, yamlConfiguration);
Config.set("Response.Command.Commands", Collections.singletonList("say hi"), yamlConfiguration); T2Cconfig.set("Response.Command.Commands", Collections.singletonList("say hi"), yamlConfiguration);
Config.set("Response.Message.Enable", true, yamlConfiguration); T2Cconfig.set("Response.Message.Enable", true, yamlConfiguration);
Config.set("Response.Message.Global.Enable", false, yamlConfiguration); T2Cconfig.set("Response.Message.Global.Enable", false, yamlConfiguration);
Config.set("Response.Message.Global.Bungee", false, yamlConfiguration); T2Cconfig.set("Response.Message.Global.Bungee", false, yamlConfiguration);
Config.set("Response.Message.Messages", Arrays.asList("[prefix] <dark_green>This is an Automated response from <dark_gray>[<dark_red>T2Code</dark_red><gray>-</gray><aqua>AutoResponse</aqua>]</dark_gray>.</dark_green>", "[prefix] <gold>Contact us for questions / support on our <dark_purple><hover:show_text:'<dark_purple>Discord:</dark_purple> <yellow>dc.t2code.net</yellow>'><click:open_url:'http://dc.t2code.net'>Discord</click></hover></dark_purple>.</gold>"), yamlConfiguration); T2Cconfig.set("Response.Message.Messages", Arrays.asList("[prefix] <dark_green>This is an Automated response from <dark_gray>[<dark_red>T2Code</dark_red><gray>-</gray><aqua>AutoResponse</aqua>]</dark_gray>.</dark_green>", "[prefix] <gold>Contact us for questions / support on our <dark_purple><hover:show_text:'<dark_purple>Discord:</dark_purple> <yellow>dc.t2code.net</yellow>'><click:open_url:'http://dc.t2code.net'>Discord</click></hover></dark_purple>.</gold>"), yamlConfiguration);
Config.set("Response.Protection.GameMode.Enable", false, yamlConfiguration); T2Cconfig.set("Response.Protection.GameMode.Enable", false, yamlConfiguration);
Config.set("Response.Protection.GameMode.Mode", "blacklist", yamlConfiguration); T2Cconfig.set("Response.Protection.GameMode.Mode", "blacklist", yamlConfiguration);
Config.set("Response.Protection.GameMode.List", Arrays.asList("CREATIVE","SPECTATOR"), yamlConfiguration); T2Cconfig.set("Response.Protection.GameMode.List", Arrays.asList("CREATIVE","SPECTATOR"), yamlConfiguration);
Config.set("Response.Protection.World.Enable", false, yamlConfiguration); T2Cconfig.set("Response.Protection.World.Enable", false, yamlConfiguration);
Config.set("Response.Protection.World.Mode", "blacklist", yamlConfiguration); T2Cconfig.set("Response.Protection.World.Mode", "blacklist", yamlConfiguration);
Config.set("Response.Protection.World.List", Arrays.asList("World1","World2"), yamlConfiguration); T2Cconfig.set("Response.Protection.World.List", Arrays.asList("World1","World2"), yamlConfiguration);
try { try {
yamlConfiguration.save(config); yamlConfiguration.save(config);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
send.console(Util.getPrefix() + " §2config.yml were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_) + "ms"); T2Csend.console(Util.getPrefix() + " §2config.yml were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_) + "ms");
} }
} }

View File

@ -1,18 +1,15 @@
package net.t2code.autoresponse.Spigot.event; package net.t2code.autoresponse.Spigot.event;
import net.md_5.bungee.api.chat.ClickEvent; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.autoresponse.Spigot.system.BungeeSend;
import net.t2code.autoresponse.Util;
import net.t2code.autoresponse.Spigot.config.config.SelectConfig; import net.t2code.autoresponse.Spigot.config.config.SelectConfig;
import net.t2code.autoresponse.Spigot.objects.ResponsesObject; import net.t2code.autoresponse.Spigot.objects.ResponsesObject;
import net.t2code.autoresponse.Spigot.system.BCommand_Sender_Reciver; import net.t2code.autoresponse.Spigot.system.BCommand_Sender_Reciver;
import net.t2code.autoresponse.Spigot.system.BungeeSend;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Util;
import net.t2code.lib.Spigot.Lib.commands.Cmd; import net.t2code.t2codelib.SPIGOT.api.commands.T2Ccmd;
import net.t2code.lib.Spigot.Lib.messages.TextBuilder; import net.t2code.t2codelib.SPIGOT.api.messages.T2Creplace;
import net.t2code.lib.Spigot.Lib.messages.send; import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.plugins.PluginCheck; import net.t2code.t2codelib.SPIGOT.api.plugins.T2CpluginCheck;
import net.t2code.lib.Spigot.Lib.replace.Replace;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -34,14 +31,14 @@ public class ResponseListener implements Listener {
if (!response.permNecessary || player.hasPermission(response.permission)) { if (!response.permNecessary || player.hasPermission(response.permission)) {
if (response.contains) { if (response.contains) {
for (String responseKey : response.responseKeys) { for (String responseKey : response.responseKeys) {
if (e.getMessage().contains(responseKey)) { if (e.getMessage().toLowerCase().contains(responseKey.toLowerCase())) {
execute(e, player, response, responseKey); execute(e, player, response, responseKey);
return; return;
} }
} }
} else { } else {
for (String responseKey : response.responseKeys) { for (String responseKey : response.responseKeys) {
if (e.getMessage().equals(responseKey)) { if (e.getMessage().toLowerCase().equals(responseKey.toLowerCase())) {
execute(e, player, response, responseKey); execute(e, player, response, responseKey);
return; return;
} }
@ -79,20 +76,20 @@ public class ResponseListener implements Listener {
BCommand_Sender_Reciver.sendToBungee(player, cmd.replace("[player]", player.getName()), BungeeSend.BUNGEECOMMAND); BCommand_Sender_Reciver.sendToBungee(player, cmd.replace("[player]", player.getName()), BungeeSend.BUNGEECOMMAND);
} else BCommand_Sender_Reciver.sendToBungee(player, cmd.replace("[player]", player.getName()), BungeeSend.COMMAND); } else BCommand_Sender_Reciver.sendToBungee(player, cmd.replace("[player]", player.getName()), BungeeSend.COMMAND);
} else { } else {
send.console(Util.getPrefix() + " §4To use bungee commands, enable the Bungee option in the config."); T2Csend.console(Util.getPrefix() + " §4To use bungee commands, enable the Bungee option in the config.");
send.sender(player, Util.getPrefix() + " §4To use bungee commands, enable the Bungee option in the config."); T2Csend.sender(player, Util.getPrefix() + " §4To use bungee commands, enable the Bungee option in the config.");
} }
} else { } else {
if (response.commandAsConsole) { if (response.commandAsConsole) {
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
Cmd.console(cmd.replace("[player]", player.getName())); T2Ccmd.console(cmd.replace("[player]", player.getName()));
} }
}.runTaskLater(Main.getPlugin(), 1L); }.runTaskLater(Main.getPlugin(), 1L);
} else { } else {
Cmd.player(player, cmd.replace("[player]", player.getName())); T2Ccmd.player(player, cmd.replace("[player]", player.getName()));
} }
} }
} }
@ -100,26 +97,26 @@ public class ResponseListener implements Listener {
if (response.messageEnable) { if (response.messageEnable) {
for (String msg : response.messages) { for (String msg : response.messages) {
String text; String text;
if (PluginCheck.papi()) { if (T2CpluginCheck.papi()) {
text = Replace.replace(Util.getPrefix(), player, msg); text = T2Creplace.replace(Util.getPrefix(), player, msg);
} else { } else {
text = Replace.replace(Util.getPrefix(), msg); text = T2Creplace.replace(Util.getPrefix(), msg);
} }
if (response.messageGlobal) { if (response.messageGlobal) {
if (response.messageGlobalBungee) { if (response.messageGlobalBungee) {
BCommand_Sender_Reciver.sendToBungee(player, text, BungeeSend.ALLPLAYERMSG); BCommand_Sender_Reciver.sendToBungee(player, text, BungeeSend.ALLPLAYERMSG);
} else { } else {
for (Player player1 : Bukkit.getOnlinePlayers()) { for (Player player1 : Bukkit.getOnlinePlayers()) {
send.player(player1, text); T2Csend.player(player1, text);
} }
} }
} else send.player(player, text); } else T2Csend.player(player, text);
} }
} }
} }
private static void use(AsyncPlayerChatEvent e, Player player, String responseKey, ResponsesObject response) { private static void use(AsyncPlayerChatEvent e, Player player, String responseKey, ResponsesObject response) {
if (response.blockKeyMessage) e.setCancelled(true); if (response.blockKeyMessage) e.setCancelled(true);
if (SelectConfig.logConsole) send.console(Util.getPrefix() + " §6Player: §e" + player.getName() + " §6use AutoResponse: §e" + responseKey); if (SelectConfig.logConsole) T2Csend.console(Util.getPrefix() + " §6Player: §e" + player.getName() + " §6use AutoResponse: §e" + responseKey);
} }
} }

View File

@ -38,10 +38,10 @@ public class BCommand_Sender_Reciver {
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
player.sendPluginMessage(Main.getPlugin(), "t2car:bungee", stream.toByteArray()); player.sendPluginMessage(Main.getPlugin(), "t2c:aresp", stream.toByteArray());
} else { } else {
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
player.sendPluginMessage(Main.getPlugin(), "t2car:bungee", stream.toByteArray()); player.sendPluginMessage(Main.getPlugin(), "t2c:aresp", stream.toByteArray());
return; return;
} }
} }

View File

@ -4,7 +4,7 @@ package net.t2code.autoresponse.Spigot.system;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.autoresponse.Util; import net.t2code.autoresponse.Util;
import net.t2code.lib.Spigot.Lib.update.UpdateAPI; import net.t2code.t2codelib.SPIGOT.api.update.T2CupdateAPI;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@ -18,6 +18,6 @@ public class JoinEvent implements Listener {
return; return;
} }
Player player = event.getPlayer(); Player player = event.getPlayer();
UpdateAPI.join(Main.getPlugin(), Util.getPrefix(),Permissions.updatemsg,player,Util.getSpigot(), Util.getDiscord()); T2CupdateAPI.join(Main.getPlugin(), Util.getPrefix(),Permissions.updatemsg,player,Util.getSpigotID(), Util.getDiscord());
} }
} }

View File

@ -10,25 +10,25 @@ import net.t2code.autoresponse.Spigot.config.languages.SelectMessages;
import net.t2code.autoresponse.Spigot.config.response.CreateExampleResponse; import net.t2code.autoresponse.Spigot.config.response.CreateExampleResponse;
import net.t2code.autoresponse.Spigot.config.response.SelectResponses; import net.t2code.autoresponse.Spigot.config.response.SelectResponses;
import net.t2code.autoresponse.Spigot.event.ResponseListener; import net.t2code.autoresponse.Spigot.event.ResponseListener;
import net.t2code.lib.Spigot.Lib.messages.T2CodeTemplate; import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import net.t2code.lib.Spigot.Lib.update.UpdateAPI; import net.t2code.t2codelib.SPIGOT.api.update.T2CupdateAPI;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import java.util.List; import java.util.List;
public class Load { public class Load {
static Main plugin = Main.getPlugin(); static Main plugin = Main.getPlugin();
public static void onLoad(String prefix, List<String> autor, String version, String spigot, int spigotID, String discord, int bstatsID) { public static void onLoad(String prefix, List<String> autor, String version, String spigot, int spigotID, String discord, int bstatsID) {
Long long_ = T2CodeTemplate.onLoadHeader(prefix, autor, version, spigot, discord); Long long_ = T2Ctemplate.onLoadHeader(prefix, autor, version, spigot, discord);
plugin.getCommand("t2code-autoresponse").setExecutor( new CmdExecuter()); plugin.getCommand("t2code-autoresponse").setExecutor( new CmdExecuter());
loadReload(); loadReload();
UpdateAPI.onUpdateCheck(plugin, prefix, spigot, spigotID, discord); T2CupdateAPI.onUpdateCheck(plugin, prefix,Util.getGit(), spigotID, discord,
SelectConfig.updateCheckOnJoin,SelectConfig.updateCheckSeePreReleaseUpdates,SelectConfig.updateCheckTimeInterval);
Bukkit.getServer().getPluginManager().registerEvents(new JoinEvent(), plugin); Bukkit.getServer().getPluginManager().registerEvents(new JoinEvent(), plugin);
Bukkit.getServer().getPluginManager().registerEvents(new ResponseListener(), plugin); Bukkit.getServer().getPluginManager().registerEvents(new ResponseListener(), plugin);
T2CodeTemplate.onLoadFooter(prefix, long_,version); T2Ctemplate.onLoadFooter(prefix, long_,version);
Metrics.Bstats(plugin, bstatsID); Metrics.Bstats(plugin, bstatsID);
if (SelectConfig.bungee) { if (SelectConfig.bungee) {
plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord"); plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord");

View File

@ -2,7 +2,7 @@ package net.t2code.autoresponse.Spigot.system;
import net.t2code.autoresponse.Spigot.Main; import net.t2code.autoresponse.Spigot.Main;
import net.t2code.autoresponse.Spigot.objects.ResponsesObject; import net.t2code.autoresponse.Spigot.objects.ResponsesObject;
import net.t2code.lib.Spigot.Lib.register.Register; import net.t2code.t2codelib.SPIGOT.api.register.T2Cregister;
import org.bukkit.permissions.PermissionDefault; import org.bukkit.permissions.PermissionDefault;
public class Permissions { public class Permissions {
@ -15,12 +15,12 @@ public class Permissions {
public static final PermissionDefault notOp = PermissionDefault.NOT_OP; public static final PermissionDefault notOp = PermissionDefault.NOT_OP;
protected static void register() { protected static void register() {
Register.permission(info, op, Main.getPlugin()); T2Cregister.permission(info, op, Main.getPlugin());
Register.permission(updatemsg, op, Main.getPlugin()); T2Cregister.permission(updatemsg, op, Main.getPlugin());
Register.permission(admin, op, info, true, Main.getPlugin()); T2Cregister.permission(admin, op, info, true, Main.getPlugin());
Register.permission(admin, op, updatemsg, true, Main.getPlugin()); T2Cregister.permission(admin, op, updatemsg, true, Main.getPlugin());
for (ResponsesObject response : Main.allResponses) { for (ResponsesObject response : Main.allResponses) {
Register.permission(response.permission, op, Main.getPlugin()); T2Cregister.permission(response.permission, op, Main.getPlugin());
} }
} }
} }

View File

@ -1,9 +1,16 @@
package net.t2code.autoresponse; package net.t2code.autoresponse;
public class Util { public class Util {
private static String requiredT2CodeLibVersion = "12.5";
public static String getInfoText() {
return "";
}
private static String requiredT2CodeLibVersion = "13.4";
private static String Prefix = "§8[§4T2Code§7-§bAutoResponse§8]"; private static String Prefix = "§8[§4T2Code§7-§bAutoResponse§8]";
private static Integer SpigotID = 100603; private static Integer SpigotID = 100603;
public static String getGit() {
return "JaTiTV/T2C-AutoResponse";
}
private static Integer BstatsID = 14091; private static Integer BstatsID = 14091;
private static String Spigot = "https://www.spigotmc.org/resources/" + SpigotID; private static String Spigot = "https://www.spigotmc.org/resources/" + SpigotID;
private static String Discord = "http://dc.t2code.net"; private static String Discord = "http://dc.t2code.net";

View File

@ -1,6 +0,0 @@
name: T2C-AutoResponse
version: ${project.version}
main: net.t2code.autoresponse.Bungee.BMain
description: T2Code Alias Plugin
author: JaTiTV
softdepends: [T2CodeLib]