22 Commits
Author SHA1 Message Date
NoScapeDev 41b54e08be 1.4.6 update push 2022-12-25 19:45:30 +00:00
NoScapeDev e10499c94e 1.4.5 error fix push 2022-12-23 21:52:53 +00:00
NoScapeDev 6ae1d51540 1.4.4 push update 2022-09-26 16:04:46 +01:00
NoScapeDev 0210dead72 push 1.4.3 update 2022-09-24 23:08:55 +01:00
NoScapeDev 6f2d7c1bb5 push 1.4.2 update 2022-08-26 04:06:10 +01:00
NoScapeDev b3f5a9ab4c push 1.4.1 update 2022-08-24 06:16:11 +01:00
NoScapeDev 18860082de push 1.14.0 update 2022-08-24 05:00:42 +01:00
NoScapeDev cfb760a582 1.3.9-3 2022-08-12 13:39:16 +01:00
NoScapeDev e19403323d 1.3.9-2 2022-08-12 00:55:20 +01:00
NoScapeDev e7ffe9e34e 1.3.9 2022-08-05 02:12:11 +01:00
NoScapeDev 6397408e35 1.3.8 2022-08-03 23:18:45 +01:00
NoScapeDev b76c9c8e19 1.3.7 2022-08-03 21:38:17 +01:00
NoScapeDev 2c17494fbd 1.3.6 2022-08-03 16:30:39 +01:00
NoScapeDev 249b1dd9c6 1.3.5 2022-08-03 13:23:06 +01:00
NoScapeDev 9a0b85c749 1.3.4 2022-08-02 21:42:00 +01:00
NoScapeDev e36eab6c2d 1.3.3 2022-08-02 03:08:31 +01:00
NoScapeDev d0a8860018 1.3.2
Patches included.
2022-07-31 03:31:24 +01:00
NoScapeDev 5f431e30af Delete tags.yml 2022-07-31 02:39:17 +01:00
NoScapeDev 51f91214e1 Create README.md 2022-07-11 02:35:21 +01:00
NoScapeDev af8abe06c1 1.3.1
Fixed permission supremetags.tag.<identifier> not properly working.
2022-07-07 01:27:52 +01:00
NoScapeDev 83c612a601 1.3
Added NBT API to support older versions with saving data for tags.
2022-07-06 22:13:50 +01:00
NoScapeDev c2b51a8e90 1.2
Changeable gui material values for older versions.
2022-07-06 01:56:37 +01:00
28 changed files with 2985 additions and 221 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
# SupremeTags
Allow players to show of their supreme tags!
> Download: [Here](https://www.spigotmc.org/resources/%E2%9C%85-supremetags-%E2%9C%85-1-8-1-19-placeholderapi-support-unlimited-tags-%E2%9C%85.103140/)
> Discord: [Here](https://discord.gg/AnPwty8asP)
+30 -3
View File
@@ -6,12 +6,12 @@
<groupId>net.noscape.project.supremetags</groupId>
<artifactId>SupremeTags</artifactId>
<version>1.1</version>
<version>1.4.6</version>
<packaging>jar</packaging>
<name>SupremeTags</name>
<description>Allow player to show off their supreme tags!</description>
<description>Allow players to show off their supreme tags!</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -70,6 +70,15 @@
<id>opencollab-snapshot</id>
<url>https://repo.opencollab.dev/maven-snapshots/</url>
</repository>
<repository>
<id>codemc-repo</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
<layout>default</layout>
</repository>
<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
@@ -90,5 +99,23 @@
<artifactId>h2</artifactId>
<version>2.1.212</version>
</dependency>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api-plugin</artifactId>
<version>2.10.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.arcaniax</groupId>
<artifactId>HeadDatabase-API</artifactId>
<version>1.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.19.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
</project>
@@ -1,38 +1,100 @@
package net.noscape.project.supremetags;
import net.noscape.project.supremetags.checkers.*;
import net.noscape.project.supremetags.commands.*;
import net.noscape.project.supremetags.handlers.hooks.*;
import net.noscape.project.supremetags.handlers.menu.*;
import net.noscape.project.supremetags.listeners.*;
import net.noscape.project.supremetags.managers.*;
import net.noscape.project.supremetags.storage.*;
import org.bukkit.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.*;
import org.bukkit.entity.*;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.*;
import java.util.*;
import java.util.logging.*;
public final class SupremeTags extends JavaPlugin {
private static SupremeTags instance;
private final TagManager tagManager = new TagManager();
private final CategoryManager categoryManager = new CategoryManager();
private static MySQL mysql;
private static H2Database h2;
private final H2UserData h2user = new H2UserData();
private static String connectionURL;
private static Database data;
private final UserData userData = new UserData();
private static String layout;
private final MySQLUserData user = new MySQLUserData();
private static final HashMap<Player, MenuUtil> menuUtilMap = new HashMap<>();
private boolean legacy_format;
private final String host = getConfig().getString("data.address");
private final int port = getConfig().getInt("data.port");
private final String database = getConfig().getString("data.database");
private final String username = getConfig().getString("data.username");
private final String password = getConfig().getString("data.password");
private final String options = getConfig().getString("data.options");
@Override
public void onEnable() {
instance = this;
connectionURL = "jdbc:h2:" + getDataFolder().getAbsolutePath() + "/database";
data = new Database(connectionURL);
Logger log = getLogger();
saveDefaultConfig();
if (getServer().getPluginManager().getPlugin("NBTAPI") == null) {
log.warning("------------------------------");
log.warning("[NBTAPI] NBTAPI is required for SupremeTags-" + getDescription().getVersion() + " to work!");
log.warning("------------------------------");
getServer().getPluginManager().disablePlugin(this);
} else {
log.fine("------------------------------");
log.fine("[NBTAPI] NBTAPI has been found for SupremeTags-" + getDescription().getVersion() + "!");
log.fine("------------------------------");
}
this.saveDefaultConfig();
this.callMetrics();
if (isH2()) {
connectionURL = "jdbc:h2:" + getDataFolder().getAbsolutePath() + "/database";
h2 = new H2Database(connectionURL);
}
if (isMySQL()) {
mysql = new MySQL(host, port, database, username, password, options);
}
if (getConfig().getBoolean("settings.update-check")) {
UpdateChecker updater = new UpdateChecker(this);
updater.fetch();
if (updater.hasUpdateAvailable()) {
log.warning("------------------------------");
log.warning("SupremeTags-Checker");
log.warning(" ");
log.warning("An update for SupremeTags has been found!");
log.warning("SupremeTags-" + updater.getSpigotVersion());
log.warning("You are running " + getDescription().getVersion());
log.warning(" ");
log.warning("Download at https://www.spigotmc.org/resources/%E2%9C%85-supremetags-%E2%9C%85-1-8-1-19-placeholderapi-support-unlimited-tags-%E2%9C%85.103140/");
log.warning("------------------------------");
} else {
log.fine("------------------------------");
log.fine("Running latest version of SupremeTags-" + getDescription().getVersion());
log.fine("------------------------------");
}
}
if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PAPI(this).register();
log.fine("------------------------------");
log.fine("PlaceholderAPI found SupremeTags! Automatically downloaded cloud.");
log.fine("------------------------------");
}
Objects.requireNonNull(getCommand("tags")).setExecutor(new Tags());
@@ -40,7 +102,20 @@ public final class SupremeTags extends JavaPlugin {
getServer().getPluginManager().registerEvents(new MenuListener(), this);
getServer().getPluginManager().registerEvents(new PlayerEvents(), this);
if (Objects.requireNonNull(getConfig().getString("settings.layout")).equalsIgnoreCase("layout1")) {
layout = "layout1";
} else if (Objects.requireNonNull(getConfig().getString("settings.layout")).equalsIgnoreCase("layout2")) {
layout = "layout2";
}
legacy_format = getConfig().getBoolean("settings.legacy-hex-format");
merge(log);
tagManager.loadTags();
categoryManager.loadCategories();
categoryManager.loadCategoriesTags();
tagManager.getDataItem().clear();
}
@Override
@@ -52,13 +127,28 @@ public final class SupremeTags extends JavaPlugin {
public TagManager getTagManager() { return tagManager; }
public CategoryManager getCategoryManager() { return categoryManager; }
public static MenuUtil getMenuUtil(Player player) {
MenuUtil menuUtil;
if (menuUtilMap.containsKey(player)) {
return menuUtilMap.get(player);
} else {
menuUtil = new MenuUtil(player, UserData.getActive(player));
menuUtil = new MenuUtil(player, UserData.getActive(player.getUniqueId()));
menuUtilMap.put(player, menuUtil);
}
return menuUtil;
}
public static MenuUtil getMenuUtil(Player player, String category) {
MenuUtil menuUtil;
if (menuUtilMap.containsKey(player)) {
return menuUtilMap.get(player);
} else {
menuUtil = new MenuUtil(player, UserData.getActive(player.getUniqueId()), category);
menuUtilMap.put(player, menuUtil);
}
@@ -69,8 +159,89 @@ public final class SupremeTags extends JavaPlugin {
return connectionURL;
}
public UserData getUserData() { return userData; }
public static String getLayout() {
return layout;
}
public static Database getDatabase() { return data; }
public static void setLayout(String layout) {
SupremeTags.layout = layout;
}
public H2UserData getUserData() { return h2user; }
public static H2Database getDatabase() { return h2; }
public MySQLUserData getUser() {
return instance.user;
}
public static MySQL getMysql() {
return mysql;
}
@Override
public void reloadConfig() {
super.reloadConfig();
}
public boolean isLegacyFormat() {
return legacy_format;
}
public void merge(Logger log) {
File configFile = new File(Bukkit.getServer().getWorldContainer().getAbsolutePath() + "/plugins/DeluxeTags/config.yml"); // First we will load the file.
FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Now we will load the file into a FileConfiguration.
if (getConfig().getBoolean("settings.auto-merge")) {
ConfigurationSection deluxeTagsSection = config.getConfigurationSection("deluxetags");
if (deluxeTagsSection != null) {
for (String identifier : deluxeTagsSection.getKeys(false)) {
if (!SupremeTags.getInstance().getTagManager().getTags().containsKey(identifier)) {
String tag = config.getString(String.format("deluxetags.%s.tag", identifier));
String description = config.getString(String.format("deluxetags.%s.description", identifier));
String permission = config.getString(String.format("deluxetags.%s.permission", identifier));
SupremeTags.getInstance().getTagManager().createTag(identifier, tag, description, permission);
}
}
log.info("Merger: Added all new tags from DeluxeTags, any existing tags with the same name were not added.");
} else {
log.warning("Error: DeluxeTags tag config section is empty.");
}
}
}
public Boolean isH2() {
return Objects.requireNonNull(getConfig().getString("data.type")).equalsIgnoreCase("H2");
}
public Boolean isMySQL() {
return Objects.requireNonNull(getConfig().getString("data.type")).equalsIgnoreCase("MYSQL");
}
private void callMetrics() {
int pluginId = 103140;
Metrics metrics = new Metrics(this, pluginId);
metrics.addCustomChart(new Metrics.SimplePie("used_language", () -> getConfig().getString("language", "en")));
metrics.addCustomChart(new Metrics.DrilldownPie("java_version", () -> {
Map<String, Map<String, Integer>> map = new HashMap<>();
String javaVersion = System.getProperty("java.version");
Map<String, Integer> entry = new HashMap<>();
entry.put(javaVersion, 1);
if (javaVersion.startsWith("1.7")) {
map.put("Java 1.7", entry);
} else if (javaVersion.startsWith("1.8")) {
map.put("Java 1.8", entry);
} else if (javaVersion.startsWith("1.9")) {
map.put("Java 1.9", entry);
} else {
map.put("Other", entry);
}
return map;
}));
}
}
@@ -0,0 +1,724 @@
package net.noscape.project.supremetags.checkers;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
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.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess"})
public class Metrics {
static {
// 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', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// The plugin id
private final int pluginId;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
* @param pluginId The id of the plugin.
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(Plugin plugin, int pluginId) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
this.pluginId = pluginId;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) {
}
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) {
}
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("id", pluginId); // Append the id of the plugin
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.add("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
}
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) {
}
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(() -> {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data);
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
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) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder);
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
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();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JsonObject getRequestJsonObject() {
JsonObject chart = new JsonObject();
chart.addProperty("chartId", chartId);
try {
JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.add("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JsonObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
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) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
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()) {
JsonObject value = new JsonObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.add(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
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) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
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()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
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 JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
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) {
continue; // Skip this invalid
}
allSkipped = false;
JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue));
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
}
@@ -0,0 +1,98 @@
package net.noscape.project.supremetags.checkers;
import net.md_5.bungee.api.chat.*;
import org.bukkit.*;
import org.bukkit.event.*;
import org.bukkit.event.player.*;
import org.bukkit.plugin.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import static net.noscape.project.supremetags.utils.Utils.*;
public class UpdateChecker implements Listener {
private final int RESOURCE_ID = 103140;
private final Plugin plugin;
private String spigotVersion;
private final String pluginVersion;
private boolean updateAvailable;
public UpdateChecker(Plugin instance) {
this.plugin = instance;
this.pluginVersion = instance.getDescription().getVersion();
}
public boolean hasUpdateAvailable() {
return this.updateAvailable;
}
public String getSpigotVersion() {
return this.spigotVersion;
}
public void fetch() {
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
try {
HttpsURLConnection con = (HttpsURLConnection)(new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID)).openConnection();
con.setRequestMethod("GET");
this.spigotVersion = (new BufferedReader(new InputStreamReader(con.getInputStream()))).readLine();
} catch (Exception ex) {
this.plugin.getLogger().info("Failed to check for updates on spigot.");
return;
}
if (this.spigotVersion == null || this.spigotVersion.isEmpty())
return;
this.updateAvailable = spigotIsNewer();
if (!this.updateAvailable)
return;
});
}
private boolean spigotIsNewer() {
if (this.spigotVersion == null || this.spigotVersion.isEmpty())
return false;
String plV = toReadable(this.pluginVersion);
String spV = toReadable(this.spigotVersion);
return (plV.compareTo(spV) < 0);
}
private String toReadable(String version) {
if (version.contains("-DEV-"))
version = version.split("-DEV-")[0];
return version.replaceAll("\\.", "");
}
@EventHandler(priority = EventPriority.MONITOR)
public void onJoin(PlayerJoinEvent e) {
if (e.getPlayer().hasPermission("supremetags.updates")) {
if (hasUpdateAvailable()) {
TextComponent message = new TextComponent(TextComponent.fromLegacyText(format("&7Click &a[HERE] &7download it!")));
setClickBroadcastEvent(message, "/");
e.getPlayer().spigot().sendMessage(message);
msgPlayer(e.getPlayer(), "&8[&aSupremeTags&8] &7Update found for &a&lST &8(&f&nSupremeTags-" + getSpigotVersion() + "&r&8)");
}
}
}
public void setClickBroadcastEvent(TextComponent component, String click) {
if (click == null || click.length() == 0)
return;
switch (click.charAt(0)) {
case '/':
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, click));
return;
case '*':
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, click.substring(1)));
return;
}
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, click));
}
}
@@ -2,10 +2,16 @@ package net.noscape.project.supremetags.commands;
import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.guis.*;
import net.noscape.project.supremetags.storage.*;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.configuration.file.*;
import org.bukkit.entity.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import static net.noscape.project.supremetags.utils.Utils.*;
public class Tags implements CommandExecutor {
@@ -14,6 +20,89 @@ public class Tags implements CommandExecutor {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {
if (!(sender instanceof Player)) {
if (cmd.getName().equalsIgnoreCase("tags")) {
if (args.length == 0) {
} else if (args.length == 3) {
if (args[0].equalsIgnoreCase("create")) {
String name = args[1];
String tag = args[2];
SupremeTags.getInstance().getTagManager().createTag(sender, name, tag, "&7My tag is " + name, "supremetags.tag." + name);
} else if (args[0].equalsIgnoreCase("settag")) {
String name = args[1];
String tag = args[2];
SupremeTags.getInstance().getTagManager().setTag(sender, name, tag);
} else if (args[0].equalsIgnoreCase("set")) {
OfflinePlayer target = Bukkit.getOfflinePlayer(args[1]);
String identifier = args[2];
if (SupremeTags.getInstance().getTagManager().getTags().containsKey(identifier)) {
UserData.setActive(target, identifier);
msgPlayer(sender, "&8[&b&lTag&8] &7Set &b" + target.getName() + "'s &7tag to &b" + identifier);
} else {
msgPlayer(sender, "&cThis tag does not exist.");
}
}
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("reload")) {
SupremeTags.getInstance().reloadConfig();
SupremeTags.getInstance().getTagManager().unloadTags();
SupremeTags.getInstance().getTagManager().loadTags();
SupremeTags.getInstance().getTagManager().getDataItem().clear();
if (Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("settings.layout")).equalsIgnoreCase("layout1")) {
SupremeTags.setLayout("layout1");
} else if (Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("settings.layout")).equalsIgnoreCase("layout2")) {
SupremeTags.setLayout("layout2");
}
SupremeTags.getInstance().getCategoryManager().loadCategories();
SupremeTags.getInstance().getCategoryManager().loadCategoriesTags();
msgPlayer(sender, "&6[TAG] &7Reloaded plugin.");
} else if (args[0].equalsIgnoreCase("help")) {
msgPlayer(sender, "",
"&eSupremeTags Admin Help:",
"",
"&6/tags &7- will open the tag menu.",
"&6/tags create <identifier> <tag> &7- creates a new tag.",
"&6/tags delete <identifier> &7- creates a new tag.",
"&6/tags settag <identifier> <tag> &7- sets tag style for the existing tag.",
"&6/tags set <player> <identifier> &7- sets a new tag for that player.",
"&6/tags reset <player> &7- resets the players tag to None.",
"&6/tags merge &7- merges deluxetags into supremetags.",
"&6/tags reload &7- reloads the config.yml & unloads/loads tags.",
"&6/tags help &7- displays this help message.",
"");
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("delete")) {
String name = args[1];
SupremeTags.getInstance().getTagManager().deleteTag(sender, name);
} else if (args[0].equalsIgnoreCase("reset")) {
OfflinePlayer target = Bukkit.getOfflinePlayer(args[1]);
H2UserData.setActive(target, "None");
msgPlayer(sender, "&8[&b&lTag&8] &7Reset &b" + target.getName() + "'s &7tag back to None.");
} else {
msgPlayer(sender, "",
"&eSupremeTags Admin Help:",
"",
"&6/tags &7- will open the tag menu.",
"&6/tags create <identifier> <tag> &7- creates a new tag.",
"&6/tags delete <identifier> &7- creates a new tag.",
"&6/tags settag <identifier> <tag> &7- sets tag style for the existing tag.",
"&6/tags set <player> <identifier> &7- sets a new tag for that player.",
"&6/tags reset <player> &7- resets the players tag to None.",
"&6/tags merge &7- merges deluxetags into supremetags.",
"&6/tags reload &7- reloads the config.yml & unloads/loads tags.",
"&6/tags help &7- displays this help message.",
"");
}
}
}
return true;
}
@@ -22,7 +111,15 @@ public class Tags implements CommandExecutor {
if (cmd.getName().equalsIgnoreCase("tags")) {
if (args.length == 0) {
if (player.hasPermission("supremetags.menu")) {
new TagMenu(SupremeTags.getMenuUtil(player)).open();
if (hasTags(player)) {
if (SupremeTags.getInstance().getConfig().getBoolean("settings.categories")) {
new MainMenu(SupremeTags.getMenuUtil(player)).open();
} else {
new TagMenu(SupremeTags.getMenuUtil(player)).open();
}
} else {
msgPlayer(player, "&cYou have no tags yet.");
}
} else {
msgPlayer(player, "&cNo Permission, required permission: &7'supremetags.menu'");
}
@@ -32,7 +129,7 @@ public class Tags implements CommandExecutor {
String name = args[1];
String tag = args[2];
SupremeTags.getInstance().getTagManager().createTag(player, name, tag);
SupremeTags.getInstance().getTagManager().createTag(player, name, tag, "&7My tag is " + name, "supremetags.tag." + name);
} else {
msgPlayer(player, "&cNo Permission.");
}
@@ -45,15 +142,48 @@ public class Tags implements CommandExecutor {
} else {
msgPlayer(player, "&cNo Permission.");
}
} else if (args[0].equalsIgnoreCase("setcategory")) {
if (player.hasPermission("supremetags.admin")) {
String name = args[1];
String category = args[2];
SupremeTags.getInstance().getTagManager().setCategory(player, name, category);
} else {
msgPlayer(player, "&cNo Permission.");
}
} else if (args[0].equalsIgnoreCase("set")) {
if (player.hasPermission("supremetags.admin")) {
OfflinePlayer target = Bukkit.getOfflinePlayer(args[1]);
String identifier = args[2];
if (SupremeTags.getInstance().getTagManager().getTags().containsKey(identifier)) {
UserData.setActive(target, identifier);
msgPlayer(player, "&8[&b&lTag&8] &7Set &b" + target.getName() + "'s &7tag to &b" + identifier);
} else {
msgPlayer(player, "&cThis tag does not exist.");
}
} else {
msgPlayer(player, "&cNo Permission.");
}
}
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("reload")) {
if (player.hasPermission("supremetags.admin")) {
SupremeTags.getInstance().reloadConfig();
SupremeTags.getInstance().getTagManager().unloadTags();
SupremeTags.getInstance().getTagManager().loadTags();
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
SupremeTags.getInstance().getTagManager().getDataItem().clear();
if (Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("settings.layout")).equalsIgnoreCase("layout1")) {
SupremeTags.setLayout("layout1");
} else if (Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("settings.layout")).equalsIgnoreCase("layout2")) {
SupremeTags.setLayout("layout2");
}
SupremeTags.getInstance().getCategoryManager().loadCategories();
SupremeTags.getInstance().getCategoryManager().loadCategoriesTags();
msgPlayer(player, "&6[TAG] &7Reloaded plugin.");
} else {
msgPlayer(player, "&cNo Permission.");
@@ -66,12 +196,52 @@ public class Tags implements CommandExecutor {
"&6/tags &7- will open the tag menu.",
"&6/tags create <identifier> <tag> &7- creates a new tag.",
"&6/tags delete <identifier> &7- creates a new tag.",
"&6/tags settag <identifier> <tag> &7- sets tag style for the existing tag.",
"&6/tags setcategory <identifier> <category> &7- sets the category of the tag.",
"&6/tags set <player> <identifier> &7- sets a new tag for that player.",
"&6/tags reset <player> &7- resets the players tag to None.",
"&6/tags merge &7- merges deluxetags into supremetags.",
"&6/tags reload &7- reloads the config.yml & unloads/loads tags.",
"&6/tags help &7- displays this help message.",
"");
} else {
msgPlayer(player, "&cNo Permission.");
}
} else if (args[0].equalsIgnoreCase("merge")) {
if (player.hasPermission("supremetags.admin")) {
File configFile = new File(Bukkit.getServer().getWorldContainer().getAbsolutePath() + "/plugins/DeluxeTags/config.yml"); // First we will load the file.
FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Now we will load the file into a FileConfiguration.
//deluxetags:
//example:
//order: 1
//tag: '&8[&bDeluxeTags&8]'
//description: '&cAwarded for using DeluxeTags!'
//permission: deluxetags.tag.example
if (configFile.exists()) {
if (config.getConfigurationSection("deluxetags") != null) {
for (String identifier : Objects.requireNonNull(config.getConfigurationSection("deluxetags")).getKeys(false)) {
if (!SupremeTags.getInstance().getTagManager().getTags().containsKey(identifier)) {
String tag = config.getString("deluxetags." + identifier + ".tag");
String description = config.getString("deluxetags." + identifier + ".description");
String permission = config.getString("deluxetags." + identifier + ".permission");
SupremeTags.getInstance().getTagManager().createTag(player, identifier, tag, description, permission);
}
msgPlayer(player, "&6Merger: &7Added all new tags from &6DeluxeTags&7 were added, any existing tags with the same name won't be added.");
}
} else {
msgPlayer(player, "&6Error: &7DeluxeTags tag config area is empty.");
}
} else {
msgPlayer(player, "&6Error: &7DeluxeTags can not be found.");
}
} else {
msgPlayer(player, "&cNo Permission.");
}
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("delete")) {
@@ -82,9 +252,40 @@ public class Tags implements CommandExecutor {
} else {
msgPlayer(player, "&cNo Permission.");
}
} else if (args[0].equalsIgnoreCase("reset")) {
if (player.hasPermission("supremetags.admin")) {
OfflinePlayer target = Bukkit.getOfflinePlayer(args[1]);
H2UserData.setActive(target, "None");
msgPlayer(player, "&8[&b&lTag&8] &7Reset &b" + target.getName() + "'s &7tag back to None.");
} else {
msgPlayer(player, "&cNo Permission.");
}
} else {
msgPlayer(player, "",
"&eSupremeTags Admin Help:",
"",
"&6/tags &7- will open the tag menu.",
"&6/tags create <identifier> <tag> &7- creates a new tag.",
"&6/tags delete <identifier> &7- creates a new tag.",
"&6/tags settag <identifier> <tag> &7- sets tag style for the existing tag.",
"&6/tags set <player> <identifier> &7- sets a new tag for that player.",
"&6/tags reset <player> &7- resets the players tag to None.",
"&6/tags merge &7- merges deluxetags into supremetags.",
"&6/tags reload &7- reloads the config.yml & unloads/loads tags.",
"&6/tags help &7- displays this help message.",
"");
}
}
}
return false;
}
public boolean hasTags(Player player) {
for (String tag : SupremeTags.getInstance().getTagManager().getTags().keySet())
if (player.hasPermission(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag + ".permission"))))
return true;
return false;
}
}
@@ -0,0 +1,400 @@
package net.noscape.project.supremetags.guis;
import de.tr7zw.nbtapi.*;
import me.arcaniax.hdb.api.*;
import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.handlers.Tag;
import net.noscape.project.supremetags.handlers.menu.*;
import net.noscape.project.supremetags.storage.*;
import org.bukkit.*;
import org.bukkit.enchantments.*;
import org.bukkit.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.*;
import java.util.*;
import static net.noscape.project.supremetags.utils.Utils.color;
import static net.noscape.project.supremetags.utils.Utils.format;
public class CategoryMenu extends Paged {
private final Map<String, Tag> tags;
private final Map<Integer, String> dataItem;
public CategoryMenu(MenuUtil menuUtil) {
super(menuUtil);
tags = SupremeTags.getInstance().getTagManager().getTags();
dataItem = SupremeTags.getInstance().getTagManager().getDataItem();
}
@Override
public String getMenuName() {
return format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("categories." + menuUtil.getCategory() + ".title")).replaceAll("%page%", String.valueOf(this.getPage())));
}
@Override
public int getSlots() {
return 54;
}
@Override
public void handleMenu(InventoryClickEvent e) {
Player player = (Player) e.getWhoClicked();
ArrayList<String> tag = new ArrayList<>(tags.keySet());
if (Objects.requireNonNull(e.getCurrentItem()).getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.tag-material")).toUpperCase()))) {
if (!ChatColor.stripColor(Objects.requireNonNull(e.getCurrentItem().getItemMeta()).getDisplayName()).startsWith("Active")) {
NBTItem nbt = new NBTItem(e.getCurrentItem());
String identifier = nbt.getString("identifier");
if (!UserData.getActive(player.getUniqueId()).equalsIgnoreCase(identifier) && identifier != null) {
UserData.setActive(player, identifier);
player.closeInventory();
super.open();
menuUtil.setIdentifier(identifier);
}
}
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.close-menu-material")).toUpperCase()))) {
player.closeInventory();
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.reset-tag-material")).toUpperCase()))) {
if (!SupremeTags.getInstance().getConfig().getBoolean("settings.forced-tag")) {
UserData.setActive(player, "None");
player.closeInventory();
super.open();
menuUtil.setIdentifier("None");
}
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.refresh-material")).toUpperCase()))) {
player.closeInventory();
super.open();
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.back-next-material")).toUpperCase()))) {
if (ChatColor.stripColor(Objects.requireNonNull(e.getCurrentItem().getItemMeta()).getDisplayName()).equalsIgnoreCase("Back")) {
if (page != 0) {
page = page - 1;
super.open();
}
} else if (ChatColor.stripColor(e.getCurrentItem().getItemMeta().getDisplayName()).equalsIgnoreCase("Next")) {
if (!((index + 1) >= tag.size())) {
page = page + 1;
super.open();
}
}
}
}
@Override
public void setMenuItems() {
applyLayout();
// add all category tags.
ArrayList<String> tag = new ArrayList<>(tags.keySet());
if (!tags.isEmpty()) {
int maxTagsPerPage = getMaxItems();
int pageNumber = 1;
for (String tg : tag) {
if (pageNumber > maxTagsPerPage) {
break;
}
Tag t = tags.get(tag.get(index));
String permission = t.getPermission();
String displayname;
if (SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".displayname") != null) {
displayname = Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".displayname")).replace("%tag%", t.getTag());
} else {
displayname = format("&7Tag: " + tags.get(tag.get(index)).getTag());
}
String material;
if (SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".display-item") != null) {
material = SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".display-item");
} else {
material = "NAME_TAG";
}
assert permission != null;
if (t.getCategory().equalsIgnoreCase(menuUtil.getCategory())) {
// toggle if they don't have permission
if (menuUtil.getOwner().hasPermission(permission) && !permission.equalsIgnoreCase("none")) {
if (UserData.getActive(menuUtil.getOwner().getUniqueId()).equalsIgnoreCase(tag.get(index))) {
if (material.contains("hdb-")) {
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
if (SupremeTags.getInstance().getConfig().getBoolean("settings.active-tag-glow")) {
nbt.getItem().addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
}
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
} else {
if (material.contains("hdb-")) {
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
}
// if permission == none
} else if (!menuUtil.getOwner().hasPermission(permission) && permission.equalsIgnoreCase("none")) {
if (UserData.getActive(menuUtil.getOwner().getUniqueId()).equalsIgnoreCase(tag.get(index))) {
if (material.contains("hdb-")) {
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
if (SupremeTags.getInstance().getConfig().getBoolean("settings.active-tag-glow")) {
nbt.getItem().addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
}
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
} else {
if (material.contains("hdb-")) {
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
}
}
}
}
}
}
}
@@ -0,0 +1,164 @@
package net.noscape.project.supremetags.guis;
import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.handlers.menu.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.*;
import java.util.*;
import static net.noscape.project.supremetags.utils.Utils.*;
public class MainMenu extends Menu {
private final List<String> catorgies;
private final Map<Integer, String> dataItem = new HashMap<>();
private final Map<String, Integer> categoriesTags;
public MainMenu(MenuUtil menuUtil) {
super(menuUtil);
this.catorgies = SupremeTags.getInstance().getCategoryManager().getCatorgies();
this.categoriesTags = SupremeTags.getInstance().getCategoryManager().getCatorgiesTags();
}
@Override
public String getMenuName() {
return format(SupremeTags.getInstance().getConfig().getString("gui.main-menu.title"));
}
@Override
public int getSlots() {
return SupremeTags.getInstance().getConfig().getInt("gui.main-menu.size");
}
@Override
public void handleMenu(InventoryClickEvent e) {
Player player = (Player) e.getWhoClicked();
String category = dataItem.get(e.getSlot());
String material = SupremeTags.getInstance().getConfig().getString("categories." + category + ".material");
String permission = SupremeTags.getInstance().getConfig().getString("categories." + category + ".permission");
if (category != null) {
if (material != null && Objects.requireNonNull(e.getCurrentItem()).getType().equals(Material.valueOf(material.toUpperCase()))) {
if (permission != null && player.hasPermission(permission)) {
menuUtil.setCategory(category);
new CategoryMenu(SupremeTags.getMenuUtil(player, category)).open();
menuUtil.getOwner().updateInventory();
} else {
msgPlayer(player, "&cYou don't have permission to access these tags.");
}
}
}
}
@Override
public void setMenuItems() {
// loop through categories items.
for (String cats : getCatorgies()) {
if (cats != null) {
boolean canSee = SupremeTags.getInstance().getConfig().getBoolean("categories." + cats + ".permission-see-category");
String permission = SupremeTags.getInstance().getConfig().getString("categories." + cats + ".permission");
String material = SupremeTags.getInstance().getConfig().getString("categories." + cats + ".material");
int slot = SupremeTags.getInstance().getConfig().getInt("categories." + cats + ".slot");
String displayname = SupremeTags.getInstance().getConfig().getString("categories." + cats + ".id_display");
if (permission != null && menuUtil.getOwner().hasPermission(permission) && canSee) {
assert material != null;
ItemStack cat_item = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta cat_itemMeta = cat_item.getItemMeta();
assert cat_itemMeta != null;
cat_itemMeta.setDisplayName(format(displayname));
cat_itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
cat_itemMeta.addItemFlags(ItemFlag.HIDE_DYE);
cat_itemMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("categories." + cats + ".lore");
if (categoriesTags.get(cats) != null) {
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tags_amount%", String.valueOf(categoriesTags.get(cats))));
} else {
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tags_amount%", String.valueOf(0)));
}
cat_itemMeta.setLore(color(lore));
cat_item.setItemMeta(cat_itemMeta);
dataItem.put(slot, cats);
inventory.setItem(slot, cat_item);
} else if (permission != null && !menuUtil.getOwner().hasPermission(permission) && !canSee) {
assert material != null;
ItemStack cat_item = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta cat_itemMeta = cat_item.getItemMeta();
assert cat_itemMeta != null;
cat_itemMeta.setDisplayName(format(displayname));
cat_itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
cat_itemMeta.addItemFlags(ItemFlag.HIDE_DYE);
cat_itemMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("categories." + cats + ".lore");
if (categoriesTags.get(cats) != null) {
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tags_amount%", String.valueOf(categoriesTags.get(cats))));
} else {
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tags_amount%", String.valueOf(0)));
}
cat_itemMeta.setLore(color(lore));
cat_item.setItemMeta(cat_itemMeta);
dataItem.put(slot, cats);
inventory.setItem(slot, cat_item);
} else if (permission != null && menuUtil.getOwner().hasPermission(permission) && !canSee) {
assert material != null;
ItemStack cat_item = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta cat_itemMeta = cat_item.getItemMeta();
assert cat_itemMeta != null;
cat_itemMeta.setDisplayName(format(displayname));
cat_itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
cat_itemMeta.addItemFlags(ItemFlag.HIDE_DYE);
cat_itemMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("categories." + cats + ".lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tags_amount%", String.valueOf(categoriesTags.get(cats))));
cat_itemMeta.setLore(color(lore));
cat_item.setItemMeta(cat_itemMeta);
dataItem.put(slot, cats);
inventory.setItem(slot, cat_item);
}
}
}
}
public List<String> getCatorgies() {
return catorgies;
}
public Map<Integer, String> getDataItem() {
return dataItem;
}
}
@@ -1,5 +1,7 @@
package net.noscape.project.supremetags.guis;
import de.tr7zw.nbtapi.*;
import me.arcaniax.hdb.api.*;
import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.handlers.Tag;
import net.noscape.project.supremetags.handlers.menu.*;
@@ -10,25 +12,25 @@ import org.bukkit.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.*;
import org.bukkit.persistence.*;
import java.util.*;
import static net.noscape.project.supremetags.utils.Utils.format;
import static net.noscape.project.supremetags.utils.Utils.*;
public class TagMenu extends Paged {
private final Map<String, Tag> tags;
private final Map<Integer, String> dataItem;
public TagMenu(MenuUtil menuUtil) {
super(menuUtil);
tags = SupremeTags.getInstance().getTagManager().getTags();
dataItem = SupremeTags.getInstance().getTagManager().getDataItem();
}
@Override
public String getMenuName() {
return "Tag Menu";
return format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.tag-menu-none-categories.title")).replaceAll("%page%", String.valueOf(this.getPage())));
}
@Override
@@ -43,24 +45,27 @@ public class TagMenu extends Paged {
ArrayList<String> tag = new ArrayList<>(tags.keySet());
if (Objects.requireNonNull(e.getCurrentItem()).getType().equals(Material.NAME_TAG)) {
if (Objects.requireNonNull(e.getCurrentItem()).getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.tag-material")).toUpperCase()))) {
if (!ChatColor.stripColor(Objects.requireNonNull(e.getCurrentItem().getItemMeta()).getDisplayName()).startsWith("Active")) {
String identifier = Objects.requireNonNull(e.getCurrentItem().getItemMeta()).getPersistentDataContainer().get(new NamespacedKey(SupremeTags.getInstance(), "identifier"), PersistentDataType.STRING);
if (!UserData.getActive(player).equalsIgnoreCase(identifier)) {
NBTItem nbt = new NBTItem(e.getCurrentItem());
String identifier = nbt.getString("identifier");
if (!UserData.getActive(player.getUniqueId()).equalsIgnoreCase(identifier) && identifier != null) {
UserData.setActive(player, identifier);
player.closeInventory();
new TagMenu(SupremeTags.getMenuUtil(player)).open();
super.open();
menuUtil.setIdentifier(identifier);
}
}
} else if (e.getCurrentItem().getType().equals(Material.BARRIER)) {
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.close-menu-material")).toUpperCase()))) {
player.closeInventory();
} else if (e.getCurrentItem().getType().equals(Material.RED_DYE)) {
UserData.setActive(player, "None");
player.closeInventory();
new TagMenu(SupremeTags.getMenuUtil(player)).open();
menuUtil.setIdentifier("None");
} else if (e.getCurrentItem().getType().equals(Material.DARK_OAK_BUTTON)) {
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.reset-tag-material")).toUpperCase()))) {
if (!SupremeTags.getInstance().getConfig().getBoolean("settings.forced-tag")) {
UserData.setActive(player, "None");
player.closeInventory();
super.open();
menuUtil.setIdentifier("None");
}
} else if (e.getCurrentItem().getType().equals(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.back-next-material")).toUpperCase()))) {
if (ChatColor.stripColor(Objects.requireNonNull(e.getCurrentItem().getItemMeta()).getDisplayName()).equalsIgnoreCase("Back")) {
if (page != 0) {
page = page - 1;
@@ -78,42 +83,311 @@ public class TagMenu extends Paged {
@Override
public void setMenuItems() {
addBottom();
applyLayout();
ArrayList<String> tag = new ArrayList<>(tags.keySet());
if (!tag.isEmpty()) {
for(int i = 0; i < getMaxItems(); i++) {
index = getMaxItems() * page + i;
if(index >= tag.size()) break;
if (tag.get(index) != null){
int maxTagsPerPage = getMaxItems();
int pageNumber = 1;
if (menuUtil.getOwner().hasPermission("playertags.tag." + tag.get(index))) {
for (int i = 0; i < maxTagsPerPage; i++) {
int index = (pageNumber - 1) * maxTagsPerPage + i;
ItemStack tagItem = new ItemStack(Material.NAME_TAG, 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
tagMeta.setDisplayName(format("&7Tag: " + tags.get(tag.get(index)).getTag()));
if (index >= tags.size()) {
break;
}
tagMeta.getPersistentDataContainer().set(new NamespacedKey(SupremeTags.getInstance(), "identifier"), PersistentDataType.STRING, tags.get(tag.get(index)).getIdentifier());
Tag t = tags.get(tag.get(index));
String identifier = Objects.requireNonNull(tagItem.getItemMeta()).getPersistentDataContainer().get(new NamespacedKey(SupremeTags.getInstance(), "identifier"), PersistentDataType.STRING);
String permission = SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".permission");
if (UserData.getActive(menuUtil.getOwner()).equals(identifier)) {
tagItem.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 1);
String displayname;
if (SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".displayname") != null) {
displayname = Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".displayname")).replace("%tag%", t.getTag());
} else {
displayname = format("&7Tag: " + tags.get(tag.get(index)).getTag());
}
String material;
if (SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".display-item") != null) {
material = SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".display-item");
} else {
material = "NAME_TAG";
}
assert permission != null;
// toggle if they don't have permission
if (menuUtil.getOwner().hasPermission(permission) && !permission.equalsIgnoreCase("none")) {
if (UserData.getActive(menuUtil.getOwner().getUniqueId()).equalsIgnoreCase(tag.get(index))) {
if (material.contains("hdb-")) {
HeadDatabaseAPI api = new HeadDatabaseAPI();
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
if (SupremeTags.getInstance().getConfig().getBoolean("settings.active-tag-glow")) {
nbt.getItem().addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
}
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
} else {
if (material.contains("hdb-")) {
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
tagItem.setItemMeta(tagMeta);
inventory.addItem(tagItem);
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
}
// if permission == none
} else if (!menuUtil.getOwner().hasPermission(permission) && permission.equalsIgnoreCase("none")) {
if (UserData.getActive(menuUtil.getOwner().getUniqueId()).equalsIgnoreCase(tag.get(index))) {
if (material.contains("hdb-")) {
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
if (SupremeTags.getInstance().getConfig().getBoolean("settings.active-tag-glow")) {
nbt.getItem().addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
}
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
} else {
if (material.contains("hdb-")) {
int id = Integer.parseInt(material.replaceAll("hdb-", ""));
HeadDatabaseAPI api = new HeadDatabaseAPI();
ItemStack tagItem = api.getItemHead(String.valueOf(id));
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
} else {
ItemStack tagItem = new ItemStack(Material.valueOf(material.toUpperCase()), 1);
ItemMeta tagMeta = tagItem.getItemMeta();
assert tagMeta != null;
NBTItem nbt = new NBTItem(tagItem);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
tagMeta.setDisplayName(format(displayname));
tagMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
tagMeta.addItemFlags(ItemFlag.HIDE_DYE);
tagMeta.addItemFlags(ItemFlag.HIDE_DESTROYS);
tagMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
// set lore
ArrayList<String> lore = (ArrayList<String>) SupremeTags.getInstance().getConfig().getStringList("gui.tag-menu-none-categories.tag-item.lore");
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%description%", format(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("tags." + tag.get(index) + ".description")))));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%identifier%", tags.get(tag.get(index)).getIdentifier()));
lore.replaceAll(s -> ChatColor.translateAlternateColorCodes('&', s).replaceAll("%tag%", tags.get(tag.get(index)).getTag()));
tagMeta.setLore(color(lore));
nbt.getItem().setItemMeta(tagMeta);
nbt.setString("identifier", tags.get(tag.get(index)).getIdentifier());
inventory.addItem(nbt.getItem());
}
}
}
}
}
}
}
}
@@ -0,0 +1,30 @@
package net.noscape.project.supremetags.handlers;
import java.util.*;
public class Category {
private String category;
private List<String> tags;
public Category(String category, List<String> tags) {
this.category = category;
this.tags = tags;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
@@ -4,10 +4,14 @@ public class Tag {
private String identifier;
private String tag;
private String category;
private String permission;
public Tag(String identifier, String tag) {
public Tag(String identifier, String tag, String category, String permission) {
this.identifier = identifier;
this.tag = tag;
this.category = category;
this.permission = permission;
}
public String getIdentifier() {
@@ -26,4 +30,20 @@ public class Tag {
this.tag = tag;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
}
@@ -38,33 +38,17 @@ public class PAPI extends PlaceholderExpansion {
}
@Override
public String onRequest(OfflinePlayer player, String params) {
public String onRequest(OfflinePlayer player, @NotNull String params) {
if (params.equalsIgnoreCase("tag")) {
String text;
if (UserData.getActive(Objects.requireNonNull(player.getPlayer())).equalsIgnoreCase("None")) {
text = "";
} else {
text = tags.get(UserData.getActive(player.getPlayer())).getTag();
String text = "";
if (!UserData.getActive(player.getUniqueId()).equalsIgnoreCase("None")) {
if (params.equalsIgnoreCase("tag")) {
text = tags.get(UserData.getActive(player.getUniqueId())).getTag();
} else if (params.equalsIgnoreCase("identifier")) {
text = UserData.getActive(player.getUniqueId());
}
return text;
}
if (params.equalsIgnoreCase("identifier")) {
String text;
if (UserData.getActive(Objects.requireNonNull(player.getPlayer())).equalsIgnoreCase("None")) {
text = "";
} else {
text = UserData.getActive(player.getPlayer());
}
return text;
}
return null;
return text;
}
}
@@ -1,5 +1,6 @@
package net.noscape.project.supremetags.handlers.menu;
import net.noscape.project.supremetags.*;
import org.bukkit.*;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.*;
@@ -12,7 +13,7 @@ public abstract class Menu implements InventoryHolder {
protected Inventory inventory;
protected MenuUtil menuUtil;
protected ItemStack GLASS = makeItem(Material.GRAY_STAINED_GLASS_PANE, " ");
protected ItemStack GLASS = makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.glass-material")).toUpperCase()), " ");
public Menu(MenuUtil menuUtil) {
this.menuUtil = menuUtil;
@@ -35,6 +36,11 @@ public abstract class Menu implements InventoryHolder {
menuUtil.getOwner().openInventory(inventory);
}
public void refresh() {
menuUtil.getOwner().updateInventory();
}
@Override
public Inventory getInventory() {
return inventory;
@@ -6,6 +6,13 @@ public class MenuUtil {
private Player owner;
private String identifier;
private String category;
public MenuUtil(Player owner, String identifier, String category) {
this.owner = owner;
this.identifier = identifier;
this.category = category;
}
public MenuUtil(Player owner, String identifier) {
this.owner = owner;
@@ -27,4 +34,12 @@ public class MenuUtil {
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
@@ -1,8 +1,11 @@
package net.noscape.project.supremetags.handlers.menu;
import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.storage.*;
import org.bukkit.*;
import java.util.*;
import static net.noscape.project.supremetags.utils.Utils.format;
public abstract class Paged extends Menu {
@@ -15,26 +18,65 @@ public abstract class Paged extends Menu {
super(menuUtil);
}
public void addBottom() {
inventory.setItem(48, makeItem(Material.DARK_OAK_BUTTON, ChatColor.GRAY + "Back"));
public void applyLayout() {
if (SupremeTags.getLayout().equalsIgnoreCase("layout1")) {
inventory.setItem(48, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.back-next-material")).toUpperCase()), ChatColor.GRAY + "Back"));
inventory.setItem(49, makeItem(Material.BARRIER, ChatColor.RED + "Close"));
inventory.setItem(49, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.close-menu-material")).toUpperCase()), ChatColor.RED + "Close"));
inventory.setItem(50, makeItem(Material.DARK_OAK_BUTTON, ChatColor.GRAY + "Next"));
inventory.setItem(50, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.back-next-material")).toUpperCase()), ChatColor.GRAY + "Next"));
inventory.setItem(46, makeItem(Material.RED_DYE, ChatColor.RED + "Reset Tag"));
if (!SupremeTags.getInstance().getConfig().getBoolean("settings.forced-tag")) {
inventory.setItem(46, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.reset-tag-material")).toUpperCase()), ChatColor.RED + "Reset Tag"));
}
inventory.setItem(52, makeItem(Material.NAME_TAG, format("&7Active: &6" + UserData.getActive(menuUtil.getOwner()))));
inventory.setItem(45, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.refresh-material")).toUpperCase()), ChatColor.GREEN + "Refresh Menu"));
inventory.setItem(36, super.GLASS);
inventory.setItem(37, super.GLASS);
inventory.setItem(38, super.GLASS);
inventory.setItem(39, super.GLASS);
inventory.setItem(40, super.GLASS);
inventory.setItem(41, super.GLASS);
inventory.setItem(42, super.GLASS);
inventory.setItem(43, super.GLASS);
inventory.setItem(44, super.GLASS);
inventory.setItem(52, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.tag-material")).toUpperCase()), format("&7Active: &6" + UserData.getActive(menuUtil.getOwner().getUniqueId()))));
inventory.setItem(36, super.GLASS);
inventory.setItem(37, super.GLASS);
inventory.setItem(38, super.GLASS);
inventory.setItem(39, super.GLASS);
inventory.setItem(40, super.GLASS);
inventory.setItem(41, super.GLASS);
inventory.setItem(42, super.GLASS);
inventory.setItem(43, super.GLASS);
inventory.setItem(44, super.GLASS);
} else if (SupremeTags.getLayout().equalsIgnoreCase("layout2")) {
inventory.setItem(3, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.back-next-material")).toUpperCase()), ChatColor.GRAY + "Back"));
inventory.setItem(4, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.close-menu-material")).toUpperCase()), ChatColor.RED + "Close"));
inventory.setItem(5, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.back-next-material")).toUpperCase()), ChatColor.GRAY + "Next"));
if (!SupremeTags.getInstance().getConfig().getBoolean("settings.forced-tag")) {
inventory.setItem(1, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.reset-tag-material")).toUpperCase()), ChatColor.RED + "Reset Tag"));
} else {
inventory.setItem(1, super.GLASS);
}
inventory.setItem(0, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.refresh-material")).toUpperCase()), ChatColor.GREEN + "Refresh Menu"));
inventory.setItem(7, makeItem(Material.valueOf(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getString("gui.layout.tag-material")).toUpperCase()), format("&7Active: &6" + UserData.getActive(menuUtil.getOwner().getUniqueId()))));
inventory.setItem(2, super.GLASS);
inventory.setItem(6, super.GLASS);
inventory.setItem(8, super.GLASS);
inventory.setItem(9, super.GLASS);
inventory.setItem(10, super.GLASS);
inventory.setItem(11, super.GLASS);
inventory.setItem(12, super.GLASS);
inventory.setItem(13, super.GLASS);
inventory.setItem(14, super.GLASS);
inventory.setItem(15, super.GLASS);
inventory.setItem(16, super.GLASS);
inventory.setItem(17, super.GLASS);
}
}
protected int getPage() {
return page + 1;
}
public int getMaxItems() {
@@ -1,31 +1,54 @@
package net.noscape.project.supremetags.listeners;
import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.handlers.*;
import net.noscape.project.supremetags.storage.*;
import org.bukkit.event.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.player.*;
import static net.noscape.project.supremetags.utils.Utils.format;
import java.util.*;
import static net.noscape.project.supremetags.utils.Utils.*;
public class PlayerEvents implements Listener {
private final Map<String, Tag> tags;
public PlayerEvents() {
tags = SupremeTags.getInstance().getTagManager().getTags();
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
SupremeTags.getInstance().getUserData().createPlayer(player);
UserData.createPlayer(player);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
String format = e.getFormat();
if (UserData.getActive(player).equals("None")) {
e.setFormat(format.replace("{tag}", "").replace("{supremetags_tag}", ""));
// Store the value of UserData.getActive(player.getUniqueId()) in a local variable
String activeTag = UserData.getActive(player.getUniqueId());
String replace = format.replace("{tag}", "").replace("{supremetags_tag}", "").replace("{TAG}", "");
if (activeTag == null || activeTag.equalsIgnoreCase("None")) {
e.setFormat(replace);
} else {
e.setFormat(format.replace("{tag}", format(SupremeTags.getInstance().getTagManager().getTags().get(UserData.getActive(player)).getTag())).replace("{supremetags_tag}", format(SupremeTags.getInstance().getTagManager().getTags().get(UserData.getActive(player)).getTag())));
// Store the value of SupremeTags.getInstance().getTagManager().getTags().get(activeTag) in a local variable
Tag tag = SupremeTags.getInstance().getTagManager().getTags().get(activeTag);
if (tag == null) {
e.setFormat(replace);
} else {
// Store the value of format(twag.getTag()) in a local variable
String formattedTag = format(tag.getTag());
e.setFormat(format.replace("{tag}", formattedTag).replace("{supremetags_tag}", formattedTag).replace("{TAG}", formattedTag));
}
}
}
public Map<String, Tag> getTags() {
return tags;
}
}
@@ -0,0 +1,43 @@
package net.noscape.project.supremetags.managers;
import net.noscape.project.supremetags.*;
import java.util.*;
public class CategoryManager {
private final List<String> catorgies = new ArrayList<>();
private final Map<String, Integer> catorgiesTags = new HashMap<>();
public CategoryManager() {}
public void loadCategories() {
catorgies.clear();
catorgies.addAll(Objects.requireNonNull(SupremeTags.getInstance().getConfig().getConfigurationSection("categories")).getKeys(false));
}
public void loadCategoriesTags() {
catorgiesTags.clear();
for (String cats : getCatorgies()) {
int value = 0;
for (String tags : Objects.requireNonNull(SupremeTags.getInstance().getConfig().getConfigurationSection("tags")).getKeys(false)) {
String cat = SupremeTags.getInstance().getConfig().getString("tags." + tags + ".category");
if (cats.equals(cat)) {
value++;
}
}
catorgiesTags.put(cats, value);
}
}
public List<String> getCatorgies() {
return catorgies;
}
public Map<String, Integer> getCatorgiesTags() {
return catorgiesTags;
}
}
@@ -4,6 +4,7 @@ import net.noscape.project.supremetags.*;
import net.noscape.project.supremetags.handlers.Tag;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.entity.*;
import java.util.*;
@@ -13,13 +14,26 @@ import static net.noscape.project.supremetags.utils.Utils.msgPlayer;
public class TagManager {
private final Map<String, Tag> tags = new HashMap<>();
private final Map<Integer, String> dataItem = new HashMap<>();
public void createTag(Player player, String identifier, String tag_string) {
public TagManager() {
this.sort();
}
public void createTag(Player player, String identifier, String tag_string, String description, String permission) {
if (!tags.containsKey(identifier)) {
Tag tag = new Tag(identifier, tag_string);
String default_category = SupremeTags.getInstance().getConfig().getString("settings.default-category");
Tag tag = new Tag(identifier, tag_string, default_category, permission);
tags.put(identifier, tag);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".tag", tag_string);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".permission", permission);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".description", description);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".category", default_category);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".display-item", "NAME_TAG");
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".displayname", "&7Tag: %tag%");
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
@@ -29,6 +43,62 @@ public class TagManager {
}
}
public void createTag(CommandSender player, String identifier, String tag_string, String description, String permission) {
if (!tags.containsKey(identifier)) {
String default_category = SupremeTags.getInstance().getConfig().getString("settings.default-category");
Tag tag = new Tag(identifier, tag_string, default_category, permission);
tags.put(identifier, tag);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".tag", tag_string);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".permission", permission);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".description", description);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".category", default_category);
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
msgPlayer(player, "&6[TAG] &7New tag created &6" + identifier + " &f- " + tag_string);
} else {
msgPlayer(player, "&c[&l!&c] &7This tag already exists.");
}
}
public void createTag(String identifier, String tag_string, String description, String permission) {
if (!tags.containsKey(identifier)) {
String default_category = SupremeTags.getInstance().getConfig().getString("settings.default-category");
Tag tag = new Tag(identifier, tag_string, default_category, permission);
tags.put(identifier, tag);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".tag", tag_string);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".permission", permission);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".description", description);
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".category", default_category);
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
}
}
public void deleteTag(CommandSender player, String identifier) {
if (tags.containsKey(identifier)) {
tags.remove(identifier);
try {
SupremeTags.getInstance().getConfig().set("tags." + identifier, null);
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
} catch (Exception e) {
e.printStackTrace();
}
msgPlayer(player, "&6[TAG] &7Tag &6" + identifier + " &7is now deleted!");
} else {
msgPlayer(player, "&c[&l!&c] &7This tag doesn't exist!");
}
}
public void deleteTag(Player player, String identifier) {
if (tags.containsKey(identifier)) {
tags.remove(identifier);
@@ -51,8 +121,10 @@ public class TagManager {
int count = 0;
for (String identifier : Objects.requireNonNull(SupremeTags.getInstance().getConfig().getConfigurationSection("tags")).getKeys(false)) {
String tag = SupremeTags.getInstance().getConfig().getString("tags." + identifier + ".tag");
String category = SupremeTags.getInstance().getConfig().getString("tags." + identifier + ".category");
String permission = SupremeTags.getInstance().getConfig().getString("tags." + identifier + ".permission");
Tag t = new Tag(identifier, tag);
Tag t = new Tag(identifier, tag, category, permission);
tags.put(identifier, t);
count++;
@@ -70,6 +142,7 @@ public class TagManager {
public Map<String, Tag> getTags() {
return tags;
}
public Map<Integer, String> getDataItem() { return dataItem; }
public void setTag(Player player, String identifier, String tag) {
if (tags.containsKey(identifier)) {
@@ -90,4 +163,52 @@ public class TagManager {
}
}
public void setCategory(Player player, String identifier, String category) {
if (tags.containsKey(identifier)) {
Tag t = tags.get(identifier);
t.setCategory(category);
try {
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".category", t.getCategory());
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
} catch (Exception e) {
e.printStackTrace();
}
msgPlayer(player, "&6[TAG] &6" + t.getIdentifier() + "'s category &7changed to " + t.getCategory());
} else {
msgPlayer(player, "&6[TAG] &7This category doesn't exist!");
}
}
public void setTag(CommandSender player, String identifier, String tag) {
if (tags.containsKey(identifier)) {
Tag t = tags.get(identifier);
t.setTag(tag);
try {
SupremeTags.getInstance().getConfig().set("tags." + identifier + ".tag", t.getTag());
SupremeTags.getInstance().saveConfig();
SupremeTags.getInstance().reloadConfig();
} catch (Exception e) {
e.printStackTrace();
}
msgPlayer(player, "&6[TAG] &6" + t.getIdentifier() + "'s tag &7changed to " + t.getTag());
} else {
msgPlayer(player, "&6[TAG] &7This tag doesn't exist!");
}
}
public void sort() {
// Create a comparator that compares Map.Entry objects by their key in ascending order
Comparator<Map.Entry<String, Tag>> comparator = Map.Entry.comparingByKey();
// Create a sorted set with the comparator
SortedSet<Map.Entry<String, Tag>> sortedSet = new TreeSet<>(comparator);
// Add all the entries from the tags map to the sorted set
sortedSet.addAll(tags.entrySet());
}
}
@@ -34,7 +34,7 @@ public class Database {
PreparedStatement preparedStatement;
String userTable = "CREATE TABLE IF NOT EXISTS `users` " +
"(`Name` VARCHAR(100), `UUID` VARCHAR(100), `Active` VARCHAR(100))";
"(`Name` VARCHAR(100), `UUID` VARCHAR(100) primary key, `Active` VARCHAR(100))";
try {
preparedStatement = getConnection().prepareStatement(userTable);
@@ -0,0 +1,51 @@
package net.noscape.project.supremetags.storage;
import net.noscape.project.supremetags.*;
import java.sql.*;
public class H2Database {
private final String ConnectionURL;
public H2Database(String connectionURL) {
ConnectionURL = connectionURL;
this.initialiseDatabase();
}
public Connection getConnection() {
Connection connection = null;
try {
Class.forName("org.h2.Driver");
connection = DriverManager.getConnection(SupremeTags.getConnectionURL());
} catch (SQLException | ClassNotFoundException throwables) {
throwables.printStackTrace();
SupremeTags.getInstance().getLogger().info("------------------------------");
SupremeTags.getInstance().getLogger().info("H2: Something wrong with connecting to h2-sql for SupremeTags, contact the developer if you see this.");
SupremeTags.getInstance().getLogger().info("------------------------------");
}
return connection;
}
public void initialiseDatabase() {
PreparedStatement preparedStatement;
String userTable = "CREATE TABLE IF NOT EXISTS `users` " +
"(`Name` VARCHAR(100), `UUID` VARCHAR(100) primary key, `Active` VARCHAR(100))";
try {
preparedStatement = getConnection().prepareStatement(userTable);
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public String getConnectionURL() {
return ConnectionURL;
}
}
@@ -0,0 +1,72 @@
package net.noscape.project.supremetags.storage;
import net.noscape.project.supremetags.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import java.sql.*;
import java.util.*;
public class H2UserData {
public boolean exists(Player player) {
try {
PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement("SELECT * FROM `users` WHERE (UUID=?)");
statement.setString(1, player.getUniqueId().toString());
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public void createPlayer(Player player) {
if (exists(player)) {
return;
}
String defaultTag = SupremeTags.getInstance().getConfig().getString("settings.default-tag");
try (PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement(
"INSERT INTO `users` (Name, UUID, Active) VALUES (?,?,?)")) {
statement.setString(1, player.getName());
statement.setString(2, player.getUniqueId().toString());
statement.setString(3, defaultTag);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void setActive(OfflinePlayer player, String identifier) {
String sql = "UPDATE `users` SET Active=? WHERE (UUID=?)";
try (PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement(sql)) {
statement.setString(1, identifier);
statement.setString(2, player.getUniqueId().toString());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static String getActive(UUID uuid) {
String value = "";
String query = "SELECT * FROM `users` WHERE (UUID=?)";
try (PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement(query)) {
statement.setString(1, uuid.toString());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
value = resultSet.getString("Active");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return value;
}
}
@@ -0,0 +1,132 @@
package net.noscape.project.supremetags.storage;
import net.noscape.project.supremetags.*;
import org.bukkit.*;
import java.sql.*;
import java.util.logging.*;
public class MySQL {
private final String host;
private final int port;
private final String database;
private final String username;
private final String password;
private final String options;
public Connection connection;
private boolean isconnected = false;
public MySQL(String host, int port, String database, String username, String password, String options) {
this.host = host;
this.port = port;
this.database = database;
this.username = username;
this.password = password;
this.options = options;
this.connect(host, port, database, username, password, true);
}
public void openConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
this.connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?" + options, username, password);
}
}
public void connect(String host, int port, String database, String user, String pass, boolean ssl) {
try {
synchronized (this) {
if (connection != null && !connection.isClosed()) {
Logger.getLogger("Error: connection to sql was not successful.");
return;
}
Class.forName("com.mysql.cj.jdbc.Driver");
this.connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=" + ssl + "&autoReconnect=true", user, pass);
this.isconnected = true;
createTable();
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
Bukkit.getConsoleSender().sendMessage("MYSQL: Something wrong with connecting to mysql database type, check mysql data details before contacting the developer if you see this.");
}
}
public void createTable() throws SQLException {
String userTable = "CREATE TABLE IF NOT EXISTS `users` " +
"(`Name` VARCHAR(100), `UUID` VARCHAR(100) primary key, `Active` VARCHAR(100))";
Statement stmt = connection.createStatement();
stmt.execute(userTable);
}
public void updateQuery(String query) {
Connection con = connection;
PreparedStatement preparedStatement = null;
try {
preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResources(null, preparedStatement);
}
}
public void disconnected() {
try {
if (isConnected()) {
this.connection.close();
this.isconnected = false;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String query) {
if (isConnected()) {
return null;
} else {
try {
this.connection.createStatement().executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
public void closeResources(ResultSet rs, PreparedStatement st) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public boolean isConnected() {
return !this.isconnected;
}
public Connection getConnection() {
return this.connection;
}
}
@@ -0,0 +1,71 @@
package net.noscape.project.supremetags.storage;
import net.noscape.project.supremetags.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import java.sql.*;
import java.util.*;
public class MySQLUserData {
public boolean exists(Player player) {
try {
PreparedStatement statement = SupremeTags.getMysql().getConnection().prepareStatement("SELECT * FROM `users` WHERE (UUID=?)");
statement.setString(1, player.getUniqueId().toString());
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public void createPlayer(Player player) {
if (exists(player)) {
return;
}
String defaultTag = SupremeTags.getInstance().getConfig().getString("settings.default-tag");
try (PreparedStatement statement = SupremeTags.getMysql().getConnection().prepareStatement(
"INSERT INTO `users` (Name, UUID, Active) VALUES (?,?,?)")) {
statement.setString(1, player.getName());
statement.setString(2, player.getUniqueId().toString());
statement.setString(3, defaultTag);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void setActive(OfflinePlayer player, String identifier) {
String sql = "UPDATE `users` SET Active=? WHERE (UUID=?)";
try (PreparedStatement statement = SupremeTags.getMysql().getConnection().prepareStatement(sql)) {
statement.setString(1, identifier);
statement.setString(2, player.getUniqueId().toString());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static String getActive(UUID uuid) {
String value = "";
String query = "SELECT * FROM `users` WHERE (UUID=?)";
try (PreparedStatement statement = SupremeTags.getMysql().getConnection().prepareStatement(query)) {
statement.setString(1, uuid.toString());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
value = resultSet.getString("Active");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return value;
}
}
@@ -1,71 +1,35 @@
package net.noscape.project.supremetags.storage;
import net.noscape.project.supremetags.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import java.sql.*;
import java.util.*;
public class UserData {
public boolean exists(Player player) {
try {
PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement("SELECT * FROM `users` WHERE (UUID=?)");
statement.setString(1, player.getUniqueId().toString());
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public void createPlayer(Player player) {
try {
if (!exists(player)) {
PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement(
"INSERT INTO `users` " +
"(Name, UUID, Active) " +
"VALUES " +
"(?,?,?)");
statement.setString(1, player.getName());
statement.setString(2, player.getUniqueId().toString());
statement.setString(3, "None");
statement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
public static void createPlayer(Player player) {
if (SupremeTags.getInstance().isH2()) {
SupremeTags.getInstance().getUserData().createPlayer(player);
} else if (SupremeTags.getInstance().isMySQL()) {
SupremeTags.getInstance().getUser().createPlayer(player);
}
}
public static void setActive(Player player, String identifier) {
try {
PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement("UPDATE `users` SET Active=? WHERE (UUID=?)");
statement.setString(1, identifier);
statement.setString(2, player.getUniqueId().toString());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
public static void setActive(OfflinePlayer player, String identifier) {
if (SupremeTags.getInstance().isH2()) {
H2UserData.setActive(player, identifier);
} else if (SupremeTags.getInstance().isMySQL()) {
MySQLUserData.setActive(player, identifier);
}
}
public static String getActive(Player player) {
try {
PreparedStatement statement = SupremeTags.getDatabase().getConnection().prepareStatement("SELECT * FROM `users` WHERE (UUID=?)");
statement.setString(1, player.getUniqueId().toString());
ResultSet resultSet = statement.executeQuery();
String value;
if (resultSet.next()) {
value = resultSet.getString("Active");
return value;
}
} catch (SQLException e) {
e.printStackTrace();
}
public static String getActive(UUID uuid) {
if (SupremeTags.getInstance().isH2())
return H2UserData.getActive(uuid);
else if (SupremeTags.getInstance().isMySQL())
return MySQLUserData.getActive(uuid);
return "";
}
}
@@ -1,25 +1,43 @@
package net.noscape.project.supremetags.utils;
import net.md_5.bungee.api.ChatColor;
import net.noscape.project.supremetags.*;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.entity.*;
import java.util.*;
import java.util.regex.*;
import java.util.stream.*;
public class Utils {
public static String format(String message) {
message = message.replace(">>", "").replace("<<", "");
Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]){6}");
Matcher matcher = hexPattern.matcher(message);
while (matcher.find()) {
ChatColor hexColor = ChatColor.of(matcher.group().substring(1));
String before = message.substring(0, matcher.start());
String after = message.substring(matcher.end());
message = before + hexColor + after;
matcher = hexPattern.matcher(message);
if (SupremeTags.getInstance().isLegacyFormat()) {
message = message.replace(">>", "").replace("<<", "");
Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]){6}");
Matcher matcher = hexPattern.matcher(message);
while (matcher.find()) {
ChatColor hexColor = ChatColor.of(matcher.group().substring(1));
String before = message.substring(0, matcher.start());
String after = message.substring(matcher.end());
message = before + hexColor + after;
matcher = hexPattern.matcher(message);
}
return ChatColor.translateAlternateColorCodes('&', message);
} else {
message = message.replace(">>", "").replace("<<", "");
Pattern hexPattern = Pattern.compile("#([A-Fa-f0-9]){6}");
Matcher matcher = hexPattern.matcher(message);
while (matcher.find()) {
ChatColor hexColor = ChatColor.of(matcher.group().substring(1));
String before = message.substring(0, matcher.start());
String after = message.substring(matcher.end());
message = before + hexColor + after;
matcher = hexPattern.matcher(message);
}
return ChatColor.translateAlternateColorCodes('&', message);
}
return ChatColor.translateAlternateColorCodes('&', message);
}
public static String deformat(String str) {
@@ -32,6 +50,12 @@ public class Utils {
}
}
public static void msgPlayer(CommandSender player, String... str) {
for (String msg : str) {
player.sendMessage(format(msg));
}
}
public static void titlePlayer(Player player, String title, String subtitle, int fadeIn, int stay, int fadeOut) {
player.sendTitle(format(title), format(subtitle), fadeIn, stay, fadeOut);
}
@@ -40,4 +64,8 @@ public class Utils {
player.playSound(player.getLocation(), sound, volume, pitch);
}
public static List<String> color(List<String> lore){
return lore.stream().map(Utils::format).collect(Collectors.toList());
}
}
+148 -52
View File
@@ -1,53 +1,149 @@
# permission: playertags.tag.<identifier>
# - to make things easier, keep all identifier names lowercase.
############################################################
# +------------------------------------------------------+ #
# | Settings | #
# +------------------------------------------------------+ #
############################################################
settings:
default-tag: 'none' # set 'none' players start with no tag.
forced-tag: false # this will make it force players to have a tag, they won't beable to take the tag off.
categories: false # should supremetags use the category system?
default-category: 'default' # used to set the tags category value when creating a new tag with the '/tag create' command
layout: 'layout1' # layouts: [layout1(default), layout2(new)]
update-check: true # the plugin will check if there is an update available.
legacy-hex-format: true # should the plugin use the legacy hex colors? (&#d5b47 instead of #d5b47)
auto-merge: false # auto merges all tags from deluxetags into supremetags (DeluxeTags is required on the server)
active-tag-glow: true # adds an hidden enchantment to the tag item that is active for the player.
############################################################
# +------------------------------------------------------+ #
# | Data | #
# +------------------------------------------------------+ #
############################################################
# mysql data settings.
# make sure you can check your panel database info to make sure everything is correct.
data:
# types: [H2 OR MYSQL]
type: 'H2'
# The address for the database server.
# - to enable this part, change type to 'MYSQL'
# - some hosts can use your domain or server ip.
address: 'host'
# The standard DB engine port is used by default
port: 3306
# The name of the database to store tag data in.
database: 'database'
# Credentials for the database.
username: 'user'
password: 'pass'
# leave this, if you don't know how to use options.
options: 'useSSL=false&autoReconnect=true'
############################################################
# +------------------------------------------------------+ #
# | Gui | #
# +------------------------------------------------------+ #
############################################################
gui:
main-menu:
title: '&8Main Menu'
size: 27
tag-menu-none-categories:
title: '&8Tag Menu'
tag-item:
displayname: '&7Tag: %tag%'
lore:
- '&7&m-----------------------------'
- ''
- '&bIdentifier: &7%identifier%'
- ''
- '&dDescription:'
- '&7%description%'
- ''
- '&7&m-----------------------------'
layout:
glass-material: 'GRAY_STAINED_GLASS_PANE'
tag-material: 'NAME_TAG'
back-next-material: 'DARK_OAK_BUTTON'
reset-tag-material: 'RED_DYE'
close-menu-material: 'BARRIER'
create-tag-material: 'NAME_TAG'
refresh-material: 'GREEN_DYE'
############################################################
# +------------------------------------------------------+ #
# | Categories | #
# +------------------------------------------------------+ #
############################################################
categories:
default:
title: '&8Default Tags' # title of the category gui.
material: 'NAME_TAG' # item material.
id_display: '&7&lDefault Tags' # item displayname.
slot: 11 # slot this item will be in the main menu.
lore:
- '&8&m-----------------------------'
- ''
- '&7Default tags: &7%tags_amount%'
- ''
- '&8&m-----------------------------'
permission: 'supremetags.category.default' # permission players will need to open this menu
permission-see-category: false # if set true and if player doesn't have the permission `supremetags.category.<category>` they will not see it.
rank:
title: '&8Rank Tags' # title of the category gui.
material: 'NAME_TAG' # item material.
id_display: '&6&lRank Tags' # item displayname.
slot: 13 # slot this item will be in the main menu.
lore:
- '&8&m-----------------------------'
- ''
- '&6Rank tags: &7%tags_amount%'
- ''
- '&8&m-----------------------------'
permission: 'supremetags.category.rank' # permission players will need to open this menu
permission-see-category: false # if set true and if player doesn't have the permission `supremetags.category.<category>` they will not see it.
xmas:
title: '&8Christmas Tags' # title of the category gui.
material: 'NAME_TAG' # item material.
id_display: '&c&lChristmas Tags' # item displayname.
slot: 15 # slot this item will be in the main menu.
lore:
- '&8&m-----------------------------'
- ''
- '&cChristmas tags: &7%tags_amount%'
- ''
- '&8&m-----------------------------'
permission: 'supremetags.category.xmas' # permission players will need to open this menu
permission-see-category: false # if set true and if player doesn't have the permission `supremetags.category.<category>` they will not see it.
############################################################
# +------------------------------------------------------+ #
# | Tags | #
# +------------------------------------------------------+ #
############################################################
tags:
love: # playertags.tag.love
tag: '&8[&c&lLove&8]' # the tag that will be display for 'legend'
legend: # playertags.tag.legend
tag: '&8[&6&lLegend&8]' # the tag that will be display for 'legend'
pro:
tag: '&8[&cPro&8]'
yolo:
tag: '&8[&eYolo&8]'
bear:
tag: '&8[&6Bear&8]'
noob:
tag: '&8[&dNoob&8]'
bae:
tag: '&8[&cBae&8]'
'420':
tag: '&8[&a420&8]'
lol:
tag: '&8[&eLoL&8]'
savage:
tag: '&8[&4Savage&8]'
elo:
tag: '&8[&6Elo&8]'
babyrage:
tag: '&8[&eBabyRage&8]'
og:
tag: '&8[&2OG&8]'
nerd:
tag: '&8[&dNerd&8]'
troll:
tag: '&8[&aTroll&8]'
minecraft:
tag: '&8[&fMinecraft&8]'
rudolph:
tag: '&8[&6Rudolph&8]'
ninja:
tag: '&8[&bNinja&8]'
elmo:
tag: '&8[&dElmo&8]'
memes:
tag: '&8[&5Memes&8]'
notch:
tag: '&8[&6Notch&8]'
master:
tag: '&8[&cMaster&8]'
halloween:
tag: '&7[&cHall&4oween&7]'
snowman:
tag: '&7[&fSnow&bMan&7]'
santa:
tag: '&f[&cSanta&f]'
hexsupport: # 1.16+ server is required for hex colors to work.
tag: '&8[&#afe4a4&lH&#b1cdb1&le&#b3b6bd&lx&#b59fca&lC&#b688d7&lo&#b871e3&ll&#ba5af0&lo&#bc43fd&lr&8]'
permission: 'supremetags.tag.hex'
description: '&7This plugin supports normal color codes(&a-f/&0-9) and hex color codes(&#123456)'
category: 'default'
displayname: '&7Tag: %tag%'
display-item: 'NAME_TAG'
headdatabasesupport: # HeadDatabase is required for this to work.
tag: '&8[&c&lHeadDatabase&8]'
permission: 'supremetags.tag.headdb'
description: '&7This plugin supports head database!'
category: 'default'
displayname: '&7Tag: %tag%'
display-item: 'hdb-7129'
santa: # christmas themed tag, shows in the xmas category.
tag: '&8[&c&lSanta&8]'
permission: 'supremetags.tag.santa'
description: '&7ho ho hooooooo!'
category: 'xmas'
displayname: '&7Tag: %tag%'
display-item: 'NAME_TAG'
+3 -2
View File
@@ -2,9 +2,10 @@ name: SupremeTags
version: '${project.version}'
main: net.noscape.project.supremetags.SupremeTags
api-version: 1.13
softdepend: [PlaceholderAPI]
depend: [NBTAPI]
softdepend: [PlaceholderAPI, HeadDatabase]
authors: [NoScape]
description: Allow player to show of their supreme tags!
description: Allow players to show of their supreme tags!
commands:
tags:
View File
Whitespace-only changes.