Skip to content

Commit

Permalink
TagUser Object & Default Tag Groups
Browse files Browse the repository at this point in the history
  • Loading branch information
Robin committed Apr 4, 2023
1 parent fba6dd5 commit 875ea46
Show file tree
Hide file tree
Showing 10 changed files with 428 additions and 74 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ dependencies {
compileOnly 'io.papermc.paper:paper-api:1.19.3-R0.1-SNAPSHOT'
compileOnly 'org.jetbrains:annotations:23.0.0'

// Plugins
compileOnly 'com.github.MilkBowl:VaultAPI:1.7'
compileOnly 'me.clip:placeholderapi:2.11.3'
compileOnly "com.github.oraxen:oraxen:afc4903680"
compileOnly 'com.arcaniax:HeadDatabase-API:1.3.1', {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/xyz/oribuin/eternaltags/EternalTags.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ public void enable() {
// Make sure the server has PlaceholderAPI
if (!pluginManager.isPluginEnabled("PlaceholderAPI")) {
this.getLogger().severe("Please install PlaceholderAPI onto your server to use this plugin.");
this.getServer().getPluginManager().disablePlugin(this);
pluginManager.disablePlugin(this);
return;
}

// Make sure the server is on MC 1.16
if (NMSUtil.getVersionNumber() < 16) {
this.getLogger().severe("This plugin only supports 1.16+ Minecraft.");
this.getServer().getPluginManager().disablePlugin(this);
pluginManager.disablePlugin(this);
return;
}

Expand Down
11 changes: 10 additions & 1 deletion src/main/java/xyz/oribuin/eternaltags/hook/Expansion.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import dev.rosewood.rosegarden.utils.HexUtils;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.oribuin.eternaltags.EternalTags;
Expand Down Expand Up @@ -52,7 +53,15 @@ public String onRequest(@Nullable OfflinePlayer offlineUser, @NotNull String par
}
}

final Tag activeTag = this.manager.getOfflineUserTag(offlineUser);
// This is the only tag that doesn't require a player
if (params.equalsIgnoreCase("total"))
return String.valueOf(this.manager.getCachedTags().size());

Player player = offlineUser.getPlayer();
if (player == null)
return "Error: Player is null";

final Tag activeTag = this.manager.getUserTag(player);
return switch (params.toLowerCase()) {
// Set bracket placeholders to allow \o/ Placeholder Inception \o/
case "tag" -> this.manager.getDisplayTag(activeTag, offlineUser, "");
Expand Down
56 changes: 56 additions & 0 deletions src/main/java/xyz/oribuin/eternaltags/hook/VaultHook.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package xyz.oribuin.eternaltags.hook;

import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;

import javax.annotation.Nullable;

public class VaultHook {

private static final boolean enabled;

static {
enabled = Bukkit.getPluginManager().isPluginEnabled("Vault");
}

/**
* Get the vault permission instance
*
* @return The permission instance
*/
@Nullable
public static Permission getPermission() {
if (!enabled)
return null;

RegisteredServiceProvider<Permission> rsp = Bukkit.getServicesManager().getRegistration(Permission.class);
if (rsp == null)
return null;

return rsp.getProvider();
}

/**
* Get the highest group of a player
*
* @param player The player to get the group of
* @return The highest group of the player
*/
public static String getPrimaryGroup(Player player) {
Permission permission = getPermission(); // Get the permission instance
if (permission == null)
return null;

return permission.getPrimaryGroup(player); // Get the highest group (This is the group with the highest priority
}

/**
* @return If vault is enabled or not
*/
public static boolean isEnabled() {
return enabled;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,16 @@
import xyz.oribuin.eternaltags.manager.DataManager;
import xyz.oribuin.eternaltags.manager.TagsManager;

import java.util.List;

public class PlayerListeners implements Listener {

private final TagsManager manager = EternalTags.getInstance().getManager(TagsManager.class);
private final DataManager dataManager = EternalTags.getInstance().getManager(DataManager.class);

@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
this.dataManager.loadUser(event.getPlayer().getUniqueId()); // Load the user from the database
this.dataManager.loadUser(event.getPlayer().getUniqueId()); // Load the user from the database
this.manager.getUserTag(event.getPlayer()); // Get the user's tag (This will detect default tags or the user's tag)

}

@EventHandler
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
package xyz.oribuin.eternaltags.manager;

import dev.rosewood.rosegarden.RosePlugin;
import dev.rosewood.rosegarden.config.CommentedConfigurationSection;
import dev.rosewood.rosegarden.config.CommentedFileConfiguration;
import dev.rosewood.rosegarden.config.RoseSetting;
import dev.rosewood.rosegarden.manager.AbstractConfigurationManager;
import xyz.oribuin.eternaltags.EternalTags;

import java.util.HashMap;
import java.util.Map;

public class ConfigurationManager extends AbstractConfigurationManager {

public enum Setting implements RoseSetting {
// Tag Settings
// Default Tag Options
DEFAULT_TAG("default-tag", "none", "The tag that will show when player does not have an active tag.", "Set to 'none' to disable.", "Set to 'random' to apply a random tag"),
DEFAULT_TAG_GROUPS("default-tag-groups", null, "The groups that will be applied to the player when they join the server.", "Set to 'none' to disable.", "Set to 'random' to apply a random tag", "This requires vault and a vault supported permission plugin."),
DEFAULT_TAG_GROUP_DEFAULT("default-tag-groups.default", "none"),
REMOVE_TAGS("remove-inaccessible-tags", false, "Should a tag be automatically removed if the player doesn't have permission to use it?"),

// Formatting
FORMATTED_PLACEHOLDER("formatted-placeholder", "None", "The placeholder that will show when the player has no active tag."),
TAG_UNLOCKED_FORMAT("tag-unlocked-format", "&a&lUnlocked", "The format that will show when the player has the tag unlocked."),
TAG_LOCKED_FORMAT("tag-locked-format", "&c&lLocked", "The format that will show when the player has the tag locked."),
REMOVE_TAGS("remove-inaccessible-tags", false, "Should a tag be automatically removed if the player doesn't have permission to use it?"),
TAG_PREFIX("tag-prefix", "", "The prefix that will be added in front of the tag in the placeholder"),
TAG_SUFFIX("tag-suffix", "", "The suffix that will be added after the tag in the placeholder"),
MYSQL_TAGDATA("save-tagdata-sql", false, "Should the tag data be stored in a MySQL/SQLite database? (Tags that would be saved in tags.yml)"),
PLUGIN_MESSAGING("plugin-messaging", false, "Should the plugin use plugin messaging to sync tag data across servers? (Recommended to keep save-tagdata-sql as false if this is enabled)"),
RE_EQUIP_CLEAR("reequip-clear", false, "Should the player's tag be cleared when they re-equip the same tag?"),
DESCRIPTION_DELIMITER("description-delimiter", "\n", "The delimiter that will be used for %eternaltags_tag_description%"),

// Other Options
RE_EQUIP_CLEAR("reequip-clear", false, "Should the player's tag be cleared when they re-equip the same tag?"),
CACHE_GUI_TAGS("cache-gui-tags", true, "Should the tag items be cached? (Keeps the items in memory instead of creating them every time the GUI is opened)",
"This will reduce the amount of lag when opening the GUI, but will use more memory.",
"This will also make tags with placeholders not update until the plugin is reloaded."
Expand All @@ -31,7 +39,12 @@ public enum Setting implements RoseSetting {
"This will also make categories with placeholders not update until the plugin is reloaded."
),
OPEN_CATEGORY_GUI_FIRST("open-category-gui-first", false, "Should the category GUI be opened first when a player types /tags?"),
;

// Data Systems
MYSQL_TAGDATA("save-tagdata-sql", false, "Should the tag data be stored in a MySQL/SQLite database? (Tags that would be saved in tags.yml)"),
PLUGIN_MESSAGING("plugin-messaging", false, "Should the plugin use plugin messaging to sync tag data across servers? (Recommended to keep save-tagdata-sql as false if this is enabled)"),

; // End of settings

private final String key;
private final Object defaultValue;
Expand Down Expand Up @@ -73,6 +86,23 @@ public void setCachedValue(Object value) {
public CommentedFileConfiguration getBaseConfig() {
return EternalTags.getInstance().getManager(ConfigurationManager.class).getConfig();
}

@SuppressWarnings("unchecked")
public Map<String, Object> getMap() {
if (this.value instanceof Map)
return (Map<String, Object>) this.value;

Map<String, Object> map = new HashMap<>();
CommentedConfigurationSection section = this.getBaseConfig().getConfigurationSection(this.key);
if (section == null) {
this.value = map;
return map;
}

section.getKeys(false).forEach(key -> map.put(key, section.get(key)));
this.value = map;
return map;
}
}

public ConfigurationManager(RosePlugin rosePlugin) {
Expand Down
56 changes: 29 additions & 27 deletions src/main/java/xyz/oribuin/eternaltags/manager/DataManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import xyz.oribuin.eternaltags.database.migration._3_ModifyTagDataItems;
import xyz.oribuin.eternaltags.obj.Tag;
import xyz.oribuin.eternaltags.obj.TagDescription;
import xyz.oribuin.eternaltags.obj.TagUser;
import xyz.oribuin.eternaltags.util.TagsUtils;

import java.sql.PreparedStatement;
Expand All @@ -26,8 +27,7 @@

public class DataManager extends AbstractDataManager {

private final Map<UUID, Tag> cachedUsers = new HashMap<>();
private final Map<UUID, Set<Tag>> cachedFavourites = new HashMap<>();
private final Map<UUID, TagUser> cachedUsers = new HashMap<>();

private final Gson gson = new Gson();

Expand All @@ -40,7 +40,6 @@ public void reload() {
super.reload();

this.cachedUsers.clear();
this.cachedFavourites.clear();
}

/**
Expand All @@ -50,9 +49,11 @@ public void reload() {
* @param tag The tag
*/
public void saveUser(@NotNull UUID uuid, @NotNull Tag tag) {
this.cachedUsers.put(uuid, tag);
TagUser user = this.cachedUsers.getOrDefault(uuid, new TagUser(uuid));
user.setActiveTag(tag.getId());
this.cachedUsers.put(uuid, user);

final String query = "REPLACE INTO " + this.getTablePrefix() + "tags (player, tagID) VALUES (?, ?)";
final String query = "REPLACE INTO " + this.getTablePrefix() + "tags (player, tagID) VALUES (?, ?)";
this.async(task -> this.databaseConnector.connect(connection -> {
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, uuid.toString());
Expand Down Expand Up @@ -86,7 +87,7 @@ public void removeUser(final UUID uuid) {
* @param id The tag id being removed.
*/
public void deleteUserTag(String id) {
this.cachedUsers.values().removeIf(tag -> tag.getId().equalsIgnoreCase(id));
this.cachedUsers.values().removeIf(tag -> tag.getActiveTag() != null && tag.getActiveTag().equalsIgnoreCase(id));

final String query = "DELETE FROM " + this.getTablePrefix() + "tags WHERE tagID = ?";
this.async(task -> this.databaseConnector.connect(connection -> {
Expand All @@ -103,7 +104,12 @@ public void deleteUserTag(String id) {
* @param tag The tag.
*/
public void updateUsers(Tag tag, List<UUID> players) {
players.forEach(player -> this.cachedUsers.put(player, tag));
players.forEach(player -> {
TagUser user = this.cachedUsers.getOrDefault(player, new TagUser(player));
user.setActiveTag(tag.getId());
this.cachedUsers.put(player, user);
});


this.async(task -> this.databaseConnector.connect(connection -> {
final String query = "REPLACE INTO " + this.getTablePrefix() + "tags (player, tagID) VALUES (?, ?)";
Expand All @@ -125,9 +131,10 @@ public void updateUsers(Tag tag, List<UUID> players) {
* @param tag The tag being added
*/
public void addFavourite(UUID uuid, Tag tag) {
Map<String, Tag> favourites = this.rosePlugin.getManager(TagsManager.class).getUsersFavourites(uuid);
favourites.put(tag.getId(), tag);
this.cachedFavourites.put(uuid, new HashSet<>(favourites.values()));
TagUser user = this.cachedUsers.getOrDefault(uuid, new TagUser(uuid));
user.getFavourites().add(tag.getId());
this.cachedUsers.put(uuid, user);


this.async(task -> this.databaseConnector.connect(connection -> {
final String query = "INSERT INTO " + this.getTablePrefix() + "favourites (player, tagID) VALUES (?, ?)";
Expand All @@ -146,10 +153,9 @@ public void addFavourite(UUID uuid, Tag tag) {
* @param tag The tag being removed.
*/
public void removeFavourite(UUID uuid, Tag tag) {

final Map<String, Tag> favourites = this.rosePlugin.getManager(TagsManager.class).getUsersFavourites(uuid);
favourites.remove(tag.getId());
this.cachedFavourites.put(uuid, new HashSet<>(favourites.values()));
TagUser user = this.cachedUsers.getOrDefault(uuid, new TagUser(uuid));
user.getFavourites().remove(tag.getId());
this.cachedUsers.put(uuid, user);

this.async(task -> this.databaseConnector.connect(connection -> {
final String query = "DELETE FROM " + this.getTablePrefix() + "favourites WHERE player = ? AND tagID = ?";
Expand Down Expand Up @@ -180,8 +186,7 @@ public void clearFavourites(UUID uuid) {
* @param uuid The player's uuid
*/
public void loadUser(@NotNull UUID uuid) {
final TagsManager manager = this.rosePlugin.getManager(TagsManager.class);
final Set<Tag> favouriteTags = new HashSet<>();
final TagUser user = new TagUser(uuid);

this.async(task -> this.databaseConnector.connect(connection -> {
final String selectTag = "SELECT tagID FROM " + this.getTablePrefix() + "tags WHERE player = ?";
Expand All @@ -191,7 +196,7 @@ public void loadUser(@NotNull UUID uuid) {
statement.setString(1, uuid.toString());
final ResultSet result = statement.executeQuery();
if (result.next()) {
this.cachedUsers.put(uuid, manager.getTagFromId(result.getString(1)));
user.setActiveTag(result.getString(1));
}
}

Expand All @@ -200,10 +205,11 @@ public void loadUser(@NotNull UUID uuid) {
statement.setString(1, uuid.toString());
final ResultSet result = statement.executeQuery();
while (result.next()) {
favouriteTags.add(manager.getTagFromId(result.getString(1)));
this.cachedFavourites.put(uuid, favouriteTags);
user.getFavourites().add(result.getString(1));
}
}

this.cachedUsers.put(uuid, user);
}));
}

Expand All @@ -228,7 +234,7 @@ public void loadTagData(Map<String, Tag> cachedTags) {
Tag tag = new Tag(id, result.getString("name"), result.getString("tag"));
tag.setPermission(result.getString("permission"));
tag.setDescription(description);
tag.setOrder(result.getInt("order"));;
tag.setOrder(result.getInt("order"));
tag.setIcon(TagsUtils.deserializeItem(result.getBytes("icon")));
cachedTags.put(id, tag);
}
Expand All @@ -251,7 +257,7 @@ public void saveTagData(@NotNull Tag tag) {
statement.setString(4, tag.getTag());
statement.setString(5, tag.getPermission());
statement.setInt(6, tag.getOrder());
statement.setBytes(7 , tag.getIcon() != null ? TagsUtils.serializeItem(tag.getIcon()) : null);
statement.setBytes(7, tag.getIcon() != null ? TagsUtils.serializeItem(tag.getIcon()) : null);
statement.executeUpdate();
}
}));
Expand All @@ -274,7 +280,7 @@ public void saveTagData(Map<String, Tag> tags) {
statement.setString(4, tag.getTag());
statement.setString(5, tag.getPermission());
statement.setInt(6, tag.getOrder());
statement.setBytes(7 , tag.getIcon() != null ? TagsUtils.serializeItem(tag.getIcon()) : null);
statement.setBytes(7, tag.getIcon() != null ? TagsUtils.serializeItem(tag.getIcon()) : null);
statement.addBatch();
}

Expand Down Expand Up @@ -319,12 +325,8 @@ private void async(Consumer<BukkitTask> callback) {
this.rosePlugin.getServer().getScheduler().runTaskAsynchronously(rosePlugin, callback);
}

public Map<UUID, Tag> getCachedUsers() {
public Map<UUID, TagUser> getCachedUsers() {
return cachedUsers;
}

public Map<UUID, Set<Tag>> getCachedFavourites() {
return cachedFavourites;
}

}
Loading

0 comments on commit 875ea46

Please sign in to comment.