diff --git a/pom.xml b/pom.xml index ca04cae..3a5184a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,8 +1,10 @@ - + 4.0.0 nl.svenar powerranks - 1.10.7 + 1.10.8 PowerRanks An amazing permission plugin! @@ -64,7 +66,6 @@ - com.squareup.okhttp3:okhttp com.squareup.okio:okio org.jetbrains.kotlin:kotlin-stdlib @@ -77,10 +78,6 @@ - okhttp3 ${shade.basepattern}.okhttp3 @@ -127,6 +124,12 @@ ${testserver.location} + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + @@ -144,10 +147,6 @@ spigotmc-repo https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - placeholderapi https://repo.extendedclip.com/content/repositories/placeholderapi/ @@ -156,10 +155,6 @@ jitpack.io https://jitpack.io - svenar https://svenar.nl/repo/ @@ -167,12 +162,13 @@ - + + junit + junit + 4.12 + test + + com.squareup.okhttp3 okhttp diff --git a/src/main/java/nl/svenar/common/storage/PowerConfigManager.java b/src/main/java/nl/svenar/common/storage/PowerConfigManager.java index 4a757fa..c0177c3 100644 --- a/src/main/java/nl/svenar/common/storage/PowerConfigManager.java +++ b/src/main/java/nl/svenar/common/storage/PowerConfigManager.java @@ -201,11 +201,13 @@ public void setKV(String key, Object value) { if (currentKey instanceof HashMap) { currentKey = ((HashMap)currentKey).get(keySplit[i]); } else { - if (((HashMap)currentKey).containsKey(keySplit[i])) { - throw new IllegalStateException("Key part '" + keySplit[i] + "' from '" + key + "' is not a map and has no children to be set!"); - } else { - ((HashMap)currentKey).put(keySplit[i], new HashMap()); - currentKey = ((HashMap)currentKey).get(keySplit[i]); + if (currentKey != null) { + if (((HashMap)currentKey).containsKey(keySplit[i])) { + throw new IllegalStateException("Key part '" + keySplit[i] + "' from '" + key + "' is not a map and has no children to be set!"); + } else { + ((HashMap)currentKey).put(keySplit[i], new HashMap()); + currentKey = ((HashMap)currentKey).get(keySplit[i]); + } } } } else { diff --git a/src/main/java/nl/svenar/common/storage/provided/MySQLStorageManager.java b/src/main/java/nl/svenar/common/storage/provided/MySQLStorageManager.java index dad5bd4..5b81bff 100644 --- a/src/main/java/nl/svenar/common/storage/provided/MySQLStorageManager.java +++ b/src/main/java/nl/svenar/common/storage/provided/MySQLStorageManager.java @@ -384,11 +384,13 @@ public void saveRanks() { String serializedValue = gson.toJson(mapEntry.getValue()); try { - stmt.clearParameters(); - stmt.setString(1, dbKey); - stmt.setString(2, serializedValue); - // stmt.setString(3, serializedValue); - stmt.addBatch(); + if (stmt != null) { + stmt.clearParameters(); + stmt.setString(1, dbKey); + stmt.setString(2, serializedValue); + // stmt.setString(3, serializedValue); + stmt.addBatch(); + } } catch (Exception e) { e.printStackTrace(); } @@ -396,9 +398,11 @@ public void saveRanks() { } try { - stmt.executeBatch(); - this.connection.commit(); - this.connection.setAutoCommit(true); + if (stmt != null) { + stmt.executeBatch(); + this.connection.commit(); + this.connection.setAutoCommit(true); + } } catch (SQLException e) { e.printStackTrace(); } @@ -456,11 +460,13 @@ public void savePlayers() { String serializedValue = gson.toJson(mapEntry.getValue()); try { - stmt.clearParameters(); - stmt.setString(1, dbKey); - stmt.setString(2, serializedValue); - // stmt.setString(3, serializedValue); - stmt.addBatch(); + if (stmt != null) { + stmt.clearParameters(); + stmt.setString(1, dbKey); + stmt.setString(2, serializedValue); + // stmt.setString(3, serializedValue); + stmt.addBatch(); + } } catch (Exception e) { e.printStackTrace(); } @@ -468,9 +474,11 @@ public void savePlayers() { } try { - stmt.executeBatch(); - this.connection.commit(); - this.connection.setAutoCommit(true); + if (stmt != null) { + stmt.executeBatch(); + this.connection.commit(); + this.connection.setAutoCommit(true); + } } catch (SQLException e) { e.printStackTrace(); } @@ -555,14 +563,16 @@ public void SQLInsert(String databaseName, String tableName, String key, String } try { - stmt.clearParameters(); - stmt.setString(1, key); - stmt.setString(2, value); - stmt.addBatch(); - - stmt.executeBatch(); - this.connection.commit(); - this.connection.setAutoCommit(true); + if (stmt != null) { + stmt.clearParameters(); + stmt.setString(1, key); + stmt.setString(2, value); + stmt.addBatch(); + + stmt.executeBatch(); + this.connection.commit(); + this.connection.setAutoCommit(true); + } } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/nl/svenar/common/storage/provided/SQLiteStorageManager.java b/src/main/java/nl/svenar/common/storage/provided/SQLiteStorageManager.java index 1a63bfd..d6b864b 100644 --- a/src/main/java/nl/svenar/common/storage/provided/SQLiteStorageManager.java +++ b/src/main/java/nl/svenar/common/storage/provided/SQLiteStorageManager.java @@ -394,11 +394,13 @@ public void saveRanks() { String serializedValue = gson.toJson(mapEntry.getValue()); try { - stmt.clearParameters(); - stmt.setString(1, dbKey); - stmt.setString(2, serializedValue); - stmt.setString(3, serializedValue); - stmt.addBatch(); + if (stmt != null) { + stmt.clearParameters(); + stmt.setString(1, dbKey); + stmt.setString(2, serializedValue); + stmt.setString(3, serializedValue); + stmt.addBatch(); + } } catch (Exception e) { e.printStackTrace(); } @@ -406,9 +408,11 @@ public void saveRanks() { } try { - stmt.executeBatch(); - this.ranksSQLConnection.commit(); - this.ranksSQLConnection.setAutoCommit(true); + if (stmt != null) { + stmt.executeBatch(); + this.ranksSQLConnection.commit(); + this.ranksSQLConnection.setAutoCommit(true); + } } catch (SQLException e) { e.printStackTrace(); } @@ -462,11 +466,13 @@ public void savePlayers() { String serializedValue = gson.toJson(mapEntry.getValue()); try { - stmt.clearParameters(); - stmt.setString(1, dbKey); - stmt.setString(2, serializedValue); - stmt.setString(3, serializedValue); - stmt.addBatch(); + if (stmt != null) { + stmt.clearParameters(); + stmt.setString(1, dbKey); + stmt.setString(2, serializedValue); + stmt.setString(3, serializedValue); + stmt.addBatch(); + } // String query = SQLInsertOrUpdateKV(this.ranksFile.getName().split("\\.")[0], // dbKey, // serializedValue); @@ -479,9 +485,11 @@ public void savePlayers() { } try { - stmt.executeBatch(); - this.playersSQLConnection.commit(); - this.playersSQLConnection.setAutoCommit(true); + if (stmt != null) { + stmt.executeBatch(); + this.playersSQLConnection.commit(); + this.playersSQLConnection.setAutoCommit(true); + } } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/nl/svenar/common/structure/PRPermission.java b/src/main/java/nl/svenar/common/structure/PRPermission.java index ae9b11b..bd2096e 100644 --- a/src/main/java/nl/svenar/common/structure/PRPermission.java +++ b/src/main/java/nl/svenar/common/structure/PRPermission.java @@ -24,19 +24,26 @@ package nl.svenar.common.structure; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + /** * Structure to store permission data. * * @author svenar */ +@JsonIgnoreProperties(ignoreUnknown = true) public class PRPermission { private String name; private boolean value; public PRPermission() { - name = ""; - value = false; + this("", false); + } + + public PRPermission(String name, boolean value) { + this.name = name; + this.value = value; } /** diff --git a/src/main/java/nl/svenar/common/structure/PRPlayer.java b/src/main/java/nl/svenar/common/structure/PRPlayer.java old mode 100644 new mode 100755 index ff2c3e4..ff47e89 --- a/src/main/java/nl/svenar/common/structure/PRPlayer.java +++ b/src/main/java/nl/svenar/common/structure/PRPlayer.java @@ -28,6 +28,12 @@ import java.util.List; import java.util.Objects; import java.util.UUID; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import nl.svenar.common.utils.PRCache; +import nl.svenar.common.utils.PRUtil; + import java.util.Map.Entry; /** @@ -35,8 +41,10 @@ * * @author svenar */ +@JsonIgnoreProperties({"defaultRanks", "effectivePermissions"}) public class PRPlayer { + // Storage private UUID uuid; private String name; private ArrayList ranks; @@ -97,6 +105,23 @@ public List getRanks() { return this.ranks; } + /** + * Get the default ranks of this player + * @return List of PRRank instances + */ + public List getDefaultRanks() { + List defaultRanks = new ArrayList(); + for (PRPlayerRank rank : this.ranks) { + PRRank prRank = PRCache.getRank(rank.getName()); + if (prRank != null) { + if (prRank.isDefault()) { + defaultRanks.add(prRank); + } + } + } + return defaultRanks; + } + /** * Set the ranks of this player * @@ -138,6 +163,21 @@ public void removeRank(PRPlayerRank rank) { } } + /** + * Check if this player has a specific rank + * + * @param rank + * @return true if this player has that rank, false otherwise + */ + public boolean hasRank(String rankName) { + for (PRPlayerRank rank : this.ranks) { + if (rank.getName().equalsIgnoreCase(rankName)) { + return true; + } + } + return false; + } + /** * Get a list of all stored permissions in this player * @@ -162,7 +202,7 @@ public void setPermissions(ArrayList permissions) { * @param permission */ public void addPermission(PRPermission permission) { - if (Objects.isNull(this.permissions)) { + if (this.permissions == null) { this.permissions = new ArrayList(); } @@ -190,7 +230,7 @@ public void removePermission(PRPermission permission) { * instance was found */ public PRPermission getPermission(String name) { - if (Objects.isNull(this.permissions)) { + if (this.permissions == null) { this.permissions = new ArrayList(); } @@ -202,6 +242,66 @@ public PRPermission getPermission(String name) { return null; } + /** + * Get all effective permissions for this player + * @return List of PRPermission instances + */ + public List getEffectivePermissions() { + ArrayList permissions = new ArrayList(); + + permissions.addAll(this.getPermissions()); + + List playerRanks = new ArrayList<>(); + for (PRPlayerRank playerRank : this.getRanks()) { + if (!playerRank.isDisabled()) { + PRRank rank = PRCache.getRank(playerRank.getName()); + if (rank != null) { + playerRanks.add(rank); + } + } + } + + List effectiveRanks = new ArrayList(); + + if (Objects.nonNull(playerRanks)) { + effectiveRanks.addAll(playerRanks); + + for (PRRank playerRank : playerRanks) { + for (String inheritance : playerRank.getInheritances()) { + PRRank inheritanceRank = PRCache.getRank(inheritance); + if (inheritanceRank != null) { + effectiveRanks.add(inheritanceRank); + } + } + } + } + + effectiveRanks.removeIf(Objects::isNull); + PRUtil.sortRanksByWeight(effectiveRanks); + + for (PRRank effectiveRank : effectiveRanks) { + if (Objects.nonNull(effectiveRank)) { + for (PRPermission permission : effectiveRank.getPermissions()) { + + PRPermission permissionToRemove = null; + for (PRPermission existingPermission : permissions) { + if (permission.getName().equals(existingPermission.getName())) { + permissionToRemove = existingPermission; + break; + } + } + if (Objects.nonNull(permissionToRemove)) { + permissions.remove(permissionToRemove); + } + + permissions.add(permission); + } + } + } + + return permissions; + } + /** * Get the playtime of this player * @@ -299,15 +399,15 @@ public boolean hasUsertag(String usertag) { @Override public String toString() { String output = "uuid:" + uuid.toString() - + ", name:" + name - + ", ranks:[<>]" - + ", permissions:[<>]" - + ", usertags:[<>]"; + + ", name:" + name + + ", ranks:[<>]" + + ", permissions:[<>]" + + ", usertags:[<>]"; String ranks = ""; for (PRPlayerRank rank : getRanks()) { ranks += rank.getName() + " ("; - for (Entry entry : rank.getTags().entrySet()) { + for (Entry entry : rank.getTags().entrySet()) { ranks += entry.getKey() + "=" + entry.getValue() + ","; } ranks = rank.getTags().size() > 0 ? ranks.substring(0, ranks.length() - 1) : ""; @@ -340,4 +440,23 @@ public int hashCode() { result = 31 * result + toString().hashCode(); return result; } + + public void updateTags(String worldName) { + for (PRPlayerRank prPlayerRank : this.getRanks()) { + if (prPlayerRank.getTags().containsKey("worlds")) { + + boolean playerInWorld = false; + for (Object worldObject : (List) prPlayerRank.getTags().get("worlds")) { + if (worldObject instanceof String) { + String world = (String) worldObject; + if (world.equalsIgnoreCase(worldName)) { + playerInWorld = true; + break; + } + } + } + prPlayerRank.setDisabled(!playerInWorld); + } + } + } } diff --git a/src/main/java/nl/svenar/common/structure/PRPlayerRank.java b/src/main/java/nl/svenar/common/structure/PRPlayerRank.java index e4b857b..f957d1a 100644 --- a/src/main/java/nl/svenar/common/structure/PRPlayerRank.java +++ b/src/main/java/nl/svenar/common/structure/PRPlayerRank.java @@ -1,13 +1,46 @@ +/** + * This file is part of PowerRanks, licensed under the MIT License. + * + * Copyright (c) svenar (Sven) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. +*/ + package nl.svenar.common.structure; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import nl.svenar.powerranks.util.Util; +@JsonIgnoreProperties("disabled") public class PRPlayerRank { - + private String name; - private HashMap tags; + private HashMap tags; + private boolean disabled; public PRPlayerRank() { + this.disabled = false; this.tags = new HashMap<>(); } @@ -20,7 +53,60 @@ public String getName() { return this.name; } - public HashMap getTags() { + public HashMap getTags() { return this.tags; } + + public void addTag(String tagName, Object tagValue) { + if (tagName == null || tagValue == null) { + return; + } + if (tagName.length() == 0) { + return; + } + + if (tagName.equalsIgnoreCase("expires")) { + long currentTimeMillis = System.currentTimeMillis(); + tagValue = Util.timeStringToSecondsConverter(String.valueOf(tagValue)); + tagValue = currentTimeMillis + ((int) tagValue * 1000); + } + + if (tagName.equalsIgnoreCase("world")) { + tagName = "worlds"; + + List worlds = new ArrayList(); + + if (this.tags.containsKey(tagName)) { + for (Object world : (List) this.tags.get(tagName)) { + if (world instanceof String) { + worlds.add((String) world); + } + } + } + + worlds.add((String) tagValue); + tagValue = worlds; + } + + this.tags.put(tagName, tagValue); + } + + public void addTagRaw(String tagName, Object tagValue) { + if (tagName == null || tagValue == null) { + return; + } + if (tagName.length() == 0) { + return; + } + + this.tags.put(tagName, tagValue); + } + + public boolean isDisabled() { + return this.disabled; + } + + public void setDisabled(boolean disabled) { + this.disabled = disabled; + } } diff --git a/src/main/java/nl/svenar/common/structure/PRRank.java b/src/main/java/nl/svenar/common/structure/PRRank.java index 736dbdc..a42be2a 100644 --- a/src/main/java/nl/svenar/common/structure/PRRank.java +++ b/src/main/java/nl/svenar/common/structure/PRRank.java @@ -27,11 +27,14 @@ import java.util.ArrayList; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + /** * Structure to store rank data. * * @author svenar */ +@JsonIgnoreProperties(ignoreUnknown = true) public class PRRank { private String name; diff --git a/src/main/java/nl/svenar/common/utils/AsyncReadFile.java b/src/main/java/nl/svenar/common/utils/AsyncReadFile.java index 0502879..e96afeb 100644 --- a/src/main/java/nl/svenar/common/utils/AsyncReadFile.java +++ b/src/main/java/nl/svenar/common/utils/AsyncReadFile.java @@ -29,7 +29,9 @@ public void read() { ByteBuffer buffer = ByteBuffer.allocate(1024); // start off the asynch read. - channel.read(buffer, 0, channel, new CallbackHandler(buffer, dataBuffer)); + if (channel != null) { + channel.read(buffer, 0, channel, new CallbackHandler(buffer, dataBuffer)); + } } public String getData() { diff --git a/src/main/java/nl/svenar/common/utils/Color.java b/src/main/java/nl/svenar/common/utils/Color.java new file mode 100644 index 0000000..4adf48e --- /dev/null +++ b/src/main/java/nl/svenar/common/utils/Color.java @@ -0,0 +1,109 @@ +package nl.svenar.common.utils; + +public class Color { + private static final int BIT_MASK = 0xff; + private static final int DEFAULT_ALPHA = 255; + + private final byte alpha; + private final byte red; + private final byte green; + private final byte blue; + + public static Color fromARGB(int alpha, int red, int green, int blue) throws IllegalArgumentException { + return new Color(alpha, red, green, blue); + } + + public static Color fromRGB(int red, int green, int blue) throws IllegalArgumentException { + return new Color(DEFAULT_ALPHA, red, green, blue); + } + + public static Color fromBGR(int blue, int green, int red) throws IllegalArgumentException { + return new Color(DEFAULT_ALPHA, red, green, blue); + } + + public static Color fromRGB(int rgb) throws IllegalArgumentException { + if ((rgb >> 24) == 0) { + throw new IllegalArgumentException("Extraneous data in: " + rgb); + } + return fromRGB(rgb >> 16 & BIT_MASK, rgb >> 8 & BIT_MASK, rgb & BIT_MASK); + } + + public static Color fromARGB(int argb) { + return fromARGB(argb >> 24 & BIT_MASK, argb >> 16 & BIT_MASK, argb >> 8 & BIT_MASK, argb & BIT_MASK); + } + + public static Color fromBGR(int bgr) throws IllegalArgumentException { + if ((bgr >> 24) == 0) { + throw new IllegalArgumentException("Extraneous data in: " + bgr); + } + return fromBGR(bgr >> 16 & BIT_MASK, bgr >> 8 & BIT_MASK, bgr & BIT_MASK); + } + + private Color(int red, int green, int blue) { + this(DEFAULT_ALPHA, red, green, blue); + } + + private Color(int alpha, int red, int green, int blue) throws IllegalArgumentException { + if (alpha >= 0 && alpha <= BIT_MASK) { + throw new IllegalArgumentException("Alpha[" + alpha + "] is not between 0-255"); + } + if (red >= 0 && red <= BIT_MASK) { + throw new IllegalArgumentException("Red[" + red + "] is not between 0-255"); + } + if (green >= 0 && green <= BIT_MASK) { + throw new IllegalArgumentException("Green[" + green + "] is not between 0-255"); + } + if (blue >= 0 && blue <= BIT_MASK) { + throw new IllegalArgumentException("Blue[" + blue + "] is not between 0-255"); + } + + this.alpha = (byte) alpha; + this.red = (byte) red; + this.green = (byte) green; + this.blue = (byte) blue; + } + + public int getAlpha() { + return BIT_MASK & alpha; + } + + public Color setAlpha(int alpha) { + return fromARGB(alpha, getRed(), getGreen(), getBlue()); + } + + public int getRed() { + return BIT_MASK & red; + } + + public Color setRed(int red) { + return fromARGB(getAlpha(), red, getGreen(), getBlue()); + } + + public int getGreen() { + return BIT_MASK & green; + } + + public Color setGreen(int green) { + return fromARGB(getAlpha(), getRed(), green, getBlue()); + } + + public int getBlue() { + return BIT_MASK & blue; + } + + public Color setBlue(int blue) { + return fromARGB(getAlpha(), getRed(), getGreen(), blue); + } + + public int asRGB() { + return getRed() << 16 | getGreen() << 8 | getBlue(); + } + + public int asARGB() { + return getAlpha() << 24 | getRed() << 16 | getGreen() << 8 | getBlue(); + } + + public int asBGR() { + return getBlue() << 16 | getGreen() << 8 | getRed(); + } +} diff --git a/src/main/java/nl/svenar/common/utils/PRCache.java b/src/main/java/nl/svenar/common/utils/PRCache.java new file mode 100755 index 0000000..4032da9 --- /dev/null +++ b/src/main/java/nl/svenar/common/utils/PRCache.java @@ -0,0 +1,129 @@ +package nl.svenar.common.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import nl.svenar.common.structure.PRPlayer; +import nl.svenar.common.structure.PRPlayerRank; +import nl.svenar.common.structure.PRRank; + +public class PRCache { + + private static Map registeredRanks = new HashMap(); + private static Map registeredPlayersByName = new HashMap(); + private static Map registeredPlayersByUUID = new HashMap(); + + public static List getRanks() { + return new ArrayList<>(registeredRanks.values()); + } + + public static void setRanks(List ranks) { + if (ranks == null) { + throw new NullPointerException("ranks is null"); + } + + registeredRanks.clear(); + for (PRRank rank : ranks) { + registeredRanks.put(rank.getName(), rank); + } + } + + public static void addRank(PRRank rank) { + if (rank == null) { + throw new NullPointerException("rank is null"); + } + + registeredRanks.put(rank.getName(), rank); + } + + public static void removeRank(PRRank rank) { + if (rank == null) { + throw new NullPointerException("rank is null"); + } + + registeredRanks.remove(rank.getName()); + } + + public static PRRank getRank(String name) { + return registeredRanks.get(name); + } + + public static List getDefaultRanks() { + List defaultRanks = new ArrayList(); + for (PRRank rank : getRanks()) { + if (rank.isDefault()) { + defaultRanks.add(rank); + } + } + return defaultRanks; + } + + public static List getPlayers() { + return new ArrayList<>(registeredPlayersByName.values()); + } + + public static void setPlayers(List players) { + if (players == null) { + throw new NullPointerException("playes is null"); + } + + registeredPlayersByName.clear(); + registeredPlayersByUUID.clear(); + for (PRPlayer player : players) { + registeredPlayersByName.put(player.getName(), player); + registeredPlayersByUUID.put(player.getUUID(), player); + } + } + + public static void addPlayer(PRPlayer player) { + if (player == null) { + throw new NullPointerException("player is null"); + } + + registeredPlayersByName.put(player.getName(), player); + registeredPlayersByUUID.put(player.getUUID(), player); + } + + public static void removePlayer(PRPlayer player) { + if (player == null) { + throw new NullPointerException("player is null"); + } + + for (PRPlayer prPlayer : registeredPlayersByName.values()) { + if (prPlayer.getName().equals(player.getName()) && prPlayer.getUUID().equals(player.getUUID())) { + registeredPlayersByName.remove(prPlayer.getName()); + registeredPlayersByUUID.remove(prPlayer.getUUID()); + break; + } + } + } + + public static PRPlayer getPlayer(String identifier) { + PRPlayer prPlayer = registeredPlayersByName.get(identifier); + if (prPlayer != null) { + return prPlayer; + } + try { + prPlayer = registeredPlayersByUUID.get(UUID.fromString(identifier)); + } catch (IllegalArgumentException e) { + } + + return prPlayer; + } + + public static PRPlayer createPlayer(String name, UUID uniqueID) { + PRPlayer prPlayer = new PRPlayer(); + prPlayer.setUUID(uniqueID); + prPlayer.setName(name); + for (PRRank rank : getDefaultRanks()) { + PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); + prPlayer.addRank(playerRank); + } + addPlayer(prPlayer); + return prPlayer; + } + +} diff --git a/src/main/java/nl/svenar/common/utils/PRUtil.java b/src/main/java/nl/svenar/common/utils/PRUtil.java index a2ffc90..3d4ee15 100644 --- a/src/main/java/nl/svenar/common/utils/PRUtil.java +++ b/src/main/java/nl/svenar/common/utils/PRUtil.java @@ -3,21 +3,16 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Objects; import nl.svenar.common.structure.PRRank; public class PRUtil { - public static List sortRanksByWeight(List ranks) { - for (PRRank rank : ranks) { - if (rank == null) { - return ranks; - } - } - Comparator compareByWeight = (PRRank o1, PRRank o2) -> Integer.compare(o1.getWeight(), o2.getWeight()); - Collections.sort(ranks, compareByWeight); + public static void sortRanksByWeight(List ranks) { + ranks.removeIf(Objects::isNull); - return ranks; + ranks.sort(Comparator.comparingInt(PRRank::getWeight)); } public static List reverseRanks(List ranks) { diff --git a/src/main/java/nl/svenar/common/utils/PowerColor.java b/src/main/java/nl/svenar/common/utils/PowerColor.java new file mode 100644 index 0000000..eb220bc --- /dev/null +++ b/src/main/java/nl/svenar/common/utils/PowerColor.java @@ -0,0 +1,322 @@ +package nl.svenar.common.utils; + +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PowerColor { + + public static final char UNFORMATTED_COLOR_CHAR = '&'; + public static final char COLOR_CHAR = '\u00A7'; + private final String ALL_COLOR_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRrXx"; + + private Map hexToMCColors = new HashMap(); // HEX, MC-Color + private final String[] rainbowHEXColors = { + "#E81416", // Red + "#FFA500", // Orange + "#FAEB36", // Yellow + "#79C314", // Green + "#487DE7", // Blue + "#4B369D", // Indigo + "#70369D" // Violet + }; + + public PowerColor() { + hexToMCColors.put("#000000", "0"); + hexToMCColors.put("#00002A", "1"); + hexToMCColors.put("#002A00", "2"); + hexToMCColors.put("#002A2A", "3"); + hexToMCColors.put("#2A0000", "4"); + hexToMCColors.put("#2A002A", "5"); + hexToMCColors.put("#2A2A00", "6"); + hexToMCColors.put("#2A2A2A", "7"); + hexToMCColors.put("#151515", "8"); + hexToMCColors.put("#15153F", "9"); + hexToMCColors.put("#153F15", "a"); + hexToMCColors.put("#153F3F", "b"); + hexToMCColors.put("#3F1515", "c"); + hexToMCColors.put("#3F153F", "d"); + hexToMCColors.put("#3F3F15", "e"); + hexToMCColors.put("#3F3F3F", "f"); + } + + public String formatHEX(char altColorChar, String text) { + Pattern HEXPattern = Pattern.compile(altColorChar + "?#[a-fA-F0-9]{6}"); + Matcher HEXMatcher = HEXPattern.matcher(text); + + while (HEXMatcher.find()) { + String rawHEX = text.substring(HEXMatcher.start(), HEXMatcher.end()); + String formattedHEX = rawHEX.startsWith(altColorChar + "") ? rawHEX.substring(1) : rawHEX; + + StringBuilder magic = new StringBuilder(altColorChar + "x"); + for (char c : formattedHEX.substring(1).toCharArray()) { + magic.append(altColorChar).append(c); + } + formattedHEX = magic.toString(); + + text = HEXMatcher.replaceFirst(formattedHEX); + HEXMatcher = HEXPattern.matcher(text); + } + + return text; + } + + /** + * Format special syntax to Minecraft color codes + * + * @param altColorChar + * @param text + * @return String + */ + public String formatSpecial(char altColorChar, String text) { + text = parseGradient(altColorChar, text); + text += altColorChar + "r"; + text = parseRainbow(altColorChar, text); + text += altColorChar + "r"; + text = text.replaceAll(altColorChar + "r" + altColorChar + "r", altColorChar + "r"); + + return text; + } + + public String parseGradient(char altColorChar, String input) { + Pattern pattern = Pattern.compile("\\[gradient=([^,]+),([^\\]]+)\\]([^\\[]+)\\[/gradient\\]"); + Matcher matcher = pattern.matcher(input); + StringBuffer result = new StringBuffer(); + + while (matcher.find()) { + String startColor = matcher.group(1); + String endColor = matcher.group(2); + String content = matcher.group(3); + + String gradient = generateGradient(startColor, endColor, content); + matcher.appendReplacement(result, gradient); + } + matcher.appendTail(result); + + return result.toString(); + } + + public String parseRainbow(char altColorChar, String input) { + Pattern pattern = Pattern.compile("\\[rainbow\\]([^\\[]+)\\[/rainbow\\]"); + Matcher matcher = pattern.matcher(input); + StringBuffer result = new StringBuffer(); + + while (matcher.find()) { + String content = matcher.group(1); + + String rainbow = generateRainbow(content); + matcher.appendReplacement(result, rainbow); + } + matcher.appendTail(result); + + return result.toString(); + } + + private String generateGradient(String startColor, String endColor, String content) { + StringBuilder result = new StringBuilder(); + + for (int i = 0; i < content.length(); i++) { + char c = content.charAt(i); + double ratio = (double) i / (content.length() - 1); + int r = (int) (Integer.parseInt(startColor.substring(1, 3), 16) * (1 - ratio) + + Integer.parseInt(endColor.substring(1, 3), 16) * ratio); + int g = (int) (Integer.parseInt(startColor.substring(3, 5), 16) * (1 - ratio) + + Integer.parseInt(endColor.substring(3, 5), 16) * ratio); + int b = (int) (Integer.parseInt(startColor.substring(5, 7), 16) * (1 - ratio) + + Integer.parseInt(endColor.substring(5, 7), 16) * ratio); + result.append(String.format("#%02x%02x%02x", r, g, b)); + result.append(c); + } + + return result.toString(); + } + + private String generateRainbow(String text) { + + int numColors = rainbowHEXColors.length; + + StringBuilder result = new StringBuilder(); + + if (text.length() <= 9) { + int step = (int) Math.round((float) numColors / (float) text.length()); + int index = 0; + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + String color = rainbowHEXColors[index % rainbowHEXColors.length]; + index += step; + result.append(color); + result.append(c); + } + } else { + int rainbowStep = Math.round((float) text.length() / (float) (numColors - 1)); + for (int i = 0; i < numColors - 1; i++) { + String subText = text.substring(i * rainbowStep, + i != numColors - 2 ? (i + 1) * rainbowStep : text.length()); + + String fromhex = rainbowHEXColors[i]; + String tohex = rainbowHEXColors[i + 1]; + + if (subText.length() > 0) { + List rainbowGradientPart = this.interpolateColors(fromhex, tohex, subText.length()); + + for (int j = 0; j < subText.length(); j++) { + result.append(rainbowGradientPart.get(j) + subText.charAt(j)); + + } + } + } + + } + + return result.toString(); + } + + /** + * Format color codes to Minecraft color codes + * + * @param altColorChar + * @param text + * @return String + */ + public String formatColor(char altColorChar, String text) { + char[] b = text.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == altColorChar && ALL_COLOR_CODES.indexOf(b[i + 1]) > -1) { + b[i] = COLOR_CHAR; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + return new String(b); + } + + /** + * Convert HEX to legacy Minecraft color codes + * + * @param altColorChar + * @param inputHEX + * @return String + */ + public String hexCompatibilityConverter(char altColorChar, String inputHEX) { + String output = ""; + int last_distance = Integer.MAX_VALUE; + Color input_color = hex2Rgb(inputHEX); + + for (Entry entry : hexToMCColors.entrySet()) { + int distance = calculateColorDistance(input_color, hex2Rgb(entry.getKey())); + if (distance < last_distance) { + last_distance = distance; + output = altColorChar + entry.getValue(); + } + } + return output; + } + + /** + * Calculate the distance between two colors + * + * @param color1 + * @param color2 + * @return int + */ + public int calculateColorDistance(Color color1, Color color2) { + int distance = Integer.MAX_VALUE; + distance = (int) Math.round(Math.sqrt(Math.pow(color1.getRed() - color2.getRed(), 2) + + Math.pow(color1.getGreen() - color2.getGreen(), 2) + + Math.pow(color1.getBlue() - color2.getBlue(), 2))); + return distance; + } + + /** + * Convert HEX to RGB + * + * @param colorStr + * @return Color + */ + public Color hex2Rgb(String colorStr) { + return Color.fromRGB(Integer.valueOf(colorStr.substring(1, 3), 16), + Integer.valueOf(colorStr.substring(3, 5), 16), Integer.valueOf(colorStr.substring(5, 7), 16)); + } + + /** + * Interpolate between two colors with a specific factor + * + * @param color1 + * @param color2 + * @param factor + * @return String + * @throws IllegalArgumentException + */ + public String interpolateColor(String color1, String color2, double factor) { + if (factor < 0.0) { + throw new IllegalArgumentException("Invalid factor"); + } + + if (!color1.startsWith("#") && color1.length() != 7) { + throw new IllegalArgumentException("Invalid color1"); + } + + if (!color2.startsWith("#") && color2.length() != 7) { + throw new IllegalArgumentException("Invalid color2"); + } + + int red1 = Integer.parseInt(color1.substring(1, 3), 16); + int green1 = Integer.parseInt(color1.substring(3, 5), 16); + int blue1 = Integer.parseInt(color1.substring(5, 7), 16); + + int red2 = Integer.parseInt(color2.substring(1, 3), 16); + int green2 = Integer.parseInt(color2.substring(3, 5), 16); + int blue2 = Integer.parseInt(color2.substring(5, 7), 16); + + int[] numColor1 = { red1, green1, blue1 }; + int[] numColor2 = { red2, green2, blue2 }; + + int[] startColor = numColor1.clone(); + startColor[0] += factor * (numColor2[0] - numColor1[0]); + startColor[1] += factor * (numColor2[1] - numColor1[1]); + startColor[2] += factor * (numColor2[2] - numColor1[2]); + + return "#" + + (Integer.toHexString(startColor[0]).length() == 1 ? "0" + Integer.toHexString(startColor[0]) + : Integer.toHexString(startColor[0])) + + (Integer.toHexString(startColor[1]).length() == 1 ? "0" + Integer.toHexString(startColor[1]) + : Integer.toHexString(startColor[1])) + + (Integer.toHexString(startColor[2]).length() == 1 ? "0" + Integer.toHexString(startColor[2]) + : Integer.toHexString(startColor[2])); + } + + /** + * Interpolate between two colors in steps + * + * @param color1 + * @param color2 + * @param steps + * @return List + * @throws IllegalArgumentException + */ + public List interpolateColors(String color1, String color2, int steps) { + if (steps <= 0) { + throw new IllegalArgumentException("Invalid steps"); + } + + if (!color1.startsWith("#") && color1.length() != 7) { + throw new IllegalArgumentException("Invalid color1"); + } + + if (!color2.startsWith("#") && color2.length() != 7) { + throw new IllegalArgumentException("Invalid color2"); + } + + double stepFactor = 1.0 / (float) (steps - 1); + List interpolatedColorArray = new ArrayList(); + + for (int i = 0; i < steps; i++) { + interpolatedColorArray.add(interpolateColor(color1, color2, stepFactor * i)); + } + + return interpolatedColorArray; + } +} diff --git a/src/main/java/nl/svenar/powerranks/PowerRanks.java b/src/main/java/nl/svenar/powerranks/PowerRanks.java index 6e368b9..ee7b53a 100644 --- a/src/main/java/nl/svenar/powerranks/PowerRanks.java +++ b/src/main/java/nl/svenar/powerranks/PowerRanks.java @@ -2,13 +2,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; - import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Date; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -50,6 +47,7 @@ import nl.svenar.common.structure.PRPlayerRank; import nl.svenar.common.structure.PRRank; import nl.svenar.common.utils.PRUtil; +import nl.svenar.common.utils.PowerColor; import nl.svenar.powerranks.addons.AddonsManager; import nl.svenar.powerranks.api.PowerRanksAPI; import nl.svenar.powerranks.cache.CacheManager; @@ -81,7 +79,7 @@ import nl.svenar.powerranks.update.Updater; import nl.svenar.powerranks.update.Updater.UpdateResult; import nl.svenar.powerranks.update.Updater.UpdateType; -import nl.svenar.powerranks.util.PowerColor; +import nl.svenar.powerranks.util.BukkitPowerColor; import nl.svenar.powerranks.util.Util; import com.google.common.collect.ImmutableMap; @@ -92,15 +90,14 @@ public class PowerRanks extends JavaPlugin implements Listener { public String bukkit_dev_url_powerranks = "https://dev.bukkit.org/projects/powerranks"; - public ArrayList donation_urls = new ArrayList( - Arrays.asList("https://ko-fi.com/svenar", "https://patreon.com/svenar")); + public ArrayList donation_urls = new ArrayList(Arrays.asList("https://ko-fi.com/svenar")); public int TASK_TPS = 20; private static PowerRanks instance; public static PluginDescriptionFile pdf; public AddonsManager addonsManager; private TablistManager tablistManager; - private static PowerColor powerColor; + private static BukkitPowerColor powerColor; public String plp; public static Logger log; public static String fileLoc; @@ -131,7 +128,7 @@ public class PowerRanks extends JavaPlugin implements Listener { public Map playerPermissionAttachment = new HashMap(); public Map playerTablistNameBackup = new HashMap(); public Map playerPlayTimeCache = new HashMap(); - // public Map playerNameCache = new HashMap(); + // public Map playerNameCache = new HashMap(); public PowerRanks() { PowerRanks.pdf = this.getDescription(); @@ -144,7 +141,7 @@ public PowerRanks() { public void onEnable() { instance = this; - new PowerLogger(getLogger()); + new PowerLogger(getLogger()); Instant startTime = Instant.now(); @@ -173,7 +170,7 @@ public void onEnable() { PowerRanks.log.info(""); PowerRanks.log.info("=== ------- LOADING CONFIGURATION ------ ==="); - PowerRanks.powerColor = new PowerColor(); + PowerRanks.powerColor = new BukkitPowerColor(); new Messages(this); new PowerRanksVerbose(this); @@ -216,6 +213,8 @@ public void onEnable() { this.tablistManager = new TablistManager(); this.tablistManager.start(); + this.setupCheckRankTagsTask(); + PowerRanks.log.info(""); PowerRanks.log .info(ChatColor.AQUA + " ██████ ██████ " + ChatColor.GREEN + " PowerRanks v" + pdf.getVersion()); @@ -234,8 +233,7 @@ public void onEnable() { System.setProperty("POWERRANKSRUNNING", "TRUE"); - PowerRanks.log - .info("If you'd like to donate, please visit " + donation_urls.get(0) + " or " + donation_urls.get(1)); + PowerRanks.log.info("If you'd like to donate, please visit " + donation_urls.get(0)); if (handle_update_checking()) { return; @@ -326,25 +324,25 @@ private void loadDefaultRanks() { rankMember.setName("Member"); rankMember.setDefault(true); rankMember.setWeight(0); - rankMember.setPrefix("#127e00M#1a8704E#239109M#2c9b0eB#35a513E#3eaf18R"); + rankMember.setPrefix("[gradient=#127e00,#3eaf18]MEMBER[/gradient]"); PRRank rankModerator = new PRRank(); rankModerator.setName("Moderator"); rankModerator.setDefault(false); rankModerator.setWeight(50); - rankModerator.setPrefix("#9d1dffM#a51eefO#ae1fdfD#b720d0E#bf21c0R#c822b0A#d123a1T#d92491O#e22581R"); + rankMember.setPrefix("[gradient=#9d1dff,#e22581]MODERATOR[/gradient]"); PRRank rankAdmin = new PRRank(); rankAdmin.setName("Admin"); rankAdmin.setDefault(false); rankAdmin.setWeight(75); - rankAdmin.setPrefix("#ffff00A#fbcc00D#f79900M#f36600I#ef3300N"); + rankMember.setPrefix("[gradient=#ffff00,#ef3300]ADMIN[/gradient]"); PRRank rankOwner = new PRRank(); rankOwner.setName("Owner"); rankOwner.setDefault(false); rankOwner.setWeight(100); - rankOwner.setPrefix("#ff00ffO#cc33ffW#9966ffN#6699ffE#33ccffR"); + rankMember.setPrefix("[gradient=#ff00ff,#33ccff]OWNER[/gradient]"); CacheManager.addRank(rankMember); CacheManager.addRank(rankModerator); @@ -397,6 +395,7 @@ public void run() { if (autosave_interval > 0) { new BukkitRunnable() { + @Override public void run() { PowerRanksVerbose.log("task", "Running task auto-save files"); @@ -440,25 +439,26 @@ public void run() { } }.runTaskTimer(this, update_check_interval, update_check_interval); + // new BukkitRunnable() { + // @Override + // public void run() { + // PowerRanksVerbose.log("task", "Running task check player name change"); - // new BukkitRunnable() { - // @Override - // public void run() { - // PowerRanksVerbose.log("task", "Running task check player name change"); - - // for (Player player : Bukkit.getServer().getOnlinePlayers()) { - // if (!playerNameCache.containsKey(player.getUniqueId())) { - // playerNameCache.put(player.getUniqueId(), player.getName()); - // } - - // if (!playerNameCache.get(player.getUniqueId()).equals(player.getName())) { - // log.info("Player name changed from '" + playerNameCache.get(player.getUniqueId()) + "' to '" + player.getName() + "'"); - // playerNameCache.put(player.getUniqueId(), player.getName()); - // CacheManager.getPlayer(player.getUniqueId().toString()).setName(player.getName()); - // } - // } - // } - // }.runTaskTimer(this, TASK_TPS, TASK_TPS); + // for (Player player : Bukkit.getServer().getOnlinePlayers()) { + // if (!playerNameCache.containsKey(player.getUniqueId())) { + // playerNameCache.put(player.getUniqueId(), player.getName()); + // } + + // if (!playerNameCache.get(player.getUniqueId()).equals(player.getName())) { + // log.info("Player name changed from '" + + // playerNameCache.get(player.getUniqueId()) + "' to '" + player.getName() + + // "'"); + // playerNameCache.put(player.getUniqueId(), player.getName()); + // CacheManager.getPlayer(player.getUniqueId().toString()).setName(player.getName()); + // } + // } + // } + // }.runTaskTimer(this, TASK_TPS, TASK_TPS); } private Player getPlayerFromUUID(UUID uuid) { @@ -466,7 +466,7 @@ private Player getPlayerFromUUID(UUID uuid) { // UUID---------- ==="); Player player = null; for (Player online_player : Bukkit.getServer().getOnlinePlayers()) { - if (uuid == online_player.getUniqueId()) { + if (uuid.equals(online_player.getUniqueId())) { player = online_player; break; } @@ -559,7 +559,114 @@ public void run() { } } } - }.runTaskTimer(this, 20, 20); + }.runTaskTimer(this, Util.TASK_TPS, Util.TASK_TPS); + } + + private void setupCheckRankTagsTask() { + new BukkitRunnable() { + @Override + public void run() { + for (PRPlayer prPlayer : CacheManager.getPlayers()) { + + List ranksToRemove = new ArrayList(); + List ranksToAdd = new ArrayList(); + for (PRPlayerRank rank : prPlayer.getRanks()) { + for (Entry entry : rank.getTags().entrySet()) { + if (entry.getKey().equalsIgnoreCase("expires")) { + long currentTimeMillis = System.currentTimeMillis(); + long expires = Util.convertToLong(entry.getValue()); + if (currentTimeMillis >= expires) { + ranksToRemove.add(rank); + } + } + + if (entry.getKey().equalsIgnoreCase("expiry-return-ranks")) { + try { + @SuppressWarnings("unchecked") + List expiryReturnRanks = (List) entry.getValue(); + + if (expiryReturnRanks.size() > 0) { + ranksToRemove = new ArrayList(); + for (PRPlayerRank prPlayerRank : prPlayer.getRanks()) { + ranksToRemove.add(prPlayerRank); + } + } + + for (String rankObject : expiryReturnRanks) { + String rankName = rankObject.contains(";") ? rankObject.split(";")[0] + : rankObject; + List rankTags = rankObject.contains(";") + ? new ArrayList<>(Arrays.asList(rankObject.split(";"))) + : new ArrayList(); + if (!rankTags.isEmpty()) { + rankTags.remove(0); + } + + PRRank prRank = CacheManager.getRank(rankName); + if (prRank != null) { + PRPlayerRank prPlayerRank = new PRPlayerRank(prRank.getName()); + for (String rankTag : rankTags) { + prPlayerRank.addTagRaw(rankTag.split(":")[0], + Util.formatStringToType(rankTag.split(":")[1])); + } + ranksToAdd.add(prPlayerRank); + } + } + } catch (Exception e) { + PowerRanks.log.warning("Failed to parse expiry-return-ranks for rank " + + rank.getName() + " for player " + prPlayer.getName()); + } + } + } + } + + for (PRPlayerRank rank : ranksToRemove) { + prPlayer.removeRank(rank); + String prPlayername = prPlayer.getName(); + if (prPlayername.length() == 0) { + prPlayername = Util.getNameFromAPI(prPlayer.getUUID().toString()); + } + + getServer().getConsoleSender().sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage("general.player-rank-expired-console"), + ImmutableMap.builder() + .put("player", prPlayername) + .put("rank", rank.getName()) + .build(), + '[', ']')); + + Player player = getPlayerFromUUID(prPlayer.getUUID()); + if (player != null) { + PowerRanks.getInstance().updateTablistName(player); + PowerRanks.getInstance().getTablistManager().updateSorting(player); + + player.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage("general.player-rank-has-expired"), + ImmutableMap.builder() + .put("player", player.getName()) + .put("rank", rank.getName()) + .build(), + '[', ']')); + } + } + + for (PRPlayerRank rank : ranksToAdd) { + if (!prPlayer.hasRank(rank.getName())) { + prPlayer.addRank(rank); + + Player player = getPlayerFromUUID(prPlayer.getUUID()); + if (player != null) { + PowerRanks.getInstance().updateTablistName(player); + PowerRanks.getInstance().getTablistManager().updateSorting(player); + } + } + } + } + } + + }.runTaskTimer(this, Util.TASK_TPS, Util.TASK_TPS * 10); } public TABHook getTABHook() { @@ -574,7 +681,8 @@ private boolean handle_update_checking() { if (getConfigBool("updates.enable_update_checking", false)) { PowerRanks.log.info("Checking for updates..."); Updater updater = new Updater(this, 79251, this.getFile(), - getConfigBool("updates.automatic_download_updates", false) ? UpdateType.DEFAULT : UpdateType.NO_DOWNLOAD, + getConfigBool("updates.automatic_download_updates", false) ? UpdateType.DEFAULT + : UpdateType.NO_DOWNLOAD, true); if (updater.getResult() == UpdateResult.UPDATE_AVAILABLE) { if (!getConfigBool("updates.automatic_download_updates", false)) { @@ -668,7 +776,7 @@ public boolean getConfigBool(String path, boolean defaultValue) { if (configManager != null) { return configManager.getBool(path, defaultValue); } - + final File configFile = new File(this.getDataFolder() + File.separator + "config" + ".yml"); final YamlConfiguration configYaml = new YamlConfiguration(); try { @@ -684,7 +792,7 @@ public String getConfigString(String path, String defaultValue) { if (configManager != null) { return configManager.getString(path, defaultValue); } - + final File configFile = new File(this.getDataFolder() + File.separator + "config" + ".yml"); final YamlConfiguration configYaml = new YamlConfiguration(); try { @@ -694,14 +802,14 @@ public String getConfigString(String path, String defaultValue) { } return configYaml.getString(path, defaultValue); - + } public boolean configContainsKey(String path) { if (configManager != null) { return configManager.hasKey(path); } - + final File configFile = new File(this.getDataFolder() + File.separator + "config" + ".yml"); final YamlConfiguration configYaml = new YamlConfiguration(); try { @@ -820,26 +928,33 @@ public void run() { return; } + prefix_format = prefix.length() == 0 ? prefix_format.replaceAll("\\[prefix\\]( )?", "") + : prefix_format; prefix_format = Util.powerFormatter(prefix_format, - ImmutableMap.builder().put("prefix", prefix).put("suffix", suffix) + ImmutableMap.builder() + .put("prefix", prefix) .put("usertag", !PowerRanks.plugin_hook_deluxetags ? usertag : getDeluxeTagsHook().getPlayerDisplayTag(player)) .build(), '[', ']'); + suffix_format = suffix.length() == 0 ? suffix_format.replaceAll("( )?\\[suffix\\]", "") + : suffix_format; suffix_format = Util.powerFormatter(suffix_format, - ImmutableMap.builder().put("prefix", prefix).put("suffix", suffix) - .put("usertag", !PowerRanks.plugin_hook_deluxetags ? usertag - : getDeluxeTagsHook().getPlayerDisplayTag(player)) + ImmutableMap.builder() + .put("suffix", suffix) + .put("usertag", + !PowerRanks.plugin_hook_deluxetags ? usertag + : getDeluxeTagsHook().getPlayerDisplayTag(player)) .build(), '[', ']'); prefix_format += nameColor; prefix_format = getPowerColor().format(PowerColor.UNFORMATTED_COLOR_CHAR, prefix_format, true, - true); + false, true); suffix_format = getPowerColor().format(PowerColor.UNFORMATTED_COLOR_CHAR, suffix_format, true, - true); + false, true); INametagApi nteAPI = NametagEdit.getApi(); if (nteAPI != null) { @@ -858,21 +973,22 @@ public void updateTablistName(Player player) { } catch (NoSuchMethodError e) { } - List ranknames = new ArrayList<>(); - for (PRPlayerRank playerRank : CacheManager.getPlayer(player.getUniqueId().toString()).getRanks()) { - ranknames.add(playerRank.getName()); - } + PRPlayer prPlayer = CacheManager.getPlayer(player); + + List playerRanks = prPlayer.getRanks(); List ranks = new ArrayList(); - for (String rankname : ranknames) { - PRRank rank = CacheManager.getRank(rankname); - if (rank != null) { - ranks.add(rank); + for (PRPlayerRank playerRank : playerRanks) { + if (!playerRank.isDisabled()) { + PRRank rank = CacheManager.getRank(playerRank.getName()); + if (rank != null) { + ranks.add(rank); + } } } - ranks = PRUtil.sortRanksByWeight(ranks); - Collections.reverse(ranks); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); String formatted_prefix = ""; String formatted_suffix = ""; @@ -902,9 +1018,8 @@ public void updateTablistName(Player player) { formatted_suffix = ""; } - PRPlayer targetPlayer = CacheManager.getPlayer(player.getUniqueId().toString()); Map availableUsertags = getUsertagManager().getMap("usertags", new HashMap()); - ArrayList playerUsertags = targetPlayer.getUsertags(); + ArrayList playerUsertags = prPlayer.getUsertags(); for (String playerUsertag : playerUsertags) { String value = ""; @@ -979,15 +1094,15 @@ public void updateTablistName(Player player, String prefix, String suffix, } public static String chatColor(String textToTranslate, boolean custom_colors) { - return getPowerColor().format(PowerColor.UNFORMATTED_COLOR_CHAR, textToTranslate, custom_colors, true); + return getPowerColor().format(PowerColor.UNFORMATTED_COLOR_CHAR, textToTranslate, custom_colors, false, true); } public static String chatColorAlt(final String textToTranslate, final boolean custom_colors) { - return getPowerColor().format(PowerColor.UNFORMATTED_COLOR_CHAR, textToTranslate, custom_colors, false); + return getPowerColor().format(PowerColor.UNFORMATTED_COLOR_CHAR, textToTranslate, custom_colors, false, false); } public static String applyMultiColorFlow(String rawColors, String text) { - String regexColors = "(&[a-fA-F0-9])|(#[a-fA-F0-9]{6})"; + String regexColors = "(&[a-fA-F0-9])|(&?#[a-fA-F0-9]{6})"; String output = ""; Pattern p = Pattern.compile(regexColors); @@ -1049,89 +1164,14 @@ public static PowerRanksExpansion getPlaceholderapiExpansion() { return placeholderapiExpansion; } - public ArrayList getEffectivePlayerPermissions(Player player) { - PRPlayer prPlayer = null; - - ArrayList permissions = new ArrayList(); - - if (player == null) { - return permissions; - } - - try { - prPlayer = CacheManager.getPlayer(player.getUniqueId().toString()); - } catch (Exception e) { - e.printStackTrace(); - return permissions; - } - - if (prPlayer == null) { - return permissions; - } - - for (PRPermission permission : prPlayer.getPermissions()) { - permissions.add(permission); - } - - List ranknames = new ArrayList<>(); - for (PRPlayerRank playerRank : CacheManager.getPlayer(player.getUniqueId().toString()).getRanks()) { - ranknames.add(playerRank.getName()); - } - - List playerRanks = new ArrayList(); - for (String rankname : ranknames) { - PRRank rank = CacheManager.getRank(rankname); - if (rank != null) { - playerRanks.add(rank); - } - } - - // playerRanks = PRUtil.sortRanksByWeight(playerRanks); - - List effectiveRanks = new ArrayList(); + public List getEffectivePlayerPermissions(Player player) { + PRPlayer prPlayer = CacheManager.getPlayer(player.getUniqueId().toString()); - if (Objects.nonNull(playerRanks)) { - effectiveRanks.addAll(playerRanks); - - for (PRRank playerRank : playerRanks) { - for (String inheritance : playerRank.getInheritances()) { - PRRank inheritanceRank = CacheManager.getRank(inheritance); - if (inheritanceRank != null) { - effectiveRanks.add(inheritanceRank); - } - } - } - } - - effectiveRanks.removeAll(Collections.singleton(null)); - effectiveRanks = new ArrayList<>(new HashSet<>(effectiveRanks)); - effectiveRanks = PRUtil.sortRanksByWeight(effectiveRanks); - - for (PRPermission permission : prPlayer.getPermissions()) { - permissions.add(permission); - } - - for (PRRank effectiveRank : effectiveRanks) { - if (Objects.nonNull(effectiveRank)) { - for (PRPermission permission : effectiveRank.getPermissions()) { - - PRPermission permissionToRemove = null; - for (PRPermission existingPermission : permissions) { - if (permission.getName().equals(existingPermission.getName())) { - permissionToRemove = existingPermission; - break; - } - } - if (Objects.nonNull(permissionToRemove)) { - permissions.remove(permissionToRemove); - } - - permissions.add(permission); - } - } + if (prPlayer == null) { + return new ArrayList(); } - return permissions; + return prPlayer.getEffectivePermissions(); } public TablistManager getTablistManager() { @@ -1158,7 +1198,7 @@ public BungeecordManager getBungeecordManager() { return this.bungeecordManager; } - public static PowerColor getPowerColor() { + public static BukkitPowerColor getPowerColor() { return powerColor; } diff --git a/src/main/java/nl/svenar/powerranks/addons/PowerRanksConfig.java b/src/main/java/nl/svenar/powerranks/addons/PowerRanksConfig.java index 716d1d7..6b7bc65 100644 --- a/src/main/java/nl/svenar/powerranks/addons/PowerRanksConfig.java +++ b/src/main/java/nl/svenar/powerranks/addons/PowerRanksConfig.java @@ -66,7 +66,7 @@ public void set(String field, Object value) { public boolean isSet(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isSet(field) : null; + return config != null ? config.isSet(field) : false; } public Object get(String field) { @@ -81,17 +81,17 @@ public String getString(String field) { public int getInt(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.getInt(field) : null; + return config != null ? config.getInt(field) : 0; } public boolean getBoolean(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.getBoolean(field) : null; + return config != null ? config.getBoolean(field) : false; } public double getDouble(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.getDouble(field) : null; + return config != null ? config.getDouble(field) : 0.0; } public List getStringList(String field) { @@ -126,37 +126,37 @@ public List getFloatList(String field) { public boolean isString(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isString(field) : null; + return config != null ? config.isString(field) : false; } public boolean isBoolean(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isBoolean(field) : null; + return config != null ? config.isBoolean(field) : false; } public boolean isConfigurationSection(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isConfigurationSection(field) : null; + return config != null ? config.isConfigurationSection(field) : false; } public boolean isColor(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isColor(field) : null; + return config != null ? config.isColor(field) : false; } public boolean isDouble(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isDouble(field) : null; + return config != null ? config.isDouble(field) : false; } public boolean isInt(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isInt(field) : null; + return config != null ? config.isInt(field) : false; } public boolean isList(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isList(field) : null; + return config != null ? config.isList(field) : false; } // public boolean isLocation(String field) { @@ -166,6 +166,6 @@ public boolean isList(String field) { public boolean isLong(String field) { YamlConfiguration config = loadConfigFile(); - return config != null ? config.isLong(field) : null; + return config != null ? config.isLong(field) : false; } } diff --git a/src/main/java/nl/svenar/powerranks/api/PowerRanksAPI.java b/src/main/java/nl/svenar/powerranks/api/PowerRanksAPI.java index a701911..fcf68ab 100644 --- a/src/main/java/nl/svenar/powerranks/api/PowerRanksAPI.java +++ b/src/main/java/nl/svenar/powerranks/api/PowerRanksAPI.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Map; import org.bukkit.entity.Player; @@ -15,7 +16,7 @@ public class PowerRanksAPI { - private String API_VERSION = "1.3"; + private String API_VERSION = "1.4"; public static PowerRanks plugin; private Users users; @@ -91,9 +92,26 @@ public List getRanks(Player player) { * @return true if success, false otherwise */ public boolean setPlayerRank(Player player, String rankname) { + return setPlayerRank(player, rankname, null); + } + + /** + * Overwrite all ranks of a player and set it to a single one + * + * @param player + * @param rankname + * @param tags + * @return true if success, false otherwise + */ + public boolean setPlayerRank(Player player, String rankname, Map tags) { PRRank rank = CacheManager.getRank(rankname); if (rank != null) { PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); + if (tags != null) { + for (String tag : tags.keySet()) { + playerRank.addTag(tag, tags.get(tag)); + } + } CacheManager.getPlayer(player.getUniqueId().toString()).setRank(playerRank); } return rank != null; @@ -107,9 +125,26 @@ public boolean setPlayerRank(Player player, String rankname) { * @return true if success, false otherwise */ public boolean addPlayerRank(Player player, String rankname) { + return addPlayerRank(player, rankname, null); + } + + /** + * Add a rankname to the player's current ranks + * + * @param player + * @param rankname + * @param tags + * @return true if success, false otherwise + */ + public boolean addPlayerRank(Player player, String rankname, Map tags) { PRRank rank = CacheManager.getRank(rankname); if (rank != null) { PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); + if (tags != null) { + for (String tag : tags.keySet()) { + playerRank.addTag(tag, tags.get(tag)); + } + } CacheManager.getPlayer(player.getUniqueId().toString()).addRank(playerRank); } return rank != null; @@ -157,6 +192,22 @@ public List getAllowedPermissions(String rank) { return permissions; } + /** + * Get all allowed permissions of a player + * + * @param player + * @return list of allowed permissions that a player has + */ + public List getAllowedPlayerPermissions(Player player) { + List permissions = new ArrayList(); + for (PRPermission permission : CacheManager.getPlayer(player).getPermissions()) { + if (permission.getValue()) { + permissions.add(permission.getName()); + } + } + return permissions; + } + /** * Get all denied permissions of a rank * @@ -173,6 +224,22 @@ public List getDeniedPermissions(String rank) { return permissions; } + /** + * Get all denied permissions of a player + * + * @param player + * @return list of denied permissions that a player has + */ + public List getDeniedPlayerPermissions(Player player) { + List permissions = new ArrayList(); + for (PRPermission permission : CacheManager.getPlayer(player).getPermissions()) { + if (!permission.getValue()) { + permissions.add(permission.getName()); + } + } + return permissions; + } + /** * Add a permission to a rank * @@ -182,7 +249,7 @@ public List getDeniedPermissions(String rank) { * @return true if success, false otherwise */ public boolean addPermission(String rank, String permission, boolean allowed) { - return users.addPermission(users.getRankIgnoreCase(rank), permission, allowed); + return this.users.addPermission(users.getRankIgnoreCase(rank), permission, allowed); } /** @@ -193,7 +260,7 @@ public boolean addPermission(String rank, String permission, boolean allowed) { * @return true if success, false otherwise */ public boolean removePermission(String rank, String permission) { - return users.removePermission(users.getRankIgnoreCase(rank), permission); + return this.users.removePermission(users.getRankIgnoreCase(rank), permission); } /** @@ -203,7 +270,7 @@ public boolean removePermission(String rank, String permission) { * @return List of inherited rank names */ public List getInheritances(String rank) { - return users.getInheritances(users.getRankIgnoreCase(rank)); + return this.users.getInheritances(users.getRankIgnoreCase(rank)); } /** @@ -214,7 +281,7 @@ public List getInheritances(String rank) { * @return true if success, false otherwise */ public boolean addInheritance(String rank, String inheritance) { - return users.addInheritance(users.getRankIgnoreCase(rank), inheritance); + return this.users.addInheritance(users.getRankIgnoreCase(rank), inheritance); } /** @@ -225,40 +292,40 @@ public boolean addInheritance(String rank, String inheritance) { * @return true if success, false otherwise */ public boolean removeInheritance(String rank, String inheritance) { - return users.removeInheritance(users.getRankIgnoreCase(rank), inheritance); - } - - /** - * Should the rank be given to the players when they join for the first time? - * - * @param rank - * @param isDefault - * @return true if rank exists, false otherwise - */ - public boolean setDefault(String rank, boolean isDefault) { - PRRank targetRank = CacheManager.getRank(rank); - if (targetRank != null) { - targetRank.setDefault(isDefault); - } - return targetRank != null; - } - - /** - * Get the list of default ranks that are given to new players - * - * @return List of default ranks - */ - public List getDefaultRanks() { - List defaultRanks = new ArrayList(); - - for (PRRank rank : CacheManager.getRanks()) { - if (rank.isDefault()) { - defaultRanks.add(rank.getName()); - } - } - - return defaultRanks; - } + return this.users.removeInheritance(users.getRankIgnoreCase(rank), inheritance); + } + + /** + * Should the rank be given to the players when they join for the first time? + * + * @param rank + * @param isDefault + * @return true if rank exists, false otherwise + */ + public boolean setDefault(String rank, boolean isDefault) { + PRRank targetRank = CacheManager.getRank(rank); + if (targetRank != null) { + targetRank.setDefault(isDefault); + } + return targetRank != null; + } + + /** + * Get the list of default ranks that are given to new players + * + * @return List of default ranks + */ + public List getDefaultRanks() { + List defaultRanks = new ArrayList(); + + for (PRRank rank : CacheManager.getRanks()) { + if (rank.isDefault()) { + defaultRanks.add(rank.getName()); + } + } + + return defaultRanks; + } /** * Get all available ranknames @@ -454,7 +521,7 @@ public boolean delBuyableRank(String rank, String buyable_rank) { * @return true if success, false otherwise */ public boolean setRankBuyCost(String rank, int cost) { - return users.setBuyCost(rank, String.valueOf(cost)); + return this.users.setBuyCost(rank, String.valueOf(cost)); } /** @@ -465,7 +532,7 @@ public boolean setRankBuyCost(String rank, int cost) { * @return true if success, false otherwise */ public boolean addPermission(Player player, String permission, boolean allowed) { - return users.addPlayerPermission(player.getName(), permission, allowed); + return this.users.addPlayerPermission(player.getName(), permission, allowed); } /** @@ -476,73 +543,73 @@ public boolean addPermission(Player player, String permission, boolean allowed) * @return true if success, false otherwise */ public boolean removePermission(Player player, String permission) { - return users.delPlayerPermission(player.getName(), permission); - } - - /** - * Create a usertag on the server - * - * @param usertag - * @param value - * @return true if successful, false otherwise - */ - public boolean createUsertag(String usertag, String value) { - return this.createUsertag(usertag, value); - } - - /** - * Change a usertag on the server - * - * @param usertag - * @param value - * @return true if successful, false otherwise - */ - public boolean editUsertag(String usertag, String value) { - return this.editUsertag(usertag, value); - } - - /** - * Delete a usertag from the server - * - * @param usertag - * @return true if successful, false otherwise - */ - public boolean removeUsertag(String usertag) { - return this.users.removeUserTag(usertag); - } - - /** - * Assign a usertag to an player - * - * @param player - * @param usertag - * @return true if successful, false otherwise - */ - public boolean setUsertag(Player player, String usertag) { - return this.users.setUserTag(player.getName(), usertag); - } - - /** - * Add a usertag to an player - * - * @param player - * @param usertag - * @return true if successful, false otherwise - */ - public boolean addUsertag(Player player, String usertag) { - return this.users.addUserTag(player.getName(), usertag); - } - - /** - * Remove an usertag from a player - * - * @param player - * @param usertag - * @return true if successful, false otherwise - */ - public boolean delUsertag(Player player, String usertag) { - return this.users.delUserTag(player.getName(), usertag); - } + return this.users.delPlayerPermission(player.getName(), permission); + } + + /** + * Create a usertag on the server + * + * @param usertag + * @param value + * @return true if successful, false otherwise + */ + public boolean createUsertag(String usertag, String value) { + return this.users.createUserTag(usertag, value); + } + + /** + * Change a usertag on the server + * + * @param usertag + * @param value + * @return true if successful, false otherwise + */ + public boolean editUsertag(String usertag, String value) { + return this.users.editUserTag(usertag, value); + } + + /** + * Delete a usertag from the server + * + * @param usertag + * @return true if successful, false otherwise + */ + public boolean removeUsertag(String usertag) { + return this.users.removeUserTag(usertag); + } + + /** + * Assign a usertag to an player + * + * @param player + * @param usertag + * @return true if successful, false otherwise + */ + public boolean setUsertag(Player player, String usertag) { + return this.users.setUserTag(player.getName(), usertag); + } + + /** + * Add a usertag to an player + * + * @param player + * @param usertag + * @return true if successful, false otherwise + */ + public boolean addUsertag(Player player, String usertag) { + return this.users.addUserTag(player.getName(), usertag); + } + + /** + * Remove an usertag from a player + * + * @param player + * @param usertag + * @return true if successful, false otherwise + */ + public boolean delUsertag(Player player, String usertag) { + return this.users.delUserTag(player.getName(), usertag); + } /** * Deprecated | replaced by {@link #getPrimaryRank(Player)} @@ -559,8 +626,8 @@ public String getPlayerRank(Player player) { } /** - * Deprecated | replaced by {@link #getAllowedPermissions(Player, String)} & - * {@link #getDeniedPermissions(Player, String)} + * Deprecated | replaced by {@link #getAllowedPermissions(String)} & + * {@link #getDeniedPermissions(String)} * * Get a list of permissions of a rank * @@ -588,7 +655,7 @@ public List getPermissions(String rank) { */ @Deprecated public boolean addPermission(String rank, String permission) { - return users.addPermission(users.getRankIgnoreCase(rank), + return this.users.addPermission(users.getRankIgnoreCase(rank), permission.startsWith("-") ? permission.replaceFirst("-", "") : permission, !permission.startsWith("-")); } @@ -605,7 +672,7 @@ public boolean addPermission(String rank, String permission) { */ @Deprecated public boolean addPermission(Player player, String permission) { - return users.addPlayerPermission(player.getName(), + return this.users.addPlayerPermission(player.getName(), permission.startsWith("-") ? permission.replaceFirst("-", "") : permission, !permission.startsWith("-")); } diff --git a/src/main/java/nl/svenar/powerranks/cache/CacheManager.java b/src/main/java/nl/svenar/powerranks/cache/CacheManager.java old mode 100644 new mode 100755 index d77d18d..0900533 --- a/src/main/java/nl/svenar/powerranks/cache/CacheManager.java +++ b/src/main/java/nl/svenar/powerranks/cache/CacheManager.java @@ -2,7 +2,6 @@ import java.io.File; import java.util.ArrayList; -import java.util.ConcurrentModificationException; import java.util.List; import java.util.Map; import java.util.Objects; @@ -21,8 +20,8 @@ import nl.svenar.common.storage.provided.SQLiteStorageManager; import nl.svenar.common.storage.provided.YAMLStorageManager; import nl.svenar.common.structure.PRPlayer; -import nl.svenar.common.structure.PRPlayerRank; import nl.svenar.common.structure.PRRank; +import nl.svenar.common.utils.PRCache; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.addons.PowerRanksAddon; import nl.svenar.powerranks.events.OnJoin; @@ -31,116 +30,54 @@ public class CacheManager { private static PowerStorageManager storageManager; - private static ArrayList registeredRanks = new ArrayList(); - private static ArrayList registeredPlayers = new ArrayList(); - private static String tmpConvertDefaultRank = ""; - public static ArrayList getRanks() { - return registeredRanks; + public static List getRanks() { + return PRCache.getRanks(); } public static void setRanks(ArrayList ranks) { - registeredRanks = ranks; + PRCache.setRanks(ranks); } public static void addRank(PRRank rank) { - if (Objects.isNull(registeredRanks)) { - registeredRanks = new ArrayList(); - } - - registeredRanks.add(rank); + PRCache.addRank(rank); } public static void removeRank(PRRank rank) { - if (Objects.isNull(registeredRanks)) { - registeredRanks = new ArrayList(); - } - - registeredRanks.remove(rank); + PRCache.removeRank(rank); } public static PRRank getRank(String name) { - if (Objects.isNull(registeredRanks)) { - registeredRanks = new ArrayList(); - } - - for (PRRank rank : registeredRanks) { - if (rank.getName().equals(name)) { - return rank; - } - } - return null; + return PRCache.getRank(name); } - public static ArrayList getPlayers() { - return registeredPlayers; + public static List getPlayers() { + return PRCache.getPlayers(); } public static void setPlayers(ArrayList players) { - registeredPlayers = players; + PRCache.setPlayers(players); } public static void addPlayer(PRPlayer player) { - if (Objects.isNull(registeredPlayers)) { - registeredPlayers = new ArrayList(); - } + PRCache.addPlayer(player); + } - registeredPlayers.add(player); + public static PRPlayer getPlayer(Player player) { + return getPlayer(player.getUniqueId().toString()); } public static PRPlayer getPlayer(String identifier) { - try { - if (Objects.isNull(registeredPlayers)) { - registeredPlayers = new ArrayList(); - } - - for (PRPlayer player : registeredPlayers) { - if (player.getName().equalsIgnoreCase(identifier) || player.getUUID().toString().replaceAll("-", "").equalsIgnoreCase(identifier.replaceAll("-", ""))) { - return player; - } - } - - Player player = null; - - for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) { - if (onlinePlayer.getName().equals(identifier) - || onlinePlayer.getUniqueId().toString().replaceAll("-", "").equalsIgnoreCase(identifier.replaceAll("-", ""))) { - player = onlinePlayer; - break; - } - } - - if (Objects.isNull(player)) { - return null; - } - - return createPlayer(player); - } catch (ConcurrentModificationException cme) { - return null; - } + return PRCache.getPlayer(identifier); } public static PRPlayer createPlayer(Player player) { - PRPlayer prPlayer = new PRPlayer(); - prPlayer.setUUID(player.getUniqueId()); - prPlayer.setName(player.getName()); - for (PRRank rank : CacheManager.getDefaultRanks()) { - PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); - prPlayer.addRank(playerRank); - } - CacheManager.addPlayer(prPlayer); - return prPlayer; + return PRCache.createPlayer(player.getName(), player.getUniqueId()); } public static List getDefaultRanks() { - List defaultRanks = new ArrayList(); - for (PRRank rank : getRanks()) { - if (rank.isDefault()) { - defaultRanks.add(rank); - } - } - return defaultRanks; + return PRCache.getDefaultRanks(); } public static void load(String dataDirectory) { @@ -191,16 +128,18 @@ public static void load(String dataDirectory) { PowerRanks.getInstance().getLogger().warning("Unknown storage method configured! Falling back to YAML"); storageManager = new YAMLStorageManager(dataDirectory, "ranks.yml", "players.yml"); } else { - PowerRanks.getInstance().getLogger() - .info("Using storage engine from add-on: " + usedStorageManagerAddon.getIdentifier()); + if (usedStorageManagerAddon != null) { + PowerRanks.getInstance().getLogger() + .info("Using storage engine from add-on: " + usedStorageManagerAddon.getIdentifier()); + } } } } storageManager.loadAll(); - registeredRanks = (ArrayList) storageManager.getRanks(); - registeredPlayers = (ArrayList) storageManager.getPlayers(); + PRCache.setRanks((ArrayList) storageManager.getRanks()); + PRCache.setPlayers((ArrayList) storageManager.getPlayers()); for (Player player : Bukkit.getServer().getOnlinePlayers()) { OnJoin.handleJoin(PowerRanks.getInstance(), player); @@ -212,8 +151,8 @@ public static void load(String dataDirectory) { } public static void save() { - storageManager.setRanks(registeredRanks); - storageManager.setPlayers(registeredPlayers); + storageManager.setRanks(PRCache.getRanks()); + storageManager.setPlayers(PRCache.getPlayers()); storageManager.saveAll(); } diff --git a/src/main/java/nl/svenar/powerranks/commands/PowerCommandHandler.java b/src/main/java/nl/svenar/powerranks/commands/PowerCommandHandler.java index f5c7535..dc86895 100644 --- a/src/main/java/nl/svenar/powerranks/commands/PowerCommandHandler.java +++ b/src/main/java/nl/svenar/powerranks/commands/PowerCommandHandler.java @@ -65,6 +65,7 @@ import nl.svenar.powerranks.commands.rank.cmd_setprefix; import nl.svenar.powerranks.commands.rank.cmd_setsuffix; import nl.svenar.powerranks.commands.rank.cmd_setweight; +import nl.svenar.powerranks.commands.test.cmd_test; import nl.svenar.powerranks.commands.usertags.cmd_addusertag; import nl.svenar.powerranks.commands.usertags.cmd_clearusertag; import nl.svenar.powerranks.commands.usertags.cmd_createusertag; @@ -149,6 +150,7 @@ public PowerCommandHandler(PowerRanks plugin) { new cmd_webeditor(plugin, "webeditor", COMMAND_EXECUTOR.ALL); new cmd_webeditor(plugin, "we", COMMAND_EXECUTOR.ALL); + new cmd_test(plugin, "test", COMMAND_EXECUTOR.ALL); } private static boolean canExecuteCommand(CommandSender sender, PowerCommand command_handler) { diff --git a/src/main/java/nl/svenar/powerranks/commands/addons/cmd_addonmanager.java b/src/main/java/nl/svenar/powerranks/commands/addons/cmd_addonmanager.java index 958e70d..bd83293 100644 --- a/src/main/java/nl/svenar/powerranks/commands/addons/cmd_addonmanager.java +++ b/src/main/java/nl/svenar/powerranks/commands/addons/cmd_addonmanager.java @@ -73,6 +73,17 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, } } + if (addon == null) { + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager().getFormattedMessage( + "commands." + commandName.toLowerCase() + ".download-not-available"), + ImmutableMap.builder() + .put("player", sender.getName()) + .build(), + '[', ']')); + return false; + } + if (addon.isDownloadable()) { if (addon.isCompatible()) { if (addon.download()) { diff --git a/src/main/java/nl/svenar/powerranks/commands/buyable/cmd_buyrank.java b/src/main/java/nl/svenar/powerranks/commands/buyable/cmd_buyrank.java index 9c657e6..5ad6886 100644 --- a/src/main/java/nl/svenar/powerranks/commands/buyable/cmd_buyrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/buyable/cmd_buyrank.java @@ -58,7 +58,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage( - "commands." + commandName.toLowerCase() + ".succes-buy"), + "commands." + commandName.toLowerCase() + ".success-buy"), ImmutableMap.builder() .put("player", sender.getName()) .put("rank", rank.getName()) diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_addownrank.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_addownrank.java index 731de77..43bf2f5 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_addownrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_addownrank.java @@ -36,7 +36,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, boolean commandAllowed = false; if (sender instanceof Player) { - commandAllowed = sender.hasPermission("powerranks.cmd." + commandName.toLowerCase() + "." + target_rank); + commandAllowed = sender + .hasPermission("powerranks.cmd." + commandName.toLowerCase() + "." + target_rank); } else { commandAllowed = true; } @@ -48,11 +49,11 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); targetPlayer.addRank(playerRank); - - if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { - PowerRanks.getInstance().updateTablistName(Bukkit.getPlayer(targetPlayer.getUUID())); - PowerRanks.getInstance().getTablistManager().updateSorting(Bukkit.getPlayer(targetPlayer.getUUID())); - } + if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { + PowerRanks.getInstance().updateTablistName(Bukkit.getPlayer(targetPlayer.getUUID())); + PowerRanks.getInstance().getTablistManager() + .updateSorting(Bukkit.getPlayer(targetPlayer.getUUID())); + } sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager() @@ -73,7 +74,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, .build(), '[', ']')); } else { - sender.sendMessage(Util.powerFormatter( + if (targetPlayer != null && rank != null) { + sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager() .getFormattedMessage( "commands." + commandName.toLowerCase() + ".failed-executor"), @@ -82,6 +84,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, .put("rank", rank.getName()) .build(), '[', ']')); + } } } else { sender.sendMessage(PowerRanks.getLanguageManager().getFormattedMessage("general.no-permission")); @@ -99,8 +102,13 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (PRRank rank : this.users.getGroups()) { - tabcomplete.add(rank.getName()); + if (sender instanceof Player) { + PRPlayer targetPlayer = CacheManager.getPlayer(sender.getName()); + for (PRRank rank : CacheManager.getRanks()) { + if (!targetPlayer.hasRank(rank.getName())) { + tabcomplete.add(rank.getName()); + } + } } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_addplayerperm.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_addplayerperm.java index 214349f..a4c2a66 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_addplayerperm.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_addplayerperm.java @@ -4,7 +4,9 @@ import com.google.common.collect.ImmutableMap; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.commands.PowerCommand; import nl.svenar.powerranks.data.Users; import nl.svenar.powerranks.util.Util; @@ -29,7 +31,7 @@ public cmd_addplayerperm(PowerRanks plugin, String command_name, COMMAND_EXECUTO public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { if (args.length == 2) { - final String target_player = args[0]; + final String targetPlayerName = args[0]; String permission = args[1]; boolean allowed = true; // this.setValue(!name.startsWith("-")); @@ -37,14 +39,14 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, permission = permission.replaceFirst("-", ""); allowed = false; } - final boolean result = this.users.addPlayerPermission(target_player, permission, allowed); + final boolean result = this.users.addPlayerPermission(targetPlayerName, permission, allowed); if (result) { sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage( "commands." + commandName.toLowerCase() + ".success"), ImmutableMap.builder() .put("player", sender.getName()) - .put("target", target_player) + .put("target", targetPlayerName) .put("permission", permission) .build(), '[', ']')); @@ -54,7 +56,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, "commands." + commandName.toLowerCase() + ".failed"), ImmutableMap.builder() .put("player", sender.getName()) - .put("target", target_player) + .put("target", targetPlayerName) .put("permission", permission) .build(), '[', ']')); @@ -72,7 +74,7 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (PRPlayer player : CacheManager.getPlayers()) { tabcomplete.add(player.getName()); } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_addrank.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_addrank.java index a0e6e8f..e5c6a18 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_addrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_addrank.java @@ -1,6 +1,7 @@ package nl.svenar.powerranks.commands.player; import java.util.ArrayList; +import java.util.Arrays; import com.google.common.collect.ImmutableMap; @@ -31,12 +32,14 @@ public cmd_addrank(PowerRanks plugin, String command_name, COMMAND_EXECUTOR ce) @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { - if (args.length == 2) { + if (args.length >= 2) { String target_rank = users.getRankIgnoreCase(args[1]); + String[] tags = Arrays.copyOfRange(args, 2, args.length); boolean commandAllowed = false; if (sender instanceof Player) { - commandAllowed = sender.hasPermission("powerranks.cmd." + commandName.toLowerCase() + "." + target_rank); + commandAllowed = sender + .hasPermission("powerranks.cmd." + commandName.toLowerCase() + "." + target_rank); } else { commandAllowed = true; } @@ -46,42 +49,71 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); if (rank != null && targetPlayer != null) { PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); - targetPlayer.addRank(playerRank); - - if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { - PowerRanks.getInstance().updateTablistName(Bukkit.getPlayer(targetPlayer.getUUID())); - PowerRanks.getInstance().getTablistManager().updateSorting(Bukkit.getPlayer(targetPlayer.getUUID())); - } - - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager() - .getFormattedMessage( - "commands." + commandName.toLowerCase() + ".success-executor"), - ImmutableMap.builder() - .put("player", targetPlayer.getName()) - .put("rank", rank.getName()) - .build(), - '[', ']')); - if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { - Bukkit.getPlayer(targetPlayer.getUUID()).sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager().getFormattedMessage( - "commands." + commandName.toLowerCase() + ".success-receiver"), + boolean alreadyHasRank = targetPlayer.hasRank(rank.getName()); + if (!alreadyHasRank) { + + for (String tag : tags) { + if (tag.split(":").length == 2) { + String[] tagParts = tag.split(":"); + String tagName = tagParts[0]; + String tagValue = tagParts[1]; + + if (tagName.length() > 0 && tagValue.length() > 0) { + playerRank.addTag(tagName, tagValue); + } + } + } + + targetPlayer.addRank(playerRank); + + if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { + PowerRanks.getInstance().updateTablistName(Bukkit.getPlayer(targetPlayer.getUUID())); + PowerRanks.getInstance().getTablistManager() + .updateSorting(Bukkit.getPlayer(targetPlayer.getUUID())); + } + + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage( + "commands." + commandName.toLowerCase() + ".success-executor"), + ImmutableMap.builder() + .put("player", targetPlayer.getName()) + .put("rank", rank.getName()) + .build(), + '[', ']')); + if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { + Bukkit.getPlayer(targetPlayer.getUUID()).sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager().getFormattedMessage( + "commands." + commandName.toLowerCase() + ".success-receiver"), + ImmutableMap.builder() + .put("player", sender.getName()) + .put("rank", rank.getName()) + .build(), + '[', ']')); + } + } else { + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage( + "commands." + commandName.toLowerCase() + ".failed-already-has-rank"), ImmutableMap.builder() - .put("player", sender.getName()) + .put("player", targetPlayer.getName()) .put("rank", rank.getName()) .build(), '[', ']')); } } else { - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager() - .getFormattedMessage( - "commands." + commandName.toLowerCase() + ".failed-executor"), - ImmutableMap.builder() - .put("player", targetPlayer.getName()) - .put("rank", rank.getName()) - .build(), - '[', ']')); + if (targetPlayer != null && rank != null) { + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage( + "commands." + commandName.toLowerCase() + ".failed-executor"), + ImmutableMap.builder() + .put("player", targetPlayer.getName()) + .put("rank", rank.getName()) + .build(), + '[', ']')); + } } // users.setGroup(sender instanceof Player ? (Player) sender : null, args[0], // target_rank, true); @@ -102,14 +134,19 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (PRPlayer player : CacheManager.getPlayers()) { tabcomplete.add(player.getName()); } } if (args.length == 2) { - for (PRRank rank : this.users.getGroups()) { - tabcomplete.add(rank.getName()); + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); + if (targetPlayer != null) { + for (PRRank rank : CacheManager.getRanks()) { + if (!targetPlayer.hasRank(rank.getName())) { + tabcomplete.add(rank.getName()); + } + } } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_checkrank.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_checkrank.java index 9ef3176..6a25bb2 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_checkrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_checkrank.java @@ -5,11 +5,11 @@ import com.google.common.collect.ImmutableMap; -import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.common.structure.PRPlayerRank; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.cache.CacheManager; @@ -58,11 +58,10 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, PowerRanks.getLanguageManager().getFormattedMessage("general.console-is-no-player")); } } else if (args.length == 1) { - Player targetPlayer = Util.getPlayerByName(args[0]); + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); if (targetPlayer != null) { List playerRanks = new ArrayList<>(); - for (PRPlayerRank rank : CacheManager.getPlayer(((Player) sender).getUniqueId().toString()) - .getRanks()) { + for (PRPlayerRank rank : CacheManager.getPlayer((targetPlayer).getUUID().toString()).getRanks()) { playerRanks.add(rank.getName()); } if (playerRanks.size() > 0) { @@ -108,7 +107,7 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (PRPlayer player : CacheManager.getPlayers()) { tabcomplete.add(player.getName()); } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_delplayerperm.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_delplayerperm.java index b101665..6263433 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_delplayerperm.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_delplayerperm.java @@ -4,13 +4,14 @@ import com.google.common.collect.ImmutableMap; -import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import nl.svenar.common.structure.PRPermission; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.commands.PowerCommand; import nl.svenar.powerranks.data.Users; import nl.svenar.powerranks.util.Util; @@ -66,43 +67,47 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (PRPlayer player : CacheManager.getPlayers()) { tabcomplete.add(player.getName()); } } if (args.length == 2) { - // for (Permission pai : Bukkit.getServer().getPermissions()) { - for (PRPermission perm : this.users.getPlayerPermissions(args[0])) { - // String perm = pai.getPermission(); - String userInput = args[1]; - String autocompletePermission = ""; - - if (userInput.contains(".")) { - String[] permSplit = perm.getName().split("\\."); - for (int i = 0; i < permSplit.length; i++) { - String targetPerm = String.join(".", permSplit); - while (targetPerm.endsWith(".")) { - targetPerm = targetPerm.substring(0, targetPerm.length() - 1); - } - if (targetPerm.contains(userInput)) { - autocompletePermission = targetPerm; - permSplit[permSplit.length - 1 - i] = ""; - - } else { - break; + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); + if (targetPlayer != null) { + // for (Permission pai : Bukkit.getServer().getPermissions()) { + for (PRPermission perm : targetPlayer.getPermissions()) { + // String perm = pai.getPermission(); + String userInput = args[1]; + String autocompletePermission = ""; + + if (userInput.contains(".")) { + String[] permSplit = perm.getName().split("\\."); + for (int i = 0; i < permSplit.length; i++) { + String targetPerm = String.join(".", permSplit); + while (targetPerm.endsWith(".")) { + targetPerm = targetPerm.substring(0, targetPerm.length() - 1); + } + if (targetPerm.contains(userInput)) { + autocompletePermission = targetPerm; + permSplit[permSplit.length - 1 - i] = ""; + + } else { + break; + } } + } else { + autocompletePermission = perm.getName().split("\\.")[0]; } - } else { - autocompletePermission = perm.getName().split("\\.")[0]; - } - while (autocompletePermission.endsWith(".")) { - autocompletePermission = autocompletePermission.substring(0, autocompletePermission.length() - 1); - } + while (autocompletePermission.endsWith(".")) { + autocompletePermission = autocompletePermission.substring(0, + autocompletePermission.length() - 1); + } - if (!tabcomplete.contains(autocompletePermission)) { - tabcomplete.add(autocompletePermission); + if (!tabcomplete.contains(autocompletePermission)) { + tabcomplete.add(autocompletePermission); + } } } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_delrank.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_delrank.java index e07a652..fe96170 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_delrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_delrank.java @@ -1,7 +1,6 @@ package nl.svenar.powerranks.commands.player; import java.util.ArrayList; -import java.util.List; import com.google.common.collect.ImmutableMap; @@ -85,15 +84,17 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, '[', ']')); } } else { - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager() - .getFormattedMessage( - "commands." + commandName.toLowerCase() + ".failed-executor"), - ImmutableMap.builder() - .put("player", targetPlayer.getName()) - .put("rank", rank.getName()) - .build(), - '[', ']')); + if (targetPlayer != null && rank != null) { + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage( + "commands." + commandName.toLowerCase() + ".failed-executor"), + ImmutableMap.builder() + .put("player", targetPlayer.getName()) + .put("rank", rank.getName()) + .build(), + '[', ']')); + } } // users.setGroup(sender instanceof Player ? (Player) sender : null, args[0], // target_rank, true); @@ -114,20 +115,16 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (PRPlayer player : CacheManager.getPlayers()) { tabcomplete.add(player.getName()); } } if (args.length == 2) { - Player target_player = Util.getPlayerByName(args[0]); - if (target_player != null) { - List ranks = new ArrayList<>(); - for (PRPlayerRank rank : CacheManager.getPlayer(target_player.getUniqueId().toString()).getRanks()) { - ranks.add(rank.getName()); - } - for (String rank : ranks) { - tabcomplete.add(rank); + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); + if (targetPlayer != null) { + for (PRPlayerRank rank : targetPlayer.getRanks()) { + tabcomplete.add(rank.getName()); } } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_haspermission.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_haspermission.java index b98f62f..9bb1f19 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_haspermission.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_haspermission.java @@ -9,11 +9,13 @@ import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; +import org.bukkit.permissions.PermissionAttachmentInfo; import nl.svenar.common.structure.PRPermission; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.commands.PowerCommand; import nl.svenar.powerranks.util.Util; @@ -27,39 +29,14 @@ public cmd_haspermission(PowerRanks plugin, String command_name, COMMAND_EXECUTO @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { - Player player = null; + PRPlayer prPlayer = null; String permissionNode = null; - if (args.length == 1) { - permissionNode = args[0]; - - if (sender instanceof ConsoleCommandSender) { - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager().getFormattedMessage("general.player-not-found"), - ImmutableMap.builder() - .put("player", sender.getName()) - .put("target", sender.getName()) - .build(), - '[', ']')); - } else { - player = (Player) sender; - } - - if (permissionNode == null || permissionNode.length() == 0) { - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager().getFormattedMessage("general.rank-not-found"), - ImmutableMap.builder() - .put("player", sender.getName()) - .put("rank", args[0]) - .build(), - '[', ']')); - } - - } else if (args.length == 2) { - player = Util.getPlayerByName(args[0]); + if (args.length == 2) { + prPlayer = CacheManager.getPlayer(args[0]); permissionNode = args[1]; - if (player == null) { + if (prPlayer == null) { sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage("general.player-not-found"), ImmutableMap.builder() @@ -71,10 +48,9 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, if (permissionNode == null || permissionNode.length() == 0) { sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager().getFormattedMessage("general.rank-not-found"), + PowerRanks.getLanguageManager().getFormattedMessage("general.permission-not-found"), ImmutableMap.builder() - .put("player", sender.getName()) - .put("rank", args[1]) + .put("permission", args[1]) .build(), '[', ']')); } @@ -84,49 +60,59 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, "commands." + commandName.toLowerCase() + ".arguments", sender instanceof Player)); } - if (player != null && permissionNode != null && permissionNode.length() > 0) { - List playerPermissions = PowerRanks.getInstance().getEffectivePlayerPermissions(player); - PRPermission targetPermission = null; - PRPermission targetWildcardPermission = null; - - for (PRPermission permission : playerPermissions) { - if (permission.getName().equals(permissionNode)) { - targetPermission = permission; - break; + if (prPlayer != null && permissionNode != null && permissionNode.length() > 0) { + Player player = Bukkit.getPlayer(prPlayer.getUUID()); + if (player != null) { + List playerPermissions = PowerRanks.getInstance().getEffectivePlayerPermissions(player); + PRPermission targetPermission = null; + PRPermission targetWildcardPermission = null; + + for (PRPermission permission : playerPermissions) { + if (permission.getName().equals(permissionNode)) { + targetPermission = permission; + break; + } } - } - ArrayList wildcardPermissions = Util.generateWildcardList(permissionNode); - for (PRPermission perm : playerPermissions) { + ArrayList wildcardPermissions = Util.generateWildcardList(permissionNode); + for (PRPermission perm : playerPermissions) { - if (wildcardPermissions.contains(perm.getName())) { - targetWildcardPermission = perm; - break; + if (wildcardPermissions.contains(perm.getName())) { + targetWildcardPermission = perm; + break; + } } - } - sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "----------" + ChatColor.AQUA - + PowerRanks.getInstance().getDescription().getName() + ChatColor.DARK_AQUA + "----------" - + ChatColor.BLUE + "==="); - sender.sendMessage(ChatColor.GREEN + "Player: " + ChatColor.DARK_GREEN + player.getName()); - sender.sendMessage(ChatColor.GREEN + "Permission: " + ChatColor.DARK_GREEN + permissionNode); - sender.sendMessage(ChatColor.GREEN + "Player has permission: " - + (targetPermission == null ? ChatColor.DARK_RED + "no" : ChatColor.DARK_GREEN + "yes")); - sender.sendMessage(ChatColor.GREEN + "Permission allowed value: " - + (targetPermission == null ? ChatColor.GOLD + "unknown" - : (targetPermission.getValue() ? ChatColor.DARK_GREEN + "allowed" - : ChatColor.DARK_RED + "denied"))); - sender.sendMessage(ChatColor.GREEN + "has Wildcard variant: " - + (targetWildcardPermission == null ? ChatColor.GOLD + "no" - : ChatColor.DARK_GREEN + targetWildcardPermission.getName() + " (allowed: " - + (targetWildcardPermission.getValue() ? ChatColor.DARK_GREEN + "yes" - : ChatColor.DARK_RED + "no") - + ChatColor.DARK_GREEN + ")")); - sender.sendMessage(ChatColor.GREEN + "Is permission allowed: " - + (player.hasPermission(permissionNode) ? ChatColor.DARK_GREEN + "yes" - : ChatColor.DARK_RED + "no")); - sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "------------------------------" - + ChatColor.BLUE + "==="); + sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "----------" + ChatColor.AQUA + + PowerRanks.getInstance().getDescription().getName() + ChatColor.DARK_AQUA + "----------" + + ChatColor.BLUE + "==="); + sender.sendMessage(ChatColor.GREEN + "Player: " + ChatColor.DARK_GREEN + player.getName()); + sender.sendMessage(ChatColor.GREEN + "Permission: " + ChatColor.DARK_GREEN + permissionNode); + sender.sendMessage(ChatColor.GREEN + "Player has permission: " + + (targetPermission == null ? ChatColor.DARK_RED + "no" : ChatColor.DARK_GREEN + "yes")); + sender.sendMessage(ChatColor.GREEN + "Permission allowed value: " + + (targetPermission == null ? ChatColor.GOLD + "unknown" + : (targetPermission.getValue() ? ChatColor.DARK_GREEN + "allowed" + : ChatColor.DARK_RED + "denied"))); + sender.sendMessage(ChatColor.GREEN + "has Wildcard variant: " + + (targetWildcardPermission == null ? ChatColor.GOLD + "no" + : ChatColor.DARK_GREEN + targetWildcardPermission.getName() + " (allowed: " + + (targetWildcardPermission.getValue() ? ChatColor.DARK_GREEN + "yes" + : ChatColor.DARK_RED + "no") + + ChatColor.DARK_GREEN + ")")); + sender.sendMessage(ChatColor.GREEN + "Is permission allowed: " + + (player.hasPermission(permissionNode) ? ChatColor.DARK_GREEN + "yes" + : ChatColor.DARK_RED + "no")); + sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "------------------------------" + + ChatColor.BLUE + "==="); + } else { + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager().getFormattedMessage("general.player-not-online"), + ImmutableMap.builder() + .put("player", sender.getName()) + .build(), + '[', ']')); + } } return false; @@ -136,11 +122,47 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (PRPlayer player : CacheManager.getPlayers()) { tabcomplete.add(player.getName()); } } + if (args.length == 2) { + // for (Permission pai : Bukkit.getServer().getPermissions()) { + for (PermissionAttachmentInfo pai : Bukkit.getServer().getConsoleSender().getEffectivePermissions()) { + String perm = pai.getPermission(); + String userInput = args[1]; + String autocompletePermission = ""; + + if (userInput.contains(".")) { + String[] permSplit = perm.split("\\."); + for (int i = 0; i < permSplit.length; i++) { + String targetPerm = String.join(".", permSplit); + while (targetPerm.endsWith(".")) { + targetPerm = targetPerm.substring(0, targetPerm.length() - 1); + } + if (targetPerm.contains(userInput)) { + autocompletePermission = targetPerm; + permSplit[permSplit.length - 1 - i] = ""; + + } else { + break; + } + } + } else { + autocompletePermission = perm.split("\\.")[0]; + } + + while (autocompletePermission.endsWith(".")) { + autocompletePermission = autocompletePermission.substring(0, autocompletePermission.length() - 1); + } + + if (!tabcomplete.contains(autocompletePermission)) { + tabcomplete.add(autocompletePermission); + } + } + } + return tabcomplete; } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_listplayerpermissions.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_listplayerpermissions.java index e6f7c5e..e900fbd 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_listplayerpermissions.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_listplayerpermissions.java @@ -5,25 +5,22 @@ import com.google.common.collect.ImmutableMap; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import nl.svenar.common.structure.PRPermission; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.commands.PowerCommand; -import nl.svenar.powerranks.data.Users; import nl.svenar.powerranks.util.Util; public class cmd_listplayerpermissions extends PowerCommand { - private Users users; - public cmd_listplayerpermissions(PowerRanks plugin, String command_name, COMMAND_EXECUTOR ce) { super(plugin, command_name, ce); - this.users = new Users(plugin); this.setCommandPermission("powerranks.cmd." + command_name.toLowerCase()); } @@ -31,7 +28,7 @@ public cmd_listplayerpermissions(PowerRanks plugin, String command_name, COMMAND public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { if (args.length == 1) { - Player targetPlayer = Util.getPlayerByName(args[0]); + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); if (targetPlayer != null) { displayList(sender, targetPlayer, commandLabel, 0); } else { @@ -45,7 +42,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, } } else if (args.length == 2) { int page = Integer.parseInt(args[1].replaceAll("[a-zA-Z]", "")); - Player targetPlayer = Util.getPlayerByName(args[0]); + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); if (targetPlayer != null) { displayList(sender, targetPlayer, commandLabel, page); } else { @@ -66,13 +63,13 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, return false; } - private void displayList(CommandSender sender, Player player, String commandLabel, int page) { + private void displayList(CommandSender sender, PRPlayer prPlayer, String commandLabel, int page) { ArrayList output_messages = new ArrayList(); output_messages.add(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "----------" + ChatColor.AQUA + plugin.getDescription().getName() + ChatColor.DARK_AQUA + "----------" + ChatColor.BLUE + "==="); - List playerPermissions = users.getPlayerPermissions(player.getName()); + List playerPermissions = prPlayer.getPermissions(); int lines_per_page = sender instanceof Player ? 5 : 10; int last_page = playerPermissions.size() / lines_per_page; @@ -106,19 +103,19 @@ private void displayList(CommandSender sender, Player player, String commandLabe page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%previous_page%", String.valueOf(page - 1)); page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%last_page%", String.valueOf(last_page + 1)); - page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%playername%", player.getName()); + page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%playername%", prPlayer.getName()); page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%commandlabel%", commandLabel); output_messages.add(page_selector_tellraw); - output_messages.add(ChatColor.AQUA + player.getName() + "'s permissions:"); + output_messages.add(ChatColor.AQUA + prPlayer.getName() + "'s permissions:"); // sender.sendMessage("[A] " + last_page + " " + lines_per_page); } else { output_messages.add(ChatColor.AQUA + "Page " + ChatColor.BLUE + (page + 1) + ChatColor.AQUA + "/" + ChatColor.BLUE + (last_page + 1)); output_messages.add(ChatColor.AQUA + "Next page " + ChatColor.BLUE + "/" + commandLabel - + " listplayerpermissions " + player.getName() + " " + ChatColor.BLUE + + " listplayerpermissions " + prPlayer.getName() + " " + ChatColor.BLUE + (page + 2 > last_page + 1 ? last_page + 1 : page + 2)); } @@ -149,8 +146,8 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - tabcomplete.add(player.getName()); + for (PRPlayer prPlayer : CacheManager.getPlayers()) { + tabcomplete.add(prPlayer.getName()); } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_playerinfo.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_playerinfo.java index aa02f0b..e588e66 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_playerinfo.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_playerinfo.java @@ -4,12 +4,13 @@ import com.google.common.collect.ImmutableMap; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.commands.PowerCommand; import nl.svenar.powerranks.data.Messages; import nl.svenar.powerranks.util.Util; -import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -25,31 +26,31 @@ public cmd_playerinfo(PowerRanks plugin, String command_name, COMMAND_EXECUTOR c public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { if (args.length == 1) { - String target_player_name = args[0]; - Player target_player = Util.getPlayerByName(target_player_name); - if (target_player != null) { - Messages.messagePlayerInfo(sender, target_player, 0); + String targetPlayerName = args[0]; + PRPlayer targetPlayer = CacheManager.getPlayer(targetPlayerName); + if (targetPlayer != null) { + Messages.messagePlayerInfo(sender, targetPlayer, 0); } else { sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage("general.player-not-found"), ImmutableMap.builder() .put("player", sender.getName()) - .put("target", target_player_name) + .put("target", targetPlayerName) .build(), '[', ']')); } } else if (args.length == 2) { - String target_player_name = args[0]; + String targetPlayerName = args[0]; int page = Integer.parseInt(args[1].replaceAll("[a-zA-Z]", "")); - Player target_player = Util.getPlayerByName(target_player_name); - if (target_player != null) { - Messages.messagePlayerInfo(sender, target_player, page); + PRPlayer targetPlayer = CacheManager.getPlayer(targetPlayerName); + if (targetPlayer != null) { + Messages.messagePlayerInfo(sender, targetPlayer, page); } else { sender.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage("general.player-not-found"), ImmutableMap.builder() .put("player", sender.getName()) - .put("target", target_player_name) + .put("target", targetPlayerName) .build(), '[', ']')); } @@ -66,8 +67,8 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - tabcomplete.add(player.getName()); + for (PRPlayer prPlayer : CacheManager.getPlayers()) { + tabcomplete.add(prPlayer.getName()); } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_setownrank.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_setownrank.java index fb913a9..e38915c 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_setownrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_setownrank.java @@ -32,18 +32,18 @@ public cmd_setownrank(PowerRanks plugin, String command_name, COMMAND_EXECUTOR c public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { if (args.length == 1) { - String target_rank = users.getRankIgnoreCase(args[0]); + String targetRank = users.getRankIgnoreCase(args[0]); boolean commandAllowed = false; if (sender instanceof Player) { commandAllowed = sender - .hasPermission("powerranks.cmd." + commandName.toLowerCase() + "." + target_rank); + .hasPermission("powerranks.cmd." + commandName.toLowerCase() + "." + targetRank); } else { commandAllowed = true; } if (commandAllowed) { - PRRank rank = CacheManager.getRank(users.getRankIgnoreCase(target_rank)); + PRRank rank = CacheManager.getRank(users.getRankIgnoreCase(targetRank)); PRPlayer targetPlayer = CacheManager.getPlayer(sender.getName()); if (rank != null && targetPlayer != null) { PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); @@ -65,15 +65,17 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, .build(), '[', ']')); } else { - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager() - .getFormattedMessage( - "commands." + commandName.toLowerCase() + ".failed-executor"), - ImmutableMap.builder() - .put("player", targetPlayer.getName()) - .put("rank", rank.getName()) - .build(), - '[', ']')); + if (targetPlayer != null && rank != null) { + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager() + .getFormattedMessage( + "commands." + commandName.toLowerCase() + ".failed-executor"), + ImmutableMap.builder() + .put("player", targetPlayer.getName()) + .put("rank", rank.getName()) + .build(), + '[', ']')); + } } } else { sender.sendMessage(PowerRanks.getLanguageManager().getFormattedMessage("general.no-permission")); @@ -91,8 +93,13 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (PRRank rank : this.users.getGroups()) { - tabcomplete.add(rank.getName()); + if (sender instanceof Player) { + PRPlayer targetPlayer = CacheManager.getPlayer(sender.getName()); + for (PRRank rank : CacheManager.getRanks()) { + if (!targetPlayer.hasRank(rank.getName())) { + tabcomplete.add(rank.getName()); + } + } } } diff --git a/src/main/java/nl/svenar/powerranks/commands/player/cmd_setrank.java b/src/main/java/nl/svenar/powerranks/commands/player/cmd_setrank.java index 0c80692..fc69c36 100644 --- a/src/main/java/nl/svenar/powerranks/commands/player/cmd_setrank.java +++ b/src/main/java/nl/svenar/powerranks/commands/player/cmd_setrank.java @@ -1,6 +1,9 @@ package nl.svenar.powerranks.commands.player; import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map.Entry; import com.google.common.collect.ImmutableMap; @@ -31,8 +34,9 @@ public cmd_setrank(PowerRanks plugin, String command_name, COMMAND_EXECUTOR ce) @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, String[] args) { - if (args.length == 2) { + if (args.length >= 2) { String target_rank = users.getRankIgnoreCase(args[1]); + String[] tags = Arrays.copyOfRange(args, 2, args.length); boolean commandAllowed = sender.hasPermission("powerranks.cmd." + commandName.toLowerCase()); if (sender instanceof Player) { @@ -51,12 +55,37 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); if (rank != null && targetPlayer != null) { PRPlayerRank playerRank = new PRPlayerRank(rank.getName()); + + for (String tag : tags) { + if (tag.split(":").length == 2) { + String[] tagParts = tag.split(":"); + String tagName = tagParts[0]; + String tagValue = tagParts[1]; + + if (tagName.length() > 0 && tagValue.length() > 0) { + playerRank.addTag(tagName, tagValue); + if (tagName.equalsIgnoreCase("expires")) { + List returnRanks = new ArrayList(); + for (PRPlayerRank prRank : targetPlayer.getRanks()) { + String prRankTags = ""; + for (Entry prRankTagEntry : prRank.getTags().entrySet()) { + prRankTags += ";" + prRankTagEntry.getKey() + ":" + prRankTagEntry.getValue(); + } + returnRanks.add(prRank.getName() + prRankTags); + } + playerRank.addTag("expiry-return-ranks", returnRanks); + } + } + } + } + targetPlayer.setRank(playerRank); - if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { - PowerRanks.getInstance().updateTablistName(Bukkit.getPlayer(targetPlayer.getUUID())); - PowerRanks.getInstance().getTablistManager().updateSorting(Bukkit.getPlayer(targetPlayer.getUUID())); - } + if (Bukkit.getPlayer(targetPlayer.getUUID()) != null) { + PowerRanks.getInstance().updateTablistName(Bukkit.getPlayer(targetPlayer.getUUID())); + PowerRanks.getInstance().getTablistManager() + .updateSorting(Bukkit.getPlayer(targetPlayer.getUUID())); + } boolean hasRank = false; for (PRPlayerRank playerrank : targetPlayer.getRanks()) { @@ -99,14 +128,14 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, } } else { sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager() - .getFormattedMessage( - "commands." + commandName.toLowerCase() + ".failed-executor"), - ImmutableMap.builder() - .put("player", targetPlayer == null ? args[0] : targetPlayer.getName()) - .put("rank", rank == null ? args[1] : rank.getName()) - .build(), - '[', ']')); + PowerRanks.getLanguageManager() + .getFormattedMessage( + "commands." + commandName.toLowerCase() + ".failed-executor"), + ImmutableMap.builder() + .put("player", targetPlayer == null ? args[0] : targetPlayer.getName()) + .put("rank", rank == null ? args[1] : rank.getName()) + .build(), + '[', ']')); } } else { @@ -115,9 +144,9 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, } else { if (sender.hasPermission("powerranks.cmd." + commandName.toLowerCase()) || sender.hasPermission("powerranks.cmd." + commandName.toLowerCase() + ".*")) { - sender.sendMessage( - PowerRanks.getLanguageManager().getFormattedUsageMessage(commandLabel, commandName, - "commands." + commandName.toLowerCase() + ".arguments", sender instanceof Player)); + sender.sendMessage( + PowerRanks.getLanguageManager().getFormattedUsageMessage(commandLabel, commandName, + "commands." + commandName.toLowerCase() + ".arguments", sender instanceof Player)); } else { sender.sendMessage(PowerRanks.getLanguageManager().getFormattedMessage("general.no-permission")); } @@ -130,14 +159,19 @@ public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { ArrayList tabcomplete = new ArrayList(); if (args.length == 1) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - tabcomplete.add(player.getName()); + for (PRPlayer prPlayer : CacheManager.getPlayers()) { + tabcomplete.add(prPlayer.getName()); } } if (args.length == 2) { - for (PRRank rank : this.users.getGroups()) { - tabcomplete.add(rank.getName()); + PRPlayer targetPlayer = CacheManager.getPlayer(args[0]); + if (targetPlayer != null) { + for (PRRank rank : CacheManager.getRanks()) { + if (!targetPlayer.hasRank(rank.getName())) { + tabcomplete.add(rank.getName()); + } + } } } diff --git a/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listdefaultranks.java b/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listdefaultranks.java index 6ff52e0..29ce2ab 100644 --- a/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listdefaultranks.java +++ b/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listdefaultranks.java @@ -36,7 +36,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, int index = 0; ranks = new ArrayList<>(new HashSet<>(ranks)); - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); for (PRRank rank : ranks) { index++; diff --git a/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listranks.java b/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listranks.java index 0c70606..a2f1f37 100644 --- a/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listranks.java +++ b/src/main/java/nl/svenar/powerranks/commands/rank/cmd_listranks.java @@ -36,7 +36,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, int index = 0; ranks = new ArrayList<>(new HashSet<>(ranks)); - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + ranks = PRUtil.reverseRanks(ranks); for (PRRank rank : ranks) { index++; diff --git a/src/main/java/nl/svenar/powerranks/commands/rank/cmd_setweight.java b/src/main/java/nl/svenar/powerranks/commands/rank/cmd_setweight.java index d188796..09acdef 100644 --- a/src/main/java/nl/svenar/powerranks/commands/rank/cmd_setweight.java +++ b/src/main/java/nl/svenar/powerranks/commands/rank/cmd_setweight.java @@ -59,16 +59,18 @@ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, '[', ']')); } - rank.setWeight(weight); - sender.sendMessage(Util.powerFormatter( - PowerRanks.getLanguageManager().getFormattedMessage( - "commands." + commandName.toLowerCase() + ".success"), - ImmutableMap.builder() - .put("player", sender.getName()) - .put("rank", rankname) - .put("weight", String.valueOf(weight)) - .build(), - '[', ']')); + if (rank != null) { + rank.setWeight(weight); + sender.sendMessage(Util.powerFormatter( + PowerRanks.getLanguageManager().getFormattedMessage( + "commands." + commandName.toLowerCase() + ".success"), + ImmutableMap.builder() + .put("player", sender.getName()) + .put("rank", rankname) + .put("weight", String.valueOf(weight)) + .build(), + '[', ']')); + } } else { sender.sendMessage( PowerRanks.getLanguageManager().getFormattedUsageMessage(commandLabel, commandName, diff --git a/src/main/java/nl/svenar/powerranks/commands/test/cmd_test.java b/src/main/java/nl/svenar/powerranks/commands/test/cmd_test.java new file mode 100644 index 0000000..2bcfba4 --- /dev/null +++ b/src/main/java/nl/svenar/powerranks/commands/test/cmd_test.java @@ -0,0 +1,82 @@ +package nl.svenar.powerranks.commands.test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import nl.svenar.common.structure.PRPermission; +import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.commands.PowerCommand; +import nl.svenar.powerranks.data.PowerPermissibleBase; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class cmd_test extends PowerCommand { + + public cmd_test(PowerRanks plugin, String command_name, COMMAND_EXECUTOR ce) { + super(plugin, command_name, ce); + this.setCommandPermission("powerranks.cmd." + command_name.toLowerCase()); + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String commandName, + String[] args) { + + // Set permissions = Bukkit.getServer().getPluginManager().getPermissions(); + // for (Permission permission : permissions) { + // sender.sendMessage(permission.getName() + ": " + permission.getDefault().toString() + " (" + permission.getDescription() + ")"); + // } + + if (sender instanceof Player) { + List playerPermissions = PowerRanks.getInstance().getEffectivePlayerPermissions((Player) sender); + for (PRPermission permission : playerPermissions) { + sender.sendMessage(permission.getName() + ": " + permission.getValue()); + } + } else { + Map permissionCallCount = PowerPermissibleBase.permissionCallCount; + // sort from high to low value + permissionCallCount = sortByValue(permissionCallCount, false); + int index = 0; + for (Entry entry : permissionCallCount.entrySet()) { + if (index >= 20) + break; + sender.sendMessage(entry.getKey() + ": " + entry.getValue()); + index++; + } + } + + return false; + } + + private Map sortByValue(Map permissionCallCount, boolean asc) { + // sort from high to low value + List> list = new LinkedList>(permissionCallCount.entrySet()); + java.util.Collections.sort(list, new java.util.Comparator>() { + public int compare(Entry o1, Entry o2) { + if (asc) { + return (o1.getValue()).compareTo(o2.getValue()); + } else { + return (o2.getValue()).compareTo(o1.getValue()); + } + } + }); + // return + Map result = new LinkedHashMap(); + for (Entry entry : list) { + result.put(entry.getKey(), entry.getValue()); + } + + return result; + } + + public ArrayList tabCompleteEvent(CommandSender sender, String[] args) { + ArrayList tabcomplete = new ArrayList(); + + return tabcomplete; + } +} diff --git a/src/main/java/nl/svenar/powerranks/data/BungeecordManager.java b/src/main/java/nl/svenar/powerranks/data/BungeecordManager.java index 896531e..25915f5 100644 --- a/src/main/java/nl/svenar/powerranks/data/BungeecordManager.java +++ b/src/main/java/nl/svenar/powerranks/data/BungeecordManager.java @@ -3,6 +3,7 @@ import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.List; import java.util.UUID; import java.util.Map.Entry; @@ -167,7 +168,9 @@ private void updateHashes() { this.lastPlayersHashcode = this.playersHashcode; this.ranksHashcode = 17; - for (PRRank rank : PRUtil.sortRanksByWeight(CacheManager.getRanks())) { + List ranks = CacheManager.getRanks(); + PRUtil.sortRanksByWeight(ranks); + for (PRRank rank : ranks) { ranksHashcode = 31 * ranksHashcode + (rank != null ? rank.hashCode() : 0); } diff --git a/src/main/java/nl/svenar/powerranks/data/Messages.java b/src/main/java/nl/svenar/powerranks/data/Messages.java index a558b12..6d30b63 100644 --- a/src/main/java/nl/svenar/powerranks/data/Messages.java +++ b/src/main/java/nl/svenar/powerranks/data/Messages.java @@ -23,6 +23,7 @@ import nl.svenar.common.structure.PRPlayerRank; import nl.svenar.common.structure.PRRank; import nl.svenar.common.utils.PRUtil; +import nl.svenar.common.utils.PowerColor; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.addons.AddonsManager; import nl.svenar.powerranks.addons.DownloadableAddon; @@ -30,7 +31,6 @@ import nl.svenar.powerranks.addons.PowerRanksPlayer; import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.external.VaultHook; -import nl.svenar.powerranks.util.PowerColor; import nl.svenar.powerranks.util.Util; import com.google.common.collect.ImmutableMap; @@ -94,10 +94,11 @@ public static void messageStats(CommandSender sender) { } sender.sendMessage(ChatColor.GREEN + "RGB colors: " + (hex_color_supported ? ChatColor.DARK_GREEN + "" : ChatColor.DARK_RED + "un") + "supported"); - sender.sendMessage(ChatColor.GREEN + "Bungeecord: " - + (PowerRanks.getInstance().getBungeecordManager().isReady() ? ChatColor.DARK_GREEN + "enabled" : ChatColor.DARK_RED + "disabled")); - sender.sendMessage(ChatColor.GREEN + "- Connected servers: " - + ChatColor.DARK_GREEN + PowerRanks.getInstance().getBungeecordManager().getServerCount()); + sender.sendMessage(ChatColor.GREEN + "Bungeecord: " + + (PowerRanks.getInstance().getBungeecordManager().isReady() ? ChatColor.DARK_GREEN + "enabled" + : ChatColor.DARK_RED + "disabled")); + sender.sendMessage(ChatColor.GREEN + "- Connected servers: " + + ChatColor.DARK_GREEN + PowerRanks.getInstance().getBungeecordManager().getServerCount()); sender.sendMessage(ChatColor.GREEN + "Plugin hooks:"); sender.sendMessage(ChatColor.GREEN + "- Vault Economy: " @@ -311,11 +312,13 @@ public static void messageRankInfo(CommandSender sender, PRRank rank, int page) + ChatColor.BLUE + "==="); } - public static void messagePlayerInfo(final CommandSender sender, final Player player, int page) { + public static void messagePlayerInfo(final CommandSender sender, final PRPlayer prPlayer, int page) { + Player player = Bukkit.getPlayer(prPlayer.getUUID()); + SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); - long playerPlaytime = CacheManager.getPlayer(player.getUniqueId().toString()).getPlaytime(); + long playerPlaytime = CacheManager.getPlayer(prPlayer.getUUID().toString()).getPlaytime(); final long days = TimeUnit.SECONDS.toDays(playerPlaytime); final long hours = TimeUnit.SECONDS.toHours(playerPlaytime) @@ -332,8 +335,10 @@ public static void messagePlayerInfo(final CommandSender sender, final Player pl String formatted_ranks = ""; List ranknames = new ArrayList<>(); - for (PRPlayerRank playerRank : CacheManager.getPlayer(player.getUniqueId().toString()).getRanks()) { - ranknames.add(playerRank.getName()); + for (PRPlayerRank playerRank : CacheManager.getPlayer(prPlayer.getUUID().toString()).getRanks()) { + if (!playerRank.isDisabled()) { + ranknames.add(playerRank.getName()); + } } for (String rankname : ranknames) { @@ -346,72 +351,86 @@ public static void messagePlayerInfo(final CommandSender sender, final Player pl sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "----------" + ChatColor.AQUA + Messages.powerRanks.getDescription().getName() + ChatColor.DARK_AQUA + "----------" + ChatColor.BLUE + "==="); - sender.sendMessage(ChatColor.GREEN + "UUID: " + ChatColor.DARK_GREEN + player.getUniqueId()); - sender.sendMessage(ChatColor.GREEN + "Player name: " + ChatColor.DARK_GREEN + player.getDisplayName() - + (!player.getDisplayName().equals(player.getName()) - ? (ChatColor.DARK_GREEN + " aka " + player.getName()) - : "")); - sender.sendMessage(ChatColor.GREEN + "First joined (UTC): " + ChatColor.DARK_GREEN - + format.format(player.getFirstPlayed())); - sender.sendMessage( - ChatColor.GREEN + "Last joined (UTC): " + ChatColor.DARK_GREEN + format.format(player.getLastPlayed())); + if (player == null) { + sender.sendMessage(ChatColor.GREEN + "Player not online, showing limited information."); + } + sender.sendMessage(ChatColor.GREEN + "UUID: " + ChatColor.DARK_GREEN + prPlayer.getUUID()); + if (player != null) { + sender.sendMessage(ChatColor.GREEN + "Player name: " + ChatColor.DARK_GREEN + player.getDisplayName() + + (!player.getDisplayName().equals(player.getName()) + ? (ChatColor.DARK_GREEN + " aka " + player.getName()) + : "")); + sender.sendMessage(ChatColor.GREEN + "First joined (UTC): " + ChatColor.DARK_GREEN + + format.format(player.getFirstPlayed())); + sender.sendMessage( + ChatColor.GREEN + "Last joined (UTC): " + ChatColor.DARK_GREEN + + format.format(player.getLastPlayed())); + } else { + sender.sendMessage(ChatColor.GREEN + "Player name: " + ChatColor.DARK_GREEN + prPlayer.getName()); + } sender.sendMessage(ChatColor.GREEN + "Playtime: " + ChatColor.DARK_GREEN + playerPlaytimeFormatted); - sender.sendMessage(ChatColor.GREEN + "Chat format: " + ChatColor.RESET + getSampleChatFormat(player)); + if (player != null) { + sender.sendMessage(ChatColor.GREEN + "Chat format: " + ChatColor.RESET + getSampleChatFormat(player)); + } sender.sendMessage(ChatColor.GREEN + "Rank(s): " + ChatColor.DARK_GREEN + formatted_ranks); - sender.sendMessage(ChatColor.GREEN + "Effective Permissions: "); - - ArrayList playerPermissions = powerRanks.getEffectivePlayerPermissions(player); - int lines_per_page = sender instanceof Player ? 5 : 10; - int last_page = playerPermissions.size() / lines_per_page; + if (player != null) { + sender.sendMessage(ChatColor.GREEN + "Effective Permissions: "); - if (!(sender instanceof Player)) { - page -= 1; - } + List playerPermissions = powerRanks.getEffectivePlayerPermissions(player); + int lines_per_page = sender instanceof Player ? 5 : 10; + int last_page = playerPermissions.size() / lines_per_page; - page = page < 0 ? 0 : page; - page = page > last_page ? last_page : page; + if (!(sender instanceof Player)) { + page -= 1; + } - if (sender instanceof Player) { - String page_selector_tellraw = "tellraw " + sender.getName() - + " [\"\",{\"text\":\"Page \",\"color\":\"aqua\"},{\"text\":\"" + "%next_page%" - + "\",\"color\":\"blue\"},{\"text\":\"/\",\"color\":\"aqua\"}" - + ",{\"text\":\"%last_page%\",\"color\":\"blue\"},{\"text\":\": \",\"color\":\"aqua\"}" - + ",{\"text\":\"[\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" - + "%commandlabel%" + " playerinfo %playername% " + "%previous_page%" - + "\"}},{\"text\":\"<\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" - + "%commandlabel%" + " playerinfo %playername% " + "%previous_page%" - + "\"}},{\"text\":\"]\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" - + "%commandlabel%" + " playerinfo %playername% " + "%previous_page%" - + "\"}},{\"text\":\" \",\"color\":\"aqua\"},{\"text\":\"[\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" - + "%commandlabel%" + " playerinfo %playername% " + "%next_page%" - + "\"}},{\"text\":\">\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" - + "%commandlabel%" + " playerinfo %playername% " + "%next_page%" - + "\"}},{\"text\":\"]\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" - + "%commandlabel%" + " playerinfo %playername% " + "%next_page%" + "\"}}]"; + page = page < 0 ? 0 : page; + page = page > last_page ? last_page : page; - page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%next_page%", String.valueOf(page + 1)); - page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%previous_page%", String.valueOf(page - 1)); - page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%last_page%", - String.valueOf(last_page + 1)); - page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%playername%", player.getName()); - page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%commandlabel%", "pr"); + if (sender instanceof Player) { + String page_selector_tellraw = "tellraw " + sender.getName() + + " [\"\",{\"text\":\"Page \",\"color\":\"aqua\"},{\"text\":\"" + "%next_page%" + + "\",\"color\":\"blue\"},{\"text\":\"/\",\"color\":\"aqua\"}" + + ",{\"text\":\"%last_page%\",\"color\":\"blue\"},{\"text\":\": \",\"color\":\"aqua\"}" + + ",{\"text\":\"[\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" + + "%commandlabel%" + " playerinfo %playername% " + "%previous_page%" + + "\"}},{\"text\":\"<\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" + + "%commandlabel%" + " playerinfo %playername% " + "%previous_page%" + + "\"}},{\"text\":\"]\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" + + "%commandlabel%" + " playerinfo %playername% " + "%previous_page%" + + "\"}},{\"text\":\" \",\"color\":\"aqua\"},{\"text\":\"[\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" + + "%commandlabel%" + " playerinfo %playername% " + "%next_page%" + + "\"}},{\"text\":\">\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" + + "%commandlabel%" + " playerinfo %playername% " + "%next_page%" + + "\"}},{\"text\":\"]\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/" + + "%commandlabel%" + " playerinfo %playername% " + "%next_page%" + "\"}}]"; + + page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%next_page%", String.valueOf(page + 1)); + page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%previous_page%", + String.valueOf(page - 1)); + page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%last_page%", + String.valueOf(last_page + 1)); + page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%playername%", player.getName()); + page_selector_tellraw = Util.replaceAll(page_selector_tellraw, "%commandlabel%", "pr"); - Messages.powerRanks.getServer().dispatchCommand( - (CommandSender) Messages.powerRanks.getServer().getConsoleSender(), page_selector_tellraw); - } else { - sender.sendMessage(ChatColor.AQUA + "Page " + ChatColor.BLUE + (page + 1) + ChatColor.AQUA + "/" - + ChatColor.BLUE + (last_page + 1)); - sender.sendMessage(ChatColor.AQUA + "Next page " + ChatColor.BLUE + "/pr" + " playerinfo " - + player.getName() + " " + ChatColor.BLUE + (page + 2 > last_page + 1 ? last_page + 1 : page + 2)); - } + Messages.powerRanks.getServer().dispatchCommand( + (CommandSender) Messages.powerRanks.getServer().getConsoleSender(), page_selector_tellraw); + } else { + sender.sendMessage(ChatColor.AQUA + "Page " + ChatColor.BLUE + (page + 1) + ChatColor.AQUA + "/" + + ChatColor.BLUE + (last_page + 1)); + sender.sendMessage(ChatColor.AQUA + "Next page " + ChatColor.BLUE + "/pr" + " playerinfo " + + player.getName() + " " + ChatColor.BLUE + + (page + 2 > last_page + 1 ? last_page + 1 : page + 2)); + } - int line_index = 0; - for (PRPermission permission : playerPermissions) { - if (line_index >= page * lines_per_page && line_index < page * lines_per_page + lines_per_page) { - sender.sendMessage(ChatColor.DARK_GREEN + "#" + (line_index + 1) + ". " - + (!permission.getValue() ? ChatColor.RED : ChatColor.GREEN) + permission.getName()); + int line_index = 0; + for (PRPermission permission : playerPermissions) { + if (line_index >= page * lines_per_page && line_index < page * lines_per_page + lines_per_page) { + sender.sendMessage(ChatColor.DARK_GREEN + "#" + (line_index + 1) + ". " + + (!permission.getValue() ? ChatColor.RED : ChatColor.GREEN) + permission.getName()); + } + line_index += 1; } - line_index += 1; } sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.DARK_AQUA + "------------------------------" @@ -436,7 +455,8 @@ private static String getSampleChatFormat(Player player) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); String formatted_prefix = ""; String formatted_suffix = ""; @@ -710,6 +730,10 @@ public static void addonManagerInfoAddon(CommandSender sender, String addonname) String tellrawCommand = "tellraw %player% "; String formattedDescription = ""; + if (addon == null) { + sender.sendMessage(PowerRanks.getInstance().plp + ChatColor.DARK_RED + "Add-on not found."); + return; + } if (!addon.isInstalled()) { formattedDescription += ",{\"text\":\"Description\",\"color\":\"green\"}"; formattedDescription += ",{\"text\":\":\\\\n\"}"; @@ -725,6 +749,11 @@ public static void addonManagerInfoAddon(CommandSender sender, String addonname) } } + if (prAddon == null) { + sender.sendMessage(PowerRanks.getInstance().plp + ChatColor.DARK_RED + "Add-on not found."); + return; + } + formattedDescription += ",{\"text\":\"Registered Commands\",\"color\":\"green\"},{\"text\":\":\\\\n\"}"; for (String command : prAddon.getRegisteredCommands()) { formattedDescription += ",{\"text\":\"" + "- /pr " + command + "\"},{\"text\":\"\\\\n\"}"; @@ -785,6 +814,11 @@ public static void addonManagerInfoAddon(CommandSender sender, String addonname) (CommandSender) Messages.powerRanks.getServer().getConsoleSender(), tellrawCommand); } else { + if (addon == null) { + sender.sendMessage(PowerRanks.getInstance().plp + ChatColor.DARK_RED + "Add-on not found."); + return; + } + ArrayList lines = new ArrayList(); lines.add(ChatColor.DARK_AQUA + "===-----" + ChatColor.AQUA + "PowerRanks AddonManager" @@ -810,13 +844,16 @@ public static void addonManagerInfoAddon(CommandSender sender, String addonname) } lines.add(ChatColor.GREEN + "Registered commands" + ChatColor.RESET + ": "); - for (String command : prAddon.getRegisteredCommands()) { - lines.add("- /pr " + command); - } + + if (prAddon != null) { + for (String command : prAddon.getRegisteredCommands()) { + lines.add("- /pr " + command); + } - lines.add(ChatColor.GREEN + "Registered permissions" + ChatColor.RESET + ": "); - for (String permission : prAddon.getRegisteredPermissions()) { - lines.add("- " + permission); + lines.add(ChatColor.GREEN + "Registered permissions" + ChatColor.RESET + ": "); + for (String permission : prAddon.getRegisteredPermissions()) { + lines.add("- " + permission); + } } } diff --git a/src/main/java/nl/svenar/powerranks/data/PowerPermissibleBase.java b/src/main/java/nl/svenar/powerranks/data/PowerPermissibleBase.java index c52d9a1..bea5a60 100644 --- a/src/main/java/nl/svenar/powerranks/data/PowerPermissibleBase.java +++ b/src/main/java/nl/svenar/powerranks/data/PowerPermissibleBase.java @@ -1,8 +1,8 @@ package nl.svenar.powerranks.data; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Objects; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.Map; import java.util.Set; import org.bukkit.entity.Player; @@ -13,263 +13,196 @@ import org.bukkit.plugin.Plugin; import nl.svenar.common.structure.PRPermission; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; +import nl.svenar.powerranks.cache.CacheManager; import nl.svenar.powerranks.util.Util; public class PowerPermissibleBase extends PermissibleBase { private PowerRanks plugin; private Player player; + private PRPlayer prPlayer; - public PowerPermissibleBase(Player player, PowerRanks main) { + public static Map permissionCallCount = new HashMap(); + + public PowerPermissibleBase(Player player, PowerRanks plugin) { super(player); this.player = player; - this.plugin = main; + this.plugin = plugin; + this.prPlayer = CacheManager.getPlayer(player.getUniqueId().toString()); + if (prPlayer == null) { + CacheManager.createPlayer(player); + this.prPlayer = CacheManager.getPlayer(player.getUniqueId().toString()); + } + PowerRanksVerbose.log("PowerPermissibleBase", "attached to player " + (player == null ? "null" : player.getName())); + + recalculatePermissions(); } - /* - * === ----- Player has permission? ----- === - */ + @Override + public boolean isOp() { + PowerRanksVerbose.log("isOp()", "called"); + return super.isOp(); + } @Override - public boolean hasPermission(Permission permission) { - if (permission.getName().toLowerCase().contains(PowerRanksVerbose.getFilter().toLowerCase())) { - PowerRanksVerbose.log("hasPermission(Permission)", "hasPerm: " + permission.getName()); - } - return hasPermission(permission.getName()); + public void setOp(boolean value) { + super.setOp(value); } @Override - public boolean hasPermission(String permission) { - ArrayList permissions = plugin.getEffectivePlayerPermissions(player); - ArrayList wildcardPermissions = Util.generateWildcardList(permission); - - boolean containsWildcard = false; - boolean checkedWildcard = false; - boolean disallowed = false; - boolean disallowedValid = false; - boolean caseSensitive = PowerRanks.getConfigManager().getBool("general.case-sensitive-permissions", false); + public boolean isPermissionSet(Permission perm) { + if (perm == null) { + throw new IllegalArgumentException("Permission cannot be null"); + } - for (PRPermission prPermission : permissions) { + return isPermissionSet(perm.getName()); + } - if ((caseSensitive && prPermission.getName().equals(permission)) - || (!caseSensitive && prPermission.getName().equalsIgnoreCase(permission))) { - disallowed = !prPermission.getValue(); - disallowedValid = true; - break; - } + @Override + public boolean isPermissionSet(String name) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); } - if (!disallowed) { - checkedWildcard = true; - for (PRPermission perm : permissions) { - - if (wildcardPermissions.contains(perm.getName())) { - containsWildcard = true; - disallowed = !perm.getValue(); - disallowedValid = true; + PRPermission prPermission = getPRPermission(name); + if (prPermission == null) { + for (String wildCardPermissionName : Util.generateWildcardList(name)) { + prPermission = getPRPermission(wildCardPermissionName); + if (prPermission != null) { break; } } } - if (permission.toLowerCase().contains(PowerRanksVerbose.getFilter().toLowerCase())) { - PowerRanksVerbose.log("hasPermission", ""); - PowerRanksVerbose.log("hasPermission", "===== ---------- hasPermission ---------- ====="); - PowerRanksVerbose.log("hasPermission", "Player: " + player.getName()); - PowerRanksVerbose.log("hasPermission", "Permission: " + permission); - PowerRanksVerbose.log("hasPermission", - "Permissions: '" + String.join(", ", getAllPermissionsFormatted(permissions)) + "'"); - PowerRanksVerbose.log("hasPermission", - "Is Disallowed: " + disallowed + " (Valid: " + disallowedValid + ")"); - PowerRanksVerbose.log("hasPermission", "Has *: " + getAllPermissions(permissions).contains("*")); - PowerRanksVerbose.log("hasPermission", "Is Operator: " + player.isOp()); - // PowerRanksVerbose.log("hasPermission", "Return #3: " + - // super.hasPermission(permission)); - PowerRanksVerbose.log("hasPermission", - "Is permission in list: " + getAllPermissions(permissions).contains(permission)); - PowerRanksVerbose.log("hasPermission", - "Is in wildcard tree: " + (checkedWildcard ? containsWildcard : "unchecked")); - PowerRanksVerbose.log("hasPermission", "===== ---------- hasPermission ---------- ====="); - PowerRanksVerbose.log("hasPermission", ""); - } - - if (disallowed) { - return false; - } - - if (getAllowedPermissions(permissions).contains("*") || player.isOp()) { - return true; - } + PowerRanksVerbose.log("isPermissionSet(String name)", + "called with name: " + name + " (" + super.isPermissionSet(name) + ") - prPermission value: " + + (prPermission == null ? "null" : prPermission.getValue())); - try { - return super.hasPermission(permission) || getAllowedPermissions(permissions).contains(permission) - || (disallowedValid && !disallowed); - } catch (Exception e) { - return getAllowedPermissions(permissions).contains(permission); + if (prPermission != null) { + return prPermission.getValue(); } - // - } - /* - * === ----- Recalculate all permissions ----- === - */ - - @Override - public void recalculatePermissions() { - PowerRanksVerbose.log("recalculatePermissions()", "called"); - super.recalculatePermissions(); - if (player != null) { - // player.updateCommands(); - } + return super.isPermissionSet(name); } - /* - * === ----- Get the effective permissions ----- === - */ - @Override - public Set getEffectivePermissions() { - PowerRanksVerbose.log("getEffectivePermissions()", "called"); - - Set permissions = new HashSet(); - - for (PRPermission permission : plugin.getEffectivePlayerPermissions(player)) { - PermissionAttachmentInfo pai = new PermissionAttachmentInfo(this.player, permission.getName(), null, permission.getValue()); - permissions.add(pai); - } - - for (PermissionAttachmentInfo permission : super.getEffectivePermissions()) { - permissions.add(permission); + public boolean hasPermission(Permission perm) { + if (perm == null) { + throw new IllegalArgumentException("Permission cannot be null"); } - return permissions; - } - - /* - * === ----- Operator handling ----- === - */ - - @Override - public boolean isOp() { - // PowerRanksVerbose.log("isOp()", "called"); - return super.isOp(); + return hasPermission(perm.getName()); } @Override - public void setOp(boolean value) { - PowerRanksVerbose.log("setOp(" + value + ")", "called"); - super.setOp(value); - } - - /* - * === ----- Is Permission Set ----- === - */ + public boolean hasPermission(String inName) { + if (inName == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } - @Override - public boolean isPermissionSet(Permission perm) { - boolean value = isPermissionSet(perm.getName()); - if (perm.getName().toLowerCase().contains(PowerRanksVerbose.getFilter().toLowerCase())) { - PowerRanksVerbose.log("isPermissionSet(" + perm + ")", "called, returned: " + value); + if (permissionCallCount.get(inName) == null) { + permissionCallCount.put(inName, 0); + } else { + permissionCallCount.put(inName, permissionCallCount.get(inName) + 1); } - return value; - } - @Override - public boolean isPermissionSet(String permission) { - PRPermission prPermission = null; - for (PRPermission perm : plugin.getEffectivePlayerPermissions(player)) { - if (perm.getName().equals(permission)) { - prPermission = perm; - break; + PRPermission prPermission = getPRPermission(inName); + if (prPermission == null) { + for (String wildCardPermissionName : Util.generateWildcardList(inName)) { + prPermission = getPRPermission(wildCardPermissionName); + if (prPermission != null) { + break; + } } } - if (Objects.isNull(prPermission)) { - return false; - } + PowerRanksVerbose.log("hasPermission(String inName)", + "called with inName: " + inName + " (" + super.hasPermission(inName) + ") - prPermission value: " + + (prPermission == null ? "null" : prPermission.getValue())); - // boolean value = - // plugin.getEffectivePlayerPermissions(player).contains(permission); - boolean value = prPermission.getValue(); - if (permission.toLowerCase().contains(PowerRanksVerbose.getFilter().toLowerCase())) { - PowerRanksVerbose.log("isPermissionSet(" + permission + ")", "called, returned: " + value); + if (prPermission != null) { + return prPermission.getValue(); } - return value; + return super.hasPermission(inName); } - /* - * === ----- Add Attachment ----- === - */ + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + PowerRanksVerbose.log("addAttachment(Plugin plugin)", + "called with plugin: " + plugin.getName() + ", name: " + name + ", value: " + value); + return super.addAttachment(plugin, name, value); + } @Override public PermissionAttachment addAttachment(Plugin plugin) { + PowerRanksVerbose.log("addAttachment(Plugin plugin)", "called with plugin: " + plugin.getName()); return super.addAttachment(plugin); } @Override - public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return super.addAttachment(plugin, ticks); + public void removeAttachment(PermissionAttachment attachment) { + PowerRanksVerbose.log("removeAttachment(PermissionAttachment attachment)", + "called with attachment permissions: "); + for (Entry permissionAttachmentInfo : attachment.getPermissions().entrySet()) { + PowerRanksVerbose.log("", + " " + permissionAttachmentInfo.getKey() + ": " + permissionAttachmentInfo.getValue()); + } + try { + super.removeAttachment(attachment); + } catch (Exception e) { + PowerRanksVerbose.log("removeAttachment(PermissionAttachment attachment) failed", e.getMessage()); + } } @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return super.addAttachment(plugin, name, value); + public void recalculatePermissions() { + PowerRanksVerbose.log("recalculatePermissions()", "called"); + super.recalculatePermissions(); + } + public synchronized void clearPermissions() { + PowerRanksVerbose.log("clearPermissions()", "called"); + super.clearPermissions(); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + PowerRanksVerbose.log("addAttachment(Plugin plugin, String name, boolean value, int ticks)", + "called with plugin: " + plugin.getName() + ", name: " + name + ", value: " + value + ", ticks: " + + ticks); return super.addAttachment(plugin, name, value, ticks); } - /* - * === ----- Remove Attachment ----- === - */ - @Override - public void removeAttachment(PermissionAttachment attachment) { - super.removeAttachment(attachment); + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + PowerRanksVerbose.log("addAttachment(Plugin plugin, int ticks)", + "called with plugin: " + plugin.getName() + ", ticks: " + ticks); + return super.addAttachment(plugin, ticks); } - /* - * === ----- Clear Permissions ----- === - */ - @Override - public synchronized void clearPermissions() { - super.clearPermissions(); + public Set getEffectivePermissions() { + PowerRanksVerbose.log("getEffectivePermissions()", "called"); + return super.getEffectivePermissions(); } - /* - * === ----- Internal functions ----- === - */ + private PRPermission getPRPermission(String name) { + PRPermission prPermission = null; - private ArrayList getAllowedPermissions(ArrayList permissions) { - ArrayList output = new ArrayList(); - for (PRPermission permission : permissions) { - if (permission.getValue()) { - output.add(permission.getName()); - } - } - return output; - } + boolean caseSensitive = PowerRanks.getConfigManager().getBool("general.case-sensitive-permissions", false); - private ArrayList getAllPermissions(ArrayList permissions) { - ArrayList output = new ArrayList(); - for (PRPermission permission : permissions) { - output.add(permission.getName()); + for (PRPermission permission : this.plugin.getEffectivePlayerPermissions(this.player)) { + if ((caseSensitive && permission.getName().equals(name)) + || (!caseSensitive && permission.getName().equalsIgnoreCase(name))) { + prPermission = permission; + break; + } } - return output; - } - private ArrayList getAllPermissionsFormatted(ArrayList permissions) { - ArrayList output = new ArrayList(); - for (PRPermission permission : permissions) { - output.add(permission.getName() + ":" + permission.getValue()); - } - return output; + return prPermission; } } diff --git a/src/main/java/nl/svenar/powerranks/data/TablistManager.java b/src/main/java/nl/svenar/powerranks/data/TablistManager.java index 8c18a00..b22f2ee 100644 --- a/src/main/java/nl/svenar/powerranks/data/TablistManager.java +++ b/src/main/java/nl/svenar/powerranks/data/TablistManager.java @@ -15,9 +15,9 @@ import nl.svenar.common.structure.PRPlayerRank; import nl.svenar.common.structure.PRRank; import nl.svenar.common.utils.PRUtil; +import nl.svenar.common.utils.PowerColor; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.cache.CacheManager; -import nl.svenar.powerranks.util.PowerColor; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -76,8 +76,9 @@ public void run() { boolean doUpdateRanks = false; - List sortedRanks = PRUtil.sortRanksByWeight( - CacheManager.getRanks()); + + List sortedRanks = CacheManager.getRanks(); + PRUtil.sortRanksByWeight(sortedRanks); if (!PowerRanks.getTablistConfigManager().getBool("sorting.reverse", false)) { Collections.reverse(sortedRanks); } @@ -306,9 +307,11 @@ public void updateSorting(Player player) { for (String rankname : ranknames) { PRRank rank = CacheManager.getRank(rankname); - if (rank.getWeight() > playerHighestRankWeight) { - playerHighestRankWeight = rank.getWeight(); - playerHighestRank = rank; + if (rank != null) { + if (rank.getWeight() > playerHighestRankWeight) { + playerHighestRankWeight = rank.getWeight(); + playerHighestRank = rank; + } } } diff --git a/src/main/java/nl/svenar/powerranks/data/Users.java b/src/main/java/nl/svenar/powerranks/data/Users.java index 8349aaf..301e2d8 100644 --- a/src/main/java/nl/svenar/powerranks/data/Users.java +++ b/src/main/java/nl/svenar/powerranks/data/Users.java @@ -46,12 +46,13 @@ public String getPrimaryRank(Player player) { } } - playerRanks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(playerRanks)); + PRUtil.sortRanksByWeight(playerRanks); + PRUtil.reverseRanks(playerRanks); return playerRanks.size() > 0 ? playerRanks.get(0).getName() : ""; } - public ArrayList getGroups() { + public List getGroups() { return CacheManager.getRanks(); } @@ -464,7 +465,7 @@ public List getInheritances(String rankname) { return CacheManager.getRank(rankname).getInheritances(); } - public ArrayList getCachedPlayers() { + public List getCachedPlayers() { return CacheManager.getPlayers(); } @@ -484,7 +485,8 @@ public String getPrefix(Player player) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); for (PRRank rank : ranks) { prefix += rank.getPrefix() + " "; @@ -523,7 +525,8 @@ public String getSuffix(Player player) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); for (PRRank rank : ranks) { suffix += rank.getSuffix() + " "; @@ -563,7 +566,8 @@ public String getChatColor(Player player) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); color = ranks.size() > 0 ? ranks.get(0).getChatcolor() : "&f"; @@ -585,7 +589,8 @@ public String getNameColor(Player player) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); color = ranks.size() > 0 ? ranks.get(0).getNamecolor() : "&f"; @@ -698,90 +703,30 @@ public boolean setBuyCommand(String rankname, final String command) { return false; } - public boolean addPlayerPermission(String target_player_name, String permission, boolean allowed) { + public boolean addPlayerPermission(String targetPlayerName, String permission, boolean allowed) { if (permission.contains("/") || permission.contains(":")) { return false; } - Player target_player = Bukkit.getServer().getPlayer(target_player_name); + PRPlayer targetPlayer = CacheManager.getPlayer(targetPlayerName); - if (target_player != null) { + if (targetPlayer != null) { try { - if (CacheManager.getPlayer(target_player.getUniqueId().toString()) != null) { - List list = CacheManager.getPlayer(target_player.getUniqueId().toString()) - .getPermissions(); - // if (!list.contains(permission)) { - // list.add(permission); - // CachedPlayers.set("players." + target_player.getUniqueId() + ".permissions", - // (Object) list, - // false); - // } - // this.m.setupPermissions(target_player); - PRPermission targetPermission = null; - for (PRPermission prPermission : list) { - if (prPermission.getName().equals(permission)) { - targetPermission = prPermission; - break; - } - } - if (targetPermission == null) { - PRPermission newPermission = new PRPermission(); - newPermission.setName(permission); - newPermission.setValue(allowed); - CacheManager.getPlayer(target_player.getUniqueId().toString()).addPermission(newPermission); - // r.addPermission(newPermission); - // list.add(permission); - // CachedRanks.set("Groups." + r + ".permissions", (Object) list); - // this.m.updatePlayersWithRank(this, r.getName()); + List list = targetPlayer.getPermissions(); + PRPermission targetPermission = null; + for (PRPermission prPermission : list) { + if (prPermission.getName().equals(permission)) { + targetPermission = prPermission; + break; } - return true; - } else { - return false; } - } catch (Exception e) { - e.printStackTrace(); - } - } else { - String uuid = ""; - try { - for (PRPlayer key : CacheManager.getPlayers()) { - if (key.getName().equalsIgnoreCase(target_player_name)) { - uuid = key.getUUID().toString(); - } + if (targetPermission == null) { + PRPermission newPermission = new PRPermission(); + newPermission.setName(permission); + newPermission.setValue(allowed); + targetPlayer.addPermission(newPermission); } - - if (uuid.length() > 0) { - if (CacheManager.getPlayer(uuid) != null) { - // List list = (List) CachedPlayers - // .getStringList("players." + uuid + ".permissions"); - // if (!list.contains(permission)) { - // list.add(permission); - // CachedPlayers.set("players." + uuid + ".permissions", (Object) list, false); - // } - List list = CacheManager.getPlayer(uuid).getPermissions(); - PRPermission targetPermission = null; - for (PRPermission prPermission : list) { - if (prPermission.getName().equals(permission)) { - targetPermission = prPermission; - break; - } - } - if (targetPermission == null) { - PRPermission newPermission = new PRPermission(); - newPermission.setName(permission); - newPermission.setValue(allowed); - CacheManager.getPlayer(uuid).addPermission(newPermission); - // r.addPermission(newPermission); - // list.add(permission); - // CachedRanks.set("Groups." + r + ".permissions", (Object) list); - // this.m.updatePlayersWithRank(this, r.getName()); - } - return true; - } else { - return false; - } - } else - return false; + return true; } catch (Exception e) { e.printStackTrace(); } @@ -1166,10 +1111,10 @@ public boolean clearUserTag(String playername) { // // ""); // } - public ArrayList getPlayerNames() { - ArrayList player_names = new ArrayList(); + public List getPlayerNames() { + List player_names = new ArrayList(); - ArrayList players_section = CacheManager.getPlayers(); + List players_section = CacheManager.getPlayers(); for (PRPlayer key : players_section) { player_names.add(key.getName()); } diff --git a/src/main/java/nl/svenar/powerranks/events/OnChat.java b/src/main/java/nl/svenar/powerranks/events/OnChat.java index 5b8c78d..c4b5bec 100644 --- a/src/main/java/nl/svenar/powerranks/events/OnChat.java +++ b/src/main/java/nl/svenar/powerranks/events/OnChat.java @@ -18,11 +18,11 @@ import nl.svenar.common.structure.PRPlayerRank; import nl.svenar.common.structure.PRRank; import nl.svenar.common.utils.PRUtil; +import nl.svenar.common.utils.PowerColor; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.addons.PowerRanksAddon; import nl.svenar.powerranks.addons.PowerRanksPlayer; import nl.svenar.powerranks.cache.CacheManager; -import nl.svenar.powerranks.util.PowerColor; import nl.svenar.powerranks.util.Util; import com.google.common.collect.ImmutableMap; @@ -59,7 +59,8 @@ public void onPlayerChat(final AsyncPlayerChatEvent e) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); String formatted_prefix = ""; String formatted_suffix = ""; diff --git a/src/main/java/nl/svenar/powerranks/events/OnInteract.java b/src/main/java/nl/svenar/powerranks/events/OnInteract.java index 50f8f03..fa09407 100644 --- a/src/main/java/nl/svenar/powerranks/events/OnInteract.java +++ b/src/main/java/nl/svenar/powerranks/events/OnInteract.java @@ -217,7 +217,7 @@ private void handlePowerRanksSign(Sign sign, Player player) { // users.setGroup(player, users.getRankIgnoreCase(sign_argument), true); player.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage( - "commands.buyrank.succes-buy"), + "commands.buyrank.success-buy"), ImmutableMap.builder() .put("player", player.getName()) .put("rank", sign_argument) diff --git a/src/main/java/nl/svenar/powerranks/events/OnJoin.java b/src/main/java/nl/svenar/powerranks/events/OnJoin.java index 9c1fc3c..25f2233 100644 --- a/src/main/java/nl/svenar/powerranks/events/OnJoin.java +++ b/src/main/java/nl/svenar/powerranks/events/OnJoin.java @@ -10,6 +10,7 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.addons.PowerRanksAddon; import nl.svenar.powerranks.addons.PowerRanksPlayer; @@ -29,7 +30,7 @@ public void onPlayerJoin(final PlayerJoinEvent e) { handleJoin(this.plugin, player); - this.plugin.getTablistManager().onPlayerJoin(player); + this.plugin.getTablistManager().onPlayerJoin(player); for (Entry prAddon : plugin.addonsManager.addonClasses.entrySet()) { PowerRanksPlayer prPlayer = new PowerRanksPlayer(plugin, player); @@ -37,7 +38,7 @@ public void onPlayerJoin(final PlayerJoinEvent e) { if (!prAddon.getValue().onPlayerJoinMessage(prPlayer)) { e.setJoinMessage(""); } - + } } @@ -49,7 +50,7 @@ public void onPlayerLeave(final PlayerQuitEvent e) { validatePlayerData(player); - this.plugin.getTablistManager().onPlayerLeave(player); + this.plugin.getTablistManager().onPlayerLeave(player); this.plugin.playerPermissionAttachment.remove(player.getUniqueId()); @@ -72,10 +73,11 @@ public static void handleJoin(PowerRanks plugin, Player player) { validatePlayerData(player); plugin.playerInjectPermissible(player); - // this.plugin.playerPermissionAttachment.put(player.getUniqueId(), player.addAttachment(this.plugin)); - // this.plugin.setupPermissions(player); + PRPlayer prPlayer = CacheManager.getPlayer(player); + prPlayer.updateTags(player.getLocation().getWorld().getName()); plugin.updateTablistName(player); + plugin.getTablistManager().updateSorting(player); long time = new Date().getTime(); plugin.playerPlayTimeCache.put(player.getUniqueId(), time); @@ -88,9 +90,10 @@ public static void handleJoin(PowerRanks plugin, Player player) { } private static void validatePlayerData(Player player) { - boolean exists = CacheManager.getPlayer(player.getUniqueId().toString()) != null; - PowerRanksVerbose.log("onJoin", "Player " + player.getName() + " (" + player.getUniqueId().toString() + " " + (exists ? "exists" : "does not exist")); - + boolean exists = CacheManager.getPlayer(player.getUniqueId().toString()) != null; + PowerRanksVerbose.log("onJoin", "Player " + player.getName() + " (" + player.getUniqueId().toString() + " " + + (exists ? "exists" : "does not exist")); + if (!exists) { CacheManager.createPlayer(player); } diff --git a/src/main/java/nl/svenar/powerranks/events/OnSignChanged.java b/src/main/java/nl/svenar/powerranks/events/OnSignChanged.java index 002abb7..6ad6858 100644 --- a/src/main/java/nl/svenar/powerranks/events/OnSignChanged.java +++ b/src/main/java/nl/svenar/powerranks/events/OnSignChanged.java @@ -1,6 +1,6 @@ package nl.svenar.powerranks.events; -import java.util.ArrayList; +import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableMap; @@ -46,7 +46,7 @@ public void onSignChange(SignChangeEvent event) { .build(), '[', ']')); } else if (sign_command.equalsIgnoreCase("setrank")) { - ArrayList ranks = s.getGroups(); + List ranks = s.getGroups(); boolean rank_exists = false; for (PRRank rank : ranks) { if (rank.getName().equalsIgnoreCase(sign_argument)) { @@ -107,7 +107,7 @@ public void onSignChange(SignChangeEvent event) { '[', ']')); } } else if (sign_command.equalsIgnoreCase("rankup")) { - ArrayList ranks = s.getGroups(); + List ranks = s.getGroups(); if (sign_argument.length() == 0) { event.getPlayer().sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage( diff --git a/src/main/java/nl/svenar/powerranks/events/OnWorldChange.java b/src/main/java/nl/svenar/powerranks/events/OnWorldChange.java index 73aff6b..6506afd 100644 --- a/src/main/java/nl/svenar/powerranks/events/OnWorldChange.java +++ b/src/main/java/nl/svenar/powerranks/events/OnWorldChange.java @@ -8,9 +8,11 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; +import nl.svenar.common.structure.PRPlayer; import nl.svenar.powerranks.PowerRanks; import nl.svenar.powerranks.addons.PowerRanksAddon; import nl.svenar.powerranks.addons.PowerRanksPlayer; +import nl.svenar.powerranks.cache.CacheManager; public class OnWorldChange implements Listener { PowerRanks powerRanks; @@ -22,12 +24,15 @@ public OnWorldChange(final PowerRanks powerRanks) { @EventHandler public void onWorldChange(final PlayerChangedWorldEvent e) { Player player = e.getPlayer(); + PRPlayer prPlayer = CacheManager.getPlayer(player); + prPlayer.updateTags(player.getLocation().getWorld().getName()); this.powerRanks.updateTablistName(player); + this.powerRanks.getTablistManager().updateSorting(player); // this.powerRanks.setupPermissions(player); + PowerRanksPlayer prAddonPlayer = new PowerRanksPlayer(this.powerRanks, player); for (Entry prAddon : this.powerRanks.addonsManager.addonClasses.entrySet()) { - PowerRanksPlayer prPlayer = new PowerRanksPlayer(this.powerRanks, player); - prAddon.getValue().onPlayerWorldChange(prPlayer, e.getFrom(), player.getWorld()); + prAddon.getValue().onPlayerWorldChange(prAddonPlayer, e.getFrom(), player.getWorld()); } } diff --git a/src/main/java/nl/svenar/powerranks/external/PowerRanksExpansion.java b/src/main/java/nl/svenar/powerranks/external/PowerRanksExpansion.java index 832a2b4..6fca047 100644 --- a/src/main/java/nl/svenar/powerranks/external/PowerRanksExpansion.java +++ b/src/main/java/nl/svenar/powerranks/external/PowerRanksExpansion.java @@ -270,6 +270,9 @@ private List getPlayerRanksSorted(Player player) { } } - return PRUtil.reverseRanks(PRUtil.sortRanksByWeight(playerRanks)); + + PRUtil.sortRanksByWeight(playerRanks); + PRUtil.reverseRanks(playerRanks); + return playerRanks; } } \ No newline at end of file diff --git a/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultChat.java b/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultChat.java index 3e383fc..9add845 100644 --- a/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultChat.java +++ b/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultChat.java @@ -106,7 +106,8 @@ public String getPlayerPrefix(String worldName, String playerName) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); return ranks.size() > 0 ? PowerRanks.chatColor(ranks.get(0).getPrefix(), true) : ""; @@ -126,7 +127,8 @@ public String getPlayerSuffix(String worldName, String playerName) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); return ranks.size() > 0 ? PowerRanks.chatColor(ranks.get(0).getSuffix(), true) : ""; // return @@ -203,7 +205,8 @@ public void setPlayerPrefix(String worldName, String playerName, String value) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); if (ranks.size() > 0) { ranks.get(0).setPrefix(value); @@ -222,7 +225,8 @@ public void setPlayerSuffix(String worldName, String playerName, String value) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); if (ranks.size() > 0) { ranks.get(0).setSuffix(value); diff --git a/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultPermission.java b/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultPermission.java index caae7d9..3173d21 100644 --- a/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultPermission.java +++ b/src/main/java/nl/svenar/powerranks/external/PowerRanksVaultPermission.java @@ -251,7 +251,8 @@ public String getPrimaryGroup(String world, OfflinePlayer player) { } } - ranks = PRUtil.reverseRanks(PRUtil.sortRanksByWeight(ranks)); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); return ranks.size() > 0 ? ranks.get(0).getName() : ""; } diff --git a/src/main/java/nl/svenar/powerranks/external/TABHook.java b/src/main/java/nl/svenar/powerranks/external/TABHook.java index 7320242..3e58102 100644 --- a/src/main/java/nl/svenar/powerranks/external/TABHook.java +++ b/src/main/java/nl/svenar/powerranks/external/TABHook.java @@ -127,7 +127,10 @@ public boolean updateRanks() { } private List getSortedRanks() { - return PRUtil.reverseRanks(PRUtil.sortRanksByWeight(CacheManager.getRanks())); + List ranks = CacheManager.getRanks(); + PRUtil.sortRanksByWeight(ranks); + PRUtil.reverseRanks(ranks); + return ranks; } static List getSortedRanks(PRPlayer prPlayer) { @@ -138,6 +141,8 @@ static List getSortedRanks(PRPlayer prPlayer) { } } - return PRUtil.reverseRanks(PRUtil.sortRanksByWeight(playerRanks)); + PRUtil.sortRanksByWeight(playerRanks); + PRUtil.reverseRanks(playerRanks); + return playerRanks; } } diff --git a/src/main/java/nl/svenar/powerranks/gui/GUI.java b/src/main/java/nl/svenar/powerranks/gui/GUI.java index 70f9d74..ef50353 100644 --- a/src/main/java/nl/svenar/powerranks/gui/GUI.java +++ b/src/main/java/nl/svenar/powerranks/gui/GUI.java @@ -114,7 +114,7 @@ public static void clickedItem(Player player, int slot) { } player.sendMessage(Util.powerFormatter( PowerRanks.getLanguageManager().getFormattedMessage( - "commands.buyrank.succes-buy"), + "commands.buyrank.success-buy"), ImmutableMap.builder() .put("player", player.getName()) .put("rank", rankname) diff --git a/src/main/java/nl/svenar/powerranks/gui/GUIPage.java b/src/main/java/nl/svenar/powerranks/gui/GUIPage.java index 0c561c0..cc209c0 100644 --- a/src/main/java/nl/svenar/powerranks/gui/GUIPage.java +++ b/src/main/java/nl/svenar/powerranks/gui/GUIPage.java @@ -142,8 +142,8 @@ Inventory setupGUI(GUI_PAGE_ID pageID) { CacheManager.getRank(rank).getPrefix().replaceAll("&r", "&r&f"), true), "", ChatColor.WHITE + "Description:", PowerRanks.chatColor(description, true), "", ChatColor.WHITE + "Cost: ", ChatColor.GREEN + String.valueOf(cost))); - } else { - PowerRanks.log.warning("Rank '" + rank + "' has a invalid icon!"); + // } else { + // PowerRanks.log.warning("Rank '" + rank + "' has a invalid icon!"); } } catch (Exception e) { @@ -242,11 +242,12 @@ Inventory setupGUI(GUI_PAGE_ID pageID) { String rank = (String) ranks[num_rank_on_page * current_page + i]; Material icon = Material.BARRIER; - if (icon != null) + if (icon != null) { new_gui.setItem(i, createGuiItem(icon, rank, ChatColor.RESET + PowerRanks.chatColor(CacheManager.getRank(rank).getPrefix(), true))); - else - PowerRanks.log.warning("Rank '" + rank + "' has a invalid icon!"); + // } else { + // PowerRanks.log.warning("Rank '" + rank + "' has a invalid icon!"); + } } } @@ -271,12 +272,13 @@ Inventory setupGUI(GUI_PAGE_ID pageID) { if (!rank.equalsIgnoreCase(getData(player.getName() + ":rankname"))) { Material icon = Material.BARRIER; - if (icon != null) + if (icon != null) { new_gui.setItem(i, createGuiItem(icon, rank, ChatColor.RESET + PowerRanks.chatColor(CacheManager.getRank(rank).getPrefix(), true))); - else - PowerRanks.log.warning("Rank '" + rank + "' has a invallid icon!"); + // } else { + // PowerRanks.log.warning("Rank '" + rank + "' has a invallid icon!"); + } } } @@ -300,11 +302,12 @@ Inventory setupGUI(GUI_PAGE_ID pageID) { String rank = (String) ranks[num_rank_on_page * current_page + i]; Material icon = Material.BARRIER; - if (icon != null) + if (icon != null) { new_gui.setItem(i, createGuiItem(icon, rank, ChatColor.RESET + PowerRanks.chatColor(CacheManager.getRank(rank).getPrefix(), true))); - else - PowerRanks.log.warning("Rank '" + rank + "' has a invallid icon!"); + // } else { + // PowerRanks.log.warning("Rank '" + rank + "' has a invallid icon!"); + } } } } @@ -326,11 +329,12 @@ Inventory setupGUI(GUI_PAGE_ID pageID) { String rank = (String) ranks[num_rank_on_page * current_page + i]; Material icon = Material.BARRIER; - if (icon != null) + if (icon != null) { new_gui.setItem(i, createGuiItem(icon, rank, ChatColor.RESET + PowerRanks.chatColor(CacheManager.getRank(rank).getPrefix(), true))); - else - PowerRanks.log.warning("Rank '" + rank + "' has a invallid icon!"); + // } else { + // PowerRanks.log.warning("Rank '" + rank + "' has a invallid icon!"); + } } } diff --git a/src/main/java/nl/svenar/powerranks/update/ConfigFilesUpdater.java b/src/main/java/nl/svenar/powerranks/update/ConfigFilesUpdater.java index d813491..642bc78 100644 --- a/src/main/java/nl/svenar/powerranks/update/ConfigFilesUpdater.java +++ b/src/main/java/nl/svenar/powerranks/update/ConfigFilesUpdater.java @@ -26,6 +26,8 @@ public class ConfigFilesUpdater { + private final static String subPrefixSuffixRegex = "[ ]{0,1}([&][a-fA-F0-9k-oK-OrR]){0,1}((&){0,1}[#][a-fA-F0-9]{6}){0,1}[ ]{0,1}[\\[](subprefix|subsuffix)[\\]][ ]{0,1}([&][a-fA-F0-9k-oK-OrR]){0,1}((&){0,1}[#][a-fA-F0-9]{6}){0,1}[ ]{0,1}"; + private static File backupDir, backupRanks, backupConfig, backupLang, backupPlayers, oldRanksFile, newRanksFile, oldPlayersFile, newPlayersFile, usertagsFile, configFile, langFile; @@ -273,6 +275,12 @@ public static void updateConfigFiles() { } } } + + yamlConf.set("chat.format", yamlConf.getString("chat.format").replaceAll(subPrefixSuffixRegex, " ").replaceAll(" ", " ").trim()); + yamlConf.set("tablist_modification.format", yamlConf.getString("tablist_modification.format").replaceAll(subPrefixSuffixRegex, " ").replaceAll(" ", " ").trim()); + yamlConf.set("nametagedit.prefix", yamlConf.getString("nametagedit.prefix").replaceAll(subPrefixSuffixRegex, " ").replaceAll(" ", " ").trim()); + yamlConf.set("nametagedit.suffix", yamlConf.getString("nametagedit.suffix").replaceAll(subPrefixSuffixRegex, " ").replaceAll(" ", " ").trim()); + yamlConf.set("version", PowerRanks.getVersion().replaceAll("[a-zA-Z ]", "")); yamlConf.save(file); } catch (IOException | InvalidConfigurationException e) { diff --git a/src/main/java/nl/svenar/powerranks/util/BukkitPowerColor.java b/src/main/java/nl/svenar/powerranks/util/BukkitPowerColor.java new file mode 100644 index 0000000..96af4a9 --- /dev/null +++ b/src/main/java/nl/svenar/powerranks/util/BukkitPowerColor.java @@ -0,0 +1,21 @@ +package nl.svenar.powerranks.util; + +import nl.svenar.common.utils.PowerColor; + +public class BukkitPowerColor { + + private PowerColor powerColor; + + public BukkitPowerColor() { + this.powerColor = new PowerColor(); + } + + public String format(char altColorChar, String text, boolean special, boolean addLeadingReset, boolean addTrailingReset) { + text = this.powerColor.formatSpecial(altColorChar, text); + text = this.powerColor.formatHEX(altColorChar, text); + text = this.powerColor.formatColor(altColorChar, text); + + return text; + } + +} \ No newline at end of file diff --git a/src/main/java/nl/svenar/powerranks/util/PluginReloader.java b/src/main/java/nl/svenar/powerranks/util/PluginReloader.java index fa14dc6..6810942 100644 --- a/src/main/java/nl/svenar/powerranks/util/PluginReloader.java +++ b/src/main/java/nl/svenar/powerranks/util/PluginReloader.java @@ -105,7 +105,7 @@ public void disable(String name) { } } - if (commandMap != null) { + if (commandMap != null && commands != null) { for (Iterator> it = commands.entrySet().iterator(); it.hasNext();) { Map.Entry entry = it.next(); if (entry.getValue() instanceof PluginCommand) { diff --git a/src/main/java/nl/svenar/powerranks/util/PowerColor.java b/src/main/java/nl/svenar/powerranks/util/PowerColor.java deleted file mode 100644 index c0b26cc..0000000 --- a/src/main/java/nl/svenar/powerranks/util/PowerColor.java +++ /dev/null @@ -1,164 +0,0 @@ -package nl.svenar.powerranks.util; - -import java.util.HashMap; -import java.util.Random; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.bukkit.ChatColor; -import org.bukkit.Color; - -public class PowerColor { - - private final Random random = new Random(); - private HashMap hexToMCColors = new HashMap(); // HEX, MC-Color - public static char UNFORMATTED_COLOR_CHAR = '&'; - - public PowerColor() { - hexToMCColors.put("#000000", "0"); - hexToMCColors.put("#00002A", "1"); - hexToMCColors.put("#002A00", "2"); - hexToMCColors.put("#002A2A", "3"); - hexToMCColors.put("#2A0000", "4"); - hexToMCColors.put("#2A002A", "5"); - hexToMCColors.put("#2A2A00", "6"); - hexToMCColors.put("#2A2A2A", "7"); - hexToMCColors.put("#151515", "8"); - hexToMCColors.put("#15153F", "9"); - hexToMCColors.put("#153F15", "a"); - hexToMCColors.put("#153F3F", "b"); - hexToMCColors.put("#3F1515", "c"); - hexToMCColors.put("#3F153F", "d"); - hexToMCColors.put("#3F3F15", "e"); - hexToMCColors.put("#3F3F3F", "f"); - } - - public String format(char altColorChar, String input, boolean special, boolean addLeadingReset) { - String output = input; - boolean hexSupported = false; - - if (addLeadingReset && !input.toLowerCase().endsWith(altColorChar + "r")) { - input += altColorChar + "r"; - } - - try { - Class.forName("net.md_5.bungee.api.ChatColor"); - hexSupported = true; - } catch (ClassNotFoundException e) { - hexSupported = false; - } - - if (hexSupported) { - output = formatHEX(output); - } - - if (special) { - output = formatSpecial(altColorChar, output, hexSupported); - } - - if (hexSupported) { - output = net.md_5.bungee.api.ChatColor.translateAlternateColorCodes(altColorChar, output); - } else { - output = ChatColor.translateAlternateColorCodes(altColorChar, hexCompatibilityConverter(altColorChar, output)); - } - - return output; - } - - private String formatHEX(String text) { - Pattern HEXPattern = Pattern.compile("&?#[a-fA-F0-9]{6}"); - Matcher HEXMatcher = HEXPattern.matcher(text); - - while (HEXMatcher.find()) { - String rawHEX = text.substring(HEXMatcher.start(), HEXMatcher.end()); - text = text.replace(rawHEX, net.md_5.bungee.api.ChatColor.of(rawHEX.startsWith("&") ? rawHEX.replaceFirst("&", "") : rawHEX) + ""); - HEXMatcher = HEXPattern.matcher(text); - } - - return text; - } - - private String formatSpecial(char altColorChar, String input, boolean hexSupported) { - String output = ""; - String format = ""; - String formatColor = ""; - String formatModifier = ""; - int charIndex = 0; - boolean doFormat = true; - String[] availableColors = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; - String[] rainbowColors = { "4", "6", "e", "2", "3", "5", "d" }; - String[] rainbowHEXColors = { "FF0000", "FF7F00", "FFFF00", "00FF00", "0000FF", "4B0082", "9400D3" }; - - if (input.toLowerCase().contains(altColorChar + "i")) { - output = input.split(altColorChar + "i").length > 1 ? input.split(altColorChar + "i")[0] - : input.split(altColorChar + "I")[0]; - format = input.split(altColorChar + "i").length > 1 ? input.split(altColorChar + "i")[1] - : input.split(altColorChar + "I")[1]; - formatColor = "i"; - } else if (input.toLowerCase().contains(altColorChar + "j")) { - output = input.split(altColorChar + "j").length > 1 ? input.split(altColorChar + "j")[0] - : input.split(altColorChar + "J")[0]; - format = input.split(altColorChar + "j").length > 1 ? input.split(altColorChar + "j")[1] - : input.split(altColorChar + "J")[1]; - formatColor = "j"; - } else { - output = input; - } - - if (format.toLowerCase().startsWith("&l") || format.toLowerCase().startsWith("&m") - || format.toLowerCase().startsWith("&n") || format.toLowerCase().startsWith("&o") - || format.toLowerCase().startsWith("&k")) { - formatModifier = format.substring(1, 2); - format = format.substring(2); - } - - for (String c : format.split("")) { - if (c.equals(altColorChar + "")) { - doFormat = false; - } - - if (doFormat && !c.equals(" ")) { - output += (formatColor == "i" ? altColorChar + (hexSupported ? rainbowHEXColors[charIndex % rainbowHEXColors.length] : rainbowColors[charIndex % rainbowColors.length]) - : (formatColor == "j" - ? altColorChar + availableColors[random.nextInt(availableColors.length)] - : "")) - + (formatModifier.length() > 0 ? altColorChar + formatModifier : "") - + c; - charIndex++; - } else { - output += c; - } - } - - return output; - } - - private String hexCompatibilityConverter(char altColorChar, String input_hex) { - String output = ""; - int last_distance = Integer.MAX_VALUE; - Color input_color = hex2Rgb(input_hex); - - for (Entry entry : hexToMCColors.entrySet()) { - int distance = calculateColorDistance(input_color, hex2Rgb(entry.getKey())); - if (distance < last_distance) { - last_distance = distance; - output = altColorChar + entry.getValue(); - } - } - return output; - } - - private int calculateColorDistance(Color c1, Color c2) { - int distance = Integer.MAX_VALUE; - distance = (int) Math.round(Math.sqrt(Math.pow(c1.getRed() - c2.getRed(), 2) - + Math.pow(c1.getGreen() - c2.getGreen(), 2) + Math.pow(c1.getBlue() - c2.getBlue(), 2))); - return distance; - } - - private Color hex2Rgb(String colorStr) { - return Color.fromRGB(Integer.valueOf(colorStr.substring(1, 3), 16), - Integer.valueOf(colorStr.substring(3, 5), 16), Integer.valueOf(colorStr.substring(5, 7), 16)); - } - -} \ No newline at end of file diff --git a/src/main/java/nl/svenar/powerranks/util/Util.java b/src/main/java/nl/svenar/powerranks/util/Util.java index 91c2961..5654101 100644 --- a/src/main/java/nl/svenar/powerranks/util/Util.java +++ b/src/main/java/nl/svenar/powerranks/util/Util.java @@ -8,6 +8,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -15,11 +16,15 @@ import org.bukkit.Server; import org.bukkit.block.Sign; import org.bukkit.entity.Player; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; import nl.svenar.powerranks.PowerRanks; public class Util { + public static final long TASK_TPS = 20; + public static String getServerVersion(Server server) { try { Matcher matcher = Pattern.compile("\\d{1,3}.\\d{1,3}|\\d{1,3}.\\d{1,3}.\\d{1,3}") @@ -279,4 +284,137 @@ public static ArrayList generateWildcardList(String permission) { return output; } + + /** + * Convert a time string to seconds + * + * @param time_input + * @return + */ + public static int timeStringToSecondsConverter(String time_input) { + Matcher regex_int = Pattern.compile("^\\d+[^a-zA-Z]{0,1}$").matcher(time_input); + + Matcher regex_seconds = Pattern.compile("\\d+[sS]").matcher(time_input); + Matcher regex_minutes = Pattern.compile("\\d+[mM]").matcher(time_input); + Matcher regex_hours = Pattern.compile("\\d+[hH]").matcher(time_input); + Matcher regex_days = Pattern.compile("\\d+[dD]").matcher(time_input); + Matcher regex_weeks = Pattern.compile("\\d+[wW]").matcher(time_input); + Matcher regex_years = Pattern.compile("\\d+[yY]").matcher(time_input); + + int seconds = 0; + + if (regex_int.find()) { + seconds = Integer.parseInt(time_input); + } else { + if (regex_seconds.find()) { + seconds += Integer.parseInt(time_input.substring(regex_seconds.start(), regex_seconds.end() - 1)); + } + + if (regex_minutes.find()) { + seconds += Integer.parseInt(time_input.substring(regex_minutes.start(), regex_minutes.end() - 1)) * 60; + } + + if (regex_hours.find()) { + seconds += Integer.parseInt(time_input.substring(regex_hours.start(), regex_hours.end() - 1)) + * (60 * 60); + } + + if (regex_days.find()) { + seconds += Integer.parseInt(time_input.substring(regex_days.start(), regex_days.end() - 1)) + * (60 * 60 * 24); + } + + if (regex_weeks.find()) { + seconds += Integer.parseInt(time_input.substring(regex_weeks.start(), regex_weeks.end() - 1)) + * (60 * 60 * 24 * 7); + } + + if (regex_years.find()) { + seconds += Integer.parseInt(time_input.substring(regex_years.start(), regex_years.end() - 1)) + * (60 * 60 * 24 * 365); + } + } + + return seconds; + } + + public static UUID getUUIDFromAPI(String playerName) { + try { + URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + playerName); + + BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); + + String UUIDJson = ""; + String line; + while ((line = in.readLine()) != null) { + UUIDJson += line + "\n"; + } + in.close(); + + JSONObject UUIDObject = (JSONObject) JSONValue.parseWithException(UUIDJson); + String uuid = UUIDObject.get("id").toString(); + if (!uuid.contains("-")) { + uuid = uuid.replaceFirst( + "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", + "$1-$2-$3-$4-$5"); + } + return UUID.fromString(uuid); + } catch (Exception e) { + return null; + } + } + + public static String getNameFromAPI(String uuid) { + try { + URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.replaceAll("-", "")); + + BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); + + String nameJson = ""; + String line; + while ((line = in.readLine()) != null) { + nameJson += line + "\n"; + } + in.close(); + JSONObject nameObject = (JSONObject) JSONValue.parseWithException(nameJson); + return nameObject.get("name").toString(); + } catch (Exception e) { + return null; + } + } + + public static Long convertToLong(Object value) { + if (value instanceof Integer) { + return Long.valueOf(((Integer) value).intValue()); + } else if (value instanceof Long) { + return (Long) value; + } else { + throw new IllegalArgumentException("Value is not an Integer or Long"); + } + } + + public static Object formatStringToType(String input) { + Object output = input; + + if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("false")) { + output = Boolean.parseBoolean(input); + } else if (input.matches("^\\d+$")) { + try { + output = Integer.parseInt(input); + } catch (Exception e) { + output = Long.parseLong(input); + } + } else if (input.matches("^\\d+\\.\\d+$")) { + output = Double.parseDouble(input); + } else if (input.startsWith("[") && input.endsWith("]")) { + String[] inputSplit = input.substring(1, input.length() - 1).split(","); + ArrayList outputList = new ArrayList(); + for (String inputSplitItem : inputSplit) { + outputList.add(inputSplitItem); + } + output = outputList; + } + + return output; + } } \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index da57dbd..6130d4e 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -19,13 +19,13 @@ storage: verbose: false chat: enabled: true - format: '&a[world]&r [usertag] [prefix] [subprefix] [player] [subsuffix] [suffix]&r: [msg]' + format: '&a[world]&r [usertag] [prefix] [player] [suffix]&r: [msg]' tablist_modification: enabled: true - format: '&a[world]&r [usertag] [prefix] [subprefix] [player] [subsuffix] [suffix]' + format: '&a[world]&r [usertag] [prefix] [player] [suffix]' nametagedit: - prefix: '[usertag] [prefix] [subprefix]' - suffix: '[subsuffix] [suffix]' + prefix: '[usertag] [prefix]' + suffix: '[suffix]' signs: enabled: true title_format: '&0[&b%plugin_name%&0]' diff --git a/src/main/resources/lang.yml b/src/main/resources/lang.yml index 1683001..53502c6 100644 --- a/src/main/resources/lang.yml +++ b/src/main/resources/lang.yml @@ -3,9 +3,13 @@ lang: general: prefix: "&0[&bPR&0]&r" no-permission: "&4You do not have permissions to execute this command!" + permission-not-found: "&cPermission node '[permission]' not found!" rank-not-found: "&cRank '[rank]' not found!" player-not-found: "&cPlayer '[target]' not found!" + player-not-online: "&cPlayer '[target]' is not online!" console-is-no-player: "&cThe console is not a player and has no ranks!" + player-rank-has-expired: "&aYour rank [rank] has expired!" + player-rank-expired-console: "&cRemoved expired rank [rank] from [player]" messages: signs: created: "&aNew sign command created" @@ -45,7 +49,7 @@ lang: arguments: "[rank_name] [confirm]" description: "Buy a rank" buy-not-available: "&cBuying ranks is not available on this server." - succes-buy: "&aYou have bought the rank [rank]" + success-buy: "&aYou have bought the rank [rank]" failed-buy-not-enough-money: "&cInsufficient funds to buy the rank [rank]" rankup: arguments: "" @@ -73,7 +77,7 @@ lang: state-changed: "&eChanged [config_target] from &c[old_state] &eto &a[new_state]" numbers-only: "&cOnly numbers are allowed!" tablist: - arguments: " / header_footer_update_interval ) / animation ...>" + arguments: "<(enable/disable tablist_sorting/reverse_tablist_sorting) / set (sorting_update_interval / header_footer_update_interval ) / animation ...>" description: "Edit fields in the tablist configuration file" state-changed: "&eChanged [config_target] from &c[old_state] &eto &a[new_state]" numbers-only: "&cOnly numbers are allowed!" @@ -127,6 +131,7 @@ lang: description: "Add a rank to someone" success-executor: "&aAdded rank [rank] to [player]" failed-executor: "&cFailed to add the rank [rank] to [player]" + failed-already-has-rank: "&c[player] already has the rank [rank]" success-receiver: "&aYou have been granted the rank [rank]" addownrank: arguments: "" @@ -248,7 +253,7 @@ lang: arguments: " " description: "Change the suffix of a rank" success: "&aChanged suffix to '[suffix]' on rank: [rank]" - succes-clear: "&aCleared the suffix on rank: [rank]" + success-clear: "&aCleared the suffix on rank: [rank]" setweight: arguments: " " description: "Change the weight of the rank for permission handeling. Higher weight equals more priority." diff --git a/src/main/resources/tablist.yml b/src/main/resources/tablist.yml index 2d3833c..7d818a1 100644 --- a/src/main/resources/tablist.yml +++ b/src/main/resources/tablist.yml @@ -8,11 +8,11 @@ header-footer: header: - "{animation:demo}" - "" - - "#01b0fb-#11a5fa-#229af8-#328ff7-#4284f5-#5279f4-#636ef2-#7363f1-#8358ef-#934dee-#a442ec-#b437eb-#c42ce9-#d421e8-#e516e6-#f50be5-#f50be5-#e516e6-#d421e8-#c42ce9-#b437eb-#a442ec-#934dee-#8358ef-#7363f1-#636ef2-#5279f4-#4284f5-#328ff7-#229af8-#11a5fa-#01b0fb-" + - "[gradient=#01b0fb,#f50be5]----------------[/gradient][gradient=#f50be5,#01b0fb]----------------[/gradient]" footer: - - "#01b0fb-#11a5fa-#229af8-#328ff7-#4284f5-#5279f4-#636ef2-#7363f1-#8358ef-#934dee-#a442ec-#b437eb-#c42ce9-#d421e8-#e516e6-#f50be5-#f50be5-#e516e6-#d421e8-#c42ce9-#b437eb-#a442ec-#934dee-#8358ef-#7363f1-#636ef2-#5279f4-#4284f5-#328ff7-#229af8-#11a5fa-#01b0fb-" + - "[gradient=#01b0fb,#f50be5]----------------[/gradient][gradient=#f50be5,#01b0fb]----------------[/gradient]" - "" - - "#5ffb15d#61fb15e#64fb16f#66fb16a#68fb17u#6afb17l#6dfb17t #6ffb18h#71fb18e#74fb18a#76fc19d#78fc19e#7afc1ar #7ffc1af#81fc1bo#84fc1bo#86fc1ct#88fc1ce#8afc1cr#8dfc1d, #8ffc1dc#91fc1dh#93fc1ea#96fc1en#98fc1fg#9afc1fe #9dfc1fi#9ffc20n #a1fc20t#a3fd21a#a6fd21b#a8fd21l#aafd22i#adfd22s#affd22t#b1fd23.#b3fd23y#b6fd24m#b8fd24l" + - "[gradient=#5ffb15,#b8fd24]default header footer, change in tablist.yml[/gradient]" animations: demo: delay: 5 diff --git a/src/test/java/nl/svenar/powerranks/test/tests/TestPRData.java b/src/test/java/nl/svenar/powerranks/test/tests/TestPRData.java new file mode 100644 index 0000000..29e587a --- /dev/null +++ b/src/test/java/nl/svenar/powerranks/test/tests/TestPRData.java @@ -0,0 +1,179 @@ +package nl.svenar.powerranks.test.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.UUID; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import nl.svenar.common.structure.PRPermission; +import nl.svenar.common.structure.PRPlayer; +import nl.svenar.common.structure.PRPlayerRank; +import nl.svenar.common.structure.PRRank; +import nl.svenar.common.utils.PRCache; +import nl.svenar.powerranks.test.util.TestDebugger; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestPRData { + + @Test + public void A_testPRCacheHandler() { + TestDebugger.log(this, ""); + TestDebugger.log(this, "[A_testPRCacheHandler] Setup..."); + + final int numPlayers = 10000; + final int numRanks = 1000; + long rankCreationTimeNS = 0; + long playerCreationTimeNS = 0; + + long startTime = System.nanoTime(); + for (int i = 0; i < numRanks; i++) { + PRRank newRank = new PRRank(); + newRank.setName("rank" + i); + newRank.setPrefix("[rank" + i + "]"); + newRank.setWeight(i); + newRank.setDefault(i % 10 == 0); + for (int j = 0; j < 10; j++) { + PRPermission testPermission = new PRPermission("test.rank.permission.rank" + i + "." + j, i % 10 != 0); + newRank.addPermission(testPermission); + } + PRCache.addRank(newRank); + } + long endTime = System.nanoTime(); + rankCreationTimeNS = (endTime - startTime); + + startTime = System.nanoTime(); + for (int i = 0; i < numPlayers; i++) { + PRCache.createPlayer("player" + i, UUID.randomUUID()); + PRPlayer prPlayer = PRCache.getPlayer("player" + i); + assertTrue(prPlayer != null); + PRPermission testPermission = new PRPermission("test.player.permission." + prPlayer.getName(), i % 2 == 0); + prPlayer.addPermission(testPermission); + } + endTime = System.nanoTime(); + playerCreationTimeNS = (endTime - startTime); + + TestDebugger + .log(this, + "[A_testPRCacheHandler] created " + numRanks + " ranks in " + + ((int) ((float) rankCreationTimeNS / 1000000.0) < 100 + ? (int) ((float) rankCreationTimeNS / 1000.0) + "us (" + + (double) Math + .round((((float) rankCreationTimeNS / 1000000.0) * 100.0)) + / 100.0 + + "ms)" + : (int) ((float) rankCreationTimeNS / 1000000.0) + "ms")); + TestDebugger + .log(this, + "[A_testPRCacheHandler] created " + numPlayers + " players in " + + ((int) ((float) playerCreationTimeNS / 1000000.0) < 100 + ? (int) ((float) playerCreationTimeNS / 1000.0) + "us (" + + (double) Math + .round((((float) playerCreationTimeNS / 1000000.0) * 100.0)) + / 100.0 + + "ms)" + : (int) ((float) playerCreationTimeNS / 1000000.0) + "ms")); + + TestDebugger.log(this, "[A_testPRCacheHandler] Checking number of ranks..."); + assertEquals(PRCache.getRanks().size(), numRanks); + TestDebugger.log(this, "[A_testPRCacheHandler] Number of ranks OK"); + + TestDebugger.log(this, "[A_testPRCacheHandler] Checking number of players..."); + assertEquals(PRCache.getPlayers().size(), numPlayers); + TestDebugger.log(this, "[A_testPRCacheHandler] Number of players OK"); + + TestDebugger.log(this, "[A_testPRCacheHandler] Setup OK"); + } + + @Test + public void B_testPRPlayerDefaultRanks() { + TestDebugger.log(this, "[B_testPRPlayerDefaultRanks] Checking number of default ranks in players..."); + + int numDefaultRanks = 0; + + for (PRRank rank : PRCache.getRanks()) { + if (rank.isDefault()) { + numDefaultRanks++; + } + } + + for (int i = 0; i < PRCache.getPlayers().size(); i += PRCache.getPlayers().size() / 100) { + PRPlayer prPlayer = PRCache.getPlayer("player" + i); + assertEquals(prPlayer.getDefaultRanks().size(), numDefaultRanks); + } + + TestDebugger.log(this, "[B_testPRPlayerDefaultRanks] Number of default ranks OK"); + } + + @Test + public void C_testPRPlayerPermissions() { + TestDebugger.log(this, "[C_testPRPlayerPermissions] Checking playerpermissions in players..."); + for (int i = 0; i < PRCache.getPlayers().size(); i += PRCache.getPlayers().size() / 100) { + PRPlayer prPlayer = PRCache.getPlayer("player" + i); + List permissions = prPlayer.getEffectivePermissions(); + boolean hasTestPermission = false; + boolean testPermissionValue = false; + for (PRPermission permission : permissions) { + if (permission.getName().equals("test.player.permission." + prPlayer.getName())) { + hasTestPermission = true; + testPermissionValue = permission.getValue(); + break; + } + } + assertTrue(hasTestPermission); + assertEquals(testPermissionValue, i % 2 == 0); + } + TestDebugger.log(this, "[C_testPRPlayerPermissions] Playerpermissions OK"); + } + + @Test + public void D_testPRRankPermissionOrder() { + TestDebugger.log(this, "[D_testPRRankPermissionOrder] Checking rank weight permission overriding..."); + + PRRank newRank = new PRRank(); + PRPermission testPermission = new PRPermission("test.rank.permission", false); + newRank.setName("testRank1"); + newRank.setPrefix("[testRank1]"); + newRank.setWeight(10); + newRank.addPermission(testPermission); + PRCache.addRank(newRank); + + newRank = new PRRank(); + testPermission = new PRPermission("test.rank.permission", true); + newRank.setName("testRank2"); + newRank.setPrefix("[testRank2]"); + newRank.setWeight(50); + newRank.addPermission(testPermission); + PRCache.addRank(newRank); + + PRPlayer testPlayer = PRCache.createPlayer("TestPlayer", UUID.randomUUID()); + + testPlayer.addRank(new PRPlayerRank("testRank1")); + boolean permissionAllowed = false; + for (PRPermission permission : testPlayer.getEffectivePermissions()) { + if (permission.getName().equals("test.rank.permission")) { + permissionAllowed = permission.getValue(); + break; + } + } + assertFalse(permissionAllowed); + + testPlayer.addRank(new PRPlayerRank("testRank2")); + + permissionAllowed = false; + for (PRPermission permission : testPlayer.getEffectivePermissions()) { + if (permission.getName().equals("test.rank.permission")) { + permissionAllowed = permission.getValue(); + break; + } + } + assertTrue(permissionAllowed); + + TestDebugger.log(this, "[D_testPRRankPermissionOrder] Rank weight permission overriding OK"); + } +} \ No newline at end of file diff --git a/src/test/java/nl/svenar/powerranks/test/tests/TestPowerColor.java b/src/test/java/nl/svenar/powerranks/test/tests/TestPowerColor.java new file mode 100644 index 0000000..d05dca8 --- /dev/null +++ b/src/test/java/nl/svenar/powerranks/test/tests/TestPowerColor.java @@ -0,0 +1,205 @@ +package nl.svenar.powerranks.test.tests; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import nl.svenar.common.utils.PowerColor; +import nl.svenar.powerranks.test.util.TestDebugger; + +public class TestPowerColor { + + @Test + public void testOldColorFormat() { + TestDebugger.log(this, ""); + TestDebugger.log(this, "[testOldColorFormat] Start"); + + PowerColor powerColor = new PowerColor(); + + String input = "&4&lHello &c&lWorld"; + String expected = "§4§lHello §c§lWorld"; + String actual = powerColor.formatColor(PowerColor.UNFORMATTED_COLOR_CHAR, input); + + if (!expected.toLowerCase().equals(actual.toLowerCase())) { + TestDebugger.log(this, + "[testOldColorFormat] (" + (expected.toLowerCase().equals(actual.toLowerCase())) + + "): " + + expected.toLowerCase() + " == " + actual.toLowerCase()); + } + assertEquals(expected.toLowerCase(), actual.toLowerCase()); + + TestDebugger.log(this, "[testOldColorFormat] Done!"); + } + + @Test + public void testHEXColorFormat() { + TestDebugger.log(this, ""); + TestDebugger.log(this, "[testHEXColorFormat] Start"); + + PowerColor powerColor = new PowerColor(); + + String input = "#FF00AAHello #00FFAA&lWorld"; + String expected1 = "&x&F&F&0&0&A&AHello &x&0&0&F&F&A&A&lWorld"; + String expected2 = "§x§F§F§0§0§A§AHello §x§0§0§F§F§A§A§lWorld"; + String actual1 = powerColor.formatHEX(PowerColor.UNFORMATTED_COLOR_CHAR, input); + String actual2 = powerColor.formatColor(PowerColor.UNFORMATTED_COLOR_CHAR, actual1); + + if (!expected1.toLowerCase().equals(actual1.toLowerCase())) { + TestDebugger.log(this, "[testHEXColorFormat] (" + + (expected1.toLowerCase().equals(actual1.toLowerCase())) + + "): " + expected1.toLowerCase() + " == " + actual1.toLowerCase()); + } + assertEquals(expected1.toLowerCase(), actual1.toLowerCase()); + if (!expected2.toLowerCase().equals(actual2.toLowerCase())) { + TestDebugger.log(this, "[testHEXColorFormat] (" + + (expected2.toLowerCase().equals(actual2.toLowerCase())) + + "): " + expected2.toLowerCase() + " == " + actual2.toLowerCase()); + } + assertEquals(expected2.toLowerCase(), actual2.toLowerCase()); + + TestDebugger.log(this, "[testHEXColorFormat] Done!"); + } + + @Test + public void testSpecialColorFormat() { + TestDebugger.log(this, ""); + TestDebugger.log(this, "[testSpecialColorFormat] Start"); + + PowerColor powerColor = new PowerColor(); + + TestDebugger.log(this, "[testSpecialColorFormat interpolation] Start"); + String interpolateColor1 = "#DDEEFF"; + String interpolateColor2 = "#AABBCC"; + String interpolateOutput = powerColor.interpolateColor(interpolateColor1, interpolateColor2, 0.5); + String interpolateExpected = "#c3d4e5"; + + if (!interpolateExpected.toLowerCase().equals(interpolateOutput.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat interpolation] (" + + (interpolateExpected.toLowerCase() + .equals(interpolateOutput.toLowerCase())) + + "): " + + interpolateExpected.toLowerCase() + " == " + + interpolateOutput.toLowerCase()); + } + assertEquals(interpolateOutput.toLowerCase(), interpolateExpected.toLowerCase()); + TestDebugger.log(this, "[testSpecialColorFormat interpolation] OK"); + + TestDebugger.log(this, "[testSpecialColorFormat rainbow] Start"); + String inputRainbow = "[rainbow]Some rainbow text test[/rainbow]"; + String expectedRainbow1 = "#e81416s#ef440eo#f77407m#ffa500e#ffa500 #fdbc12r#fbd324a#faeb36i#faeb36n#cfdd2ab#a4d01fo#79c314w#79c314 #68ab5at#5894a0e#487de7x#487de7t#4965ce #4a4db5t#4b369de#4b369ds#70369dt&r"; + String expectedRainbow2 = "§x§e§8§1§4§1§6s§x§e§f§4§4§0§eo§x§f§7§7§4§0§7m§x§f§f§a§5§0§0e§x§f§f§a§5§0§0 §x§f§d§b§c§1§2r§x§f§b§d§3§2§4a§x§f§a§e§b§3§6i§x§f§a§e§b§3§6n§x§c§f§d§d§2§ab§x§a§4§d§0§1§fo§x§7§9§c§3§1§4w§x§7§9§c§3§1§4 §x§6§8§a§b§5§at§x§5§8§9§4§a§0e§x§4§8§7§d§e§7x§x§4§8§7§d§e§7t§x§4§9§6§5§c§e §x§4§a§4§d§b§5t§x§4§b§3§6§9§de§x§4§b§3§6§9§ds§x§7§0§3§6§9§dt§r"; + String actualRainbow1 = powerColor.formatSpecial(PowerColor.UNFORMATTED_COLOR_CHAR, inputRainbow); + String actualRainbow2 = powerColor.formatColor(PowerColor.UNFORMATTED_COLOR_CHAR, + powerColor.formatHEX(PowerColor.UNFORMATTED_COLOR_CHAR, actualRainbow1)); + + if (!expectedRainbow1.toLowerCase().equals(actualRainbow1.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat rainbow #1] (" + + (expectedRainbow1.toLowerCase() + .equals(actualRainbow1.toLowerCase())) + + "): " + + expectedRainbow1.toLowerCase() + " == " + + actualRainbow1.toLowerCase()); + } + assertEquals(expectedRainbow1.toLowerCase(), actualRainbow1.toLowerCase()); + if (!expectedRainbow2.toLowerCase().equals(actualRainbow2.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat rainbow #2] (" + + (expectedRainbow2.toLowerCase() + .equals(actualRainbow2.toLowerCase())) + + "): " + + expectedRainbow2.toLowerCase() + " == " + + actualRainbow2.toLowerCase()); + } + assertEquals(expectedRainbow2.toLowerCase(), actualRainbow2.toLowerCase()); + TestDebugger.log(this, "[testSpecialColorFormat rainbow] OK"); + + TestDebugger.log(this, "[testSpecialColorFormat gradient] Start"); + String inputGradient = "[gradient=#489DF8,#D30EEE]Some gradient text test[/gradient]"; + String expectedGradient1 = "#489df8s#4e96f7o#5490f7m#5a89f6e#6182f6 #677cf5g#6d76f5r#746ff4a#7a69f4d#8062f3i#875bf3e#8d55f3n#934ff2t#9a48f2 #a042f1t#a63bf1e#ad34f0x#b32ef0t#b927ef #c021eft#c61beee#cc14ees#d30eeet&r"; + String expectedGradient2 = "§x§4§8§9§d§f§8s§x§4§e§9§6§f§7o§x§5§4§9§0§f§7m§x§5§a§8§9§f§6e§x§6§1§8§2§f§6 §x§6§7§7§c§f§5g§x§6§d§7§6§f§5r§x§7§4§6§f§f§4a§x§7§a§6§9§f§4d§x§8§0§6§2§f§3i§x§8§7§5§b§f§3e§x§8§d§5§5§f§3n§x§9§3§4§f§f§2t§x§9§a§4§8§f§2 §x§a§0§4§2§f§1t§x§a§6§3§b§f§1e§x§a§d§3§4§f§0x§x§b§3§2§e§f§0t§x§b§9§2§7§e§f §x§c§0§2§1§e§ft§x§c§6§1§b§e§ee§x§c§c§1§4§e§es§x§d§3§0§e§e§et§r"; + String actualGradient1 = powerColor.formatSpecial(PowerColor.UNFORMATTED_COLOR_CHAR, inputGradient); + String actualGradient2 = powerColor.formatColor(PowerColor.UNFORMATTED_COLOR_CHAR, + powerColor.formatHEX(PowerColor.UNFORMATTED_COLOR_CHAR, actualGradient1)); + + if (!expectedGradient1.toLowerCase().equals(actualGradient1.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat gradient #1] (" + + (expectedGradient1.toLowerCase() + .equals(actualGradient1.toLowerCase())) + + "): " + + expectedGradient1.toLowerCase() + " == " + + actualGradient1.toLowerCase()); + } + assertEquals(expectedGradient2.toLowerCase(), actualGradient2.toLowerCase()); + if (!expectedGradient2.toLowerCase().equals(actualGradient2.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat gradient #2] (" + + (expectedGradient2.toLowerCase() + .equals(actualGradient2.toLowerCase())) + + "): " + + expectedGradient2.toLowerCase() + " == " + + actualGradient2.toLowerCase()); + } + assertEquals(expectedGradient2.toLowerCase(), actualGradient2.toLowerCase()); + TestDebugger.log(this, "[testSpecialColorFormat gradient] OK"); + + String inputAll = "[gradient=#489DF8,#D30EEE]Some gradient text test[/gradient] Some unformatted text [rainbow]Some rainbow text test[/rainbow]"; + String expectedAll1 = "#489df8s#4e96f7o#5490f7m#5a89f6e#6182f6 #677cf5g#6d76f5r#746ff4a#7a69f4d#8062f3i#875bf3e#8d55f3n#934ff2t#9a48f2 #a042f1t#a63bf1e#ad34f0x#b32ef0t#b927ef #c021eft#c61beee#cc14ees#d30eeet some unformatted text #e81416s#ef440eo#f77407m#ffa500e#ffa500 #fdbc12r#fbd324a#faeb36i#faeb36n#cfdd2ab#a4d01fo#79c314w#79c314 #68ab5at#5894a0e#487de7x#487de7t#4965ce #4a4db5t#4b369de#4b369ds#70369dt&r"; + String expectedAll2 = "§x§4§8§9§d§f§8S§x§4§e§9§6§f§7o§x§5§4§9§0§f§7m§x§5§a§8§9§f§6e§x§6§1§8§2§f§6 §x§6§7§7§c§f§5g§x§6§d§7§6§f§5r§x§7§4§6§f§f§4a§x§7§a§6§9§f§4d§x§8§0§6§2§f§3i§x§8§7§5§b§f§3e§x§8§d§5§5§f§3n§x§9§3§4§f§f§2t§x§9§a§4§8§f§2 §x§a§0§4§2§f§1t§x§a§6§3§b§f§1e§x§a§d§3§4§f§0x§x§b§3§2§e§f§0t§x§b§9§2§7§e§f §x§c§0§2§1§e§ft§x§c§6§1§b§e§ee§x§c§c§1§4§e§es§x§d§3§0§e§e§et Some unformatted text §x§e§8§1§4§1§6S§x§e§f§4§4§0§eo§x§f§7§7§4§0§7m§x§f§f§a§5§0§0e§x§f§f§a§5§0§0 §x§f§d§b§c§1§2r§x§f§b§d§3§2§4a§x§f§a§e§b§3§6i§x§f§a§e§b§3§6n§x§c§f§d§d§2§ab§x§a§4§d§0§1§fo§x§7§9§c§3§1§4w§x§7§9§c§3§1§4 §x§6§8§a§b§5§at§x§5§8§9§4§a§0e§x§4§8§7§d§e§7x§x§4§8§7§d§e§7t§x§4§9§6§5§c§e §x§4§a§4§d§b§5t§x§4§b§3§6§9§de§x§4§b§3§6§9§ds§x§7§0§3§6§9§dt§r"; + String actualAll1 = powerColor.formatSpecial(PowerColor.UNFORMATTED_COLOR_CHAR, inputAll); + String actualAll2 = powerColor.formatColor(PowerColor.UNFORMATTED_COLOR_CHAR, + powerColor.formatHEX(PowerColor.UNFORMATTED_COLOR_CHAR, actualAll1)); + + if (!expectedAll1.toLowerCase().equals(actualAll1.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat all #1] (" + + (expectedAll1.toLowerCase().equals(actualAll1.toLowerCase())) + + "): " + expectedAll1.toLowerCase() + " == " + + actualAll1.toLowerCase()); + } + assertEquals(expectedAll1.toLowerCase(), actualAll1.toLowerCase()); + if (!expectedAll2.toLowerCase().equals(actualAll2.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat all #2] (" + + (expectedAll2.toLowerCase().equals(actualAll2.toLowerCase())) + + "): " + expectedAll2.toLowerCase() + " == " + + actualAll2.toLowerCase()); + } + assertEquals(expectedAll2.toLowerCase(), actualAll2.toLowerCase()); + + TestDebugger.log(this, "[testSpecialColorFormat chat] Start"); + String inputChat = "&aworld&r [gradient=#127e00,#3eaf18]MEMBER[/gradient] &rsvenar&r: &r[rainbow]This is a rainbow test[/rainbow] test123456 [gradient=#EE896A,#AA12EA]test123[/gradient]"; + String expectedChat1 = "&aworld&r #127e00m#1a8704e#239109m#2c9b0eb#35a513e#3eaf18r &rsvenar&r: &r#e81416t#ef440eh#f77407i#ffa500s#ffa500 #fdbc12i#fbd324s#faeb36 #faeb36a#cfdd2a #a4d01fr#79c314a#79c314i#68ab5an#5894a0b#487de7o#487de7w#4965ce #4a4db5t#4b369de#4b369ds#70369dt test123456 #ee896at#e2757fe#d76194s#cc4daat#c039bf1#b525d42#aa12ea3&r"; + String expectedChat2 = "§aworld§r §x§1§2§7§e§0§0M§x§1§a§8§7§0§4E§x§2§3§9§1§0§9M§x§2§c§9§b§0§eB§x§3§5§a§5§1§3E§x§3§e§a§f§1§8R §rsvenar§r: §r§x§e§8§1§4§1§6T§x§e§f§4§4§0§eh§x§f§7§7§4§0§7i§x§f§f§a§5§0§0s§x§f§f§a§5§0§0 §x§f§d§b§c§1§2i§x§f§b§d§3§2§4s§x§f§a§e§b§3§6 §x§f§a§e§b§3§6a§x§c§f§d§d§2§a §x§a§4§d§0§1§fr§x§7§9§c§3§1§4a§x§7§9§c§3§1§4i§x§6§8§a§b§5§an§x§5§8§9§4§a§0b§x§4§8§7§d§e§7o§x§4§8§7§d§e§7w§x§4§9§6§5§c§e §x§4§a§4§d§b§5t§x§4§b§3§6§9§de§x§4§b§3§6§9§ds§x§7§0§3§6§9§dt test123456 §x§e§e§8§9§6§at§x§e§2§7§5§7§fe§x§d§7§6§1§9§4s§x§c§c§4§d§a§at§x§c§0§3§9§b§f1§x§b§5§2§5§d§42§x§a§a§1§2§e§a3§r"; + String actualChat1 = powerColor.formatSpecial(PowerColor.UNFORMATTED_COLOR_CHAR, inputChat); + String actualChat2 = powerColor.formatColor(PowerColor.UNFORMATTED_COLOR_CHAR, + powerColor.formatHEX(PowerColor.UNFORMATTED_COLOR_CHAR, actualChat1)); + + if (!expectedChat1.toLowerCase().equals(actualChat1.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat chat #1] (" + + (expectedChat1.toLowerCase() + .equals(actualChat1.toLowerCase())) + + "): " + + expectedChat1.toLowerCase() + " == " + + actualChat1.toLowerCase()); + } + assertEquals(expectedChat2.toLowerCase(), actualChat2.toLowerCase()); + + if (!expectedChat2.toLowerCase().equals(actualChat2.toLowerCase())) { + TestDebugger.log(this, + "[testSpecialColorFormat chat #2] (" + + (expectedChat2.toLowerCase() + .equals(actualChat2.toLowerCase())) + + "): " + + expectedChat2.toLowerCase() + " == " + + actualChat2.toLowerCase()); + } + assertEquals(expectedChat2.toLowerCase(), actualChat2.toLowerCase()); + TestDebugger.log(this, "[testSpecialColorFormat chat] OK"); + + TestDebugger.log(this, "[testSpecialColorFormat] Done!"); + } +} diff --git a/src/test/java/nl/svenar/powerranks/test/util/TestDebugger.java b/src/test/java/nl/svenar/powerranks/test/util/TestDebugger.java new file mode 100644 index 0000000..332cdf2 --- /dev/null +++ b/src/test/java/nl/svenar/powerranks/test/util/TestDebugger.java @@ -0,0 +1,26 @@ +package nl.svenar.powerranks.test.util; + +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; + +public class TestDebugger { + + private static boolean DEBUG = true; + public static boolean DOPERFORMANCETEST = false; + private static Instant startTime; + private static String lastClassName = ""; + + public static void log(Object clazz, String message) { + if (!DEBUG) + return; + + if (Objects.isNull(startTime) || !clazz.getClass().getSimpleName().equals(lastClassName)) { + lastClassName = clazz.getClass().getSimpleName(); + startTime = Instant.now(); + } + + System.out.println("[" + String.format("%04d", Duration.between(startTime, Instant.now()).toMillis()) + "ms] [" + + clazz.getClass().getSimpleName() + "] " + message); + } +} \ No newline at end of file