Merge branch 'master' of github.com:mcMMO-Dev/mcMMO into tridentsxbows

This commit is contained in:
nossr50 2021-04-20 14:35:31 -07:00
commit 256dbc14e2
182 changed files with 8098 additions and 3854 deletions

View File

@ -103,21 +103,88 @@ Version 2.2.000
Parties got unnecessarily complex in my absence, I have removed many party features in order to simplify parties and bring them closer to my vision. I have also added new features which should improve parties where it matters. Parties got unnecessarily complex in my absence, I have removed many party features in order to simplify parties and bring them closer to my vision. I have also added new features which should improve parties where it matters.
About the removed party features, all the features I removed I consider poor quality features and I don't think they belong in mcMMO. Feel free to yell at me in discord if you disagree. About the removed party features, all the features I removed I consider poor quality features and I don't think they belong in mcMMO. Feel free to yell at me in discord if you disagree.
I don't know what genius decided to make parties public by default, when I found out that parties had been changed to such a system I could barely contain my disgust. Parties are back to being private, you get invited by a party leader or party officer. That is the only way to join a party. I don't know what genius decided to make parties public by default, when I found out that parties had been changed to such a system I could barely contain my disgust. Parties are back to being private, you get invited by a party leader or party officer. That is the only way to join a party.
Version 2.1.189 Version 2.1.196
Removed UP warning Crossbows can now be fished up with enchantments
Updated pl locale (Thanks Mich3l3k)
NOTES: NOTES:
Ultra Permissions is SAFE to use with mcMMO Crossbows is not in the default fishing loot list, you'd have to add it yourself.
Version 2.1.195
Fixed a null connection error which affected some SQL users
Version 2.1.194
Fixed an XP exploit
Updated SQL to not throw errors if upgrades.yml was reset for any reason
Updated SQL to use the newest driver path (and fall back to the old one if the new one doesn't exist on the server)
Locale override files are now named locale_override.properties (converted automatically/generated automatically)
Existing in use locale override files will be renamed to locale_override.properties and have some useful text put in them
mcMMO will now generate a locale override file with some detailed instructions if one doesn't exist (will be found in /plugins/mcMMO/locales/locale_override.properties)
NOTES:
If you were overriding locale before this update mcMMO will just rename the existing override file to locale_override.properties add some useful text and then load it
Remember you can use /mcreloadlocale to swap the edits in without restarting the server
Version 2.1.193
Fixed another bug where mcrank/mctop/leaderboards weren't loading
Fixed a bug where override locales weren't being loaded (but worked after a reloadlocale command)
(Unit Tests) Added a test to make sure leaderboards for FlatFile were working
Fixed blocks being dropped from blast mining even if yield was set to 0 (thanks Warriorrrr)
Fixed Tree feller not working entirely if one fake block break event is cancelled. (thanks Warriorrrr)
Fixes no woodcutting xp being rewarded if a tree is too big while using tree feller. (thanks Warriorrrr)
Updated pl locale (thanks Mich3l3k)
Version 2.1.192
Removed some debug messages from FlatFileDatabaseManager
Fixed another bug where player names could be saved as null for FlatFileDB (they will update on the players next login at the next save interval)
(API) Removed deprecation from com.gmail.nossr50.api.ExperienceAPI.getOfflineProfile(java.lang.String)
(API) Added com.gmail.nossr50.api.DatabaseAPI.doesPlayerExistInDB(org.bukkit.OfflinePlayer)
(API) Added com.gmail.nossr50.api.ExperienceAPI.getOfflineProfile(org.bukkit.OfflinePlayer)
(API) Added com.gmail.nossr50.api.ExperienceAPI.getOfflineXP(org.bukkit.OfflinePlayer, java.lang.String)
(API) Added com.gmail.nossr50.api.ExperienceAPI.getOfflineXPRaw(org.bukkit.OfflinePlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType)
(API) Added com.gmail.nossr50.api.ExperienceAPI.getOfflineXPRaw(org.bukkit.OfflinePlayer, java.lang.String)
(API) Added com.gmail.nossr50.api.ExperienceAPI.getOfflineXPToNextLevel(org.bukkit.OfflinePlayer, java.lang.String)
(API) Added com.gmail.nossr50.api.DatabaseAPI.doesPlayerExistInDB(java.lang.String)
(Unit Tests) Added some more unit tests to FlatFileDB
Version 2.1.191
Fixed a bug related to our blocktracker
Fixed a bug that prevented the leaderboards from working on FlatFile in some circumstances
Some minor optimizations to our Block events
(Unit Tests) Added a test for initializing the leaderboard on FlatFile
Version 2.1.190
Fixed a null error in BitSetChunkStore
Version 2.1.189
Fixed a bug that would remove components from death messages when players were killed by mobs (thanks lexikiq)
Rewrote how FlatFileDatabase verifies data integrity
FlatFileDatabase has much better data validation and will repair broken/invalid data much better
Fixed a bug where FlatFileDatabase users could have their names saved as "null" (names will be fixed the next time the player logs in)
Added 20~ unit tests for FlatFileDatabaseManager (see notes)
FlatFileDB now stores the last login of users again (was completely non functional for a while)
Newly created flat file databases (mcmmo.users file) will have a comment line at the top noting the date the database was created
Minor performance optimizations to FlatFile database
mcMMO will once again purge old users if the config option is on (see notes)
Fixed a bug where FlatFileDatabaseManager didn't properly upgrade older database entries to the newest schema
The setting to disable the mcMMO user block tracker has been moved from our "hidden config" to persistent_data.yml
Added 'mcMMO_Region_System.Enabled' to persistent_data.yml (don't touch this setting unless you know what you are doing)
Removed MHD command (it didn't do anything for a while now)
Removed UltraPermissions warning
Updated pl locale (Thanks Mich3l3k)
Fixed an IllegalPluginAccessException error that could happen during server shutdown
Minor performance optimizations to misc parts of the codebase
(API) Added com.gmail.nossr50.database.DatabaseManager.loadPlayerProfile(org.bukkit.OfflinePlayer)
(API) Deprecated com.gmail.nossr50.database.DatabaseManager.loadPlayerProfile(java.util.UUID, java.lang.String)
(API) Removed com.gmail.nossr50.database.DatabaseManager.newUser(java.lang.String, java.util.UUID)
(API) PrimarySkillType will soon be just an enum with nothing special going on
(API) Deprecated the members of PrimarySkillType use mcMMO::getSkillTools instead, deprecated members will be removed in Tridents & Crossbows (due soon)
(API) Some members of PrimarySkillType were removed and not deprecated (such as the field constants)
NOTES:
I spent over 26 hours refactoring FlatFileDB and writing unit tests for it, this will ensure that any changes in the code that could break the database are caught at compile time (so long as we have enough tests, could probably use more)
Regarding purging old users on the FlatFileDB, since this wasn't functioning for a while, the last login of users has been reset and if mcMMO hasn't seen that user since this update, it won't purge them as it has no way to know if they are truly an old user
I'm likely going to add SQLite DB as an option in the future, I spent time to fix up the FlatFileDB as some Unit Testing practice.
Ultra Permissions is SAFE to use with mcMMO, disregard previous messages stating otherwise
After getting in contact with the UltraPermissions devs and exhaustive testing, I have concluded that using UltraPermissions is completely safe with mcMMO. The users who had an issue with performance currently have an unknown cause, potentially it is from a plugin using the UltraPermissions API I really can't say without more data. My apologies to the UltraPermissions team for reporting an issue between our two plugins directly, as that is not the case. I would have tested it myself sooner but UltraPermissions was closed source and premium so I wasn't particularly motivated to do so, however I have been given access to the binaries so now I can do all the testing I want if future issues ever arise which I have zero expectations that they will. After getting in contact with the UltraPermissions devs and exhaustive testing, I have concluded that using UltraPermissions is completely safe with mcMMO. The users who had an issue with performance currently have an unknown cause, potentially it is from a plugin using the UltraPermissions API I really can't say without more data. My apologies to the UltraPermissions team for reporting an issue between our two plugins directly, as that is not the case. I would have tested it myself sooner but UltraPermissions was closed source and premium so I wasn't particularly motivated to do so, however I have been given access to the binaries so now I can do all the testing I want if future issues ever arise which I have zero expectations that they will.
UltraPermissions is as efficient as LuckPerms
I have done a lot of profiling of UltraPermissions via Spark in the last few hours, I also compared it to LuckPerms. I wasn't expecting it, but UltraPermissions runs just as fast as LuckPerms if not faster. So it has no performance issues whatsoever from my point of view.
Use whatever permission plugin you like, there will be no difference between using LuckPerms or UltraPermissions with mcMMO.
If you had issues with UltraPermissions please contact the UP devs
If you experience lag with mcMMO and UltraPermissions, we are trying to determine the culprit. It is likely the culprit is from another plugin doing bad things with the UltraPermissions API. Please get in contact with the UltraPermission devs if you run into issues ( @MATRIX | Timo K. & @Liz3 ). Neither I nor they can replicate it so we need you guys to provide more data.
Version 2.1.188 Version 2.1.188
Updated default entries in treasures.yml to use "Level_Requirement" instead of "Drop_Level" Updated default entries in treasures.yml to use "Level_Requirement" instead of "Drop_Level"
Fixed a bug where excavation treasures only required level 0 instead of loading the value from the config Fixed a bug where excavation treasures only required level 0 instead of loading the value from the config

64
pom.xml
View File

@ -11,6 +11,11 @@
<developerConnection>scm:git:git@github.com:mcMMO-Dev/mcMMO.git</developerConnection> <developerConnection>scm:git:git@github.com:mcMMO-Dev/mcMMO.git</developerConnection>
<tag>HEAD</tag> <tag>HEAD</tag>
</scm> </scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<issueManagement> <issueManagement>
<url>https://github.com/mcMMO-Dev/mcMMO/issues</url> <url>https://github.com/mcMMO-Dev/mcMMO/issues</url>
<system>GitHub</system> <system>GitHub</system>
@ -65,6 +70,15 @@
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId> <artifactId>maven-release-plugin</artifactId>
@ -209,7 +223,10 @@
<id>sk89q-repo</id> <id>sk89q-repo</id>
<url>https://maven.sk89q.com/repo/</url> <url>https://maven.sk89q.com/repo/</url>
</repository> </repository>
<!-- ... --> <repository> <!-- for development builds -->
<id>sonatype-oss</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
<repository> <repository>
<id>aikar</id> <id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url> <url>https://repo.aikar.co/content/groups/aikar/</url>
@ -218,8 +235,18 @@
<id>sonatype-oss</id> <id>sonatype-oss</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url> <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository> </repository>
<!-- ... -->
</repositories> </repositories>
<!-- <dependencyManagement>-->
<!-- <dependencies>-->
<!-- <dependency>-->
<!-- <groupId>org.junit</groupId>-->
<!-- <artifactId>junit-bom</artifactId>-->
<!-- <version>5.7.1</version>-->
<!-- <type>pom</type>-->
<!-- <scope>import</scope>-->
<!-- </dependency>-->
<!-- </dependencies>-->
<!-- </dependencyManagement>-->
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.neetgames</groupId> <groupId>com.neetgames</groupId>
@ -241,6 +268,12 @@
<artifactId>NEET-lib</artifactId> <artifactId>NEET-lib</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>com.github.seeseemelk</groupId>
<artifactId>MockBukkit-v1.16</artifactId>
<version>0.25.0</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>co.aikar</groupId> <groupId>co.aikar</groupId>
<artifactId>acf-bukkit</artifactId> <!-- Don't forget to replace this --> <artifactId>acf-bukkit</artifactId> <!-- Don't forget to replace this -->
@ -286,6 +319,12 @@
<groupId>net.kyori</groupId> <groupId>net.kyori</groupId>
<artifactId>adventure-platform-common</artifactId> <artifactId>adventure-platform-common</artifactId>
<version>4.0.0-SNAPSHOT</version> <version>4.0.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>net.kyori</groupId>
<artifactId>adventure-nbt</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven.scm</groupId> <groupId>org.apache.maven.scm</groupId>
@ -329,9 +368,21 @@
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-dep</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>4.11</version> <version>5.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.6.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -364,7 +415,4 @@
<version>19.0.0</version> <version>19.0.0</version>
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project> </project>

View File

@ -1,30 +1,50 @@
//package com.gmail.nossr50.api; package com.gmail.nossr50.api;
//
//import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
//import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
// import org.bukkit.OfflinePlayer;
//import java.util.UUID; import org.jetbrains.annotations.NotNull;
//
//public class DatabaseAPI { import java.util.UUID;
//
// /** public class DatabaseAPI {
// * Checks if a player exists in the mcMMO Database
// * @param uuid player UUID /**
// * @return true if the player exists in the DB, false if they do not * Checks if a player exists in the mcMMO Database
// */ * @param offlinePlayer target player
// public boolean doesPlayerExistInDB(String uuid) { * @return true if the player exists in the DB, false if they do not
// return doesPlayerExistInDB(UUID.fromString(uuid)); */
// } public boolean doesPlayerExistInDB(@NotNull OfflinePlayer offlinePlayer) {
// PlayerProfile playerProfile = mcMMO.getDatabaseManager().loadPlayerProfile(offlinePlayer);
// /**
// * Checks if a player exists in the mcMMO Database return playerProfile.isLoaded();
// * @param uuid player UUID }
// * @return true if the player exists in the DB, false if they do not
// */ /**
// public boolean doesPlayerExistInDB(UUID uuid) { * Checks if a player exists in the mcMMO Database
// PlayerProfile playerProfile = mcMMO.getDatabaseManager().loadPlayerProfile(uuid, null); * @param uuid target player
// * @return true if the player exists in the DB, false if they do not
// return playerProfile.isLoaded(); */
// } public boolean doesPlayerExistInDB(@NotNull UUID uuid) {
// PlayerProfile playerProfile = null;
//} try {
playerProfile = mcMMO.getDatabaseManager().loadPlayerProfile(uuid);
} catch (Exception e) {
return false;
}
return playerProfile.isLoaded();
}
/**
* Checks if a player exists in the mcMMO Database
* @param playerName target player
* @return true if the player exists in the DB, false if they do not
*/
public boolean doesPlayerExistInDB(@NotNull String playerName) {
PlayerProfile playerProfile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName);
return playerProfile.isLoaded();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,258 +1,257 @@
//package com.gmail.nossr50.api; package com.gmail.nossr50.api;
//
//import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.interactions.NotificationType;
//import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.party.Party;
//import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.PartyLeader;
//import com.gmail.nossr50.datatypes.party.PartyLeader; import com.gmail.nossr50.mcMMO;
//import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.party.PartyManager;
//import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.util.player.NotificationManager;
//import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager;
//import com.gmail.nossr50.util.player.UserManager; import org.bukkit.OfflinePlayer;
//import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player;
//import org.bukkit.entity.Player;
// import java.util.*;
//import java.util.*;
// public final class PartyAPI {
//public final class PartyAPI { private PartyAPI() {}
// private PartyAPI() {}
// /**
// /** * Get the name of the party a player is in.
// * Get the name of the party a player is in. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to check the party name of
// * @param player The player to check the party name of * @return the name of the player's party, or null if not in a party
// * @return the name of the player's party, or null if not in a party */
// */ public static String getPartyName(Player player) {
// public static String getPartyName(Player player) { if (!inParty(player)) {
// if (!inParty(player)) { return null;
// return null; }
// }
// return UserManager.getPlayer(player).getParty().getName();
// return UserManager.getPlayer(player).getParty().getName(); }
// }
// /**
// /** * Checks if a player is in a party.
// * Checks if a player is in a party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to check
// * @param player The player to check * @return true if the player is in a party, false otherwise
// * @return true if the player is in a party, false otherwise */
// */ public static boolean inParty(Player player) {
// public static boolean inParty(Player player) { if(UserManager.getPlayer(player) == null)
// if(UserManager.getPlayer(player) == null) return false;
// return false;
// return UserManager.getPlayer(player).inParty();
// return UserManager.getPlayer(player).inParty(); }
// }
// /**
// /** * Check if two players are in the same party.
// * Check if two players are in the same party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param playera The first player to check
// * @param playera The first player to check * @param playerb The second player to check
// * @param playerb The second player to check * @return true if the two players are in the same party, false otherwise
// * @return true if the two players are in the same party, false otherwise */
// */ public static boolean inSameParty(Player playera, Player playerb) {
// public static boolean inSameParty(Player playera, Player playerb) { return PartyManager.inSameParty(playera, playerb);
// return PartyManager.inSameParty(playera, playerb); }
// }
// /**
// /** * Get a list of all current parties.
// * Get a list of all current parties. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @return the list of parties.
// * @return the list of parties. */
// */ public static List<Party> getParties() {
// public static List<Party> getParties() { return PartyManager.getParties();
// return PartyManager.getParties(); }
// }
// /**
// /** * Add a player to a party.
// * Add a player to a party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to add to the party
// * @param player The player to add to the party * @param partyName The party to add the player to
// * @param partyName The party to add the player to * @deprecated parties can have limits, use the other method
// * @deprecated parties can have limits, use the other method */
// */ @Deprecated
// @Deprecated public static void addToParty(Player player, String partyName) {
// public static void addToParty(Player player, String partyName) { //Check if player profile is loaded
// //Check if player profile is loaded if(UserManager.getPlayer(player) == null)
// if(UserManager.getPlayer(player) == null) return;
// return;
// Party party = PartyManager.getParty(partyName);
// Party party = PartyManager.getParty(partyName);
// if (party == null) {
// if (party == null) { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName);
// party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); } else {
// } else { if(PartyManager.isPartyFull(player, party))
// if(PartyManager.isPartyFull(player, party)) {
// { NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString());
// NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString()); return;
// return; }
// } }
// }
// PartyManager.addToParty(UserManager.getPlayer(player), party);
// PartyManager.addToParty(UserManager.getPlayer(player), party); }
// }
// /**
// /** * The max party size of the server
// * The max party size of the server * 0 or less for no size limit
// * 0 or less for no size limit * @return the max party size on this server
// * @return the max party size on this server */
// */ public static int getMaxPartySize()
// public static int getMaxPartySize() {
// { return mcMMO.p.getGeneralConfig().getPartyMaxSize();
// return Config.getInstance().getPartyMaxSize(); }
// }
// /**
// /** * Add a player to a party.
// * Add a player to a party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to add to the party
// * @param player The player to add to the party * @param partyName The party to add the player to
// * @param partyName The party to add the player to * @param bypassLimit if true bypasses party size limits
// * @param bypassLimit if true bypasses party size limits */
// */ //TODO: bypasslimit not used?
// //TODO: bypasslimit not used? public static void addToParty(Player player, String partyName, boolean bypassLimit) {
// public static void addToParty(Player player, String partyName, boolean bypassLimit) { //Check if player profile is loaded
// //Check if player profile is loaded if(UserManager.getPlayer(player) == null)
// if(UserManager.getPlayer(player) == null) return;
// return;
// Party party = PartyManager.getParty(partyName);
// Party party = PartyManager.getParty(partyName);
// if (party == null) {
// if (party == null) { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName);
// party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); }
// }
// PartyManager.addToParty(UserManager.getPlayer(player), party);
// PartyManager.addToParty(UserManager.getPlayer(player), party); }
// }
// /**
// /** * Remove a player from a party.
// * Remove a player from a party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to remove
// * @param player The player to remove */
// */ public static void removeFromParty(Player player) {
// public static void removeFromParty(Player player) { //Check if player profile is loaded
// //Check if player profile is loaded if(UserManager.getPlayer(player) == null)
// if(UserManager.getPlayer(player) == null) return;
// return;
// PartyManager.removeFromParty(UserManager.getPlayer(player));
// PartyManager.removeFromParty(UserManager.getPlayer(player)); }
// }
// /**
// /** * Get the leader of a party.
// * Get the leader of a party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param partyName The party name
// * @param partyName The party name * @return the leader of the party
// * @return the leader of the party */
// */ public static String getPartyLeader(String partyName) {
// public static String getPartyLeader(String partyName) { return PartyManager.getPartyLeaderName(partyName);
// return PartyManager.getPartyLeaderName(partyName); }
// }
// /**
// /** * Set the leader of a party.
// * Set the leader of a party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param partyName The name of the party to set the leader of
// * @param partyName The name of the party to set the leader of * @param playerName The playerName to set as leader
// * @param playerName The playerName to set as leader */
// */ @Deprecated
// @Deprecated public static void setPartyLeader(String partyName, String playerName) {
// public static void setPartyLeader(String partyName, String playerName) { PartyManager.setPartyLeader(mcMMO.p.getServer().getOfflinePlayer(playerName).getUniqueId(), PartyManager.getParty(partyName));
// PartyManager.setPartyLeader(mcMMO.p.getServer().getOfflinePlayer(playerName).getUniqueId(), PartyManager.getParty(partyName)); }
// }
// /**
// /** * Get a list of all players in this player's party.
// * Get a list of all players in this player's party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to check
// * @param player The player to check * @return all the players in the player's party
// * @return all the players in the player's party */
// */ @Deprecated
// @Deprecated public static List<OfflinePlayer> getOnlineAndOfflineMembers(Player player) {
// public static List<OfflinePlayer> getOnlineAndOfflineMembers(Player player) { List<OfflinePlayer> members = new ArrayList<>();
// List<OfflinePlayer> members = new ArrayList<>();
// for (UUID memberUniqueId : PartyManager.getAllMembers(player).keySet()) {
// for (UUID memberUniqueId : PartyManager.getAllMembers(player).keySet()) { OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberUniqueId);
// OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberUniqueId); members.add(member);
// members.add(member); }
// } return members;
// return members; }
// }
// /**
// /** * Get a list of all player names in this player's party.
// * Get a list of all player names in this player's party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to check
// * @param player The player to check * @return all the player names in the player's party
// * @return all the player names in the player's party */
// */ @Deprecated
// @Deprecated public static LinkedHashSet<String> getMembers(Player player) {
// public static LinkedHashSet<String> getMembers(Player player) { return (LinkedHashSet<String>) PartyManager.getAllMembers(player).values();
// return (LinkedHashSet<String>) PartyManager.getAllMembers(player).values(); }
// }
// /**
// /** * Get a list of all player names and uuids in this player's party.
// * Get a list of all player names and uuids in this player's party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to check
// * @param player The player to check * @return all the player names and uuids in the player's party
// * @return all the player names and uuids in the player's party */
// */ public static LinkedHashMap<UUID, String> getMembersMap(Player player) {
// public static LinkedHashMap<UUID, String> getMembersMap(Player player) { return PartyManager.getAllMembers(player);
// return PartyManager.getAllMembers(player); }
// }
// /**
// /** * Get a list of all online players in this party.
// * Get a list of all online players in this party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param partyName The party to check
// * @param partyName The party to check * @return all online players in this party
// * @return all online players in this party */
// */ public static List<Player> getOnlineMembers(String partyName) {
// public static List<Player> getOnlineMembers(String partyName) { return PartyManager.getOnlineMembers(partyName);
// return PartyManager.getOnlineMembers(partyName); }
// }
// /**
// /** * Get a list of all online players in this player's party.
// * Get a list of all online players in this player's party. * </br>
// * </br> * This function is designed for API usage.
// * This function is designed for API usage. *
// * * @param player The player to check
// * @param player The player to check * @return all online players in the player's party
// * @return all online players in the player's party */
// */ public static List<Player> getOnlineMembers(Player player) {
// public static List<Player> getOnlineMembers(Player player) { return PartyManager.getOnlineMembers(player);
// return PartyManager.getOnlineMembers(player); }
// }
// public static boolean hasAlly(String partyName) {
// public static boolean hasAlly(String partyName) { return getAllyName(partyName) != null;
// return getAllyName(partyName) != null; }
// }
// public static String getAllyName(String partyName) {
// public static String getAllyName(String partyName) { Party ally = PartyManager.getParty(partyName).getAlly();
// Party ally = PartyManager.getParty(partyName).getAlly(); if (ally != null) {
// if (ally != null) { return ally.getName();
// return ally.getName(); }
// }
// return null;
// return null; }
// } }
//}

View File

@ -1,93 +1,95 @@
//package com.gmail.nossr50.api; package com.gmail.nossr50.api;
//
//import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
// import com.gmail.nossr50.mcMMO;
//import java.util.ArrayList; import com.gmail.nossr50.util.skills.SkillTools;
//import java.util.Arrays;
//import java.util.List; import java.util.ArrayList;
// import java.util.Arrays;
//public final class SkillAPI { import java.util.List;
// private SkillAPI() {}
// public final class SkillAPI {
// /** private SkillAPI() {}
// * Returns a list of strings with mcMMO's skills
// * This includes parent and child skills /**
// * </br> * Returns a list of strings with mcMMO's skills
// * This function is designed for API usage. * This includes parent and child skills
// * * </br>
// * @return a list of strings with valid skill names * This function is designed for API usage.
// */ *
// public static List<String> getSkills() { * @return a list of strings with valid skill names
// return getListFromEnum(Arrays.asList(PrimarySkillType.values())); */
// } public static List<String> getSkills() {
// return getListFromEnum(Arrays.asList(PrimarySkillType.values()));
// /** }
// * Returns a list of strings with mcMMO's skills
// * This only includes parent skills /**
// * </br> * Returns a list of strings with mcMMO's skills
// * This function is designed for API usage. * This only includes parent skills
// * * </br>
// * @return a list of strings with valid skill names * This function is designed for API usage.
// */ *
// public static List<String> getNonChildSkills() { * @return a list of strings with valid skill names
// return getListFromEnum(PrimarySkillType.NON_CHILD_SKILLS); */
// } public static List<String> getNonChildSkills() {
// return getListFromEnum(SkillTools.NON_CHILD_SKILLS);
// /** }
// * Returns a list of strings with mcMMO's skills
// * This only includes child skills /**
// * </br> * Returns a list of strings with mcMMO's skills
// * This function is designed for API usage. * This only includes child skills
// * * </br>
// * @return a list of strings with valid skill names * This function is designed for API usage.
// */ *
// public static List<String> getChildSkills() { * @return a list of strings with valid skill names
// return getListFromEnum(PrimarySkillType.CHILD_SKILLS); */
// } public static List<String> getChildSkills() {
// return getListFromEnum(mcMMO.p.getSkillTools().CHILD_SKILLS);
// /** }
// * Returns a list of strings with mcMMO's skills
// * This only includes combat skills /**
// * </br> * Returns a list of strings with mcMMO's skills
// * This function is designed for API usage. * This only includes combat skills
// * * </br>
// * @return a list of strings with valid skill names * This function is designed for API usage.
// */ *
// public static List<String> getCombatSkills() { * @return a list of strings with valid skill names
// return getListFromEnum(PrimarySkillType.COMBAT_SKILLS); */
// } public static List<String> getCombatSkills() {
// return getListFromEnum(mcMMO.p.getSkillTools().COMBAT_SKILLS);
// /** }
// * Returns a list of strings with mcMMO's skills
// * This only includes gathering skills /**
// * </br> * Returns a list of strings with mcMMO's skills
// * This function is designed for API usage. * This only includes gathering skills
// * * </br>
// * @return a list of strings with valid skill names * This function is designed for API usage.
// */ *
// public static List<String> getGatheringSkills() { * @return a list of strings with valid skill names
// return getListFromEnum(PrimarySkillType.GATHERING_SKILLS); */
// } public static List<String> getGatheringSkills() {
// return getListFromEnum(mcMMO.p.getSkillTools().GATHERING_SKILLS);
// /** }
// * Returns a list of strings with mcMMO's skills
// * This only includes misc skills /**
// * </br> * Returns a list of strings with mcMMO's skills
// * This function is designed for API usage. * This only includes misc skills
// * * </br>
// * @return a list of strings with valid skill names * This function is designed for API usage.
// */ *
// public static List<String> getMiscSkills() { * @return a list of strings with valid skill names
// return getListFromEnum(PrimarySkillType.MISC_SKILLS); */
// } public static List<String> getMiscSkills() {
// return getListFromEnum(mcMMO.p.getSkillTools().MISC_SKILLS);
// private static List<String> getListFromEnum(List<PrimarySkillType> skillsTypes) { }
// List<String> skills = new ArrayList<>();
// private static List<String> getListFromEnum(List<PrimarySkillType> skillsTypes) {
// for (PrimarySkillType primarySkillType : skillsTypes) { List<String> skills = new ArrayList<>();
// skills.add(primarySkillType.name());
// } for (PrimarySkillType primarySkillType : skillsTypes) {
// skills.add(primarySkillType.name());
// return skills; }
// }
//} return skills;
}
}

View File

@ -1,46 +0,0 @@
package com.gmail.nossr50.commands;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.FlatFileDatabaseManager;
import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class MHDCommand implements TabExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (mcMMO.getDatabaseManager() instanceof SQLDatabaseManager) {
SQLDatabaseManager m = (SQLDatabaseManager) mcMMO.getDatabaseManager();
m.resetMobHealthSettings();
for (McMMOPlayer player : UserManager.getPlayers()) {
player.getProfile().setMobHealthbarType(Config.getInstance().getMobHealthbarDefault());
}
sender.sendMessage("Mob health reset");
return true;
}
if (mcMMO.getDatabaseManager() instanceof FlatFileDatabaseManager) {
FlatFileDatabaseManager m = (FlatFileDatabaseManager) mcMMO.getDatabaseManager();
m.resetMobHealthSettings();
for (McMMOPlayer player : UserManager.getPlayers()) {
player.getProfile().setMobHealthbarType(Config.getInstance().getMobHealthbarDefault());
}
sender.sendMessage("Mob health reset");
return true;
}
return false;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
return ImmutableList.of();
}
}

View File

@ -1,6 +1,7 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.commands.party.PartySubcommandType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
@ -25,7 +26,7 @@ public class McmmoCommand implements CommandExecutor {
sender.sendMessage(mcSplit); sender.sendMessage(mcSplit);
sender.sendMessage(LocaleLoader.getString("mcMMO.Description.FormerDevs")); sender.sendMessage(LocaleLoader.getString("mcMMO.Description.FormerDevs"));
if (Config.getInstance().getDonateMessageEnabled()) { if (mcMMO.p.getGeneralConfig().getDonateMessageEnabled()) {
sender.sendMessage(LocaleLoader.getString("MOTD.Donate")); sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "nossr50@gmail.com" + ChatColor.GOLD + " Paypal"); sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "nossr50@gmail.com" + ChatColor.GOLD + " Paypal");
} }

View File

@ -1,7 +1,7 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -32,7 +32,7 @@ public class McscoreboardCommand implements TabExecutor {
} }
if (args[0].equalsIgnoreCase("keep")) { if (args[0].equalsIgnoreCase("keep")) {
if (!Config.getInstance().getAllowKeepBoard() || !Config.getInstance().getScoreboardsEnabled()) { if (!mcMMO.p.getGeneralConfig().getAllowKeepBoard() || !mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
sender.sendMessage(LocaleLoader.getString("Commands.Disabled")); sender.sendMessage(LocaleLoader.getString("Commands.Disabled"));
return true; return true;
} }

View File

@ -1,7 +1,5 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.notifications.SensitiveCommandType; import com.gmail.nossr50.datatypes.notifications.SensitiveCommandType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@ -39,7 +37,7 @@ public class XprateCommand implements TabExecutor {
if (mcMMO.p.isXPEventEnabled()) { if (mcMMO.p.isXPEventEnabled()) {
if(AdvancedConfig.getInstance().useTitlesForXPEvent()) if(mcMMO.p.getAdvancedConfig().useTitlesForXPEvent())
{ {
NotificationManager.broadcastTitle(mcMMO.p.getServer(), NotificationManager.broadcastTitle(mcMMO.p.getServer(),
LocaleLoader.getString("Commands.Event.Stop"), LocaleLoader.getString("Commands.Event.Stop"),
@ -47,7 +45,7 @@ public class XprateCommand implements TabExecutor {
10, 10*20, 20); 10, 10*20, 20);
} }
if(Config.getInstance().broadcastEventMessages()) if(mcMMO.p.getGeneralConfig().broadcastEventMessages())
{ {
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop"));
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop.Subtitle")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop.Subtitle"));
@ -92,7 +90,7 @@ public class XprateCommand implements TabExecutor {
ExperienceConfig.getInstance().setExperienceGainsGlobalMultiplier(newXpRate); ExperienceConfig.getInstance().setExperienceGainsGlobalMultiplier(newXpRate);
if(AdvancedConfig.getInstance().useTitlesForXPEvent()) if(mcMMO.p.getAdvancedConfig().useTitlesForXPEvent())
{ {
NotificationManager.broadcastTitle(mcMMO.p.getServer(), NotificationManager.broadcastTitle(mcMMO.p.getServer(),
LocaleLoader.getString("Commands.Event.Start"), LocaleLoader.getString("Commands.Event.Start"),
@ -100,7 +98,7 @@ public class XprateCommand implements TabExecutor {
10, 10*20, 20); 10, 10*20, 20);
} }
if(Config.getInstance().broadcastEventMessages()) if(mcMMO.p.getGeneralConfig().broadcastEventMessages())
{ {
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start"));
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate)); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate));

View File

@ -27,7 +27,11 @@ public class ConvertDatabaseCommand implements CommandExecutor {
return true; return true;
} }
DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType); DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType, mcMMO.getUsersFilePath(), mcMMO.p.getLogger(), mcMMO.p.getPurgeTime(), mcMMO.p.getAdvancedConfig().getStartingLevel());
if(oldDatabase == null) {
sender.sendMessage("Unable to load the old database! Check your log for errors.");
return true;
}
if (previousType == DatabaseType.CUSTOM) { if (previousType == DatabaseType.CUSTOM) {
Class<?> clazz; Class<?> clazz;
@ -54,7 +58,7 @@ public class ConvertDatabaseCommand implements CommandExecutor {
UserManager.clearAll(); UserManager.clearAll();
for (Player player : mcMMO.p.getServer().getOnlinePlayers()) { for (Player player : mcMMO.p.getServer().getOnlinePlayers()) {
PlayerProfile profile = oldDatabase.loadPlayerProfile(player.getUniqueId(), null); PlayerProfile profile = oldDatabase.loadPlayerProfile(player);
if (profile.isLoaded()) { if (profile.isLoaded()) {
mcMMO.getDatabaseManager().saveUser(profile.getPlayerData()); mcMMO.getDatabaseManager().saveUser(profile.getPlayerData());

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.commands.database; package com.gmail.nossr50.commands.database;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -17,7 +16,7 @@ public class McpurgeCommand implements TabExecutor {
if (args.length == 0) { if (args.length == 0) {
mcMMO.getDatabaseManager().purgePowerlessUsers(); mcMMO.getDatabaseManager().purgePowerlessUsers();
if (Config.getInstance().getOldUsersCutoff() != -1) { if (mcMMO.p.getGeneralConfig().getOldUsersCutoff() != -1) {
mcMMO.getDatabaseManager().purgeOldUsers(); mcMMO.getDatabaseManager().purgeOldUsers();
} }

View File

@ -1,8 +1,8 @@
package com.gmail.nossr50.commands.database; package com.gmail.nossr50.commands.database;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.DatabaseManagerFactory; import com.gmail.nossr50.database.DatabaseManagerFactory;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -22,7 +22,7 @@ public class MmoshowdbCommand implements TabExecutor {
return true; return true;
} }
sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", (Config.getInstance().getUseMySQL() ? "sql" : "flatfile"))); sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", (mcMMO.p.getGeneralConfig().getUseMySQL() ? "sql" : "flatfile")));
return true; return true;
} }
return false; return false;

View File

@ -4,6 +4,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@ -55,6 +56,6 @@ public class AddlevelsCommand extends ExperienceCommand {
if(isSilent) if(isSilent)
return; return;
player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, skill.getName())); player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill)));
} }
} }

View File

@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.experience.XPGainSource;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -49,6 +50,6 @@ public class AddxpCommand extends ExperienceCommand {
if(isSilent) if(isSilent)
return; return;
player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, skill.getName())); player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill)));
} }
} }

View File

@ -7,8 +7,8 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillTools;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
@ -18,7 +18,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
public abstract class ExperienceCommand implements TabExecutor { public abstract class ExperienceCommand implements TabExecutor {
@Override @Override
@ -44,13 +43,13 @@ public abstract class ExperienceCommand implements TabExecutor {
return true; return true;
} }
skill = PrimarySkillType.getSkill(args[0]); skill = mcMMO.p.getSkillTools().matchSkill(args[0]);
if (args[1].equalsIgnoreCase("all")) { if (args[1].equalsIgnoreCase("all")) {
skill = null; skill = null;
} }
if (skill != null && skill.isChildSkill()) if (skill != null && SkillTools.isChildSkill(skill))
{ {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill"));
return true; return true;
@ -77,13 +76,13 @@ public abstract class ExperienceCommand implements TabExecutor {
return true; return true;
} }
skill = PrimarySkillType.getSkill(args[1]); skill = mcMMO.p.getSkillTools().matchSkill(args[1]);
if (args[1].equalsIgnoreCase("all")) { if (args[1].equalsIgnoreCase("all")) {
skill = null; skill = null;
} }
if (skill != null && skill.isChildSkill()) if (skill != null && SkillTools.isChildSkill(skill))
{ {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill"));
return true; return true;
@ -96,12 +95,9 @@ public abstract class ExperienceCommand implements TabExecutor {
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) { if (mcMMOPlayer == null) {
UUID uuid = null;
OfflinePlayer offlinePlayer = mcMMO.p.getServer().getOfflinePlayer(playerName);
PlayerProfile profile; PlayerProfile profile;
uuid = offlinePlayer.getUniqueId(); profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName);
profile = mcMMO.getDatabaseManager().loadPlayerProfile(uuid, null);
//Check loading by UUID //Check loading by UUID
if (CommandUtils.unloadedProfile(sender, profile)) { if (CommandUtils.unloadedProfile(sender, profile)) {
@ -144,7 +140,7 @@ public abstract class ExperienceCommand implements TabExecutor {
List<String> playerNames = CommandUtils.getOnlinePlayerNames(sender); List<String> playerNames = CommandUtils.getOnlinePlayerNames(sender);
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size()));
case 2: case 2:
return StringUtil.copyPartialMatches(args[1], PrimarySkillType.SKILL_NAMES, new ArrayList<>(PrimarySkillType.SKILL_NAMES.size())); return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size()));
default: default:
return ImmutableList.of(); return ImmutableList.of();
} }
@ -165,13 +161,13 @@ public abstract class ExperienceCommand implements TabExecutor {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName));
} }
else { else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", skill.getName(), playerName)); sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName));
} }
} }
protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill, int value, boolean isSilent) { protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill, int value, boolean isSilent) {
if (skill == null) { if (skill == null) {
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
handleCommand(player, profile, primarySkillType, value); handleCommand(player, profile, primarySkillType, value);
} }

View File

@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@ -62,6 +63,6 @@ public class MmoeditCommand extends ExperienceCommand {
if(isSilent) if(isSilent)
return; return;
player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", skill.getName(), value)); player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), value));
} }
} }

View File

@ -9,6 +9,7 @@ import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillTools;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -20,7 +21,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
/** /**
* This class mirrors the structure of ExperienceCommand, except the * This class mirrors the structure of ExperienceCommand, except the
@ -49,7 +49,7 @@ public class SkillResetCommand implements TabExecutor {
skill = null; skill = null;
} }
else { else {
skill = PrimarySkillType.getSkill(args[0]); skill = mcMMO.p.getSkillTools().matchSkill(args[0]);
} }
editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill); editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill);
@ -69,7 +69,7 @@ public class SkillResetCommand implements TabExecutor {
skill = null; skill = null;
} }
else { else {
skill = PrimarySkillType.getSkill(args[1]); skill = mcMMO.p.getSkillTools().matchSkill(args[1]);
} }
String playerName = CommandUtils.getMatchedPlayerName(args[0]); String playerName = CommandUtils.getMatchedPlayerName(args[0]);
@ -77,11 +77,8 @@ public class SkillResetCommand implements TabExecutor {
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) { if (mcMMOPlayer == null) {
UUID uuid = null; OfflinePlayer offlinePlayer = mcMMO.p.getServer().getOfflinePlayer(playerName);
OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(playerName); PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(offlinePlayer);
uuid = player.getUniqueId();
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(uuid, playerName);
//Check loading by UUID //Check loading by UUID
if (CommandUtils.unloadedProfile(sender, profile)) { if (CommandUtils.unloadedProfile(sender, profile)) {
@ -115,7 +112,7 @@ public class SkillResetCommand implements TabExecutor {
List<String> playerNames = CommandUtils.getOnlinePlayerNames(sender); List<String> playerNames = CommandUtils.getOnlinePlayerNames(sender);
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size()));
case 2: case 2:
return StringUtil.copyPartialMatches(args[1], PrimarySkillType.SKILL_NAMES, new ArrayList<>(PrimarySkillType.SKILL_NAMES.size())); return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size()));
default: default:
return ImmutableList.of(); return ImmutableList.of();
} }
@ -148,7 +145,7 @@ public class SkillResetCommand implements TabExecutor {
} }
protected void handlePlayerMessageSkill(Player player, PrimarySkillType skill) { protected void handlePlayerMessageSkill(Player player, PrimarySkillType skill) {
player.sendMessage(LocaleLoader.getString("Commands.Reset.Single", skill.getName())); player.sendMessage(LocaleLoader.getString("Commands.Reset.Single", mcMMO.p.getSkillTools().getLocalizedSkillName(skill)));
} }
private boolean validateArguments(CommandSender sender, String skillName) { private boolean validateArguments(CommandSender sender, String skillName) {
@ -160,13 +157,13 @@ public class SkillResetCommand implements TabExecutor {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName));
} }
else { else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", skill.getName(), playerName)); sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName));
} }
} }
protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill) { protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill) {
if (skill == null) { if (skill == null) {
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
handleCommand(player, profile, primarySkillType); handleCommand(player, profile, primarySkillType);
} }

View File

@ -51,7 +51,7 @@
// //
// private void toggle(boolean enable, PrimarySkillType skill) { // private void toggle(boolean enable, PrimarySkillType skill) {
// if (skill == null) { // if (skill == null) {
// for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { // for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
// primarySkillType.setHardcoreStatLossEnabled(enable); // primarySkillType.setHardcoreStatLossEnabled(enable);
// } // }
// } // }
@ -59,6 +59,6 @@
// skill.setHardcoreStatLossEnabled(enable); // skill.setHardcoreStatLossEnabled(enable);
// } // }
// //
// mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Hardcore.Mode." + (enable ? "Enabled" : "Disabled"), LocaleLoader.getString("Hardcore.DeathStatLoss.Name"), (skill == null ? "all skills" : skill.getName()))); // mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Hardcore.Mode." + (enable ? "Enabled" : "Disabled"), LocaleLoader.getString("Hardcore.DeathStatLoss.Name"), (skill == null ? "all skills" : mcMMO.p.getSkillTools().getLocalizedSkillName(skill))));
// } // }
//} //}

View File

@ -1,129 +1,129 @@
package com.gmail.nossr50.commands.hardcore; //package com.gmail.nossr50.commands.hardcore;
//
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; //import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.util.Permissions; //import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils; //import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.text.StringUtils; //import com.gmail.nossr50.util.text.StringUtils;
import com.google.common.collect.ImmutableList; //import com.google.common.collect.ImmutableList;
import org.bukkit.command.Command; //import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; //import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; //import org.bukkit.command.TabExecutor;
import org.bukkit.util.StringUtil; //import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull; //import org.jetbrains.annotations.NotNull;
//
import java.text.DecimalFormat; //import java.text.DecimalFormat;
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
//
public abstract class HardcoreModeCommand implements TabExecutor { //public abstract class HardcoreModeCommand implements TabExecutor {
protected final DecimalFormat percent = new DecimalFormat("##0.00%"); // protected final DecimalFormat percent = new DecimalFormat("##0.00%");
//
@Override // @Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { // public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
switch (args.length) { // switch (args.length) {
case 0: // case 0:
if (!checkTogglePermissions(sender)) { // if (!checkTogglePermissions(sender)) {
sender.sendMessage(command.getPermissionMessage()); // sender.sendMessage(command.getPermissionMessage());
return true; // return true;
} // }
//
if (checkEnabled(null)) { // if (checkEnabled(null)) {
disable(null); // disable(null);
} // }
else { // else {
enable(null); // enable(null);
} // }
//
return true; // return true;
//
case 1: // case 1:
if (CommandUtils.shouldEnableToggle(args[0])) { // if (CommandUtils.shouldEnableToggle(args[0])) {
if (!Permissions.hardcoreToggle(sender)) { // if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage()); // sender.sendMessage(command.getPermissionMessage());
return true; // return true;
} // }
//
enable(null); // enable(null);
return true; // return true;
} // }
//
if (CommandUtils.shouldDisableToggle(args[0])) { // if (CommandUtils.shouldDisableToggle(args[0])) {
if (!Permissions.hardcoreToggle(sender)) { // if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage()); // sender.sendMessage(command.getPermissionMessage());
return true; // return true;
} // }
//
disable(null); // disable(null);
return true; // return true;
} // }
//
if (CommandUtils.isInvalidDouble(sender, args[0])) { // if (CommandUtils.isInvalidDouble(sender, args[0])) {
return true; // return true;
} // }
//
if (!Permissions.hardcoreModify(sender)) { // if (!Permissions.hardcoreModify(sender)) {
sender.sendMessage(command.getPermissionMessage()); // sender.sendMessage(command.getPermissionMessage());
return true; // return true;
} // }
//
modify(sender, Double.parseDouble(args[0])); // modify(sender, Double.parseDouble(args[0]));
return true; // return true;
//
//
case 2: // case 2:
if (CommandUtils.isInvalidSkill(sender, args[0])) { // if (CommandUtils.isInvalidSkill(sender, args[0])) {
return true; // return true;
} // }
//
PrimarySkillType skill = PrimarySkillType.getSkill(args[0]); // PrimarySkillType skill = PrimarySkillType.getSkill(args[0]);
//
if (!CommandUtils.isChildSkill(sender, skill)) { // if (!CommandUtils.isChildSkill(sender, skill)) {
return true; // return true;
} // }
//
if (CommandUtils.shouldEnableToggle(args[1])) { // if (CommandUtils.shouldEnableToggle(args[1])) {
if (!Permissions.hardcoreToggle(sender)) { // if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage()); // sender.sendMessage(command.getPermissionMessage());
return true; // return true;
} // }
//
enable(skill); // enable(skill);
return true; // return true;
} // }
//
if (CommandUtils.shouldDisableToggle(args[1])) { // if (CommandUtils.shouldDisableToggle(args[1])) {
if (!Permissions.hardcoreToggle(sender)) { // if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage()); // sender.sendMessage(command.getPermissionMessage());
return true; // return true;
} // }
//
enable(skill); // enable(skill);
return true; // return true;
} // }
//
return true; // return true;
//
default: // default:
return false; // return false;
} // }
} // }
//
@Override // @Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { // public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
if (args.length == 1) { // if (args.length == 1) {
if (StringUtils.isDouble(args[0])) { // if (StringUtils.isDouble(args[0])) {
return ImmutableList.of(); // return ImmutableList.of();
} // }
//
return StringUtil.copyPartialMatches(args[0], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); // return StringUtil.copyPartialMatches(args[0], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
} // }
return ImmutableList.of(); // return ImmutableList.of();
} // }
//
protected abstract boolean checkTogglePermissions(CommandSender sender); // protected abstract boolean checkTogglePermissions(CommandSender sender);
protected abstract boolean checkModifyPermissions(CommandSender sender); // protected abstract boolean checkModifyPermissions(CommandSender sender);
protected abstract boolean checkEnabled(PrimarySkillType skill); // protected abstract boolean checkEnabled(PrimarySkillType skill);
protected abstract void enable(PrimarySkillType skill); // protected abstract void enable(PrimarySkillType skill);
protected abstract void disable(PrimarySkillType skill); // protected abstract void disable(PrimarySkillType skill);
protected abstract void modify(CommandSender sender, double newPercentage); // protected abstract void modify(CommandSender sender, double newPercentage);
} //}

View File

@ -51,7 +51,7 @@
// //
// private void toggle(boolean enable, PrimarySkillType skill) { // private void toggle(boolean enable, PrimarySkillType skill) {
// if (skill == null) { // if (skill == null) {
// for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { // for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
// primarySkillType.setHardcoreVampirismEnabled(enable); // primarySkillType.setHardcoreVampirismEnabled(enable);
// } // }
// } // }

View File

@ -1,11 +1,11 @@
package com.gmail.nossr50.commands.party; package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyFeature; import com.gmail.nossr50.datatypes.party.PartyFeature;
import com.gmail.nossr50.datatypes.party.ShareMode; import com.gmail.nossr50.datatypes.party.ShareMode;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -85,7 +85,7 @@ public class PartyInfoCommand implements CommandExecutor {
} }
private boolean isUnlockedFeature(Party party, PartyFeature partyFeature) { private boolean isUnlockedFeature(Party party, PartyFeature partyFeature) {
return party.getLevel() >= Config.getInstance().getPartyFeatureUnlockLevel(partyFeature); return party.getLevel() >= mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(partyFeature);
} }
private void displayShareModeInfo(Player player, Party party) { private void displayShareModeInfo(Player player, Party party) {

View File

@ -1,9 +1,9 @@
package com.gmail.nossr50.commands.party; package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@ -53,7 +53,7 @@ public class PartyInviteCommand implements CommandExecutor {
Party playerParty = mcMMOPlayer.getParty(); Party playerParty = mcMMOPlayer.getParty();
if (PartyManager.isPartyFull(target, playerParty)) { if (PartyManager.isPartyFull(target, playerParty)) {
player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull.Invite", target.getName(), playerParty.toString(), Config.getInstance().getPartyMaxSize())); player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull.Invite", target.getName(), playerParty.toString(), mcMMO.p.getGeneralConfig().getPartyMaxSize()));
return true; return true;
} }

View File

@ -1,10 +1,10 @@
package com.gmail.nossr50.commands.party; package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyFeature; import com.gmail.nossr50.datatypes.party.PartyFeature;
import com.gmail.nossr50.datatypes.party.ShareMode; import com.gmail.nossr50.datatypes.party.ShareMode;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.StringUtils;
@ -25,7 +25,7 @@ public class PartyXpShareCommand implements CommandExecutor {
Party party = UserManager.getPlayer((Player) sender).getParty(); Party party = UserManager.getPlayer((Player) sender).getParty();
if (party.getLevel() < Config.getInstance().getPartyFeatureUnlockLevel(PartyFeature.XP_SHARE)) { if (party.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.XP_SHARE)) {
sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.5")); sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.5"));
return true; return true;
} }

View File

@ -1,8 +1,8 @@
package com.gmail.nossr50.commands.party.teleport; package com.gmail.nossr50.commands.party.teleport;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.PartyTeleportRecord; import com.gmail.nossr50.datatypes.party.PartyTeleportRecord;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
@ -35,7 +35,7 @@ public class PtpAcceptCommand implements CommandExecutor {
return true; return true;
} }
if (SkillUtils.cooldownExpired(ptpRecord.getTimeout(), Config.getInstance().getPTPCommandTimeout())) { if (SkillUtils.cooldownExpired(ptpRecord.getTimeout(), mcMMO.p.getGeneralConfig().getPTPCommandTimeout())) {
ptpRecord.removeRequest(); ptpRecord.removeRequest();
player.sendMessage(LocaleLoader.getString("Commands.ptp.RequestExpired")); player.sendMessage(LocaleLoader.getString("Commands.ptp.RequestExpired"));
return true; return true;
@ -48,7 +48,7 @@ public class PtpAcceptCommand implements CommandExecutor {
return true; return true;
} }
if (Config.getInstance().getPTPCommandWorldPermissions()) { if (mcMMO.p.getGeneralConfig().getPTPCommandWorldPermissions()) {
World targetWorld = target.getWorld(); World targetWorld = target.getWorld();
World playerWorld = player.getWorld(); World playerWorld = player.getWorld();

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.commands.party.teleport; package com.gmail.nossr50.commands.party.teleport;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.WorldBlacklist;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyFeature; import com.gmail.nossr50.datatypes.party.PartyFeature;
@ -76,7 +75,7 @@ public class PtpCommand implements TabExecutor {
Party party = mcMMOPlayer.getParty(); Party party = mcMMOPlayer.getParty();
if (party.getLevel() < Config.getInstance().getPartyFeatureUnlockLevel(PartyFeature.TELEPORT)) { if (party.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.TELEPORT)) {
sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.2")); sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.2"));
return true; return true;
} }
@ -91,7 +90,7 @@ public class PtpCommand implements TabExecutor {
} }
long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int hurtCooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown(); int hurtCooldown = mcMMO.p.getGeneralConfig().getPTPCommandRecentlyHurtCooldown();
if (hurtCooldown > 0) { if (hurtCooldown > 0) {
int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
@ -111,7 +110,7 @@ public class PtpCommand implements TabExecutor {
return true; return true;
} }
int ptpCooldown = Config.getInstance().getPTPCommandCooldown(); int ptpCooldown = mcMMO.p.getGeneralConfig().getPTPCommandCooldown();
long ptpLastUse = mcMMOPlayer.getPartyTeleportRecord().getLastUse(); long ptpLastUse = mcMMOPlayer.getPartyTeleportRecord().getLastUse();
if (ptpCooldown > 0) { if (ptpCooldown > 0) {
@ -165,7 +164,7 @@ public class PtpCommand implements TabExecutor {
Player target = mcMMOTarget.getPlayer(); Player target = mcMMOTarget.getPlayer();
if (Config.getInstance().getPTPCommandWorldPermissions()) { if (mcMMO.p.getGeneralConfig().getPTPCommandWorldPermissions()) {
World targetWorld = target.getWorld(); World targetWorld = target.getWorld();
World playerWorld = player.getWorld(); World playerWorld = player.getWorld();
@ -194,7 +193,7 @@ public class PtpCommand implements TabExecutor {
player.sendMessage(LocaleLoader.getString("Commands.Invite.Success")); player.sendMessage(LocaleLoader.getString("Commands.Invite.Success"));
target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName())); target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName()));
target.sendMessage(LocaleLoader.getString("Commands.ptp.Request2", Config.getInstance().getPTPCommandTimeout())); target.sendMessage(LocaleLoader.getString("Commands.ptp.Request2", mcMMO.p.getGeneralConfig().getPTPCommandTimeout()));
} }
protected static boolean canTeleport(CommandSender sender, Player player, String targetName) { protected static boolean canTeleport(CommandSender sender, Player player, String targetName) {
@ -245,7 +244,7 @@ public class PtpCommand implements TabExecutor {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer);
McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetPlayer); McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetPlayer);
long warmup = Config.getInstance().getPTPCommandWarmup(); long warmup = mcMMO.p.getGeneralConfig().getPTPCommandWarmup();
mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer); mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer);

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@ -36,12 +35,12 @@ public class InspectCommand implements TabExecutor {
return true; return true;
} }
if (Config.getInstance().getScoreboardsEnabled() if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()
&& sender instanceof Player && sender instanceof Player
&& Config.getInstance().getInspectUseBoard()) { && mcMMO.p.getGeneralConfig().getInspectUseBoard()) {
ScoreboardManager.enablePlayerInspectScoreboard((Player) sender, profile); ScoreboardManager.enablePlayerInspectScoreboard((Player) sender, profile);
if (!Config.getInstance().getInspectUseChat()) { if (!mcMMO.p.getGeneralConfig().getInspectUseChat()) {
return true; return true;
} }
} }
@ -49,17 +48,17 @@ public class InspectCommand implements TabExecutor {
sender.sendMessage(LocaleLoader.getString("Inspect.OfflineStats", playerName)); sender.sendMessage(LocaleLoader.getString("Inspect.OfflineStats", playerName));
sender.sendMessage(LocaleLoader.getString("Stats.Header.Gathering")); sender.sendMessage(LocaleLoader.getString("Stats.Header.Gathering"));
for (PrimarySkillType skill : PrimarySkillType.GATHERING_SKILLS) { for (PrimarySkillType skill : mcMMO.p.getSkillTools().GATHERING_SKILLS) {
sender.sendMessage(CommandUtils.displaySkill(profile, skill)); sender.sendMessage(CommandUtils.displaySkill(profile, skill));
} }
sender.sendMessage(LocaleLoader.getString("Stats.Header.Combat")); sender.sendMessage(LocaleLoader.getString("Stats.Header.Combat"));
for (PrimarySkillType skill : PrimarySkillType.COMBAT_SKILLS) { for (PrimarySkillType skill : mcMMO.p.getSkillTools().COMBAT_SKILLS) {
sender.sendMessage(CommandUtils.displaySkill(profile, skill)); sender.sendMessage(CommandUtils.displaySkill(profile, skill));
} }
sender.sendMessage(LocaleLoader.getString("Stats.Header.Misc")); sender.sendMessage(LocaleLoader.getString("Stats.Header.Misc"));
for (PrimarySkillType skill : PrimarySkillType.MISC_SKILLS) { for (PrimarySkillType skill : mcMMO.p.getSkillTools().MISC_SKILLS) {
sender.sendMessage(CommandUtils.displaySkill(profile, skill)); sender.sendMessage(CommandUtils.displaySkill(profile, skill));
} }
@ -76,12 +75,12 @@ public class InspectCommand implements TabExecutor {
return true; return true;
} }
if (Config.getInstance().getScoreboardsEnabled() if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()
&& sender instanceof Player && sender instanceof Player
&& Config.getInstance().getInspectUseBoard()) { && mcMMO.p.getGeneralConfig().getInspectUseBoard()) {
ScoreboardManager.enablePlayerInspectScoreboard((Player) sender, mcMMOPlayer); ScoreboardManager.enablePlayerInspectScoreboard((Player) sender, mcMMOPlayer);
if (!Config.getInstance().getInspectUseChat()) { if (!mcMMO.p.getGeneralConfig().getInspectUseChat()) {
return true; return true;
} }
} }

View File

@ -1,9 +1,9 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
@ -30,10 +30,10 @@ public class MccooldownCommand implements TabExecutor {
if (args.length == 0) { if (args.length == 0) {
Player player = (Player) sender; Player player = (Player) sender;
if (Config.getInstance().getScoreboardsEnabled() && Config.getInstance().getCooldownUseBoard()) { if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && mcMMO.p.getGeneralConfig().getCooldownUseBoard()) {
ScoreboardManager.enablePlayerCooldownScoreboard(player); ScoreboardManager.enablePlayerCooldownScoreboard(player);
if (!Config.getInstance().getCooldownUseChat()) { if (!mcMMO.p.getGeneralConfig().getCooldownUseChat()) {
return true; return true;
} }
} }

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@ -91,7 +90,7 @@ public class McrankCommand implements TabExecutor {
return; return;
} }
long cooldownMillis = Math.min(Config.getInstance().getDatabasePlayerCooldown(), 1750); long cooldownMillis = Math.min(mcMMO.p.getGeneralConfig().getDatabasePlayerCooldown(), 1750);
if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) { if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) {
sender.sendMessage(LocaleLoader.getString("Commands.Database.CooldownMS", getCDSeconds(mcMMOPlayer, cooldownMillis))); sender.sendMessage(LocaleLoader.getString("Commands.Database.CooldownMS", getCDSeconds(mcMMOPlayer, cooldownMillis)));
@ -108,8 +107,8 @@ public class McrankCommand implements TabExecutor {
mcMMOPlayer.actualizeDatabaseATS(); mcMMOPlayer.actualizeDatabaseATS();
} }
boolean useBoard = Config.getInstance().getScoreboardsEnabled() && (sender instanceof Player) && (Config.getInstance().getRankUseBoard()); boolean useBoard = mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getRankUseBoard());
boolean useChat = !useBoard || Config.getInstance().getRankUseChat(); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getRankUseChat();
new McrankCommandAsyncTask(playerName, sender, useBoard, useChat).runTaskAsynchronously(mcMMO.p); new McrankCommandAsyncTask(playerName, sender, useBoard, useChat).runTaskAsynchronously(mcMMO.p);
} }

View File

@ -1,7 +1,7 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
@ -33,10 +33,10 @@ public class McstatsCommand implements TabExecutor {
Player player = (Player) sender; Player player = (Player) sender;
if (Config.getInstance().getStatsUseBoard() && Config.getInstance().getScoreboardsEnabled()) { if (mcMMO.p.getGeneralConfig().getStatsUseBoard() && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
ScoreboardManager.enablePlayerStatsScoreboard(player); ScoreboardManager.enablePlayerStatsScoreboard(player);
if (!Config.getInstance().getStatsUseChat()) { if (!mcMMO.p.getGeneralConfig().getStatsUseChat()) {
return true; return true;
} }
} }
@ -48,7 +48,7 @@ public class McstatsCommand implements TabExecutor {
CommandUtils.printCombatSkills(player); CommandUtils.printCombatSkills(player);
CommandUtils.printMiscSkills(player); CommandUtils.printMiscSkills(player);
int powerLevelCap = Config.getInstance().getPowerLevelCap(); int powerLevelCap = mcMMO.p.getGeneralConfig().getPowerLevelCap();
if (powerLevelCap != Integer.MAX_VALUE) { if (powerLevelCap != Integer.MAX_VALUE) {
player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", UserManager.getPlayer(player).getPowerLevel(), powerLevelCap)); player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", UserManager.getPlayer(player).getPowerLevel(), powerLevelCap));

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@ -69,7 +68,7 @@ public class MctopCommand implements TabExecutor {
@Override @Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
if (args.length == 1) { if (args.length == 1) {
return StringUtil.copyPartialMatches(args[0], PrimarySkillType.SKILL_NAMES, new ArrayList<>(PrimarySkillType.SKILL_NAMES.size())); return StringUtil.copyPartialMatches(args[0], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size()));
} }
return ImmutableList.of(); return ImmutableList.of();
} }
@ -86,7 +85,7 @@ public class MctopCommand implements TabExecutor {
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName());
long cooldownMillis = Math.max(Config.getInstance().getDatabasePlayerCooldown(), 1750); long cooldownMillis = Math.max(mcMMO.p.getGeneralConfig().getDatabasePlayerCooldown(), 1750);
if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) { if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) {
double seconds = ((mcMMOPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()) / 1000.0D; double seconds = ((mcMMOPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()) / 1000.0D;
@ -112,8 +111,8 @@ public class MctopCommand implements TabExecutor {
} }
private void display(int page, PrimarySkillType skill, CommandSender sender) { private void display(int page, PrimarySkillType skill, CommandSender sender) {
boolean useBoard = (sender instanceof Player) && (Config.getInstance().getTopUseBoard()); boolean useBoard = (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getTopUseBoard());
boolean useChat = !useBoard || Config.getInstance().getTopUseChat(); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getTopUseChat();
new MctopCommandAsyncTask(page, skill, sender, useBoard, useChat).runTaskAsynchronously(mcMMO.p); new MctopCommandAsyncTask(page, skill, sender, useBoard, useChat).runTaskAsynchronously(mcMMO.p);
} }
@ -123,7 +122,7 @@ public class MctopCommand implements TabExecutor {
return null; return null;
} }
PrimarySkillType skill = PrimarySkillType.getSkill(skillName); PrimarySkillType skill = mcMMO.p.getSkillTools().matchSkill(skillName);
if (CommandUtils.isChildSkill(sender, skill)) { if (CommandUtils.isChildSkill(sender, skill)) {
return null; return null;

View File

@ -2,6 +2,7 @@ package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.experience.ExperienceBarManager; import com.gmail.nossr50.util.experience.ExperienceBarManager;
import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@ -51,7 +52,7 @@ public class XPBarCommand implements TabExecutor {
if(SkillUtils.isSkill(skillName)) { if(SkillUtils.isSkill(skillName)) {
PrimarySkillType targetSkill = PrimarySkillType.getSkill(skillName); PrimarySkillType targetSkill = mcMMO.p.getSkillTools().matchSkill(skillName);
//Target setting //Target setting
String option = args[0].toLowerCase(); String option = args[0].toLowerCase();
@ -103,7 +104,7 @@ public class XPBarCommand implements TabExecutor {
return StringUtil.copyPartialMatches(args[0], options, new ArrayList<>(ExperienceBarManager.XPBarSettingTarget.values().length)); return StringUtil.copyPartialMatches(args[0], options, new ArrayList<>(ExperienceBarManager.XPBarSettingTarget.values().length));
case 2: case 2:
if(!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) if(!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString()))
return StringUtil.copyPartialMatches(args[1], PrimarySkillType.SKILL_NAMES, new ArrayList<>(PrimarySkillType.SKILL_NAMES.size())); return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size()));
default: default:
return ImmutableList.of(); return ImmutableList.of();
} }

View File

@ -69,7 +69,7 @@ public class AcrobaticsCommand extends SkillCommand {
//Chance Stat Calculations //Chance Stat Calculations
rollChance = RandomChanceUtil.getRandomChanceExecutionChance(roll_rcs); rollChance = RandomChanceUtil.getRandomChanceExecutionChance(roll_rcs);
graceChance = RandomChanceUtil.getRandomChanceExecutionChance(grace_rcs); graceChance = RandomChanceUtil.getRandomChanceExecutionChance(grace_rcs);
//damageThreshold = AdvancedConfig.getInstance().getRollDamageThreshold(); //damageThreshold = mcMMO.p.getAdvancedConfig().getRollDamageThreshold();
String[] rollStrings = getAbilityDisplayValues(SkillActivationType.RANDOM_LINEAR_100_SCALE_WITH_CAP, player, SubSkillType.ACROBATICS_ROLL); String[] rollStrings = getAbilityDisplayValues(SkillActivationType.RANDOM_LINEAR_100_SCALE_WITH_CAP, player, SubSkillType.ACROBATICS_ROLL);

View File

@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillActivationType; import com.gmail.nossr50.util.skills.SkillActivationType;
@ -93,7 +94,7 @@ public class HerbalismCommand extends SkillCommand {
canGreenThumbPlants = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbPlant(player, Material.WHEAT) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.BEETROOT) || Permissions.greenThumbPlant(player, Material.NETHER_WART) || Permissions.greenThumbPlant(player, Material.COCOA)); canGreenThumbPlants = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbPlant(player, Material.WHEAT) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.BEETROOT) || Permissions.greenThumbPlant(player, Material.NETHER_WART) || Permissions.greenThumbPlant(player, Material.COCOA));
canGreenThumbBlocks = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLESTONE_WALL) || Permissions.greenThumbBlock(player, Material.STONE_BRICKS)); canGreenThumbBlocks = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLESTONE_WALL) || Permissions.greenThumbBlock(player, Material.STONE_BRICKS));
canFarmersDiet = canUseSubskill(player, SubSkillType.HERBALISM_FARMERS_DIET); canFarmersDiet = canUseSubskill(player, SubSkillType.HERBALISM_FARMERS_DIET);
canDoubleDrop = canUseSubskill(player, SubSkillType.HERBALISM_DOUBLE_DROPS) && !skill.getDoubleDropsDisabled(); canDoubleDrop = canUseSubskill(player, SubSkillType.HERBALISM_DOUBLE_DROPS) && !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill);
canShroomThumb = canUseSubskill(player, SubSkillType.HERBALISM_SHROOM_THUMB); canShroomThumb = canUseSubskill(player, SubSkillType.HERBALISM_SHROOM_THUMB);
} }

View File

@ -1,9 +1,9 @@
package com.gmail.nossr50.commands.skills; package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.listeners.InteractionManager; import com.gmail.nossr50.listeners.InteractionManager;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.text.TextComponentFactory; import com.gmail.nossr50.util.text.TextComponentFactory;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -45,7 +45,7 @@ public class MmoInfoCommand implements TabExecutor {
player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader"));
player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mystery")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mystery"));
return true; return true;
} else if(InteractionManager.getAbstractByName(args[0]) != null || PrimarySkillType.SUBSKILL_NAMES.contains(args[0])) } else if(InteractionManager.getAbstractByName(args[0]) != null || mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES.contains(args[0]))
{ {
displayInfo(player, args[0]); displayInfo(player, args[0]);
return true; return true;
@ -63,7 +63,7 @@ public class MmoInfoCommand implements TabExecutor {
@Override @Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
if (args.length == 1) { if (args.length == 1) {
return StringUtil.copyPartialMatches(args[0], PrimarySkillType.SUBSKILL_NAMES, new ArrayList<>(PrimarySkillType.SUBSKILL_NAMES.size())); return StringUtil.copyPartialMatches(args[0], mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES.size()));
} }
return ImmutableList.of(); return ImmutableList.of();
} }

View File

@ -1,11 +1,10 @@
package com.gmail.nossr50.commands.skills; package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.child.FamilyTree; import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
@ -16,6 +15,7 @@ import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.PerksUtils; import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillActivationType; import com.gmail.nossr50.util.skills.SkillActivationType;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.StringUtils;
import com.gmail.nossr50.util.text.TextComponentFactory; import com.gmail.nossr50.util.text.TextComponentFactory;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -45,7 +45,7 @@ public abstract class SkillCommand implements TabExecutor {
public SkillCommand(PrimarySkillType skill) { public SkillCommand(PrimarySkillType skill) {
this.skill = skill; this.skill = skill;
skillName = skill.getName(); skillName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill);
skillGuideCommand = new SkillGuideCommand(skill); skillGuideCommand = new SkillGuideCommand(skill);
} }
@ -74,7 +74,7 @@ public abstract class SkillCommand implements TabExecutor {
float skillValue = mcMMOPlayer.getSkillLevel(skill); float skillValue = mcMMOPlayer.getSkillLevel(skill);
//Send the players a few blank lines to make finding the top of the skill command easier //Send the players a few blank lines to make finding the top of the skill command easier
if (AdvancedConfig.getInstance().doesSkillCommandSendBlankLines()) if (mcMMO.p.getAdvancedConfig().doesSkillCommandSendBlankLines())
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
player.sendMessage(""); player.sendMessage("");
} }
@ -106,13 +106,13 @@ public abstract class SkillCommand implements TabExecutor {
//Link Header //Link Header
if (Config.getInstance().getUrlLinksEnabled()) { if (mcMMO.p.getGeneralConfig().getUrlLinksEnabled()) {
player.sendMessage(LocaleLoader.getString("Overhaul.mcMMO.Header")); player.sendMessage(LocaleLoader.getString("Overhaul.mcMMO.Header"));
TextComponentFactory.sendPlayerUrlHeader(player); TextComponentFactory.sendPlayerUrlHeader(player);
} }
if (Config.getInstance().getScoreboardsEnabled() && Config.getInstance().getSkillUseBoard()) { if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && mcMMO.p.getGeneralConfig().getSkillUseBoard()) {
ScoreboardManager.enablePlayerSkillScoreboard(player, skill); ScoreboardManager.enablePlayerSkillScoreboard(player, skill);
} }
@ -143,7 +143,7 @@ public abstract class SkillCommand implements TabExecutor {
player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName)); player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName));
if(!skill.isChildSkill()) if(!SkillTools.isChildSkill(skill))
{ {
/* /*
* NON-CHILD SKILLS * NON-CHILD SKILLS
@ -173,10 +173,10 @@ public abstract class SkillCommand implements TabExecutor {
{ {
if(i+1 < parentList.size()) if(i+1 < parentList.size())
{ {
parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", parentList.get(i).getName(), mcMMOPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i))));
parentMessage.append(ChatColor.GRAY).append(", "); parentMessage.append(ChatColor.GRAY).append(", ");
} else { } else {
parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", parentList.get(i).getName(), mcMMOPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i))));
} }
} }
@ -189,7 +189,7 @@ public abstract class SkillCommand implements TabExecutor {
} }
/* /*
if (!skill.isChildSkill()) { if (!SkillTools.isChildSkill(skill)) {
player.sendMessage(LocaleLoader.getString("Skills.Header", skillName)); player.sendMessage(LocaleLoader.getString("Skills.Header", skillName));
player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain." + StringUtils.getCapitalized(skill.toString())))); player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain." + StringUtils.getCapitalized(skill.toString()))));
player.sendMessage(LocaleLoader.getString("Effects.Level", skillValue, mcMMOPlayer.getSkillXpLevel(skill), mcMMOPlayer.getXpToLevel(skill))); player.sendMessage(LocaleLoader.getString("Effects.Level", skillValue, mcMMOPlayer.getSkillXpLevel(skill), mcMMOPlayer.getXpToLevel(skill)));
@ -225,9 +225,9 @@ public abstract class SkillCommand implements TabExecutor {
} }
protected String[] calculateLengthDisplayValues(Player player, float skillValue) { protected String[] calculateLengthDisplayValues(Player player, float skillValue) {
int maxLength = skill.getAbility().getMaxLength(); int maxLength = mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill));
int abilityLengthVar = AdvancedConfig.getInstance().getAbilityLength(); int abilityLengthVar = mcMMO.p.getAdvancedConfig().getAbilityLength();
int abilityLengthCap = AdvancedConfig.getInstance().getAbilityLengthCap(); int abilityLengthCap = mcMMO.p.getAdvancedConfig().getAbilityLengthCap();
int length; int length;
@ -268,7 +268,7 @@ public abstract class SkillCommand implements TabExecutor {
} }
protected String getLimitBreakDescriptionParameter() { protected String getLimitBreakDescriptionParameter() {
if(AdvancedConfig.getInstance().canApplyLimitBreakPVE()) { if(mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) {
return "(PVP/PVE)"; return "(PVP/PVE)";
} else { } else {
return "(PVP)"; return "(PVP)";

View File

@ -2,6 +2,7 @@ package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.StringUtils;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@ -18,7 +19,7 @@ public class SkillGuideCommand implements CommandExecutor {
private final String invalidPage = LocaleLoader.getString("Guides.Page.Invalid"); private final String invalidPage = LocaleLoader.getString("Guides.Page.Invalid");
public SkillGuideCommand(PrimarySkillType skill) { public SkillGuideCommand(PrimarySkillType skill) {
header = LocaleLoader.getString("Guides.Header", skill.getName()); header = LocaleLoader.getString("Guides.Header", mcMMO.p.getSkillTools().getLocalizedSkillName(skill));
guide = getGuide(skill); guide = getGuide(skill);
} }

View File

@ -1,9 +1,9 @@
package com.gmail.nossr50.commands.skills; package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.CombatUtils;
@ -46,17 +46,17 @@ public class SwordsCommand extends SkillCommand {
// SWORDS_RUPTURE // SWORDS_RUPTURE
if (canRupture) { if (canRupture) {
int ruptureRank = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE); int ruptureRank = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE);
ruptureLengthSecondsAgainstPlayers = String.valueOf(AdvancedConfig.getInstance().getRuptureDurationSeconds(true)); ruptureLengthSecondsAgainstPlayers = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(true));
ruptureLengthSecondsAgainstMobs = String.valueOf(AdvancedConfig.getInstance().getRuptureDurationSeconds(false)); ruptureLengthSecondsAgainstMobs = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(false));
rupturePureTickDamageAgainstPlayers = String.valueOf(AdvancedConfig.getInstance().getRuptureTickDamage(true, ruptureRank)); rupturePureTickDamageAgainstPlayers = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureTickDamage(true, ruptureRank));
rupturePureTickDamageAgainstMobs = String.valueOf(AdvancedConfig.getInstance().getRuptureTickDamage(false, ruptureRank)); rupturePureTickDamageAgainstMobs = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureTickDamage(false, ruptureRank));
ruptureExplosionDamageAgainstPlayers = String.valueOf(AdvancedConfig.getInstance().getRuptureExplosionDamage(true, ruptureRank)); ruptureExplosionDamageAgainstPlayers = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureExplosionDamage(true, ruptureRank));
ruptureExplosionDamageAgainstMobs = String.valueOf(AdvancedConfig.getInstance().getRuptureExplosionDamage(false, ruptureRank)); ruptureExplosionDamageAgainstMobs = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureExplosionDamage(false, ruptureRank));
ruptureChanceToApply = String.valueOf(AdvancedConfig.getInstance().getRuptureChanceToApplyOnHit(ruptureRank) + "%"); ruptureChanceToApply = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(ruptureRank) + "%");
ruptureChanceToApplyLucky = String.valueOf(AdvancedConfig.getInstance().getRuptureChanceToApplyOnHit(ruptureRank) * 1.33); ruptureChanceToApplyLucky = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(ruptureRank) * 1.33);
} }
// SERRATED STRIKES // SERRATED STRIKES

View File

@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillActivationType; import com.gmail.nossr50.util.skills.SkillActivationType;
@ -55,7 +56,9 @@ public class WoodcuttingCommand extends SkillCommand {
@Override @Override
protected void permissionsCheck(Player player) { protected void permissionsCheck(Player player) {
canTreeFell = RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_TREE_FELLER) && Permissions.treeFeller(player); canTreeFell = RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_TREE_FELLER) && Permissions.treeFeller(player);
canDoubleDrop = canUseSubskill(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER) && !skill.getDoubleDropsDisabled() && RankUtils.getRank(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER) >= 1; canDoubleDrop = canUseSubskill(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER)
&& !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill)
&& RankUtils.getRank(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER) >= 1;
canLeafBlow = canUseSubskill(player, SubSkillType.WOODCUTTING_LEAF_BLOWER); canLeafBlow = canUseSubskill(player, SubSkillType.WOODCUTTING_LEAF_BLOWER);
canKnockOnWood = canTreeFell && canUseSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD); canKnockOnWood = canTreeFell && canUseSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD);
/*canSplinter = canUseSubskill(player, SubSkillType.WOODCUTTING_SPLINTER); /*canSplinter = canUseSubskill(player, SubSkillType.WOODCUTTING_SPLINTER);

View File

@ -6,25 +6,17 @@ import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class AdvancedConfig extends AutoUpdateConfigLoader { public class AdvancedConfig extends AutoUpdateConfigLoader {
private static AdvancedConfig instance;
private AdvancedConfig() { public AdvancedConfig(File dataFolder) {
super("advanced.yml"); super("advanced.yml", dataFolder);
validate(); validate();
} }
public static AdvancedConfig getInstance() {
if (instance == null) {
instance = new AdvancedConfig();
}
return instance;
}
@Override @Override
protected boolean validateKeys() { protected boolean validateKeys() {
// Validate all the settings! // Validate all the settings!
@ -68,15 +60,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
reason.add("Skills.Acrobatics.GracefulRoll.DamageThreshold should be at least 0!"); reason.add("Skills.Acrobatics.GracefulRoll.DamageThreshold should be at least 0!");
} }
/* ALCHEMY */
/*if (getCatalysisUnlockLevel() < 0) {
reason.add("Skills.Alchemy.Catalysis.UnlockLevel should be at least 0!");
}
if (getCatalysisMaxBonusLevel() <= getCatalysisUnlockLevel()) {
reason.add("Skills.Alchemy.Catalysis.MaxBonusLevel should be greater than Skills.Alchemy.Catalysis.UnlockLevel!");
}*/
if (getCatalysisMinSpeed() <= 0) { if (getCatalysisMinSpeed() <= 0) {
reason.add("Skills.Alchemy.Catalysis.MinSpeed must be greater than 0!"); reason.add("Skills.Alchemy.Catalysis.MinSpeed must be greater than 0!");
} }
@ -85,21 +68,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
reason.add("Skills.Alchemy.Catalysis.MaxSpeed should be at least Skills.Alchemy.Catalysis.MinSpeed!"); reason.add("Skills.Alchemy.Catalysis.MaxSpeed should be at least Skills.Alchemy.Catalysis.MinSpeed!");
} }
/*List<Alchemy.Tier> alchemyTierList = Arrays.asList(Alchemy.Tier.values());
for (Alchemy.Tier tier : alchemyTierList) {
if (getConcoctionsTierLevel(tier) < 0) {
reason.add("Skills.Alchemy.Rank_Levels.Rank_" + rank + " should be at least 0!");
}
if (tier != Alchemy.Tier.fromNumerical(Alchemy.Tier.values().length)) {
Alchemy.Tier nextTier = alchemyTierList.get(alchemyTierList.indexOf(tier) - 1);
if (getConcoctionsTierLevel(tier) > getConcoctionsTierLevel(nextTier)) {
reason.add("Skills.Alchemy.Rank_Levels.Rank_" + rank + " should be less than or equal to Skills.Alchemy.Rank_Levels.Rank_" + nextrank + "!");
}
}
}*/
/* ARCHERY */ /* ARCHERY */
if (getSkillShotRankDamageMultiplier() <= 0) { if (getSkillShotRankDamageMultiplier() <= 0) {

View File

@ -1,5 +1,6 @@
package com.gmail.nossr50.config; package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -11,17 +12,27 @@ import java.util.LinkedHashMap;
import java.util.Set; import java.util.Set;
public abstract class AutoUpdateConfigLoader extends ConfigLoader { public abstract class AutoUpdateConfigLoader extends ConfigLoader {
public AutoUpdateConfigLoader(String relativePath, String fileName, File dataFolder) {
super(relativePath, fileName, dataFolder);
}
public AutoUpdateConfigLoader(String fileName, File dataFolder) {
super(fileName, dataFolder);
}
@Deprecated
public AutoUpdateConfigLoader(String relativePath, String fileName) { public AutoUpdateConfigLoader(String relativePath, String fileName) {
super(relativePath, fileName); super(relativePath, fileName);
} }
@Deprecated
public AutoUpdateConfigLoader(String fileName) { public AutoUpdateConfigLoader(String fileName) {
super(fileName); super(fileName);
} }
protected void saveConfig() { protected void saveConfig() {
try { try {
plugin.getLogger().info("Saving changes to config file - "+fileName); mcMMO.p.getLogger().info("Saving changes to config file - "+fileName);
config.save(configFile); config.save(configFile);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -29,13 +40,13 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
} }
protected @NotNull FileConfiguration getInternalConfig() { protected @NotNull FileConfiguration getInternalConfig() {
return YamlConfiguration.loadConfiguration(plugin.getResourceAsReader(fileName)); return YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName));
} }
@Override @Override
protected void loadFile() { protected void loadFile() {
super.loadFile(); super.loadFile();
FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(plugin.getResourceAsReader(fileName)); FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName));
Set<String> configKeys = config.getKeys(true); Set<String> configKeys = config.getKeys(true);
Set<String> internalConfigKeys = internalConfig.getKeys(true); Set<String> internalConfigKeys = internalConfig.getKeys(true);
@ -55,12 +66,12 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
} }
// //
// for (String key : oldKeys) { // for (String key : oldKeys) {
// plugin.debug("Detected potentially unused key: " + key); // mcMMO.p.debug("Detected potentially unused key: " + key);
// //config.set(key, null); // //config.set(key, null);
// } // }
for (String key : newKeys) { for (String key : newKeys) {
plugin.debug("Adding new key: " + key + " = " + internalConfig.get(key)); mcMMO.p.debug("Adding new key: " + key + " = " + internalConfig.get(key));
config.set(key, internalConfig.get(key)); config.set(key, internalConfig.get(key));
} }
@ -79,7 +90,7 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
// Read the internal config to get comments, then put them in the new one // Read the internal config to get comments, then put them in the new one
try { try {
// Read internal // Read internal
BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getResource(fileName))); BufferedReader reader = new BufferedReader(new InputStreamReader(mcMMO.p.getResource(fileName)));
LinkedHashMap<String, String> comments = new LinkedHashMap<>(); LinkedHashMap<String, String> comments = new LinkedHashMap<>();
StringBuilder temp = new StringBuilder(); StringBuilder temp = new StringBuilder();
@ -129,14 +140,21 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
} }
// Save it // Save it
if(dataFolder == null) {
mcMMO.p.getLogger().severe("Data folder should never be null!");
return;
}
try { try {
String saveName = fileName; String saveName = fileName;
// At this stage we cannot guarantee that Config has been loaded, so we do the check directly here // At this stage we cannot guarantee that Config has been loaded, so we do the check directly here
if (!plugin.getConfig().getBoolean("General.Config_Update_Overwrite", true)) { if (!mcMMO.p.getConfig().getBoolean("General.Config_Update_Overwrite", true)) {
saveName += ".new"; saveName += ".new";
} }
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(plugin.getDataFolder(), saveName))); File newSaveFile = new File(dataFolder, saveName);
FileWriter fileWriter = new FileWriter(newSaveFile.getAbsolutePath());
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(output); writer.write(output);
writer.flush(); writer.flush();
writer.close(); writer.close();

View File

@ -3,41 +3,60 @@ package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
public abstract class ConfigLoader { public abstract class ConfigLoader {
protected static final mcMMO plugin = mcMMO.p;
protected String fileName; protected String fileName;
protected final File configFile; protected final File configFile;
protected FileConfiguration config; protected FileConfiguration config;
protected @NotNull final File dataFolder;
public ConfigLoader(String relativePath, String fileName) { public ConfigLoader(String relativePath, String fileName, @NotNull File dataFolder) {
this.fileName = fileName; this.fileName = fileName;
configFile = new File(plugin.getDataFolder(), relativePath + File.separator + fileName); this.dataFolder = dataFolder;
configFile = new File(dataFolder, relativePath + File.separator + fileName);
loadFile(); loadFile();
} }
public ConfigLoader(String fileName, @NotNull File dataFolder) {
this.fileName = fileName;
this.dataFolder = dataFolder;
configFile = new File(dataFolder, fileName);
loadFile();
}
@Deprecated
public ConfigLoader(String relativePath, String fileName) {
this.fileName = fileName;
configFile = new File(mcMMO.p.getDataFolder(), relativePath + File.separator + fileName);
this.dataFolder = mcMMO.p.getDataFolder();
loadFile();
}
@Deprecated
public ConfigLoader(String fileName) { public ConfigLoader(String fileName) {
this.fileName = fileName; this.fileName = fileName;
configFile = new File(plugin.getDataFolder(), fileName); configFile = new File(mcMMO.p.getDataFolder(), fileName);
this.dataFolder = mcMMO.p.getDataFolder();
loadFile(); loadFile();
} }
protected void loadFile() { protected void loadFile() {
if (!configFile.exists()) { if (!configFile.exists()) {
plugin.debug("Creating mcMMO " + fileName + " File..."); mcMMO.p.debug("Creating mcMMO " + fileName + " File...");
try { try {
plugin.saveResource(fileName, false); // Normal files mcMMO.p.saveResource(fileName, false); // Normal files
} }
catch (IllegalArgumentException ex) { catch (IllegalArgumentException ex) {
plugin.saveResource(configFile.getParentFile().getName() + File.separator + fileName, false); // Mod files mcMMO.p.saveResource(configFile.getParentFile().getName() + File.separator + fileName, false); // Mod files
} }
} }
else { else {
plugin.debug("Loading mcMMO " + fileName + " File..."); mcMMO.p.debug("Loading mcMMO " + fileName + " File...");
} }
config = YamlConfiguration.loadConfiguration(configFile); config = YamlConfiguration.loadConfiguration(configFile);
@ -51,7 +70,7 @@ public abstract class ConfigLoader {
protected boolean noErrorsInConfig(List<String> issues) { protected boolean noErrorsInConfig(List<String> issues) {
for (String issue : issues) { for (String issue : issues) {
plugin.getLogger().warning(issue); mcMMO.p.getLogger().warning(issue);
} }
return issues.isEmpty(); return issues.isEmpty();
@ -59,12 +78,12 @@ public abstract class ConfigLoader {
protected void validate() { protected void validate() {
if (validateKeys()) { if (validateKeys()) {
plugin.debug("No errors found in " + fileName + "!"); mcMMO.p.debug("No errors found in " + fileName + "!");
} }
else { else {
plugin.getLogger().warning("Errors were found in " + fileName + "! mcMMO was disabled!"); mcMMO.p.getLogger().warning("Errors were found in " + fileName + "! mcMMO was disabled!");
plugin.getServer().getPluginManager().disablePlugin(plugin); mcMMO.p.getServer().getPluginManager().disablePlugin(mcMMO.p);
plugin.noErrorsInConfigFiles = false; mcMMO.p.noErrorsInConfigFiles = false;
} }
} }
@ -73,16 +92,16 @@ public abstract class ConfigLoader {
} }
public void backup() { public void backup() {
plugin.getLogger().warning("You are using an old version of the " + fileName + " file."); mcMMO.p.getLogger().warning("You are using an old version of the " + fileName + " file.");
plugin.getLogger().warning("Your old file has been renamed to " + fileName + ".old and has been replaced by an updated version."); mcMMO.p.getLogger().warning("Your old file has been renamed to " + fileName + ".old and has been replaced by an updated version.");
configFile.renameTo(new File(configFile.getPath() + ".old")); configFile.renameTo(new File(configFile.getPath() + ".old"));
if (plugin.getResource(fileName) != null) { if (mcMMO.p.getResource(fileName) != null) {
plugin.saveResource(fileName, true); mcMMO.p.saveResource(fileName, true);
} }
plugin.getLogger().warning("Reloading " + fileName + " with new values..."); mcMMO.p.getLogger().warning("Reloading " + fileName + " with new values...");
loadFile(); loadFile();
loadKeys(); loadKeys();
} }

View File

@ -12,27 +12,19 @@ import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
public class Config extends AutoUpdateConfigLoader { public class GeneralConfig extends AutoUpdateConfigLoader {
private static Config instance;
private Config() { public GeneralConfig(@NotNull File dataFolder) {
super("config.yml"); super("config.yml", dataFolder);
validate(); validate();
} }
public static Config getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
@Override @Override
protected void loadKeys() { protected void loadKeys() {
@ -63,47 +55,6 @@ public class Config extends AutoUpdateConfigLoader {
reason.add("Mob_Healthbar.Display_Time cannot be 0! Set to -1 to disable or set a valid value."); reason.add("Mob_Healthbar.Display_Time cannot be 0! Set to -1 to disable or set a valid value.");
} }
/* Scoreboards */
/*if (getRankScoreboardTime() != -1 && getRankScoreboardTime() <= 0) {
reason.add("Scoreboard.Types.Rank.Display_Time should be greater than 0, or -1!");
}
if (getStatsScoreboardTime() != -1 && getStatsScoreboardTime() <= 0) {
reason.add("Scoreboard.Types.Stats.Display_Time should be greater than 0, or -1!");
}
if (getTopScoreboardTime() != -1 && getTopScoreboardTime() <= 0) {
reason.add("Scoreboard.Types.Top.Display_Time should be greater than 0, or -1!");
}
if (getInspectScoreboardTime() != -1 && getInspectScoreboardTime() <= 0) {
reason.add("Scoreboard.Types.Inspect.Display_Time should be greater than 0, or -1!");
}
if (getSkillScoreboardTime() != -1 && getSkillScoreboardTime() <= 0) {
reason.add("Scoreboard.Types.Skill.Display_Time should be greater than 0, or -1!");
}
if (getSkillLevelUpTime() != -1 && getSkillScoreboardTime() <= 0) {
reason.add("Scoreboard.Types.Skill.Display_Time should be greater than 0, or -1!");
}
if (!(getRankUseChat() || getRankUseBoard())) {
reason.add("Either Board or Print in Scoreboard.Types.Rank must be true!");
}
if (!(getTopUseChat() || getTopUseBoard())) {
reason.add("Either Board or Print in Scoreboard.Types.Top must be true!");
}
if (!(getStatsUseChat() || getStatsUseBoard())) {
reason.add("Either Board or Print in Scoreboard.Types.Stats must be true!");
}
if (!(getInspectUseChat() || getInspectUseBoard())) {
reason.add("Either Board or Print in Scoreboard.Types.Inspect must be true!");
}*/
/* Database Purging */ /* Database Purging */
if (getPurgeInterval() < -1) { if (getPurgeInterval() < -1) {
reason.add("Database_Purging.Purge_Interval should be greater than, or equal to -1!"); reason.add("Database_Purging.Purge_Interval should be greater than, or equal to -1!");
@ -200,42 +151,6 @@ public class Config extends AutoUpdateConfigLoader {
reason.add("Cannot use the same item for Repair and Salvage anvils!"); reason.add("Cannot use the same item for Repair and Salvage anvils!");
} }
// if (getTamingCOTWMaterial(EntityType.WOLF) == null) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Wolf.Item_Material is invalid!!");
// }
//
// if (getTamingCOTWMaterial(EntityType.OCELOT) == null) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Ocelot.Item_Material is invalid!!");
// }
//
// if (getTamingCOTWMaterial(EntityType.HORSE) == null) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Horse.Item_Material is invalid!!");
// }
//
// if (getTamingCOTWCost(EntityType.WOLF) <= 0) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Wolf.Item_Amount should be greater than 0!");
// }
//
// if (getTamingCOTWCost(EntityType.OCELOT) <= 0) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Ocelot.Item_Amount should be greater than 0!");
// }
//
// if (getTamingCOTWCost(EntityType.HORSE) <= 0) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Horse.Item_Amount should be greater than 0!");
// }
//
// if (getTamingCOTWAmount(EntityType.WOLF) <= 0) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Wolf.Summon_Amount should be greater than 0!");
// }
//
// if (getTamingCOTWAmount(EntityType.OCELOT) <= 0) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Ocelot.Summon_Amount should be greater than 0!");
// }
//
// if (getTamingCOTWAmount(EntityType.HORSE) <= 0) {
// reason.add("Skills.Taming.Call_Of_The_Wild.Horse.Summon_Amount should be greater than 0!");
// }
return noErrorsInConfig(reason); return noErrorsInConfig(reason);
} }
@ -249,7 +164,7 @@ public class Config extends AutoUpdateConfigLoader {
//Retro mode will default the value to true if the config file doesn't contain the entry (server is from a previous mcMMO install) //Retro mode will default the value to true if the config file doesn't contain the entry (server is from a previous mcMMO install)
public boolean getIsRetroMode() { return config.getBoolean("General.RetroMode.Enabled", true); } public boolean getIsRetroMode() { return config.getBoolean("General.RetroMode.Enabled", true); }
public String getLocale() { return config.getString("General.Locale", "en_us"); } public String getLocale() { return config.getString("General.Locale", "en_US"); }
public boolean getMOTDEnabled() { return config.getBoolean("General.MOTD_Enabled", true); } public boolean getMOTDEnabled() { return config.getBoolean("General.MOTD_Enabled", true); }
public boolean getShowProfileLoadedMessage() { return config.getBoolean("General.Show_Profile_Loaded", true); } public boolean getShowProfileLoadedMessage() { return config.getBoolean("General.Show_Profile_Loaded", true); }
public boolean getDonateMessageEnabled() { return config.getBoolean("Commands.mcmmo.Donate_Message", true); } public boolean getDonateMessageEnabled() { return config.getBoolean("Commands.mcmmo.Donate_Message", true); }

View File

@ -9,7 +9,6 @@ public class HiddenConfig {
private static HiddenConfig instance; private static HiddenConfig instance;
private final String fileName; private final String fileName;
private YamlConfiguration config; private YamlConfiguration config;
private boolean chunkletsEnabled;
private int conversionRate; private int conversionRate;
private boolean useEnchantmentBuffs; private boolean useEnchantmentBuffs;
@ -30,15 +29,11 @@ public class HiddenConfig {
InputStreamReader reader = mcMMO.p.getResourceAsReader(fileName); InputStreamReader reader = mcMMO.p.getResourceAsReader(fileName);
if (reader != null) { if (reader != null) {
config = YamlConfiguration.loadConfiguration(reader); config = YamlConfiguration.loadConfiguration(reader);
chunkletsEnabled = config.getBoolean("Options.Chunklets", true);
conversionRate = config.getInt("Options.ConversionRate", 1); conversionRate = config.getInt("Options.ConversionRate", 1);
useEnchantmentBuffs = config.getBoolean("Options.EnchantmentBuffs", true); useEnchantmentBuffs = config.getBoolean("Options.EnchantmentBuffs", true);
} }
} }
public boolean getChunkletsEnabled() {
return chunkletsEnabled;
}
public int getConversionRate() { public int getConversionRate() {
return conversionRate; return conversionRate;

View File

@ -34,4 +34,9 @@ public class PersistentDataConfig extends AutoUpdateConfigLoader {
return config.getBoolean(key, false); return config.getBoolean(key, false);
} }
public boolean useBlockTracker() {
return config.getBoolean("mcMMO_Region_System.Enabled", true);
}
} }

View File

@ -2,6 +2,7 @@ package com.gmail.nossr50.config;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill;
import com.gmail.nossr50.mcMMO;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
@ -88,7 +89,7 @@ public class RankConfig extends AutoUpdateConfigLoader {
* @return the level requirement for a subskill at this particular rank * @return the level requirement for a subskill at this particular rank
*/ */
private int findRankByRootAddress(int rank, String key) { private int findRankByRootAddress(int rank, String key) {
String scalingKey = Config.getInstance().getIsRetroMode() ? ".RetroMode." : ".Standard."; String scalingKey = mcMMO.p.getGeneralConfig().getIsRetroMode() ? ".RetroMode." : ".Standard.";
String targetRank = "Rank_" + rank; String targetRank = "Rank_" + rank;
@ -126,7 +127,7 @@ public class RankConfig extends AutoUpdateConfigLoader {
String key = getRankAddressKey(subSkillType, rank, retroMode); String key = getRankAddressKey(subSkillType, rank, retroMode);
int defaultValue = getInternalConfig().getInt(key); int defaultValue = getInternalConfig().getInt(key);
config.set(key, defaultValue); config.set(key, defaultValue);
plugin.getLogger().info(key +" SET -> " + defaultValue); mcMMO.p.getLogger().info(key +" SET -> " + defaultValue);
} }
/** /**
@ -144,10 +145,10 @@ public class RankConfig extends AutoUpdateConfigLoader {
if(badSkillSetup.isEmpty()) if(badSkillSetup.isEmpty())
return; return;
plugin.getLogger().info("(FIXING CONFIG) mcMMO is correcting a few mistakes found in your skill rank config setup"); mcMMO.p.getLogger().info("(FIXING CONFIG) mcMMO is correcting a few mistakes found in your skill rank config setup");
for(SubSkillType subSkillType : badSkillSetup) { for(SubSkillType subSkillType : badSkillSetup) {
plugin.getLogger().info("(FIXING CONFIG) Resetting rank config settings for skill named - "+subSkillType.toString()); mcMMO.p.getLogger().info("(FIXING CONFIG) Resetting rank config settings for skill named - "+subSkillType.toString());
fixBadEntries(subSkillType); fixBadEntries(subSkillType);
} }
} }
@ -179,7 +180,7 @@ public class RankConfig extends AutoUpdateConfigLoader {
if(prevRank > curRank) if(prevRank > curRank)
{ {
//We're going to allow this but we're going to warn them //We're going to allow this but we're going to warn them
plugin.getLogger().info("(CONFIG ISSUE) You have the ranks for the subskill "+ subSkillType.toString()+" set up poorly, sequential ranks should have ascending requirements"); mcMMO.p.getLogger().info("(CONFIG ISSUE) You have the ranks for the subskill "+ subSkillType.toString()+" set up poorly, sequential ranks should have ascending requirements");
badSkillSetup.add(subSkillType); badSkillSetup.add(subSkillType);
} }
} }

View File

@ -1,5 +1,6 @@
package com.gmail.nossr50.config; package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.sounds.SoundType;
public class SoundConfig extends AutoUpdateConfigLoader { public class SoundConfig extends AutoUpdateConfigLoader {
@ -31,7 +32,7 @@ public class SoundConfig extends AutoUpdateConfigLoader {
{ {
if(config.getDouble("Sounds."+soundType.toString()+".Volume") < 0) if(config.getDouble("Sounds."+soundType.toString()+".Volume") < 0)
{ {
plugin.getLogger().info("[mcMMO] Sound volume cannot be below 0 for "+soundType.toString()); mcMMO.p.getLogger().info("[mcMMO] Sound volume cannot be below 0 for "+soundType.toString());
return false; return false;
} }
@ -40,7 +41,7 @@ public class SoundConfig extends AutoUpdateConfigLoader {
{ {
if(config.getDouble("Sounds."+soundType.toString()+".Pitch") < 0) if(config.getDouble("Sounds."+soundType.toString()+".Pitch") < 0)
{ {
plugin.getLogger().info("[mcMMO] Sound pitch cannot be below 0 for "+soundType.toString()); mcMMO.p.getLogger().info("[mcMMO] Sound pitch cannot be below 0 for "+soundType.toString());
return false; return false;
} }
} }

View File

@ -3,6 +3,7 @@ package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.skills.ItemType; import com.gmail.nossr50.datatypes.skills.ItemType;
import com.gmail.nossr50.datatypes.skills.MaterialType; import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.repairables.Repairable; import com.gmail.nossr50.skills.repair.repairables.Repairable;
import com.gmail.nossr50.skills.repair.repairables.RepairableFactory; import com.gmail.nossr50.skills.repair.repairables.RepairableFactory;
import org.bukkit.Material; import org.bukkit.Material;
@ -62,7 +63,7 @@ public class CustomArmorConfig extends ConfigLoader {
Material armorMaterial = Material.matchMaterial(armorName); Material armorMaterial = Material.matchMaterial(armorName);
if (armorMaterial == null) { if (armorMaterial == null) {
plugin.getLogger().warning("Invalid material name. This item will be skipped. - " + armorName); mcMMO.p.getLogger().warning("Invalid material name. This item will be skipped. - " + armorName);
continue; continue;
} }
@ -70,7 +71,7 @@ public class CustomArmorConfig extends ConfigLoader {
Material repairMaterial = Material.matchMaterial(config.getString(armorType + "." + armorName + ".Repair_Material", "")); Material repairMaterial = Material.matchMaterial(config.getString(armorType + "." + armorName + ".Repair_Material", ""));
if (repairable && (repairMaterial == null)) { if (repairable && (repairMaterial == null)) {
plugin.getLogger().warning("Incomplete repair information. This item will be unrepairable. - " + armorName); mcMMO.p.getLogger().warning("Incomplete repair information. This item will be unrepairable. - " + armorName);
repairable = false; repairable = false;
} }

View File

@ -2,6 +2,7 @@ package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomBlock; import com.gmail.nossr50.datatypes.mods.CustomBlock;
import com.gmail.nossr50.mcMMO;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
@ -66,7 +67,7 @@ public class CustomBlockConfig extends ConfigLoader {
Material blockMaterial = Material.matchMaterial(blockInfo[0]); Material blockMaterial = Material.matchMaterial(blockInfo[0]);
if (blockMaterial == null) { if (blockMaterial == null) {
plugin.getLogger().warning("Invalid material name. This item will be skipped. - " + blockInfo[0]); mcMMO.p.getLogger().warning("Invalid material name. This item will be skipped. - " + blockInfo[0]);
continue; continue;
} }

View File

@ -2,6 +2,7 @@ package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomEntity; import com.gmail.nossr50.datatypes.mods.CustomEntity;
import com.gmail.nossr50.mcMMO;
import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.ClassUtils;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -32,8 +33,8 @@ public class CustomEntityConfig extends ConfigLoader {
clazz = ClassUtils.getClass(className); clazz = ClassUtils.getClass(className);
} }
catch (ClassNotFoundException e) { catch (ClassNotFoundException e) {
plugin.getLogger().warning("Invalid class (" + className + ") detected for " + entityName + "."); mcMMO.p.getLogger().warning("Invalid class (" + className + ") detected for " + entityName + ".");
plugin.getLogger().warning("This custom entity may not function properly."); mcMMO.p.getLogger().warning("This custom entity may not function properly.");
} }
String entityTypeName = entityName.replace("_", "."); String entityTypeName = entityName.replace("_", ".");
@ -48,7 +49,7 @@ public class CustomEntityConfig extends ConfigLoader {
int callOfTheWildAmount = config.getInt(entityName + ".COTW_Material_Amount"); int callOfTheWildAmount = config.getInt(entityName + ".COTW_Material_Amount");
if (canBeSummoned && (callOfTheWildMaterial == null || callOfTheWildAmount == 0)) { if (canBeSummoned && (callOfTheWildMaterial == null || callOfTheWildAmount == 0)) {
plugin.getLogger().warning("Incomplete Call of the Wild information. This entity will not be able to be summoned by Call of the Wild."); mcMMO.p.getLogger().warning("Incomplete Call of the Wild information. This entity will not be able to be summoned by Call of the Wild.");
canBeSummoned = false; canBeSummoned = false;
} }

View File

@ -4,6 +4,7 @@ import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomTool; import com.gmail.nossr50.datatypes.mods.CustomTool;
import com.gmail.nossr50.datatypes.skills.ItemType; import com.gmail.nossr50.datatypes.skills.ItemType;
import com.gmail.nossr50.datatypes.skills.MaterialType; import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.repairables.Repairable; import com.gmail.nossr50.skills.repair.repairables.Repairable;
import com.gmail.nossr50.skills.repair.repairables.RepairableFactory; import com.gmail.nossr50.skills.repair.repairables.RepairableFactory;
import org.bukkit.Material; import org.bukkit.Material;
@ -70,7 +71,7 @@ public class CustomToolConfig extends ConfigLoader {
Material toolMaterial = Material.matchMaterial(toolName); Material toolMaterial = Material.matchMaterial(toolName);
if (toolMaterial == null) { if (toolMaterial == null) {
plugin.getLogger().warning("Invalid material name. This item will be skipped. - " + toolName); mcMMO.p.getLogger().warning("Invalid material name. This item will be skipped. - " + toolName);
continue; continue;
} }
@ -78,7 +79,7 @@ public class CustomToolConfig extends ConfigLoader {
Material repairMaterial = Material.matchMaterial(config.getString(toolType + "." + toolName + ".Repair_Material", "")); Material repairMaterial = Material.matchMaterial(config.getString(toolType + "." + toolName + ".Repair_Material", ""));
if (repairable && (repairMaterial == null)) { if (repairable && (repairMaterial == null)) {
plugin.getLogger().warning("Incomplete repair information. This item will be unrepairable. - " + toolName); mcMMO.p.getLogger().warning("Incomplete repair information. This item will be unrepairable. - " + toolName);
repairable = false; repairable = false;
} }

View File

@ -182,7 +182,7 @@ public class RepairConfig extends ConfigLoader {
private boolean noErrorsInRepairable(List<String> issues) { private boolean noErrorsInRepairable(List<String> issues) {
for (String issue : issues) { for (String issue : issues) {
plugin.getLogger().warning(issue); mcMMO.p.getLogger().warning(issue);
} }
return issues.isEmpty(); return issues.isEmpty();

View File

@ -200,12 +200,12 @@ public class SalvageConfig extends ConfigLoader {
private boolean noErrorsInSalvageable(List<String> issues) { private boolean noErrorsInSalvageable(List<String> issues) {
if (!issues.isEmpty()) { if (!issues.isEmpty()) {
plugin.getLogger().warning("Errors have been found in: " + fileName); mcMMO.p.getLogger().warning("Errors have been found in: " + fileName);
plugin.getLogger().warning("The following issues were found:"); mcMMO.p.getLogger().warning("The following issues were found:");
} }
for (String issue : issues) { for (String issue : issues) {
plugin.getLogger().warning(issue); mcMMO.p.getLogger().warning(issue);
} }
return issues.isEmpty(); return issues.isEmpty();

View File

@ -348,7 +348,7 @@ public class FishingTreasureConfig extends ConfigLoader {
Enchantment enchantment = EnchantmentUtils.getByName(enchantmentName); Enchantment enchantment = EnchantmentUtils.getByName(enchantmentName);
if (enchantment == null) { if (enchantment == null) {
plugin.getLogger().warning("Skipping invalid enchantment in " + FILENAME + ": " + enchantmentName); mcMMO.p.getLogger().warning("Skipping invalid enchantment in " + FILENAME + ": " + enchantmentName);
continue; continue;
} }

View File

@ -1,13 +1,13 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.MMODataSnapshot; import com.gmail.nossr50.datatypes.player.MMODataSnapshot;
import com.gmail.nossr50.datatypes.player.PlayerData; import com.gmail.nossr50.datatypes.player.PlayerData;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -17,15 +17,13 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public interface DatabaseManager { public interface DatabaseManager {
// One month in milliseconds
long PURGE_TIME = 2630000000L * Config.getInstance().getOldUsersCutoff();
// During convertUsers, how often to output a status // During convertUsers, how often to output a status
int progressInterval = 200; int progressInterval = 200;
/** /**
* Purge users with 0 power level from the database. * Purge users with 0 power level from the database.
*/ */
void purgePowerlessUsers(); int purgePowerlessUsers();
/** /**
* Purge users who haven't logged on in over a certain time frame from the database. * Purge users who haven't logged on in over a certain time frame from the database.
@ -87,11 +85,11 @@ public interface DatabaseManager {
/** /**
* Add a new user to the database. * Add a new user to the database.
*
* @param playerName The name of the player to be added to the database * @param playerName The name of the player to be added to the database
* @param uuid The uuid of the player to be added to the database * @param uuid The uuid of the player to be added to the database
* @return
*/ */
void newUser(String playerName, UUID uuid); @NotNull PlayerProfile newUser(String playerName, UUID uuid);
@NotNull PlayerProfile newUser(@NotNull Player player); @NotNull PlayerProfile newUser(@NotNull Player player);
@ -104,13 +102,9 @@ public interface DatabaseManager {
*/ */
@NotNull PlayerProfile loadPlayerProfile(@NotNull String playerName); @NotNull PlayerProfile loadPlayerProfile(@NotNull String playerName);
/** @NotNull PlayerProfile loadPlayerProfile(@NotNull OfflinePlayer offlinePlayer);
* Load a player from the database.
* @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid);
* @param uuid The uuid of the player to load from the database
* @return The player's data, or an unloaded PlayerProfile if not found
*/
@NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, @Nullable String playerName);
/** /**
* Get all users currently stored in the database. * Get all users currently stored in the database.

View File

@ -1,13 +1,16 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.logging.Logger;
public class DatabaseManagerFactory { public class DatabaseManagerFactory {
private static Class<? extends DatabaseManager> customManager = null; private static Class<? extends DatabaseManager> customManager = null;
public static DatabaseManager getDatabaseManager() { public static DatabaseManager getDatabaseManager(@NotNull String userFilePath, @NotNull Logger logger, long purgeTime, int startingLevel) {
if (customManager != null) { if (customManager != null) {
try { try {
return createDefaultCustomDatabaseManager(); return createDefaultCustomDatabaseManager();
@ -20,10 +23,10 @@ public class DatabaseManagerFactory {
mcMMO.p.getLogger().info("Failed to create custom database manager"); mcMMO.p.getLogger().info("Failed to create custom database manager");
e.printStackTrace(); e.printStackTrace();
} }
mcMMO.p.getLogger().info("Falling back on " + (Config.getInstance().getUseMySQL() ? "SQL" : "Flatfile") + " database"); mcMMO.p.getLogger().info("Falling back on " + (mcMMO.p.getGeneralConfig().getUseMySQL() ? "SQL" : "Flatfile") + " database");
} }
return Config.getInstance().getUseMySQL() ? new SQLDatabaseManager() : new FlatFileDatabaseManager(); return mcMMO.p.getGeneralConfig().getUseMySQL() ? new SQLDatabaseManager() : new FlatFileDatabaseManager(userFilePath, logger, purgeTime, startingLevel);
} }
/** /**
@ -56,11 +59,11 @@ public class DatabaseManagerFactory {
return customManager; return customManager;
} }
public static DatabaseManager createDatabaseManager(DatabaseType type) { public static @Nullable DatabaseManager createDatabaseManager(@NotNull DatabaseType type, @NotNull String userFilePath, @NotNull Logger logger, long purgeTime, int startingLevel) {
switch (type) { switch (type) {
case FLATFILE: case FLATFILE:
mcMMO.p.getLogger().info("Using FlatFile Database"); mcMMO.p.getLogger().info("Using FlatFile Database");
return new FlatFileDatabaseManager(); return new FlatFileDatabaseManager(userFilePath, logger, purgeTime, startingLevel);
case SQL: case SQL:
mcMMO.p.getLogger().info("Using SQL Database"); mcMMO.p.getLogger().info("Using SQL Database");
@ -80,7 +83,7 @@ public class DatabaseManagerFactory {
} }
} }
public static DatabaseManager createDefaultCustomDatabaseManager() throws Throwable { private static DatabaseManager createDefaultCustomDatabaseManager() throws Throwable {
return customManager.getConstructor().newInstance(); return customManager.getConstructor().newInstance();
} }

View File

@ -0,0 +1,13 @@
package com.gmail.nossr50.database;
public enum ExpectedType {
STRING,
INTEGER,
LONG,
BOOLEAN,
FLOAT,
DOUBLE,
UUID,
IGNORED,
OUT_OF_RANGE
}

View File

@ -0,0 +1,13 @@
package com.gmail.nossr50.database;
public enum FlatFileDataFlag {
INCOMPLETE,
BAD_VALUES,
LAST_LOGIN_SCHEMA_UPGRADE,
MISSING_NAME,
DUPLICATE_NAME,
DUPLICATE_UUID,
BAD_UUID_DATA, //Can be because it is missing, null, or corrupted or some other reason
TOO_INCOMPLETE,
CORRUPTED_OR_UNRECOGNIZABLE,
}

View File

@ -0,0 +1,345 @@
package com.gmail.nossr50.database;
import com.gmail.nossr50.database.flatfile.FlatFileDataBuilder;
import com.gmail.nossr50.database.flatfile.FlatFileDataContainer;
import com.gmail.nossr50.database.flatfile.FlatFileDataUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.logging.Logger;
import static com.gmail.nossr50.database.FlatFileDatabaseManager.*;
public class FlatFileDataProcessor {
private final @NotNull List<FlatFileDataContainer> flatFileDataContainers;
private final @NotNull List<FlatFileDataFlag> flatFileDataFlags;
private final @NotNull Logger logger;
private final HashSet<String> names;
private final HashSet<UUID> uuids;
private int uniqueProcessingID; //TODO: Not being used, should we use it?
boolean corruptDataFound;
public FlatFileDataProcessor(@NotNull Logger logger) {
this.logger = logger;
flatFileDataContainers = new ArrayList<>();
flatFileDataFlags = new ArrayList<>();
names = new HashSet<>();
uuids = new HashSet<>();
uniqueProcessingID = 0;
}
public void processData(@NotNull String lineData) {
assert !lineData.isEmpty();
//Make sure the data line is "correct"
if(lineData.charAt(lineData.length() - 1) != ':') {
// Length checks depend on last rawSplitData being ':'
// We add it here if it is missing
lineData = lineData.concat(":");
}
//Split the data into an array
String[] splitDataLine = lineData.split(":");
FlatFileDataBuilder builder = new FlatFileDataBuilder(splitDataLine, uniqueProcessingID);
uniqueProcessingID++;
boolean[] badDataValues = new boolean[DATA_ENTRY_COUNT];
boolean anyBadData = false;
//This is the minimum size of the split array needed to be considered proper data
if(splitDataLine.length < getMinimumSplitDataLength()) {
//Data is considered junk
if(!corruptDataFound) {
logger.severe("Some corrupt data was found in mcmmo.users and has been repaired, it is possible that some player data has been lost in this process.");
corruptDataFound = true;
}
//Flag as junk (corrupt)
builder.appendFlag(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE);
//TODO: This block here is probably pointless
if(splitDataLine.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever
&& splitDataLine[0] != null && !splitDataLine[0].isEmpty()) {
if(splitDataLine[0].length() <= 16 && splitDataLine[0].length() >= 3) {
logger.severe("Not enough data found to recover corrupted player data for user: "+splitDataLine[0]);
registerData(builder.appendFlag(FlatFileDataFlag.TOO_INCOMPLETE));
return;
}
}
registerData(builder.appendFlag(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE));
return;
}
/*
* Check for duplicate names
*/
boolean invalidUUID = false;
String name = splitDataLine[USERNAME_INDEX];
String strOfUUID = splitDataLine[UUID_INDEX];
if(name.isEmpty()) {
reportBadDataLine("No name found for data", "[MISSING NAME]", lineData);
builder.appendFlag(FlatFileDataFlag.MISSING_NAME);
anyBadData = true;
badDataValues[USERNAME_INDEX] = true;
}
if(strOfUUID.isEmpty() || strOfUUID.equalsIgnoreCase("NULL")) {
invalidUUID = true;
badDataValues[UUID_INDEX] = true;
reportBadDataLine("Empty/null UUID for user", "Empty/null", lineData);
builder.appendFlag(FlatFileDataFlag.BAD_UUID_DATA);
anyBadData = true;
}
UUID uuid = null;
try {
uuid = UUID.fromString(strOfUUID);
} catch (IllegalArgumentException e) {
//UUID does not conform
invalidUUID = true;
badDataValues[UUID_INDEX] = true;
reportBadDataLine("Invalid UUID data found for user", strOfUUID, lineData);
builder.appendFlag(FlatFileDataFlag.BAD_UUID_DATA);
}
//Duplicate UUID is no good, reject them
if(!invalidUUID && uuid != null && uuids.contains(uuid)) {
registerData(builder.appendFlag(FlatFileDataFlag.DUPLICATE_UUID));
return;
}
uuids.add(uuid);
if(names.contains(name)) {
builder.appendFlag(FlatFileDataFlag.DUPLICATE_NAME);
anyBadData = true;
badDataValues[USERNAME_INDEX] = true;
}
if(!name.isEmpty())
names.add(name);
//Make sure the data is up to date schema wise, if it isn't we adjust it to the correct size and flag it for repair
splitDataLine = isDataSchemaUpToDate(splitDataLine, builder, badDataValues);
/*
* After establishing this data has at least an identity we check for bad data
* Bad Value checks
*/
//Check each data for bad values
for(int i = 0; i < DATA_ENTRY_COUNT; i++) {
if(shouldNotBeEmpty(splitDataLine[i], i)) {
if(i == OVERHAUL_LAST_LOGIN) {
builder.appendFlag(FlatFileDataFlag.LAST_LOGIN_SCHEMA_UPGRADE);
}
badDataValues[i] = true;
anyBadData = true;
continue;
}
boolean isCorrectType = isOfExpectedType(splitDataLine[i], getExpectedValueType(i));
if(!isCorrectType) {
anyBadData = true;
badDataValues[i] = true;
}
}
if(anyBadData) {
builder.appendFlag(FlatFileDataFlag.BAD_VALUES);
builder.appendBadDataValues(badDataValues);
}
registerData(builder);
}
public @NotNull String[] isDataSchemaUpToDate(@NotNull String[] splitDataLine, @NotNull FlatFileDataBuilder builder, boolean[] badDataValues) {
assert splitDataLine.length <= DATA_ENTRY_COUNT; //should NEVER be higher
if(splitDataLine.length < DATA_ENTRY_COUNT) {
int oldLength = splitDataLine.length;
splitDataLine = Arrays.copyOf(splitDataLine, DATA_ENTRY_COUNT);
int newLength = splitDataLine.length;
//TODO: Test this
for(int i = oldLength; i < (newLength - 1); i++){
badDataValues[i] = true;
}
builder.appendFlag(FlatFileDataFlag.INCOMPLETE);
builder.setSplitStringData(splitDataLine);
}
return splitDataLine;
}
public boolean shouldNotBeEmpty(@Nullable String data, int index) {
if(getExpectedValueType(index) == ExpectedType.IGNORED) {
return false;
} else {
return data == null || data.isEmpty();
}
}
public boolean isOfExpectedType(@NotNull String data, @NotNull ExpectedType expectedType) {
switch(expectedType) {
case STRING:
return true;
case INTEGER:
try {
Integer.valueOf(data);
return true;
} catch (Exception e) {
return false;
}
case BOOLEAN:
return data.equalsIgnoreCase("true") || data.equalsIgnoreCase("false");
case FLOAT:
try {
Float.valueOf(data);
return true;
} catch (NumberFormatException e) {
return false;
}
case DOUBLE:
try {
Double.valueOf(data);
return true;
} catch (NumberFormatException e) {
return false;
}
case UUID:
try {
UUID.fromString(data);
return true;
} catch (IllegalArgumentException e) {
return false;
}
case OUT_OF_RANGE:
throw new ArrayIndexOutOfBoundsException("Value matched type OUT_OF_RANGE, this should never happen.");
case IGNORED:
default:
return true;
}
}
private void reportBadDataLine(String warning, String context, String dataLine) {
logger.warning("FlatFileDatabaseBuilder Warning: " + warning + " - " + context);
logger.warning("FlatFileDatabaseBuilder: (Line Data) - " + dataLine);
logger.warning("mcMMO will repair this data if automatically (if it is possible).");
}
private int getMinimumSplitDataLength() {
return UUID_INDEX + 1;
}
private void registerData(@NotNull FlatFileDataBuilder builder) {
FlatFileDataContainer flatFileDataContainer = builder.build();
flatFileDataContainers.add(flatFileDataContainer);
if(flatFileDataContainer.getDataFlags() != null)
flatFileDataFlags.addAll(flatFileDataContainer.getDataFlags());
}
public static @NotNull ExpectedType getExpectedValueType(int dataIndex) throws IndexOutOfBoundsException {
switch(dataIndex) {
case USERNAME_INDEX:
return ExpectedType.STRING;
case 2: //Assumption: Used to be for something, no longer used
case 3: //Assumption: Used to be for something, no longer used
case 23: //Assumption: Used to be used for something, no longer used
case 33: //Assumption: Used to be used for something, no longer used
case HEALTHBAR:
case LEGACY_LAST_LOGIN:
return ExpectedType.IGNORED;
case SKILLS_MINING:
case SKILLS_REPAIR:
case SKILLS_UNARMED:
case SKILLS_HERBALISM:
case SKILLS_EXCAVATION:
case SKILLS_ARCHERY:
case SKILLS_SWORDS:
case SKILLS_AXES:
case SKILLS_WOODCUTTING:
case SKILLS_ACROBATICS:
case SKILLS_TAMING:
case SKILLS_FISHING:
case SKILLS_ALCHEMY:
case COOLDOWN_BERSERK:
case COOLDOWN_GIGA_DRILL_BREAKER:
case COOLDOWN_TREE_FELLER:
case COOLDOWN_GREEN_TERRA:
case COOLDOWN_SERRATED_STRIKES:
case COOLDOWN_SKULL_SPLITTER:
case COOLDOWN_SUPER_BREAKER:
case COOLDOWN_BLAST_MINING:
case SCOREBOARD_TIPS:
case COOLDOWN_CHIMAERA_WING:
return ExpectedType.INTEGER;
case EXP_MINING:
case EXP_WOODCUTTING:
case EXP_REPAIR:
case EXP_UNARMED:
case EXP_HERBALISM:
case EXP_EXCAVATION:
case EXP_ARCHERY:
case EXP_SWORDS:
case EXP_AXES:
case EXP_ACROBATICS:
case EXP_TAMING:
case EXP_FISHING:
case EXP_ALCHEMY:
return ExpectedType.FLOAT;
case UUID_INDEX:
return ExpectedType.UUID;
case OVERHAUL_LAST_LOGIN:
return ExpectedType.LONG;
}
throw new IndexOutOfBoundsException();
}
public @NotNull List<FlatFileDataContainer> getFlatFileDataContainers() {
return flatFileDataContainers;
}
public @NotNull List<FlatFileDataFlag> getFlatFileDataFlags() {
return flatFileDataFlags;
}
public int getDataFlagCount() {
return flatFileDataFlags.size();
}
public @NotNull StringBuilder processDataForSave() {
StringBuilder stringBuilder = new StringBuilder();
//Fix our data if needed and prepare it to be saved
for(FlatFileDataContainer dataContainer : flatFileDataContainers) {
String[] splitData = FlatFileDataUtil.getPreparedSaveDataLine(dataContainer);
if(splitData == null)
continue;
//We add a trailing : as it is needed for some reason (is it?)
//TODO: Is the trailing ":" actually necessary?
String fromSplit = org.apache.commons.lang.StringUtils.join(splitData, ":") + ":";
stringBuilder.append(fromSplit).append("\r\n");
}
return stringBuilder;
}
}

View File

@ -13,6 +13,7 @@ import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask; import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
import com.neetgames.mcmmo.MobHealthBarType; import com.neetgames.mcmmo.MobHealthBarType;
import com.neetgames.mcmmo.UniqueDataType; import com.neetgames.mcmmo.UniqueDataType;
@ -21,6 +22,7 @@ import com.neetgames.mcmmo.exceptions.InvalidSkillException;
import com.neetgames.mcmmo.skill.SkillBossBarState; import com.neetgames.mcmmo.skill.SkillBossBarState;
import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties; import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -35,7 +37,9 @@ public final class SQLDatabaseManager implements DatabaseManager {
public static final String MOBHEALTHBAR_VARCHAR = "VARCHAR(50)"; public static final String MOBHEALTHBAR_VARCHAR = "VARCHAR(50)";
public static final String UUID_VARCHAR = "VARCHAR(36)"; public static final String UUID_VARCHAR = "VARCHAR(36)";
public static final String USER_VARCHAR = "VARCHAR(40)"; public static final String USER_VARCHAR = "VARCHAR(40)";
private final String tablePrefix = Config.getInstance().getMySQLTablePrefix(); public static final int CHILD_SKILLS_SIZE = 2;
public static final String LEGACY_DRIVER_PATH = "com.mysql.jdbc.Driver";
private final String tablePrefix = mcMMO.p.getGeneralConfig().getMySQLTablePrefix();
private final Map<UUID, Integer> cachedUserIDs = new HashMap<>(); private final Map<UUID, Integer> cachedUserIDs = new HashMap<>();
@ -48,12 +52,13 @@ public final class SQLDatabaseManager implements DatabaseManager {
private final ReentrantLock massUpdateLock = new ReentrantLock(); private final ReentrantLock massUpdateLock = new ReentrantLock();
private final String CHARSET_SQL = "utf8mb4"; //This is compliant with UTF-8 while "utf8" is not, confusing but this is how it is. private final String CHARSET_SQL = "utf8mb4"; //This is compliant with UTF-8 while "utf8" is not, confusing but this is how it is.
private String driverPath = "com.mysql.cj.jdbc.Driver"; //modern driver
protected SQLDatabaseManager() { protected SQLDatabaseManager() {
String connectionString = "jdbc:mysql://" + Config.getInstance().getMySQLServerName() String connectionString = "jdbc:mysql://" + mcMMO.p.getGeneralConfig().getMySQLServerName()
+ ":" + Config.getInstance().getMySQLServerPort() + "/" + Config.getInstance().getMySQLDatabaseName(); + ":" + mcMMO.p.getGeneralConfig().getMySQLServerPort() + "/" + mcMMO.p.getGeneralConfig().getMySQLDatabaseName();
if(Config.getInstance().getMySQLSSL()) if(mcMMO.p.getGeneralConfig().getMySQLSSL())
connectionString += connectionString +=
"?verifyServerCertificate=false"+ "?verifyServerCertificate=false"+
"&useSSL=true"+ "&useSSL=true"+
@ -64,24 +69,29 @@ public final class SQLDatabaseManager implements DatabaseManager {
try { try {
// Force driver to load if not yet loaded // Force driver to load if not yet loaded
Class.forName("com.mysql.jdbc.Driver"); Class.forName(driverPath);
} } catch (ClassNotFoundException e) {
catch (ClassNotFoundException e) { try {
driverPath = LEGACY_DRIVER_PATH; //fall on deprecated path if new path isn't found
Class.forName(driverPath);
} catch (ClassNotFoundException ex) {
e.printStackTrace(); e.printStackTrace();
ex.printStackTrace();
mcMMO.p.getLogger().severe("Neither driver found");
return; return;
}
//throw e; // aborts onEnable() Riking if you want to do this, fully implement it. //throw e; // aborts onEnable() Riking if you want to do this, fully implement it.
} }
debug = Config.getInstance().getMySQLDebug(); debug = mcMMO.p.getGeneralConfig().getMySQLDebug();
PoolProperties poolProperties = new PoolProperties(); PoolProperties poolProperties = new PoolProperties();
poolProperties.setDriverClassName("com.mysql.jdbc.Driver"); poolProperties.setDriverClassName(driverPath);
poolProperties.setUrl(connectionString); poolProperties.setUrl(connectionString);
poolProperties.setUsername(Config.getInstance().getMySQLUserName()); poolProperties.setUsername(mcMMO.p.getGeneralConfig().getMySQLUserName());
poolProperties.setPassword(Config.getInstance().getMySQLUserPassword()); poolProperties.setPassword(mcMMO.p.getGeneralConfig().getMySQLUserPassword());
poolProperties.setMaxIdle(Config.getInstance().getMySQLMaxPoolSize(PoolIdentifier.MISC)); poolProperties.setMaxIdle(mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.MISC));
poolProperties.setMaxActive(Config.getInstance().getMySQLMaxConnections(PoolIdentifier.MISC)); poolProperties.setMaxActive(mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.MISC));
poolProperties.setInitialSize(0); poolProperties.setInitialSize(0);
poolProperties.setMaxWait(-1); poolProperties.setMaxWait(-1);
poolProperties.setRemoveAbandoned(true); poolProperties.setRemoveAbandoned(true);
@ -91,13 +101,13 @@ public final class SQLDatabaseManager implements DatabaseManager {
poolProperties.setValidationInterval(30000); poolProperties.setValidationInterval(30000);
miscPool = new DataSource(poolProperties); miscPool = new DataSource(poolProperties);
poolProperties = new PoolProperties(); poolProperties = new PoolProperties();
poolProperties.setDriverClassName("com.mysql.jdbc.Driver"); poolProperties.setDriverClassName(driverPath);
poolProperties.setUrl(connectionString); poolProperties.setUrl(connectionString);
poolProperties.setUsername(Config.getInstance().getMySQLUserName()); poolProperties.setUsername(mcMMO.p.getGeneralConfig().getMySQLUserName());
poolProperties.setPassword(Config.getInstance().getMySQLUserPassword()); poolProperties.setPassword(mcMMO.p.getGeneralConfig().getMySQLUserPassword());
poolProperties.setInitialSize(0); poolProperties.setInitialSize(0);
poolProperties.setMaxIdle(Config.getInstance().getMySQLMaxPoolSize(PoolIdentifier.SAVE)); poolProperties.setMaxIdle(mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.SAVE));
poolProperties.setMaxActive(Config.getInstance().getMySQLMaxConnections(PoolIdentifier.SAVE)); poolProperties.setMaxActive(mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.SAVE));
poolProperties.setMaxWait(-1); poolProperties.setMaxWait(-1);
poolProperties.setRemoveAbandoned(true); poolProperties.setRemoveAbandoned(true);
poolProperties.setRemoveAbandonedTimeout(60); poolProperties.setRemoveAbandonedTimeout(60);
@ -106,13 +116,13 @@ public final class SQLDatabaseManager implements DatabaseManager {
poolProperties.setValidationInterval(30000); poolProperties.setValidationInterval(30000);
savePool = new DataSource(poolProperties); savePool = new DataSource(poolProperties);
poolProperties = new PoolProperties(); poolProperties = new PoolProperties();
poolProperties.setDriverClassName("com.mysql.jdbc.Driver"); poolProperties.setDriverClassName(driverPath);
poolProperties.setUrl(connectionString); poolProperties.setUrl(connectionString);
poolProperties.setUsername(Config.getInstance().getMySQLUserName()); poolProperties.setUsername(mcMMO.p.getGeneralConfig().getMySQLUserName());
poolProperties.setPassword(Config.getInstance().getMySQLUserPassword()); poolProperties.setPassword(mcMMO.p.getGeneralConfig().getMySQLUserPassword());
poolProperties.setInitialSize(0); poolProperties.setInitialSize(0);
poolProperties.setMaxIdle(Config.getInstance().getMySQLMaxPoolSize(PoolIdentifier.LOAD)); poolProperties.setMaxIdle(mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.LOAD));
poolProperties.setMaxActive(Config.getInstance().getMySQLMaxConnections(PoolIdentifier.LOAD)); poolProperties.setMaxActive(mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.LOAD));
poolProperties.setMaxWait(-1); poolProperties.setMaxWait(-1);
poolProperties.setRemoveAbandoned(true); poolProperties.setRemoveAbandoned(true);
poolProperties.setRemoveAbandonedTimeout(60); poolProperties.setRemoveAbandonedTimeout(60);
@ -124,7 +134,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
checkStructure(); checkStructure();
} }
public void purgePowerlessUsers() { public int purgePowerlessUsers() {
massUpdateLock.lock(); massUpdateLock.lock();
mcMMO.p.getLogger().info("Purging powerless users..."); mcMMO.p.getLogger().info("Purging powerless users...");
@ -157,11 +167,12 @@ public final class SQLDatabaseManager implements DatabaseManager {
} }
mcMMO.p.getLogger().info("Purged " + purged + " users from the database."); mcMMO.p.getLogger().info("Purged " + purged + " users from the database.");
return purged;
} }
public void purgeOldUsers() { public void purgeOldUsers() {
massUpdateLock.lock(); massUpdateLock.lock();
mcMMO.p.getLogger().info("Purging inactive users older than " + (PURGE_TIME / 2630000000L) + " months..."); mcMMO.p.getLogger().info("Purging inactive users older than " + (mcMMO.p.getPurgeTime() / 2630000000L) + " months...");
Connection connection = null; Connection connection = null;
Statement statement = null; Statement statement = null;
@ -176,12 +187,11 @@ public final class SQLDatabaseManager implements DatabaseManager {
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + PURGE_TIME + ")"); "WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + mcMMO.p.getPurgeTime() + ")");
} }
catch (SQLException ex) { catch (SQLException ex) {
printErrors(ex); printErrors(ex);
} } finally {
finally {
tryClose(statement); tryClose(statement);
tryClose(connection); tryClose(connection);
massUpdateLock.unlock(); massUpdateLock.unlock();
@ -279,7 +289,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
statement.setInt(14, dataSnapshot.getSkillLevel(PrimarySkillType.TRIDENTS)); statement.setInt(14, dataSnapshot.getSkillLevel(PrimarySkillType.TRIDENTS));
statement.setInt(15, dataSnapshot.getSkillLevel(PrimarySkillType.CROSSBOWS)); statement.setInt(15, dataSnapshot.getSkillLevel(PrimarySkillType.CROSSBOWS));
int total = 0; int total = 0;
for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills())
total += dataSnapshot.getSkillLevel(primarySkillType); total += dataSnapshot.getSkillLevel(primarySkillType);
statement.setInt(16, total); statement.setInt(16, total);
statement.setInt(17, id); statement.setInt(17, id);
@ -343,7 +353,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
} }
statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?, scoreboardtips = ? WHERE user_id = ?"); statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?, scoreboardtips = ? WHERE user_id = ?");
statement.setString(1, Config.getInstance().getMobHealthbarDefault().name()); statement.setString(1, MobHealthbarType.HEARTS.name());
statement.setInt(2, dataSnapshot.getScoreboardTipsShown()); statement.setInt(2, dataSnapshot.getScoreboardTipsShown());
statement.setInt(3, id); statement.setInt(3, id);
success = (statement.executeUpdate() != 0); success = (statement.executeUpdate() != 0);
@ -416,7 +426,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
List<PlayerStat> stats = new ArrayList<>(); List<PlayerStat> stats = new ArrayList<>();
//Fix for a plugin that people are using that is throwing SQL errors //Fix for a plugin that people are using that is throwing SQL errors
if(primarySkillType != null && PrimarySkillType.isChildSkill(primarySkillType)) { if(primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) {
mcMMO.p.getLogger().severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); mcMMO.p.getLogger().severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!");
throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!");
} }
@ -467,7 +477,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
try { try {
connection = getConnection(PoolIdentifier.MISC); connection = getConnection(PoolIdentifier.MISC);
for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) { for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills()) {
String skillName = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH); String skillName = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH);
// Get count of all users with higher skill level than player // Get count of all users with higher skill level than player
String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " + String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
@ -554,19 +564,19 @@ public final class SQLDatabaseManager implements DatabaseManager {
return skills; return skills;
} }
public void insertNewUser(@NotNull String playerName, @NotNull UUID uuid) { public @NotNull PlayerProfile newUser(String playerName, UUID uuid) {
Connection connection = null; Connection connection = null;
try { try {
connection = getConnection(PoolIdentifier.MISC); connection = getConnection(PoolIdentifier.MISC);
newUser(connection, playerName, uuid); newUser(connection, playerName, uuid);
} } catch (SQLException ex) {
catch (SQLException ex) {
printErrors(ex); printErrors(ex);
} } finally {
finally {
tryClose(connection); tryClose(connection);
} }
return new PlayerProfile(playerName, uuid, true, mcMMO.p.getAdvancedConfig().getStartingLevel());
} }
@Override @Override
@ -576,15 +586,15 @@ public final class SQLDatabaseManager implements DatabaseManager {
int id = newUser(connection, player.getName(), player.getUniqueId()); int id = newUser(connection, player.getName(), player.getUniqueId());
if (id == -1) { if (id == -1) {
return new PlayerProfile(player.getName(), player.getUniqueId(), false); return new PlayerProfile(player.getName(), player.getUniqueId(), false, mcMMO.p.getAdvancedConfig().getStartingLevel());
} else { } else {
return loadPlayerProfile(player.getUniqueId(), player.getName()); return loadPlayerProfile(player);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
return new PlayerProfile(player.getName(), player.getUniqueId(), false); return new PlayerProfile(player.getName(), player.getUniqueId(), false, mcMMO.p.getAdvancedConfig().getStartingLevel());
} }
private int newUser(Connection connection, String playerName, UUID uuid) { private int newUser(Connection connection, String playerName, UUID uuid) {
@ -630,14 +640,25 @@ public final class SQLDatabaseManager implements DatabaseManager {
return loadPlayerFromDB(null, playerName); return loadPlayerFromDB(null, playerName);
} catch (RuntimeException e) { } catch (RuntimeException e) {
e.printStackTrace(); e.printStackTrace();
return new PlayerProfile(playerName, false); return new PlayerProfile(playerName, false, mcMMO.p.getAdvancedConfig().getStartingLevel());
} }
} }
@Override
public @NotNull PlayerProfile loadPlayerProfile(@NotNull OfflinePlayer offlinePlayer) {
return loadPlayerFromDB(offlinePlayer.getUniqueId(), offlinePlayer.getName());
}
public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, @Nullable String playerName) { public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, @Nullable String playerName) {
return loadPlayerFromDB(uuid, playerName); return loadPlayerFromDB(uuid, playerName);
} }
@Override
public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid) {
return loadPlayerFromDB(uuid, null);
}
private PlayerProfile loadPlayerFromDB(@Nullable UUID uuid, @Nullable String playerName) throws RuntimeException { private PlayerProfile loadPlayerFromDB(@Nullable UUID uuid, @Nullable String playerName) throws RuntimeException {
if(uuid == null && playerName == null) { if(uuid == null && playerName == null) {
throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be."); throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be.");
@ -657,7 +678,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
if (id == -1) { if (id == -1) {
// There is no such user // There is no such user
return new PlayerProfile(playerName, false); return new PlayerProfile(playerName, mcMMO.p.getAdvancedConfig().getStartingLevel());
} }
// There is such a user // There is such a user
writeMissingRows(connection, id); writeMissingRows(connection, id);
@ -715,7 +736,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
} }
//Return empty profile //Return empty profile
return new PlayerProfile(playerName, false); return new PlayerProfile(playerName, mcMMO.p.getAdvancedConfig().getStartingLevel());
} }
public void convertUsers(DatabaseManager destination) { public void convertUsers(DatabaseManager destination) {
@ -885,7 +906,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
statement = connection.prepareStatement("SELECT table_name FROM INFORMATION_SCHEMA.TABLES" statement = connection.prepareStatement("SELECT table_name FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE table_schema = ?" + " WHERE table_schema = ?"
+ " AND table_name = ?"); + " AND table_name = ?");
statement.setString(1, Config.getInstance().getMySQLDatabaseName()); statement.setString(1, mcMMO.p.getGeneralConfig().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "users"); statement.setString(2, tablePrefix + "users");
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (!resultSet.next()) { if (!resultSet.next()) {
@ -901,21 +922,21 @@ public final class SQLDatabaseManager implements DatabaseManager {
tryClose(createStatement); tryClose(createStatement);
} }
tryClose(resultSet); tryClose(resultSet);
statement.setString(1, Config.getInstance().getMySQLDatabaseName()); statement.setString(1, mcMMO.p.getGeneralConfig().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "huds"); statement.setString(2, tablePrefix + "huds");
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (!resultSet.next()) { if (!resultSet.next()) {
createStatement = connection.createStatement(); createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` (" createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
+ "`user_id` int(10) unsigned NOT NULL," + "`user_id` int(10) unsigned NOT NULL,"
+ "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "'," + "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + mcMMO.p.getGeneralConfig().getMobHealthbarDefault() + "',"
+ "`scoreboardtips` int(10) NOT NULL DEFAULT '0'," + "`scoreboardtips` int(10) NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) " + "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=" + CHARSET_SQL + ";"); + "DEFAULT CHARSET=" + CHARSET_SQL + ";");
tryClose(createStatement); tryClose(createStatement);
} }
tryClose(resultSet); tryClose(resultSet);
statement.setString(1, Config.getInstance().getMySQLDatabaseName()); statement.setString(1, mcMMO.p.getGeneralConfig().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "cooldowns"); statement.setString(2, tablePrefix + "cooldowns");
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (!resultSet.next()) { if (!resultSet.next()) {
@ -942,10 +963,12 @@ public final class SQLDatabaseManager implements DatabaseManager {
tryClose(createStatement); tryClose(createStatement);
} }
tryClose(resultSet); tryClose(resultSet);
statement.setString(1, Config.getInstance().getMySQLDatabaseName()); statement.setString(1, mcMMO.p.getGeneralConfig().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "skills"); statement.setString(2, tablePrefix + "skills");
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (!resultSet.next()) { if (!resultSet.next()) {
String startingLevel = "'" + mcMMO.p.getAdvancedConfig().getStartingLevel() + "'";
String totalLevel = "'" + (mcMMO.p.getAdvancedConfig().getStartingLevel() * (PrimarySkillType.values().length - CHILD_SKILLS_SIZE)) + "'";
createStatement = connection.createStatement(); createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` (" createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
+ "`user_id` int(10) unsigned NOT NULL," + "`user_id` int(10) unsigned NOT NULL,"
@ -970,7 +993,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
tryClose(createStatement); tryClose(createStatement);
} }
tryClose(resultSet); tryClose(resultSet);
statement.setString(1, Config.getInstance().getMySQLDatabaseName()); statement.setString(1, mcMMO.p.getGeneralConfig().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "experience"); statement.setString(2, tablePrefix + "experience");
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (!resultSet.next()) { if (!resultSet.next()) {
@ -1050,9 +1073,9 @@ public final class SQLDatabaseManager implements DatabaseManager {
checkDatabaseStructure(connection, updateType); checkDatabaseStructure(connection, updateType);
} }
if (Config.getInstance().getTruncateSkills()) { if (mcMMO.p.getGeneralConfig().getTruncateSkills()) {
for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) { for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills()) {
int cap = Config.getInstance().getLevelCap(primarySkillType); int cap = mcMMO.p.getSkillTools().getLevelCap(primarySkillType);
if (cap != Integer.MAX_VALUE) { if (cap != Integer.MAX_VALUE) {
statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `" statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `"
+ primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `" + primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `"
@ -1129,7 +1152,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
break; break;
case ADD_SQL_INDEXES: case ADD_SQL_INDEXES:
checkUpgradeAddSQLIndexes(statement); // checkUpgradeAddSQLIndexes(statement);
break; break;
case ADD_MOB_HEALTHBARS: case ADD_MOB_HEALTHBARS:
@ -1207,7 +1230,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar, scoreboardtips) VALUES (?, ?, ?)"); statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar, scoreboardtips) VALUES (?, ?, ?)");
statement.setInt(1, id); statement.setInt(1, id);
statement.setString(2, Config.getInstance().getMobHealthbarDefault().name()); statement.setString(2, mcMMO.p.getGeneralConfig().getMobHealthbarDefault().name());
statement.setInt(3, 0); statement.setInt(3, 0);
statement.execute(); statement.execute();
statement.close(); statement.close();
@ -1220,15 +1243,12 @@ public final class SQLDatabaseManager implements DatabaseManager {
} }
} }
private @Nullable PlayerData loadFromResult(@NotNull String playerName, @NotNull ResultSet result) throws SQLException { private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException {
MMODataBuilder MMODataBuilder = new MMODataBuilder(); Map<PrimarySkillType, Integer> skills = new EnumMap<PrimarySkillType, Integer>(PrimarySkillType.class); // Skill & Level
Map<PrimarySkillType, Integer> skills = new HashMap<>(); // Skill & Level Map<PrimarySkillType, Float> skillsXp = new EnumMap<PrimarySkillType, Float>(PrimarySkillType.class); // Skill & XP
Map<PrimarySkillType, Float> skillsXp = new HashMap<>(); // Skill & XP Map<SuperAbilityType, Integer> skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown
Map<SuperAbilityType, Integer> skillsDATS = new HashMap<>(); // Ability & Cooldown Map<UniqueDataType, Integer> uniqueData = new EnumMap<>(UniqueDataType.class); //Chimaera wing cooldown and other misc info
Map<UniqueDataType, Integer> uniqueData = new EnumMap<UniqueDataType, Integer>(UniqueDataType.class); //Chimaera wing cooldown and other misc info MobHealthbarType mobHealthbarType;
Map<PrimarySkillType, SkillBossBarState> xpBarStateMap = new HashMap<PrimarySkillType, SkillBossBarState>();
MobHealthBarType mobHealthbarType;
UUID uuid; UUID uuid;
int scoreboardTipsShown; int scoreboardTipsShown;
@ -1291,14 +1311,6 @@ public final class SQLDatabaseManager implements DatabaseManager {
// //
try {
mobHealthbarType = MobHealthBarType.valueOf(result.getString(OFFSET_OTHER + 1));
}
catch (Exception e) {
mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
}
try { try {
scoreboardTipsShown = result.getInt(OFFSET_OTHER + 2); scoreboardTipsShown = result.getInt(OFFSET_OTHER + 2);
} }
@ -1358,6 +1370,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
return null; return null;
} }
return new PlayerProfile(playerName, uuid, skills, skillsXp, skillsDATS, scoreboardTipsShown, uniqueData, null);
} }
private void printErrors(SQLException ex) { private void printErrors(SQLException ex) {
@ -1469,7 +1482,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
} }
catch (SQLException ex) { catch (SQLException ex) {
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars..."); mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "'"); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + mcMMO.p.getGeneralConfig().getMobHealthbarDefault() + "'");
} }
} }
@ -1491,10 +1504,10 @@ public final class SQLDatabaseManager implements DatabaseManager {
resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'"); resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'");
resultSet.last(); resultSet.last();
if (resultSet.getRow() != PrimarySkillType.getNonChildSkills().size()) { if (resultSet.getRow() != SkillTools.getNonChildSkills().size()) {
mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases"); mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) { for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills()) {
String skill_name = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH); String skill_name = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH);
try { try {
@ -1778,7 +1791,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
try { try {
connection = getConnection(PoolIdentifier.MISC); connection = getConnection(PoolIdentifier.MISC);
statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?"); statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?");
statement.setString(1, Config.getInstance().getMobHealthbarDefault().toString()); statement.setString(1, mcMMO.p.getGeneralConfig().getMobHealthbarDefault().toString());
statement.executeUpdate(); statement.executeUpdate();
} }
catch (SQLException ex) { catch (SQLException ex) {

View File

@ -0,0 +1,7 @@
package com.gmail.nossr50.database;
import org.jetbrains.annotations.NotNull;
public interface UserQuery {
@NotNull UserQueryType getType();
}

View File

@ -0,0 +1,31 @@
package com.gmail.nossr50.database;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class UserQueryFull implements UserQueryUUID, UserQueryName {
private final @NotNull String name;
private final @NotNull UUID uuid;
public UserQueryFull(@NotNull String name, @NotNull UUID uuid) {
this.name = name;
this.uuid = uuid;
}
@Override
public @NotNull UserQueryType getType() {
return UserQueryType.UUID_AND_NAME;
}
@Override
public @NotNull String getName() {
return name;
}
@Override
public @NotNull UUID getUUID() {
return uuid;
}
}

View File

@ -0,0 +1,7 @@
package com.gmail.nossr50.database;
import org.jetbrains.annotations.NotNull;
public interface UserQueryName extends UserQuery {
@NotNull String getName();
}

View File

@ -0,0 +1,20 @@
package com.gmail.nossr50.database;
import org.jetbrains.annotations.NotNull;
public class UserQueryNameImpl implements UserQueryName {
private final @NotNull String name;
public UserQueryNameImpl(@NotNull String name) {
this.name = name;
}
@Override
public @NotNull UserQueryType getType() {
return UserQueryType.NAME;
}
public @NotNull String getName() {
return name;
}
}

View File

@ -0,0 +1,7 @@
package com.gmail.nossr50.database;
public enum UserQueryType {
UUID_AND_NAME,
UUID,
NAME
}

View File

@ -0,0 +1,11 @@
package com.gmail.nossr50.database;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public interface UserQueryUUID extends UserQuery {
@NotNull UUID getUUID();
}

View File

@ -0,0 +1,23 @@
package com.gmail.nossr50.database;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class UserQueryUUIDImpl implements UserQueryUUID {
private final @NotNull UUID uuid;
public UserQueryUUIDImpl(@NotNull UUID uuid) {
this.uuid = uuid;
}
@Override
public @NotNull UserQueryType getType() {
return UserQueryType.UUID;
}
@Override
public @NotNull UUID getUUID() {
return uuid;
}
}

View File

@ -0,0 +1,42 @@
package com.gmail.nossr50.database.flatfile;
import com.gmail.nossr50.database.FlatFileDataFlag;
import com.google.common.base.Objects;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.HashSet;
public class BadCategorizedFlatFileData extends CategorizedFlatFileData {
private final boolean[] badDataIndexes;
protected BadCategorizedFlatFileData(int uniqueProcessingId, @NotNull HashSet<FlatFileDataFlag> dataFlags, @NotNull String[] splitData, boolean[] badDataIndexes) {
super(uniqueProcessingId, dataFlags, splitData);
this.badDataIndexes = badDataIndexes;
}
public boolean[] getBadDataIndexes() {
return badDataIndexes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
BadCategorizedFlatFileData that = (BadCategorizedFlatFileData) o;
return Objects.equal(badDataIndexes, that.badDataIndexes);
}
@Override
public int hashCode() {
return Objects.hashCode(super.hashCode(), badDataIndexes);
}
@Override
public String toString() {
return "BadCategorizedFlatFileData{" +
"badDataIndexes=" + Arrays.toString(badDataIndexes) +
'}';
}
}

View File

@ -0,0 +1,58 @@
package com.gmail.nossr50.database.flatfile;
import com.gmail.nossr50.database.FlatFileDataFlag;
import com.google.common.base.Objects;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
public class CategorizedFlatFileData implements FlatFileDataContainer {
private final @NotNull Set<FlatFileDataFlag> dataFlags;
private final @NotNull String[] splitData;
private final int uniqueProcessingId;
public CategorizedFlatFileData(int uniqueProcessingId, @NotNull HashSet<FlatFileDataFlag> dataFlags, @NotNull String[] splitData) {
this.uniqueProcessingId = uniqueProcessingId;
this.dataFlags = dataFlags;
this.splitData = splitData;
}
public @NotNull Set<FlatFileDataFlag> getDataFlags() {
return dataFlags;
}
public @NotNull String[] getSplitData() {
return splitData;
}
public int getUniqueProcessingId() {
return uniqueProcessingId;
}
public boolean isHealthyData() {
return dataFlags.size() == 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CategorizedFlatFileData that = (CategorizedFlatFileData) o;
return uniqueProcessingId == that.uniqueProcessingId && Objects.equal(dataFlags, that.dataFlags) && Objects.equal(splitData, that.splitData);
}
@Override
public int hashCode() {
return Objects.hashCode(dataFlags, splitData, uniqueProcessingId);
}
@Override
public String toString() {
return "CategorizedFlatFileData{" +
"dataFlags=" + dataFlags +
", stringDataRepresentation='" + splitData + '\'' +
", uniqueProcessingId=" + uniqueProcessingId +
'}';
}
}

View File

@ -0,0 +1,42 @@
package com.gmail.nossr50.database.flatfile;
import com.gmail.nossr50.database.FlatFileDataFlag;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
public class FlatFileDataBuilder {
private final @NotNull HashSet<FlatFileDataFlag> dataFlags;
private @NotNull String[] splitStringData;
private final int uniqueProcessingId;
private boolean[] badDataValues;
public FlatFileDataBuilder(@NotNull String[] splitStringData, int uniqueProcessingId) {
this.uniqueProcessingId = uniqueProcessingId;
this.splitStringData = splitStringData;
dataFlags = new HashSet<>();
}
public @NotNull FlatFileDataBuilder appendFlag(@NotNull FlatFileDataFlag dataFlag) {
dataFlags.add(dataFlag);
return this;
}
public @NotNull FlatFileDataBuilder appendBadDataValues(boolean[] badDataValues) {
this.badDataValues = badDataValues;
return this;
}
public @NotNull FlatFileDataContainer build() {
if(dataFlags.contains(FlatFileDataFlag.BAD_VALUES)) {
return new BadCategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData, badDataValues);
}
return new CategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData);
}
public @NotNull FlatFileDataBuilder setSplitStringData(@NotNull String[] splitStringData) {
this.splitStringData = splitStringData;
return this;
}
}

View File

@ -0,0 +1,21 @@
package com.gmail.nossr50.database.flatfile;
import com.gmail.nossr50.database.FlatFileDataFlag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public interface FlatFileDataContainer {
default @Nullable Set<FlatFileDataFlag> getDataFlags() {
return null;
}
@NotNull String[] getSplitData();
int getUniqueProcessingId();
default boolean isHealthyData() {
return getDataFlags() == null || getDataFlags().size() == 0;
}
}

View File

@ -0,0 +1,116 @@
package com.gmail.nossr50.database.flatfile;
import com.gmail.nossr50.database.FlatFileDataFlag;
import com.gmail.nossr50.database.FlatFileDatabaseManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.gmail.nossr50.database.FlatFileDatabaseManager.*;
public class FlatFileDataUtil {
public static @Nullable String[] getPreparedSaveDataLine(@NotNull FlatFileDataContainer dataContainer) {
if(dataContainer.getDataFlags() == null) {
return dataContainer.getSplitData();
}
//Data of this type is not salvageable
//TODO: Test that we ignore the things we are supposed to ignore
//TODO: Should we even keep track of the bad data or just not even build data containers for it? Making containers for it is only really useful for debugging.. well I suppose operations are typically async so it shouldn't matter
if(dataContainer.getDataFlags().contains(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE)
|| dataContainer.getDataFlags().contains(FlatFileDataFlag.DUPLICATE_UUID) //For now we will not try to fix any issues with UUIDs
|| dataContainer.getDataFlags().contains(FlatFileDataFlag.BAD_UUID_DATA) //For now we will not try to fix any issues with UUIDs
|| dataContainer.getDataFlags().contains(FlatFileDataFlag.TOO_INCOMPLETE)) {
return null;
}
String[] splitData;
/*
* First fix the bad data values if they exist
*/
if(dataContainer instanceof BadCategorizedFlatFileData) {
BadCategorizedFlatFileData badData = (BadCategorizedFlatFileData) dataContainer;
splitData = repairBadData(dataContainer.getSplitData(), badData.getBadDataIndexes());
} else {
splitData = dataContainer.getSplitData();
}
//Make sure we have as many values as we are supposed to
assert splitData.length == FlatFileDatabaseManager.DATA_ENTRY_COUNT;
return splitData;
}
public static @NotNull String[] repairBadData(@NotNull String[] splitData, boolean[] badDataValues) {
for(int i = 0; i < FlatFileDatabaseManager.DATA_ENTRY_COUNT; i++) {
if(badDataValues[i]) {
//This data value was marked as bad so we zero initialize it
splitData[i] = getZeroInitialisedData(i, 0);
}
}
return splitData;
}
/**
* @param index "zero" Initialization will depend on what the index is for
* @return the "zero" initialized data corresponding to the index
*/
public static @NotNull String getZeroInitialisedData(int index, int startingLevel) throws IndexOutOfBoundsException {
switch(index) {
case USERNAME_INDEX:
return LEGACY_INVALID_OLD_USERNAME; //We'll keep using this value for legacy compatibility reasons (not sure if needed but don't care)
case 2: //Assumption: Used to be for something, no longer used
case 3: //Assumption: Used to be for something, no longer used
case 23: //Assumption: Used to be used for something, no longer used
case 33: //Assumption: Used to be used for something, no longer used
case LEGACY_LAST_LOGIN:
case HEALTHBAR:
return "IGNORED";
case SKILLS_MINING:
case SKILLS_REPAIR:
case SKILLS_UNARMED:
case SKILLS_HERBALISM:
case SKILLS_EXCAVATION:
case SKILLS_ARCHERY:
case SKILLS_SWORDS:
case SKILLS_AXES:
case SKILLS_WOODCUTTING:
case SKILLS_ACROBATICS:
case SKILLS_TAMING:
case SKILLS_FISHING:
case SKILLS_ALCHEMY:
return String.valueOf(startingLevel);
case OVERHAUL_LAST_LOGIN:
return String.valueOf(-1L);
case COOLDOWN_BERSERK:
case COOLDOWN_GIGA_DRILL_BREAKER:
case COOLDOWN_TREE_FELLER:
case COOLDOWN_GREEN_TERRA:
case COOLDOWN_SERRATED_STRIKES:
case COOLDOWN_SKULL_SPLITTER:
case COOLDOWN_SUPER_BREAKER:
case COOLDOWN_BLAST_MINING:
case SCOREBOARD_TIPS:
case COOLDOWN_CHIMAERA_WING:
case EXP_MINING:
case EXP_WOODCUTTING:
case EXP_REPAIR:
case EXP_UNARMED:
case EXP_HERBALISM:
case EXP_EXCAVATION:
case EXP_ARCHERY:
case EXP_SWORDS:
case EXP_AXES:
case EXP_ACROBATICS:
case EXP_TAMING:
case EXP_FISHING:
case EXP_ALCHEMY:
return "0";
case UUID_INDEX:
throw new IndexOutOfBoundsException(); //TODO: Add UUID recovery? Might not even be worth it.
}
throw new IndexOutOfBoundsException();
}
}

View File

@ -0,0 +1,7 @@
package com.gmail.nossr50.database.flatfile;
public enum LeaderboardStatus {
TOO_SOON_TO_UPDATE,
UPDATED,
FAILED
}

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.datatypes; package com.gmail.nossr50.datatypes;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@ -42,7 +41,7 @@ public class LevelUpBroadcastPredicate<T extends CommandSender> implements Predi
Player listeningPlayer = (Player) t; Player listeningPlayer = (Player) t;
//Party Member Check //Party Member Check
if(Config.getInstance().isLevelUpBroadcastsPartyMembersOnly()) { if(mcMMO.p.getGeneralConfig().isLevelUpBroadcastsPartyMembersOnly()) {
McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer); McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer);
if(mmoListeningPlayer == null) { if(mmoListeningPlayer == null) {
@ -68,8 +67,8 @@ public class LevelUpBroadcastPredicate<T extends CommandSender> implements Predi
} }
//Distance checks //Distance checks
if(Config.getInstance().shouldLevelUpBroadcastsRestrictDistance()) { if(mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastsRestrictDistance()) {
if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), Config.getInstance().getLevelUpBroadcastRadius())) { if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) {
return false; return false;
} }
} }
@ -83,12 +82,12 @@ public class LevelUpBroadcastPredicate<T extends CommandSender> implements Predi
return true; return true;
} else { } else {
//Send out to console //Send out to console
return Config.getInstance().shouldLevelUpBroadcastToConsole(); return mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastToConsole();
} }
} }
private static boolean isLevelUpBroadcastsSameWorldOnly() { private static boolean isLevelUpBroadcastsSameWorldOnly() {
return Config.getInstance().isLevelUpBroadcastsSameWorldOnly(); return mcMMO.p.getGeneralConfig().isLevelUpBroadcastsSameWorldOnly();
} }
@Override @Override

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.datatypes; package com.gmail.nossr50.datatypes;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@ -42,7 +41,7 @@ public class PowerLevelUpBroadcastPredicate<T extends CommandSender> implements
Player listeningPlayer = (Player) t; Player listeningPlayer = (Player) t;
//Party Member Check //Party Member Check
if(Config.getInstance().isPowerLevelUpBroadcastsPartyMembersOnly()) { if(mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsPartyMembersOnly()) {
McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer); McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer);
if(mmoListeningPlayer == null) { if(mmoListeningPlayer == null) {
@ -68,8 +67,8 @@ public class PowerLevelUpBroadcastPredicate<T extends CommandSender> implements
} }
//Distance checks //Distance checks
if(Config.getInstance().shouldPowerLevelUpBroadcastsRestrictDistance()) { if(mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastsRestrictDistance()) {
if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), Config.getInstance().getPowerLevelUpBroadcastRadius())) { if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) {
return false; return false;
} }
} }
@ -83,12 +82,12 @@ public class PowerLevelUpBroadcastPredicate<T extends CommandSender> implements
return true; return true;
} else { } else {
//Send out to console //Send out to console
return Config.getInstance().shouldPowerLevelUpBroadcastToConsole(); return mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastToConsole();
} }
} }
private static boolean isPowerLevelUpBroadcastsSameWorldOnly() { private static boolean isPowerLevelUpBroadcastsSameWorldOnly() {
return Config.getInstance().isPowerLevelUpBroadcastsSameWorldOnly(); return mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsSameWorldOnly();
} }
@Override @Override

View File

@ -0,0 +1,422 @@
package com.gmail.nossr50.datatypes.party;
import com.gmail.nossr50.chat.SamePartyPredicate;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.sounds.SoundManager;
import com.gmail.nossr50.util.sounds.SoundType;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;
public class Party {
private final @NotNull Predicate<CommandSender> samePartyPredicate;
private final LinkedHashMap<UUID, String> members = new LinkedHashMap<>();
private final List<Player> onlineMembers = new ArrayList<>();
private PartyLeader leader;
private String name;
private String password;
private boolean locked;
private Party ally;
private int level;
private float xp;
private ShareMode xpShareMode = ShareMode.NONE;
private ShareMode itemShareMode = ShareMode.NONE;
private boolean shareLootDrops = true;
private boolean shareMiningDrops = true;
private boolean shareHerbalismDrops = true;
private boolean shareWoodcuttingDrops = true;
private boolean shareMiscDrops = true;
public Party(String name) {
this.name = name;
samePartyPredicate = new SamePartyPredicate<>(this);
}
public Party(PartyLeader leader, String name) {
this.leader = leader;
this.name = name;
this.locked = true;
this.level = 0;
samePartyPredicate = new SamePartyPredicate<>(this);
}
public Party(PartyLeader leader, String name, String password) {
this.leader = leader;
this.name = name;
this.password = password;
this.locked = true;
this.level = 0;
samePartyPredicate = new SamePartyPredicate<>(this);
}
public Party(PartyLeader leader, String name, String password, boolean locked) {
this.leader = leader;
this.name = name;
this.password = password;
this.locked = locked;
this.level = 0;
samePartyPredicate = new SamePartyPredicate<>(this);
}
public LinkedHashMap<UUID, String> getMembers() {
return members;
}
public List<Player> getOnlineMembers() {
return onlineMembers;
}
public List<Player> getVisibleMembers(Player player)
{
ArrayList<Player> visibleMembers = new ArrayList<>();
for(Player p : onlineMembers)
{
if(player.canSee(p))
visibleMembers.add(p);
}
return visibleMembers;
}
public List<String> getOnlinePlayerNames(CommandSender sender) {
Player player = sender instanceof Player ? (Player) sender : null;
List<String> onlinePlayerNames = new ArrayList<>();
for (Player onlinePlayer : getOnlineMembers()) {
if (player != null && player.canSee(onlinePlayer)) {
onlinePlayerNames.add(onlinePlayer.getName());
}
}
return onlinePlayerNames;
}
public boolean addOnlineMember(Player player) {
return onlineMembers.add(player);
}
public boolean removeOnlineMember(Player player) {
return onlineMembers.remove(player);
}
public String getName() {
return name;
}
public PartyLeader getLeader() {
return leader;
}
public String getPassword() {
return password;
}
public boolean isLocked() {
return locked;
}
public Party getAlly() {
return ally;
}
public List<String> getItemShareCategories() {
List<String> shareCategories = new ArrayList<>();
for (ItemShareType shareType : ItemShareType.values()) {
if (sharingDrops(shareType)) {
shareCategories.add(shareType.getLocaleString());
}
}
return shareCategories;
}
public void setName(String name) {
this.name = name;
}
public void setLeader(PartyLeader leader) {
this.leader = leader;
}
public void setPassword(String password) {
this.password = password;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public void setAlly(Party ally) {
this.ally = ally;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public float getXp() {
return xp;
}
public void setXp(float xp) {
this.xp = xp;
}
public void addXp(float xp) {
setXp(getXp() + xp);
}
protected float levelUp() {
float xpRemoved = getXpToLevel();
setLevel(getLevel() + 1);
setXp(getXp() - xpRemoved);
return xpRemoved;
}
public int getXpToLevel() {
FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType();
return (mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType)) * (getOnlineMembers().size() + mcMMO.p.getGeneralConfig().getPartyXpCurveMultiplier());
}
public String getXpToLevelPercentage() {
DecimalFormat percent = new DecimalFormat("##0.00%");
return percent.format(this.getXp() / getXpToLevel());
}
/**
* Applies an experience gain
*
* @param xp Experience amount to add
*/
public void applyXpGain(float xp) {
if (!EventUtils.handlePartyXpGainEvent(this, xp)) {
return;
}
if (getXp() < getXpToLevel()) {
return;
}
int levelsGained = 0;
float xpRemoved = 0;
while (getXp() >= getXpToLevel()) {
if (hasReachedLevelCap()) {
setXp(0);
return;
}
xpRemoved += levelUp();
levelsGained++;
}
if (!EventUtils.handlePartyLevelChangeEvent(this, levelsGained, xpRemoved)) {
return;
}
if (!mcMMO.p.getGeneralConfig().getPartyInformAllMembers()) {
Player leader = mcMMO.p.getServer().getPlayer(this.leader.getUniqueId());
if (leader != null) {
leader.sendMessage(LocaleLoader.getString("Party.LevelUp", levelsGained, getLevel()));
if (mcMMO.p.getGeneralConfig().getLevelUpSoundsEnabled()) {
SoundManager.sendSound(leader, leader.getLocation(), SoundType.LEVEL_UP);
}
}
return;
}
PartyManager.informPartyMembersLevelUp(this, levelsGained, getLevel());
}
public boolean hasReachedLevelCap() {
return mcMMO.p.getGeneralConfig().getPartyLevelCap() < getLevel() + 1;
}
public void setXpShareMode(ShareMode xpShareMode) {
this.xpShareMode = xpShareMode;
}
public ShareMode getXpShareMode() {
return xpShareMode;
}
public void setItemShareMode(ShareMode itemShareMode) {
this.itemShareMode = itemShareMode;
}
public ShareMode getItemShareMode() {
return itemShareMode;
}
public boolean sharingDrops(ItemShareType shareType) {
switch (shareType) {
case HERBALISM:
return shareHerbalismDrops;
case LOOT:
return shareLootDrops;
case MINING:
return shareMiningDrops;
case MISC:
return shareMiscDrops;
case WOODCUTTING:
return shareWoodcuttingDrops;
default:
return false;
}
}
public void setSharingDrops(ItemShareType shareType, boolean enabled) {
switch (shareType) {
case HERBALISM:
shareHerbalismDrops = enabled;
break;
case LOOT:
shareLootDrops = enabled;
break;
case MINING:
shareMiningDrops = enabled;
break;
case MISC:
shareMiscDrops = enabled;
break;
case WOODCUTTING:
shareWoodcuttingDrops = enabled;
break;
default:
}
}
public boolean hasMember(String memberName) {
return this.getMembers().containsValue(memberName);
}
public boolean hasMember(UUID uuid) {
return this.getMembers().containsKey(uuid);
}
/**
* Makes a formatted list of party members based on the perspective of a target player
* Players that are hidden will be shown as offline (formatted in the same way)
* Party leader will be formatted a specific way as well
* @param player target player to use as POV
* @return formatted list of party members from the POV of a player
*/
public String createMembersList(Player player) {
StringBuilder memberList = new StringBuilder();
List<String> coloredNames = new ArrayList<>();
for(UUID playerUUID : members.keySet()) {
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerUUID);
if(offlinePlayer.isOnline() && player.canSee((Player) offlinePlayer)) {
ChatColor onlineColor = leader.getUniqueId().equals(playerUUID) ? ChatColor.GOLD : ChatColor.GREEN;
coloredNames.add(onlineColor + offlinePlayer.getName());
} else {
coloredNames.add(ChatColor.DARK_GRAY + members.get(playerUUID));
}
}
buildChatMessage(memberList, coloredNames.toArray(new String[0]));
return memberList.toString();
}
private void buildChatMessage(@NotNull StringBuilder stringBuilder, String @NotNull [] names) {
for(int i = 0; i < names.length; i++) {
if(i + 1 >= names.length) {
stringBuilder
.append(names[i]);
} else {
stringBuilder
.append(names[i])
.append(" ");
}
}
}
/**
* Get the near party members.
*
* @param mcMMOPlayer The player to check
* @return the near party members
*/
public List<Player> getNearMembers(McMMOPlayer mcMMOPlayer) {
List<Player> nearMembers = new ArrayList<>();
Party party = mcMMOPlayer.getParty();
if (party != null) {
Player player = mcMMOPlayer.getPlayer();
double range = mcMMO.p.getGeneralConfig().getPartyShareRange();
for (Player member : party.getOnlineMembers()) {
if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), member.getLocation(), range)) {
nearMembers.add(member);
}
}
}
return nearMembers;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Party)) {
return false;
}
Party other = (Party) obj;
if ((this.getName() == null) || (other.getName() == null)) {
return false;
}
return this.getName().equals(other.getName());
}
public @NotNull Predicate<CommandSender> getSamePartyPredicate() {
return samePartyPredicate;
}
}

View File

@ -1,257 +1,251 @@
package com.gmail.nossr50.datatypes.skills; package com.gmail.nossr50.datatypes.skills;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.GeneralConfig;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager;
import com.gmail.nossr50.skills.alchemy.AlchemyManager;
import com.gmail.nossr50.skills.archery.ArcheryManager;
import com.gmail.nossr50.skills.axes.AxesManager;
import com.gmail.nossr50.skills.crossbows.CrossbowsManager;
import com.gmail.nossr50.skills.excavation.ExcavationManager;
import com.gmail.nossr50.skills.fishing.FishingManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager;
import com.gmail.nossr50.skills.mining.MiningManager;
import com.gmail.nossr50.skills.repair.RepairManager;
import com.gmail.nossr50.skills.salvage.SalvageManager;
import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.skills.swords.SwordsManager;
import com.gmail.nossr50.skills.taming.TamingManager;
import com.gmail.nossr50.skills.tridents.TridentsManager;
import com.gmail.nossr50.skills.unarmed.UnarmedManager;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.util.text.StringUtils;
import com.google.common.collect.ImmutableList;
import com.neetgames.mcmmo.skill.CorePrimarySkillType;
import org.bukkit.Color;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
public enum PrimarySkillType { public enum PrimarySkillType {
ACROBATICS(AcrobaticsManager.class, Color.WHITE, ACROBATICS,
ImmutableList.of(SubSkillType.ACROBATICS_DODGE, SubSkillType.ACROBATICS_ROLL)), ALCHEMY,
ALCHEMY(AlchemyManager.class, Color.FUCHSIA, ARCHERY,
ImmutableList.of(SubSkillType.ALCHEMY_CATALYSIS, SubSkillType.ALCHEMY_CONCOCTIONS)), AXES,
ARCHERY(ArcheryManager.class, Color.MAROON, EXCAVATION,
ImmutableList.of(SubSkillType.ARCHERY_DAZE, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, SubSkillType.ARCHERY_ARROW_RETRIEVAL, SubSkillType.ARCHERY_SKILL_SHOT)), FISHING,
AXES(AxesManager.class, Color.AQUA, SuperAbilityType.SKULL_SPLITTER, HERBALISM,
ImmutableList.of(SubSkillType.AXES_SKULL_SPLITTER, SubSkillType.AXES_AXES_LIMIT_BREAK, SubSkillType.AXES_ARMOR_IMPACT, SubSkillType.AXES_AXE_MASTERY, SubSkillType.AXES_CRITICAL_STRIKES, SubSkillType.AXES_GREATER_IMPACT)), MINING,
EXCAVATION(ExcavationManager.class, Color.fromRGB(139, 69, 19), SuperAbilityType.GIGA_DRILL_BREAKER, REPAIR,
ImmutableList.of(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, SubSkillType.EXCAVATION_ARCHAEOLOGY)), SALVAGE,
FISHING(FishingManager.class, Color.NAVY, SMELTING,
ImmutableList.of(SubSkillType.FISHING_FISHERMANS_DIET, SubSkillType.FISHING_TREASURE_HUNTER, SubSkillType.FISHING_ICE_FISHING, SubSkillType.FISHING_MAGIC_HUNTER, SubSkillType.FISHING_MASTER_ANGLER, SubSkillType.FISHING_SHAKE)), SWORDS,
HERBALISM(HerbalismManager.class, Color.GREEN, SuperAbilityType.GREEN_TERRA, TAMING,
ImmutableList.of(SubSkillType.HERBALISM_GREEN_TERRA, SubSkillType.HERBALISM_FARMERS_DIET, SubSkillType.HERBALISM_GREEN_THUMB, SubSkillType.HERBALISM_DOUBLE_DROPS, SubSkillType.HERBALISM_HYLIAN_LUCK, SubSkillType.HERBALISM_SHROOM_THUMB)), UNARMED,
MINING(MiningManager.class, Color.GRAY, SuperAbilityType.SUPER_BREAKER, WOODCUTTING;
ImmutableList.of(SubSkillType.MINING_SUPER_BREAKER, SubSkillType.MINING_DEMOLITIONS_EXPERTISE, SubSkillType.MINING_BIGGER_BOMBS, SubSkillType.MINING_BLAST_MINING, SubSkillType.MINING_DOUBLE_DROPS)), // boolean issueWarning = true;
REPAIR(RepairManager.class, Color.SILVER,
ImmutableList.of(SubSkillType.REPAIR_ARCANE_FORGING, SubSkillType.REPAIR_REPAIR_MASTERY, SubSkillType.REPAIR_SUPER_REPAIR)),
SALVAGE(SalvageManager.class, Color.ORANGE,
ImmutableList.of(SubSkillType.SALVAGE_SCRAP_COLLECTOR, SubSkillType.SALVAGE_ARCANE_SALVAGE)),
SMELTING(SmeltingManager.class, Color.YELLOW,
ImmutableList.of(SubSkillType.SMELTING_UNDERSTANDING_THE_ART, /*SubSkillType.SMELTING_FLUX_MINING,*/ SubSkillType.SMELTING_FUEL_EFFICIENCY, SubSkillType.SMELTING_SECOND_SMELT)),
SWORDS(SwordsManager.class, Color.fromRGB(178, 34, 34), SuperAbilityType.SERRATED_STRIKES,
ImmutableList.of(SubSkillType.SWORDS_SERRATED_STRIKES, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, SubSkillType.SWORDS_STAB, SubSkillType.SWORDS_RUPTURE, SubSkillType.SWORDS_COUNTER_ATTACK)),
TAMING(TamingManager.class, Color.PURPLE,
ImmutableList.of(SubSkillType.TAMING_BEAST_LORE, SubSkillType.TAMING_CALL_OF_THE_WILD, SubSkillType.TAMING_ENVIRONMENTALLY_AWARE, SubSkillType.TAMING_FAST_FOOD_SERVICE, SubSkillType.TAMING_GORE, SubSkillType.TAMING_HOLY_HOUND, SubSkillType.TAMING_SHARPENED_CLAWS, SubSkillType.TAMING_SHOCK_PROOF, SubSkillType.TAMING_THICK_FUR, SubSkillType.TAMING_PUMMEL)),
UNARMED(UnarmedManager.class, Color.BLACK, SuperAbilityType.BERSERK,
ImmutableList.of(SubSkillType.UNARMED_BERSERK, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, SubSkillType.UNARMED_BLOCK_CRACKER, SubSkillType.UNARMED_ARROW_DEFLECT, SubSkillType.UNARMED_DISARM, SubSkillType.UNARMED_STEEL_ARM_STYLE, SubSkillType.UNARMED_IRON_GRIP)),
WOODCUTTING(WoodcuttingManager.class, Color.OLIVE, SuperAbilityType.TREE_FELLER,
ImmutableList.of(SubSkillType.WOODCUTTING_LEAF_BLOWER, SubSkillType.WOODCUTTING_TREE_FELLER, SubSkillType.WOODCUTTING_HARVEST_LUMBER, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)),
TRIDENTS(TridentsManager.class, Color.TEAL, ImmutableList.of(SubSkillType.TRIDENTS_MULTI_TASKING, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)),
CROSSBOWS(CrossbowsManager.class, Color.ORANGE, ImmutableList.of(SubSkillType.CROSSBOWS_SUPER_SHOTGUN, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK));
private final Class<? extends SkillManager> managerClass; /*
private final Color skillColor; * Everything below here will be removed in 2.2 (Tridents & Crossbows)
private final SuperAbilityType superAbilityType; * Everything below here will be removed in 2.2 (Tridents & Crossbows)
private final List<SubSkillType> subSkillTypes; * Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
* Everything below here will be removed in 2.2 (Tridents & Crossbows)
*/
public static final List<String> SKILL_NAMES;
public static final List<String> SUBSKILL_NAMES;
public static final List<PrimarySkillType> CHILD_SKILLS; // private void processWarning() {
public static final List<PrimarySkillType> NON_CHILD_SKILLS; // if(issueWarning) {
// StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
// Bukkit.getScheduler().scheduleSyncDelayedTask(mcMMO.p, () -> {
// mcMMO.p.getLogger().severe("A plugin that hooks into mcMMO via the mcMMO API is using soon to be deprecated API calls. Contact the plugin author and inform them to update their code before it breaks.");
// mcMMO.p.getLogger().severe("Deprecation Call from: " + stackTraceElements[2].toString());
// mcMMO.p.getLogger().severe("This warning will not repeat itself. Nothing is broken for now, but in the future it will be.");
// });
//
// issueWarning = !issueWarning;
// }
// }
public static final List<PrimarySkillType> COMBAT_SKILLS = ImmutableList.of(ARCHERY, AXES, SWORDS, TAMING, UNARMED, TRIDENTS, CROSSBOWS); /**
public static final List<PrimarySkillType> GATHERING_SKILLS = ImmutableList.of(EXCAVATION, FISHING, HERBALISM, MINING, WOODCUTTING); * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
public static final List<PrimarySkillType> MISC_SKILLS = ImmutableList.of(ACROBATICS, ALCHEMY, REPAIR, SALVAGE, SMELTING); * @return the max level of this skill
* @see SkillTools#getLevelCap(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
static { * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
List<PrimarySkillType> childSkills = new ArrayList<>(); */
List<PrimarySkillType> nonChildSkills = new ArrayList<>(); @Deprecated
ArrayList<String> names = new ArrayList<>(); public int getMaxLevel() {
ArrayList<String> subSkillNames = new ArrayList<>(); return mcMMO.p.getSkillTools().getLevelCap(this);
for (PrimarySkillType skill : values()) {
if (skill.isChildSkill()) {
childSkills.add(skill);
}
else {
nonChildSkills.add(skill);
}
for(SubSkillType subSkillType : skill.subSkillTypes) {
subSkillNames.add(subSkillType.getNiceNameNoSpaces(subSkillType));
}
names.add(skill.getName());
}
Collections.sort(names);
SKILL_NAMES = ImmutableList.copyOf(names);
SUBSKILL_NAMES = ImmutableList.copyOf(subSkillNames);
CHILD_SKILLS = ImmutableList.copyOf(childSkills);
NON_CHILD_SKILLS = ImmutableList.copyOf(nonChildSkills);
}
PrimarySkillType(Class<? extends SkillManager> managerClass, Color skillColor, List<SubSkillType> subSkillTypes) {
this(managerClass, skillColor, null, subSkillTypes);
}
PrimarySkillType(Class<? extends SkillManager> managerClass, Color skillColor, SuperAbilityType superAbilityType, List<SubSkillType> subSkillTypes) {
this.managerClass = managerClass;
this.skillColor = skillColor;
this.superAbilityType = superAbilityType;
this.subSkillTypes = subSkillTypes;
}
public Class<? extends SkillManager> getManagerClass() {
return managerClass;
}
public SuperAbilityType getSuperAbilityType() {
return superAbilityType;
} }
/** /**
* Get the max level of this skill. * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*
* @return the max level of this skill * @return the max level of this skill
* @see SkillTools#isSuperAbilityUnlocked(com.gmail.nossr50.datatypes.skills.PrimarySkillType, org.bukkit.entity.Player)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/ */
public int getMaxLevel() {
return Config.getInstance().getLevelCap(this);
}
public boolean isSuperAbilityUnlocked(Player player) { return RankUtils.getRank(player, getSuperAbilityType().getSubSkillTypeDefinition()) >= 1; }
public boolean getPVPEnabled() {
return Config.getInstance().getPVPEnabled(this);
}
public boolean getPVEEnabled() {
return Config.getInstance().getPVEEnabled(this);
}
public boolean getDoubleDropsDisabled() {
return Config.getInstance().getDoubleDropsDisabled(this);
}
public boolean getHardcoreStatLossEnabled() {
return Config.getInstance().getHardcoreStatLossEnabled(this);
}
public void setHardcoreStatLossEnabled(boolean enable) {
Config.getInstance().setHardcoreStatLossEnabled(this, enable);
}
public boolean getHardcoreVampirismEnabled() {
return Config.getInstance().getHardcoreVampirismEnabled(this);
}
public void setHardcoreVampirismEnabled(boolean enable) {
Config.getInstance().setHardcoreVampirismEnabled(this, enable);
}
public List<SubSkillType> getSkillAbilities() {
return subSkillTypes;
}
public double getXpModifier() {
return ExperienceConfig.getInstance().getFormulaSkillModifier(this);
}
@Deprecated @Deprecated
public static @Nullable PrimarySkillType getSkill(String skillName) { public boolean isSuperAbilityUnlocked(@NotNull Player player) {
if (!Config.getInstance().getLocale().equalsIgnoreCase("en_US")) { return mcMMO.p.getSkillTools().isSuperAbilityUnlocked(this, player);
for (PrimarySkillType type : values()) {
if (skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(type.name()) + ".SkillName"))) {
return type;
}
}
} }
for (PrimarySkillType type : values()) { /**
if (type.name().equalsIgnoreCase(skillName)) { * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
return type; * @return the max level of this skill
} * @see SkillTools#getPVPEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean getPVPEnabled() {
return mcMMO.p.getSkillTools().getPVPEnabled(this);
} }
if (!skillName.equalsIgnoreCase("all")) { /**
mcMMO.p.getLogger().warning("Invalid mcMMO skill (" + skillName + ")"); //TODO: Localize * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getPVEEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean getPVEEnabled() {
return mcMMO.p.getSkillTools().getPVEEnabled(this);
} }
return null; /**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see GeneralConfig#getDoubleDropsDisabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean getDoubleDropsDisabled() {
return mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(this);
} }
// TODO: This is a little "hacky", we probably need to add something to distinguish child skills in the enum, or to use another enum for them /**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getHardcoreStatLossEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean getHardcoreStatLossEnabled() {
return mcMMO.p.getSkillTools().getHardcoreStatLossEnabled(this);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getHardcoreVampirismEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean getHardcoreVampirismEnabled() {
return mcMMO.p.getSkillTools().getHardcoreVampirismEnabled(this);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getPrimarySkillToolType(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public ToolType getTool() {
return mcMMO.p.getSkillTools().getPrimarySkillToolType(this);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getSubSkills(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public List<SubSkillType> getSkillAbilities() {
return new ArrayList<>(mcMMO.p.getSkillTools().getSubSkills(this));
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getXpModifier(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public double getXpModifier() {
return mcMMO.p.getSkillTools().getXpModifier(this);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#matchSkill(java.lang.String)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public static PrimarySkillType getSkill(String skillName) {
return mcMMO.p.getSkillTools().matchSkill(skillName);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#isChildSkill(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean isChildSkill() { public boolean isChildSkill() {
switch (this) { return SkillTools.isChildSkill(this);
case SALVAGE:
case SMELTING:
return true;
default:
return false;
}
} }
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getPrimarySkillBySubSkill(com.gmail.nossr50.datatypes.skills.SubSkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public static PrimarySkillType bySecondaryAbility(SubSkillType subSkillType) { public static PrimarySkillType bySecondaryAbility(SubSkillType subSkillType) {
for (PrimarySkillType type : values()) { return mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType);
if (type.getSkillAbilities().contains(subSkillType)) {
return type;
}
}
return null;
} }
public static PrimarySkillType byAbility(SuperAbilityType ability) { /**
for (PrimarySkillType type : values()) { * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
if (type.getSuperAbilityType() == ability) { * @return the max level of this skill
return type; * @see SkillTools#getPrimarySkillBySuperAbility(com.gmail.nossr50.datatypes.skills.SuperAbilityType)
} * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
} */
@Deprecated
return null; public static PrimarySkillType byAbility(SuperAbilityType superAbilityType) {
return mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(superAbilityType);
} }
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @return the max level of this skill
* @see SkillTools#getLocalizedSkillName(com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public String getName() { public String getName() {
return StringUtils.getCapitalized(LocaleLoader.getString(StringUtils.getCapitalized(this.toString()) + ".SkillName")); return mcMMO.p.getSkillTools().getLocalizedSkillName(this);
} }
// public String getName() { /**
// return StringUtils.getCapitalized(StringUtils.getCapitalized(this.toString())); * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
// } * @return the max level of this skill
* @see Permissions#skillEnabled(org.bukkit.permissions.Permissible, com.gmail.nossr50.datatypes.skills.PrimarySkillType)
* @deprecated this is being removed in an upcoming update
*/
@Deprecated
public boolean getPermissions(Player player) { public boolean getPermissions(Player player) {
return Permissions.skillEnabled(player, this); return mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, this);
} }
/* public void celebrateLevelUp(Player player) { /**
ParticleEffectUtils.fireworkParticleShower(player, skillColor); * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
}*/ * @return the max level of this skill
* @see SkillTools#canCombatSkillsTrigger(com.gmail.nossr50.datatypes.skills.PrimarySkillType, org.bukkit.entity.Entity)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public boolean shouldProcess(Entity target) { public boolean shouldProcess(Entity target) {
return (target instanceof Player || (target instanceof Tameable && ((Tameable) target).isTamed())) ? getPVPEnabled() : getPVEEnabled(); return mcMMO.p.getSkillTools().canCombatSkillsTrigger(this, target);
} }
} }

View File

@ -1,6 +1,7 @@
package com.gmail.nossr50.datatypes.skills; package com.gmail.nossr50.datatypes.skills;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.StringUtils;
import java.util.Locale; import java.util.Locale;
@ -145,7 +146,7 @@ public enum SubSkillType {
* If we add skills, those immutable lists need to be updated * If we add skills, those immutable lists need to be updated
* @return * @return
*/ */
public PrimarySkillType getParentSkill() { return PrimarySkillType.bySecondaryAbility(this); } public PrimarySkillType getParentSkill() { return mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(this); }
/** /**
* Returns the root address for this skill in the advanced.yml file * Returns the root address for this skill in the advanced.yml file

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.datatypes.skills; package com.gmail.nossr50.datatypes.skills;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.BlockUtils;
@ -137,11 +136,11 @@ public enum SuperAbilityType {
} }
public int getCooldown() { public int getCooldown() {
return Config.getInstance().getCooldown(this); return mcMMO.p.getSkillTools().getSuperAbilityCooldown(this);
} }
public int getMaxLength() { public int getMaxLength() {
return Config.getInstance().getMaxLength(this); return mcMMO.p.getGeneralConfig().getMaxLength(this);
} }
public String getAbilityOn() { public String getAbilityOn() {

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.datatypes.skills.subskills.acrobatics; package com.gmail.nossr50.datatypes.skills.subskills.acrobatics;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.interactions.NotificationType;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@ -83,7 +82,7 @@ public class Roll extends AcrobaticsSubSkill {
entityDamageEvent.setCancelled(true); entityDamageEvent.setCancelled(true);
return true; return true;
} }
} else if(Permissions.skillEnabled(player, PrimarySkillType.ACROBATICS)) { } else if(mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.ACROBATICS)) {
//Give XP Anyways //Give XP Anyways
SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE);
} }
@ -199,7 +198,7 @@ public class Roll extends AcrobaticsSubSkill {
return gracefulRollCheck(player, mmoPlayer, damage, skillLevel); return gracefulRollCheck(player, mmoPlayer, damage, skillLevel);
} }
double modifiedDamage = calculateModifiedRollDamage(damage, AdvancedConfig.getInstance().getRollDamageThreshold()); double modifiedDamage = calculateModifiedRollDamage(damage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold());
if (!isFatal(player, modifiedDamage) if (!isFatal(player, modifiedDamage)
&& RandomChanceUtil.isActivationSuccessful(SkillActivationType.RANDOM_LINEAR_100_SCALE_WITH_CAP, SubSkillType.ACROBATICS_ROLL, player)) { && RandomChanceUtil.isActivationSuccessful(SkillActivationType.RANDOM_LINEAR_100_SCALE_WITH_CAP, SubSkillType.ACROBATICS_ROLL, player)) {
@ -237,7 +236,7 @@ public class Roll extends AcrobaticsSubSkill {
* @return the modified event damage if the ability was successful, the original event damage otherwise * @return the modified event damage if the ability was successful, the original event damage otherwise
*/ */
private double gracefulRollCheck(Player player, OnlineMMOPlayer mmoPlayer, double damage, int skillLevel) { private double gracefulRollCheck(Player player, OnlineMMOPlayer mmoPlayer, double damage, int skillLevel) {
double modifiedDamage = calculateModifiedRollDamage(damage, AdvancedConfig.getInstance().getRollDamageThreshold() * 2); double modifiedDamage = calculateModifiedRollDamage(damage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold() * 2);
RandomChanceSkill rcs = new RandomChanceSkill(player, subSkillType); RandomChanceSkill rcs = new RandomChanceSkill(player, subSkillType);
rcs.setSkillLevel(rcs.getSkillLevel() * 2); //Double the effective odds rcs.setSkillLevel(rcs.getSkillLevel() * 2); //Double the effective odds
@ -380,7 +379,7 @@ public class Roll extends AcrobaticsSubSkill {
// //
// //Chance to roll at half max skill // //Chance to roll at half max skill
// RandomChanceSkill rollHalfMaxSkill = new RandomChanceSkill(null, subSkillType); // RandomChanceSkill rollHalfMaxSkill = new RandomChanceSkill(null, subSkillType);
// int halfMaxSkillValue = AdvancedConfig.getInstance().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL)/2; // int halfMaxSkillValue = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL)/2;
// rollHalfMaxSkill.setSkillLevel(halfMaxSkillValue); // rollHalfMaxSkill.setSkillLevel(halfMaxSkillValue);
// //
// //Chance to graceful roll at full skill // //Chance to graceful roll at full skill
@ -394,11 +393,11 @@ public class Roll extends AcrobaticsSubSkill {
// //Chance Stat Calculations // //Chance Stat Calculations
// rollChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollHalfMaxSkill); // rollChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollHalfMaxSkill);
// graceChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollGraceHalfMaxSkill); // graceChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollGraceHalfMaxSkill);
// damageThreshold = AdvancedConfig.getInstance().getRollDamageThreshold(); // damageThreshold = mcMMO.p.getAdvancedConfig().getRollDamageThreshold();
// //
// chancePerLevel = RandomChanceUtil.getRandomChanceExecutionChance(rollOneSkillLevel); // chancePerLevel = RandomChanceUtil.getRandomChanceExecutionChance(rollOneSkillLevel);
// //
// double maxLevel = AdvancedConfig.getInstance().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL); // double maxLevel = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL);
// //
// return LocaleLoader.getString("Acrobatics.SubSkill.Roll.Mechanics", rollChanceHalfMax, graceChanceHalfMax, maxLevel, chancePerLevel, damageThreshold, damageThreshold * 2,halfMaxSkillValue); // return LocaleLoader.getString("Acrobatics.SubSkill.Roll.Mechanics", rollChanceHalfMax, graceChanceHalfMax, maxLevel, chancePerLevel, damageThreshold, damageThreshold * 2,halfMaxSkillValue);
} }
@ -435,4 +434,5 @@ public class Roll extends AcrobaticsSubSkill {
{ {
return player.getLocation().getBlock().getLocation(); return player.getLocation().getBlock().getLocation();
} }
} }

View File

@ -3,6 +3,7 @@ package com.gmail.nossr50.events.skills.abilities;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
import com.gmail.nossr50.mcMMO;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent { public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent {
@ -10,7 +11,7 @@ public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent {
protected McMMOPlayerAbilityEvent(Player player, PrimarySkillType skill) { protected McMMOPlayerAbilityEvent(Player player, PrimarySkillType skill) {
super(player, skill); super(player, skill);
ability = skill.getSuperAbilityType(); ability = mcMMO.p.getSkillTools().getSuperAbility(skill);
} }
public SuperAbilityType getAbility() { public SuperAbilityType getAbility() {

View File

@ -1,9 +1,9 @@
package com.gmail.nossr50.events.skills.secondaryabilities; package com.gmail.nossr50.events.skills.secondaryabilities;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
import com.gmail.nossr50.mcMMO;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
@ -20,7 +20,7 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable
*/ */
@Deprecated @Deprecated
public SubSkillEvent(Player player, SubSkillType subSkillType) { public SubSkillEvent(Player player, SubSkillType subSkillType) {
super(player, PrimarySkillType.bySecondaryAbility(subSkillType)); super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType));
this.subSkillType = subSkillType; this.subSkillType = subSkillType;
} }
@ -33,7 +33,7 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable
*/ */
@Deprecated @Deprecated
public SubSkillEvent(Player player, SubSkillType subSkillType, double resultModifier) { public SubSkillEvent(Player player, SubSkillType subSkillType, double resultModifier) {
super(player, PrimarySkillType.bySecondaryAbility(subSkillType)); super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType));
this.subSkillType = subSkillType; this.subSkillType = subSkillType;
this.resultModifier = resultModifier; this.resultModifier = resultModifier;
} }

View File

@ -1,7 +1,6 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.api.ItemSpawnReason;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig; import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.WorldBlacklist;
import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.experience.ExperienceConfig;
@ -20,6 +19,8 @@ import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.skills.salvage.Salvage;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager; import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.*; import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.compat.layers.world.WorldCompatibilityLayer;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundManager;
import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.sounds.SoundType;
@ -78,9 +79,9 @@ public class BlockListener implements Listener {
continue; continue;
//TODO: Ignore this abomination its rewritten in 2.2 //TODO: Ignore this abomination its rewritten in 2.2
if(!Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) if(!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType())
&& !Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.HERBALISM, is.getType()) && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.HERBALISM, is.getType())
&& !Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, is.getType())) && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, is.getType()))
continue; continue;
//If we suspect TEs might be duped only reward block //If we suspect TEs might be duped only reward block
@ -122,12 +123,16 @@ public class BlockListener implements Listener {
BlockFace direction = event.getDirection(); BlockFace direction = event.getDirection();
Block movedBlock; Block movedBlock;
WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
for (Block b : event.getBlocks()) { for (Block block : event.getBlocks()) {
movedBlock = b.getRelative(direction); movedBlock = block.getRelative(direction);
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, movedBlock)) {
mcMMO.getPlaceStore().setTrue(movedBlock); mcMMO.getPlaceStore().setTrue(movedBlock);
} }
} }
}
/** /**
* Monitor BlockPistonRetract events. * Monitor BlockPistonRetract events.
@ -147,14 +152,18 @@ public class BlockListener implements Listener {
// Get opposite direction so we get correct block // Get opposite direction so we get correct block
BlockFace direction = event.getDirection(); BlockFace direction = event.getDirection();
Block movedBlock = event.getBlock().getRelative(direction); Block movedBlock = event.getBlock().getRelative(direction);
if (movedBlock.getY() >= Misc.getWorldMinCompat(movedBlock.getWorld())) // Very weird that the event is giving us these, they shouldn't exist
WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
//Spigot makes bad things happen in its API
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, movedBlock)) {
mcMMO.getPlaceStore().setTrue(movedBlock); mcMMO.getPlaceStore().setTrue(movedBlock);
}
for (Block block : event.getBlocks()) { for (Block block : event.getBlocks()) {
movedBlock = block.getRelative(direction); if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, block)) {
if (movedBlock.getY() < Misc.getWorldMinCompat(movedBlock.getWorld())) // Very weird that the event is giving us these, they shouldn't exist mcMMO.getPlaceStore().setTrue(block.getRelative(direction));
continue; }
mcMMO.getPlaceStore().setTrue(movedBlock);
} }
} }
@ -171,11 +180,16 @@ public class BlockListener implements Listener {
if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld()))
return; return;
BlockState blockState = event.getNewState(); BlockState blockState = event.getNewState();
if(ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) if(ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) {
{ WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
mcMMO.getPlaceStore().setTrue(blockState.getBlock()); Block block = blockState.getBlock();
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, block)) {
mcMMO.getPlaceStore().setTrue(block);
}
} }
} }
@ -185,19 +199,23 @@ public class BlockListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockFormEvent(BlockFormEvent event) public void onBlockFormEvent(BlockFormEvent event)
{ {
World world = event.getBlock().getWorld();
/* WORLD BLACKLIST CHECK */ /* WORLD BLACKLIST CHECK */
if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) if(WorldBlacklist.isWorldBlacklisted(world))
return; return;
BlockState newState = event.getNewState();
if(ExperienceConfig.getInstance().preventStoneLavaFarming()) { if(ExperienceConfig.getInstance().preventStoneLavaFarming()) {
if(newState.getType() != Material.OBSIDIAN BlockState newState = event.getNewState();
&& ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, newState.getBlockData())) { WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
if(newState.getType() != Material.OBSIDIAN && ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, newState.getBlockData())) {
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, newState.getBlock())) {
mcMMO.getPlaceStore().setTrue(newState); mcMMO.getPlaceStore().setTrue(newState);
} }
} }
} }
}
/** /**
* Monitor BlockPlace events. * Monitor BlockPlace events.
@ -207,16 +225,23 @@ public class BlockListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onBlockPlace(BlockPlaceEvent event) { public void onBlockPlace(BlockPlaceEvent event) {
BlockState blockState = event.getBlock().getState(); BlockState blockState = event.getBlock().getState();
Block block = blockState.getBlock();
/* Check if the blocks placed should be monitored so they do not give out XP in the future */ /* Check if the blocks placed should be monitored so they do not give out XP in the future */
// if (!Tag.LOGS.isTagged(event.getBlockReplacedState().getType()) || !Tag.LOGS.isTagged(event.getBlockPlaced().getType())) // if (!Tag.LOGS.isTagged(event.getBlockReplacedState().getType()) || !Tag.LOGS.isTagged(event.getBlockPlaced().getType()))
mcMMO.getPlaceStore().setTrue(blockState);
/* WORLD BLACKLIST CHECK */ /* WORLD BLACKLIST CHECK */
if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) { if(WorldBlacklist.isWorldBlacklisted(block.getWorld())) {
return; return;
} }
WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, block)) {
mcMMO.getPlaceStore().setTrue(blockState);
}
Player player = event.getPlayer(); Player player = event.getPlayer();
if (!UserManager.hasPlayerDataKey(player)) { if (!UserManager.hasPlayerDataKey(player)) {
@ -228,10 +253,10 @@ public class BlockListener implements Listener {
if(mmoPlayer == null) if(mmoPlayer == null)
return; return;
if (blockState.getType() == Repair.anvilMaterial && PrimarySkillType.REPAIR.getPermissions(player)) { if (blockState.getType() == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)) {
((McMMOPlayer) (mmoPlayer)).getRepairManager().placedAnvilCheck(); ((McMMOPlayer) (mmoPlayer)).getRepairManager().placedAnvilCheck();
} }
else if (blockState.getType() == Salvage.anvilMaterial && PrimarySkillType.SALVAGE.getPermissions(player)) { else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) {
((McMMOPlayer) (mmoPlayer)).getSalvageManager().placedAnvilCheck(); ((McMMOPlayer) (mmoPlayer)).getSalvageManager().placedAnvilCheck();
} }
} }
@ -243,18 +268,21 @@ public class BlockListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockMultiPlace(BlockMultiPlaceEvent event) { public void onBlockMultiPlace(BlockMultiPlaceEvent event) {
for (BlockState replacedBlockState : event.getReplacedBlockStates()) for (BlockState replacedBlockState : event.getReplacedBlockStates()) {
{
BlockState blockState = replacedBlockState.getBlock().getState(); BlockState blockState = replacedBlockState.getBlock().getState();
Block block = blockState.getBlock();
WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
/* Check if the blocks placed should be monitored so they do not give out XP in the future */ /* Check if the blocks placed should be monitored so they do not give out XP in the future */
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, block)) {
mcMMO.getPlaceStore().setTrue(blockState); mcMMO.getPlaceStore().setTrue(blockState);
} }
} }
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event) public void onBlockGrow(BlockGrowEvent event) {
{
Block block = event.getBlock(); Block block = event.getBlock();
World world = block.getWorld(); World world = block.getWorld();
@ -263,11 +291,12 @@ public class BlockListener implements Listener {
return; return;
// Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created // Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created
if (block.getY() >= world.getMaxHeight()) WorldCompatibilityLayer worldCompatibilityLayer = mcMMO.getCompatibilityManager().getWorldCompatibilityLayer();
return;
if(BlockUtils.isWithinWorldBounds(worldCompatibilityLayer, block)) {
mcMMO.getPlaceStore().setFalse(block); mcMMO.getPlaceStore().setFalse(block);
} }
}
/** /**
* Monitor BlockBreak events. * Monitor BlockBreak events.
@ -333,7 +362,7 @@ public class BlockListener implements Listener {
* We don't check the block store here because herbalism has too many unusual edge cases. * We don't check the block store here because herbalism has too many unusual edge cases.
* Instead, we check it inside the drops handler. * Instead, we check it inside the drops handler.
*/ */
if (PrimarySkillType.HERBALISM.getPermissions(player)) { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.HERBALISM)) {
herbalismManager.processHerbalismBlockBreakEvent(event); herbalismManager.processHerbalismBlockBreakEvent(event);
} }
/* /*
@ -344,13 +373,14 @@ public class BlockListener implements Listener {
} }
/* MINING */ /* MINING */
else if (BlockUtils.affectedBySuperBreaker(blockState) && ItemUtils.isPickaxe(heldItem) && PrimarySkillType.MINING.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) { else if (BlockUtils.affectedBySuperBreaker(blockState) && ItemUtils.isPickaxe(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MINING) && !mcMMO.getPlaceStore().isTrue(blockState)) {
MiningManager miningManager = ((McMMOPlayer) (mmoPlayer)).getMiningManager(); MiningManager miningManager = ((McMMOPlayer) (mmoPlayer)).getMiningManager();
miningManager.miningBlockCheck(blockState); miningManager.miningBlockCheck(blockState);
} }
/* WOOD CUTTING */ /* WOOD CUTTING */
else if (BlockUtils.hasWoodcuttingXP(blockState) && ItemUtils.isAxe(heldItem) && PrimarySkillType.WOODCUTTING.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) { else if (BlockUtils.hasWoodcuttingXP(blockState) && ItemUtils.isAxe(heldItem)
&& mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getPlaceStore().isTrue(blockState)) {
WoodcuttingManager woodcuttingManager = ((McMMOPlayer) (mmoPlayer)).getWoodcuttingManager(); WoodcuttingManager woodcuttingManager = ((McMMOPlayer) (mmoPlayer)).getWoodcuttingManager();
if (woodcuttingManager.canUseTreeFeller(heldItem)) { if (woodcuttingManager.canUseTreeFeller(heldItem)) {
woodcuttingManager.processTreeFeller(blockState); woodcuttingManager.processTreeFeller(blockState);
@ -365,7 +395,7 @@ public class BlockListener implements Listener {
} }
/* EXCAVATION */ /* EXCAVATION */
else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && PrimarySkillType.EXCAVATION.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) { else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getPlaceStore().isTrue(blockState)) {
ExcavationManager excavationManager = ((McMMOPlayer) (mmoPlayer)).getExcavationManager(); ExcavationManager excavationManager = ((McMMOPlayer) (mmoPlayer)).getExcavationManager();
excavationManager.excavationBlockCheck(blockState); excavationManager.excavationBlockCheck(blockState);
@ -523,7 +553,7 @@ public class BlockListener implements Listener {
* *
* We don't need to check permissions here because they've already been checked for the ability to even activate. * We don't need to check permissions here because they've already been checked for the ability to even activate.
*/ */
if (mmoPlayer.getSuperAbilityManager().getAbilityMode(SuperAbilityType.TREE_FELLER) && BlockUtils.hasWoodcuttingXP(blockState) && Config.getInstance().getTreeFellerSoundsEnabled()) { if (mmoPlayer.getSuperAbilityManager().getAbilityMode(SuperAbilityType.TREE_FELLER) && BlockUtils.hasWoodcuttingXP(blockState) && mcMMO.p.getGeneralConfig().getTreeFellerSoundsEnabled()) {
SoundManager.sendSound(player, blockState.getLocation(), SoundType.FIZZ); SoundManager.sendSound(player, blockState.getLocation(), SoundType.FIZZ);
} }
} }
@ -578,7 +608,7 @@ public class BlockListener implements Listener {
blockState.update(true); blockState.update(true);
} }
} }
else if (mmoPlayer.getSuperAbilityManager().getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || Config.getInstance().getUnarmedItemsAsUnarmed())) { else if (mmoPlayer.getSuperAbilityManager().getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed())) {
if (((McMMOPlayer) (mmoPlayer)).getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState)) { if (((McMMOPlayer) (mmoPlayer)).getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState)) {
if (EventUtils.simulateBlockBreak(block, player, true) && ((McMMOPlayer) (mmoPlayer)).getUnarmedManager().blockCrackerCheck(blockState)) { if (EventUtils.simulateBlockBreak(block, player, true) && ((McMMOPlayer) (mmoPlayer)).getUnarmedManager().blockCrackerCheck(blockState)) {
blockState.update(); blockState.update();

View File

@ -1,7 +1,5 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.WorldBlacklist;
import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.meta.ProjectileOriginMeta; import com.gmail.nossr50.datatypes.meta.ProjectileOriginMeta;
@ -163,7 +161,7 @@ public class EntityListener implements Listener {
projectile.setMetadata(mcMMO.infiniteArrowKey, mcMMO.metadataValue); projectile.setMetadata(mcMMO.infiniteArrowKey, mcMMO.metadataValue);
} }
projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(pluginRef, Math.min(event.getForce() * AdvancedConfig.getInstance().getForceMultiplier(), 1.0))); projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(pluginRef, Math.min(event.getForce() * mcMMO.p.getAdvancedConfig().getForceMultiplier(), 1.0)));
projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(pluginRef, projectile.getLocation())); projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(pluginRef, projectile.getLocation()));
//Cleanup metadata in 1 minute in case normal collection falls through //Cleanup metadata in 1 minute in case normal collection falls through
CombatUtils.delayArrowMetaCleanup((Projectile) projectile); CombatUtils.delayArrowMetaCleanup((Projectile) projectile);
@ -507,7 +505,7 @@ public class EntityListener implements Listener {
} }
//Party Friendly Fire //Party Friendly Fire
if(!Config.getInstance().getPartyFriendlyFire()) if(!mcMMO.p.getGeneralConfig().getPartyFriendlyFire())
if ((mcMMO.getPartyManager().inSameParty(defendingPlayer, attackingPlayer) if ((mcMMO.getPartyManager().inSameParty(defendingPlayer, attackingPlayer)
|| mcMMO.getPartyManager().areAllies(defendingPlayer, attackingPlayer)) || mcMMO.getPartyManager().areAllies(defendingPlayer, attackingPlayer))
&& !(Permissions.friendlyFire(attackingPlayer) && !(Permissions.friendlyFire(attackingPlayer)

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.WorldBlacklist;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType;
@ -381,17 +380,17 @@ public class InventoryListener implements Listener {
ItemStack item = event.getItem(); ItemStack item = event.getItem();
if (Config.getInstance().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) { if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (Config.getInstance().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) { if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (Config.getInstance().getEnabledForHoppers() && AlchemyPotionBrewer.isValidIngredient(null, item)) { if (mcMMO.p.getGeneralConfig().getEnabledForHoppers() && AlchemyPotionBrewer.isValidIngredient(null, item)) {
AlchemyPotionBrewer.scheduleCheck(null, (BrewingStand) holder); AlchemyPotionBrewer.scheduleCheck(null, (BrewingStand) holder);
} }
} }

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.WorldBlacklist;
import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.chat.ChatChannel; import com.gmail.nossr50.datatypes.chat.ChatChannel;
@ -13,6 +12,7 @@ import com.gmail.nossr50.events.fake.FakePlayerAnimationEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.ShareHandler; import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.runnables.MobHealthDisplayUpdaterTask;
import com.gmail.nossr50.runnables.player.PlayerProfileLoadingTask; import com.gmail.nossr50.runnables.player.PlayerProfileLoadingTask;
import com.gmail.nossr50.skills.fishing.FishingManager; import com.gmail.nossr50.skills.fishing.FishingManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager; import com.gmail.nossr50.skills.herbalism.HerbalismManager;
@ -45,11 +45,13 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*; import org.bukkit.event.player.*;
import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Locale; import java.util.Locale;
@ -74,11 +76,11 @@ public class PlayerListener implements Listener {
/* WORLD BLACKLIST CHECK */ /* WORLD BLACKLIST CHECK */
if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) { if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) {
//Remove scoreboards //Remove scoreboards
if(Config.getInstance().getScoreboardsEnabled()) { if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
ScoreboardManager.teardownPlayer(event.getPlayer()); ScoreboardManager.teardownPlayer(event.getPlayer());
} }
return; return;
} else if(WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && Config.getInstance().getScoreboardsEnabled()) { } else if(WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
//This only fires if they are travelling to a non-blacklisted world from a blacklisted world //This only fires if they are travelling to a non-blacklisted world from a blacklisted world
//Setup scoreboards //Setup scoreboards
@ -94,7 +96,7 @@ public class PlayerListener implements Listener {
return; return;
} }
if (!UserManager.hasPlayerDataKey(player) || Config.getInstance().getXPAfterTeleportCooldown() <= 0 || event.getFrom().equals(event.getTo())) { if (!UserManager.hasPlayerDataKey(player) || mcMMO.p.getGeneralConfig().getXPAfterTeleportCooldown() <= 0 || event.getFrom().equals(event.getTo())) {
return; return;
} }
@ -107,36 +109,56 @@ public class PlayerListener implements Listener {
mmoPlayer.actualizeTeleportATS(); mmoPlayer.actualizeTeleportATS();
} }
/** /**
* Handle PlayerDeathEvents at the lowest priority. * Handle {@link EntityDamageByEntityEvent} at the highest priority.
* <p> * <p>
* These events are used to modify the death message of a player when * This handler is used to clear the names of mobs with health bars to
* needed to correct issues potentially caused by the custom naming used * fix death messages showing mob health bars on death.
* for mob healthbars.
* *
* @param event The event to modify * @param event the event to listen to
*/ */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerDeathLowest(PlayerDeathEvent event) { public void onEntityDamageByEntityHighest(EntityDamageByEntityEvent event) {
/* WORLD BLACKLIST CHECK */ // we only care about players as this is for fixing player death messages
if (!(event.getEntity() instanceof Player))
return;
Player player = (Player) event.getEntity();
// get the attacker
LivingEntity attacker;
if (event.getDamager() instanceof LivingEntity)
attacker = (LivingEntity) event.getDamager();
// attempt to find creator of a projectile
else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity)
attacker = (LivingEntity) ((Projectile) event.getDamager()).getShooter();
else
return;
if (attacker instanceof HumanEntity)
return;
// world blacklist check
if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld()))
return; return;
// world guard main flag check
String deathMessage = event.getDeathMessage(); if (WorldGuardUtils.isWorldGuardLoaded() && !WorldGuardManager.getInstance().hasMainFlag((Player) event.getEntity()))
/* WORLD GUARD MAIN FLAG CHECK */
if(WorldGuardUtils.isWorldGuardLoaded())
{
if(!WorldGuardManager.getInstance().hasMainFlag(event.getEntity()))
return; return;
}
if (deathMessage == null) { // we only want to handle player deaths
if ((player.getHealth() - event.getFinalDamage()) > 0)
return; return;
}
Player player = event.getEntity(); // temporarily clear the mob's name
event.setDeathMessage(MobHealthbarUtils.fixDeathMessage(deathMessage, player)); new MobHealthDisplayUpdaterTask(attacker).run();
// set the name back
new BukkitRunnable() {
@Override
public void run() {
MobHealthbarUtils.handleMobHealthbars(attacker, 0, mcMMO.p);
}
}.runTaskLater(mcMMO.p, 1);
} }
/** /**
@ -276,7 +298,7 @@ public class PlayerListener implements Listener {
return; return;
} }
if (!UserManager.hasPlayerDataKey(player) || !PrimarySkillType.FISHING.getPermissions(player)) { if (!UserManager.hasPlayerDataKey(player) || !mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.FISHING)) {
return; return;
} }
@ -295,7 +317,7 @@ public class PlayerListener implements Listener {
if(event.getCaught() != null) { if(event.getCaught() != null) {
Item fishingCatch = (Item) event.getCaught(); Item fishingCatch = (Item) event.getCaught();
if (Config.getInstance().getFishingOverrideTreasures() && if (mcMMO.p.getGeneralConfig().getFishingOverrideTreasures() &&
fishingCatch.getItemStack().getType() != Material.SALMON && fishingCatch.getItemStack().getType() != Material.SALMON &&
fishingCatch.getItemStack().getType() != Material.COD && fishingCatch.getItemStack().getType() != Material.COD &&
fishingCatch.getItemStack().getType() != Material.TROPICAL_FISH && fishingCatch.getItemStack().getType() != Material.TROPICAL_FISH &&
@ -363,7 +385,7 @@ public class PlayerListener implements Listener {
return; return;
} }
if (!UserManager.hasPlayerDataKey(player) || !PrimarySkillType.FISHING.getPermissions(player)) { if (!UserManager.hasPlayerDataKey(player) || !mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.FISHING)) {
return; return;
} }
@ -570,11 +592,11 @@ public class PlayerListener implements Listener {
//Delay loading for 3 seconds in case the player has a save task running, its hacky but it should do the trick //Delay loading for 3 seconds in case the player has a save task running, its hacky but it should do the trick
new PlayerProfileLoadingTask(player).runTaskLaterAsynchronously(mcMMO.p, 60); new PlayerProfileLoadingTask(player).runTaskLaterAsynchronously(mcMMO.p, 60);
if (Config.getInstance().getMOTDEnabled() && Permissions.motd(player)) { if (mcMMO.p.getGeneralConfig().getMOTDEnabled() && Permissions.motd(player)) {
Motd.displayAll(player); Motd.displayAll(player);
} }
if (plugin.isXPEventEnabled() && Config.getInstance().playerJoinEventInfo()) { if (plugin.isXPEventEnabled() && mcMMO.p.getGeneralConfig().playerJoinEventInfo()) {
player.sendMessage(LocaleLoader.getString("XPRate.Event", ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier())); player.sendMessage(LocaleLoader.getString("XPRate.Event", ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()));
} }
} }
@ -657,10 +679,10 @@ public class PlayerListener implements Listener {
case RIGHT_CLICK_BLOCK: case RIGHT_CLICK_BLOCK:
Material type = clickedBlock.getType(); Material type = clickedBlock.getType();
if (!Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) { if (!mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) {
/* REPAIR CHECKS */ /* REPAIR CHECKS */
if (type == Repair.anvilMaterial if (type == Repair.anvilMaterial
&& PrimarySkillType.REPAIR.getPermissions(player) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)
&& mcMMO.getRepairableManager().isRepairable(heldItem) && mcMMO.getRepairableManager().isRepairable(heldItem)
&& heldItem.getAmount() <= 1) { && heldItem.getAmount() <= 1) {
RepairManager repairManager = ((McMMOPlayer) (mmoPlayer)).getRepairManager(); RepairManager repairManager = ((McMMOPlayer) (mmoPlayer)).getRepairManager();
@ -674,7 +696,7 @@ public class PlayerListener implements Listener {
} }
/* SALVAGE CHECKS */ /* SALVAGE CHECKS */
else if (type == Salvage.anvilMaterial else if (type == Salvage.anvilMaterial
&& PrimarySkillType.SALVAGE.getPermissions(player) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)
&& RankUtils.hasUnlockedSubskill(player, SubSkillType.SALVAGE_SCRAP_COLLECTOR) && RankUtils.hasUnlockedSubskill(player, SubSkillType.SALVAGE_SCRAP_COLLECTOR)
&& mcMMO.getSalvageableManager().isSalvageable(heldItem) && mcMMO.getSalvageableManager().isSalvageable(heldItem)
&& heldItem.getAmount() <= 1) { && heldItem.getAmount() <= 1) {
@ -705,9 +727,9 @@ public class PlayerListener implements Listener {
case LEFT_CLICK_BLOCK: case LEFT_CLICK_BLOCK:
type = clickedBlock.getType(); type = clickedBlock.getType();
if (!Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) { if (!mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) {
/* REPAIR CHECKS */ /* REPAIR CHECKS */
if (type == Repair.anvilMaterial && PrimarySkillType.REPAIR.getPermissions(player) && mcMMO.getRepairableManager().isRepairable(heldItem)) { if (type == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) {
RepairManager repairManager = ((McMMOPlayer) (mmoPlayer)).getRepairManager(); RepairManager repairManager = ((McMMOPlayer) (mmoPlayer)).getRepairManager();
// Cancel repairing an enchanted item // Cancel repairing an enchanted item
@ -717,7 +739,7 @@ public class PlayerListener implements Listener {
} }
} }
/* SALVAGE CHECKS */ /* SALVAGE CHECKS */
else if (type == Salvage.anvilMaterial && PrimarySkillType.SALVAGE.getPermissions(player) && mcMMO.getSalvageableManager().isSalvageable(heldItem)) { else if (type == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE) && mcMMO.getSalvageableManager().isSalvageable(heldItem)) {
SalvageManager salvageManager = ((McMMOPlayer) (mmoPlayer)).getSalvageManager(); SalvageManager salvageManager = ((McMMOPlayer) (mmoPlayer)).getSalvageManager();
// Cancel salvaging an enchanted item // Cancel salvaging an enchanted item
@ -799,7 +821,7 @@ public class PlayerListener implements Listener {
/* ACTIVATION & ITEM CHECKS */ /* ACTIVATION & ITEM CHECKS */
if (BlockUtils.canActivateTools(blockState)) { if (BlockUtils.canActivateTools(blockState)) {
if (Config.getInstance().getAbilitiesEnabled()) { if (mcMMO.p.getGeneralConfig().getAbilitiesEnabled()) {
if (BlockUtils.canActivateHerbalism(blockState)) { if (BlockUtils.canActivateHerbalism(blockState)) {
mcMMOPlayer.processAbilityActivation(PrimarySkillType.HERBALISM); mcMMOPlayer.processAbilityActivation(PrimarySkillType.HERBALISM);
} }
@ -865,7 +887,7 @@ public class PlayerListener implements Listener {
} }
/* ACTIVATION CHECKS */ /* ACTIVATION CHECKS */
if (Config.getInstance().getAbilitiesEnabled()) { if (mcMMO.p.getGeneralConfig().getAbilitiesEnabled()) {
mcMMOPlayer.processAbilityActivation(PrimarySkillType.AXES); mcMMOPlayer.processAbilityActivation(PrimarySkillType.AXES);
mcMMOPlayer.processAbilityActivation(PrimarySkillType.EXCAVATION); mcMMOPlayer.processAbilityActivation(PrimarySkillType.EXCAVATION);
mcMMOPlayer.processAbilityActivation(PrimarySkillType.HERBALISM); mcMMOPlayer.processAbilityActivation(PrimarySkillType.HERBALISM);
@ -897,13 +919,13 @@ public class PlayerListener implements Listener {
Material type = heldItem.getType(); Material type = heldItem.getType();
TamingManager tamingManager = mcMMOPlayer.getTamingManager(); TamingManager tamingManager = mcMMOPlayer.getTamingManager();
if (type == Config.getInstance().getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry())) { if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry())) {
tamingManager.summonWolf(); tamingManager.summonWolf();
} }
else if (type == Config.getInstance().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) {
tamingManager.summonOcelot(); tamingManager.summonOcelot();
} }
else if (type == Config.getInstance().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) {
tamingManager.summonHorse(); tamingManager.summonHorse();
} }
@ -956,7 +978,7 @@ public class PlayerListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (!Config.getInstance().getLocale().equalsIgnoreCase("en_US")) { if (!mcMMO.p.getGeneralConfig().getLocale().equalsIgnoreCase("en_US")) {
String message = event.getMessage(); String message = event.getMessage();
String command = message.substring(1).split(" ")[0]; String command = message.substring(1).split(" ")[0];
String lowerCaseCommand = command.toLowerCase(Locale.ENGLISH); String lowerCaseCommand = command.toLowerCase(Locale.ENGLISH);
@ -964,7 +986,7 @@ public class PlayerListener implements Listener {
// Do these ACTUALLY have to be lower case to work properly? // Do these ACTUALLY have to be lower case to work properly?
for (PrimarySkillType skill : PrimarySkillType.values()) { for (PrimarySkillType skill : PrimarySkillType.values()) {
String skillName = skill.toString().toLowerCase(Locale.ENGLISH); String skillName = skill.toString().toLowerCase(Locale.ENGLISH);
String localizedName = skill.getName().toLowerCase(Locale.ENGLISH); String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill).toLowerCase(Locale.ENGLISH);
if (lowerCaseCommand.equals(localizedName)) { if (lowerCaseCommand.equals(localizedName)) {
event.setMessage(message.replace(command, skillName)); event.setMessage(message.replace(command, skillName));

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent; import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
@ -10,6 +9,7 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.player.PlayerLevelUtils; import com.gmail.nossr50.util.player.PlayerLevelUtils;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardManager;
import com.gmail.nossr50.worldguard.WorldGuardUtils; import com.gmail.nossr50.worldguard.WorldGuardUtils;
import com.neetgames.mcmmo.player.OnlineMMOPlayer; import com.neetgames.mcmmo.player.OnlineMMOPlayer;
@ -50,7 +50,7 @@ public class SelfListener implements Listener {
//Reset the delay timer //Reset the delay timer
RankUtils.resetUnlockDelayTimer(); RankUtils.resetUnlockDelayTimer();
if(Config.getInstance().getScoreboardsEnabled()) if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled())
ScoreboardManager.handleLevelUp(player, skill); ScoreboardManager.handleLevelUp(player, skill);
if(Config.getInstance().getScoreboardsEnabled()) if(Config.getInstance().getScoreboardsEnabled())
@ -63,7 +63,7 @@ public class SelfListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
if(player.isOnline()) { if(player.isOnline()) {
if(Config.getInstance().getScoreboardsEnabled()) if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled())
ScoreboardManager.handleXp(player, event.getSkill()); ScoreboardManager.handleXp(player, event.getSkill());
} }
} }
@ -72,7 +72,7 @@ public class SelfListener implements Listener {
public void onAbility(McMMOPlayerAbilityActivateEvent event) { public void onAbility(McMMOPlayerAbilityActivateEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if(player.isOnline()) { if(player.isOnline()) {
if(Config.getInstance().getScoreboardsEnabled()) if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled())
ScoreboardManager.cooldownUpdate(event.getPlayer(), event.getSkill()); ScoreboardManager.cooldownUpdate(event.getPlayer(), event.getSkill());
} }
} }
@ -141,7 +141,7 @@ public class SelfListener implements Listener {
return; return;
} }
if (primarySkillType.isChildSkill()) { if (SkillTools.isChildSkill(primarySkillType)) {
return; return;
} }
@ -149,7 +149,7 @@ public class SelfListener implements Listener {
float guaranteedMinimum = ExperienceConfig.getInstance().getDiminishedReturnsCap() * rawXp; float guaranteedMinimum = ExperienceConfig.getInstance().getDiminishedReturnsCap() * rawXp;
float modifiedThreshold = (float) (threshold / primarySkillType.getXpModifier() * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); float modifiedThreshold = (float) (threshold / ExperienceConfig.getInstance().getFormulaSkillModifier(primarySkillType) * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier());
float difference = (mmoPlayer.getExperienceHandler().getRegisteredXpGain(primarySkillType) - modifiedThreshold) / modifiedThreshold; float difference = (mmoPlayer.getExperienceHandler().getRegisteredXpGain(primarySkillType) - modifiedThreshold) / modifiedThreshold;
if (difference > 0) { if (difference > 0) {

View File

@ -1,22 +1,24 @@
package com.gmail.nossr50.locale; package com.gmail.nossr50.locale;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.text.TextUtils; import com.gmail.nossr50.util.text.TextUtils;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.jetbrains.annotations.NotNull;
import java.io.IOException; import java.io.*;
import java.io.Reader;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
public final class LocaleLoader { public final class LocaleLoader {
private static final String BUNDLE_ROOT = "com.gmail.nossr50.locale.locale"; private static final String BUNDLE_ROOT = "com.gmail.nossr50.locale.locale";
private static final String OVERRIDE_FILE_NAME = "locale_override.properties";
private static Map<String, String> bundleCache = new HashMap<>(); private static Map<String, String> bundleCache = new HashMap<>();
private static ResourceBundle bundle = null; private static ResourceBundle bundle = null;
private static ResourceBundle filesystemBundle = null; private static ResourceBundle filesystemBundle = null;
@ -33,6 +35,7 @@ public final class LocaleLoader {
* *
* @param key The key to look up the string with * @param key The key to look up the string with
* @param messageArguments Any arguments to be added to the string * @param messageArguments Any arguments to be added to the string
*
* @return The properly formatted locale string * @return The properly formatted locale string
*/ */
public static String getString(String key, Object... messageArguments) { public static String getString(String key, Object... messageArguments) {
@ -45,11 +48,13 @@ public final class LocaleLoader {
} }
//TODO: Remove this hacky crap with something better later //TODO: Remove this hacky crap with something better later
/** /**
* Gets the appropriate TextComponent representation of a formatted string from the Locale files. * Gets the appropriate TextComponent representation of a formatted string from the Locale files.
* *
* @param key The key to look up the string with * @param key The key to look up the string with
* @param messageArguments Any arguments to be added to the text component * @param messageArguments Any arguments to be added to the text component
*
* @return The properly formatted text component * @return The properly formatted text component
*/ */
public static TextComponent getTextComponent(String key, Object... messageArguments) { public static TextComponent getTextComponent(String key, Object... messageArguments) {
@ -76,19 +81,18 @@ public final class LocaleLoader {
if (filesystemBundle != null) { if (filesystemBundle != null) {
try { try {
return filesystemBundle.getString(key); return filesystemBundle.getString(key);
} catch (MissingResourceException ignored) {
} }
catch (MissingResourceException ignored) {}
} }
try { try {
return bundle.getString(key); return bundle.getString(key);
} catch (MissingResourceException ignored) {
} }
catch (MissingResourceException ignored) {}
try { try {
return enBundle.getString(key); return enBundle.getString(key);
} } catch (MissingResourceException ignored) {
catch (MissingResourceException ignored) {
if (!key.contains("Guides")) { if (!key.contains("Guides")) {
mcMMO.p.getLogger().warning("Could not find locale string: " + key); mcMMO.p.getLogger().warning("Could not find locale string: " + key);
} }
@ -130,31 +134,169 @@ public final class LocaleLoader {
if (bundle == null) { if (bundle == null) {
Locale.setDefault(new Locale("en", "US")); Locale.setDefault(new Locale("en", "US"));
Locale locale = null; Locale locale = null;
String[] myLocale = Config.getInstance().getLocale().split("[-_ ]");
String[] myLocale = mcMMO.p.getGeneralConfig().getLocale().split("[-_ ]");
if (myLocale.length == 1) { if (myLocale.length == 1) {
locale = new Locale(myLocale[0]); locale = new Locale(myLocale[0]);
} } else if (myLocale.length >= 2) {
else if (myLocale.length >= 2) {
locale = new Locale(myLocale[0], myLocale[1]); locale = new Locale(myLocale[0], myLocale[1]);
} }
if (locale == null) { if (locale == null) {
throw new IllegalStateException("Failed to parse locale string '" + Config.getInstance().getLocale() + "'"); throw new IllegalStateException("Failed to parse locale string '" + mcMMO.p.getGeneralConfig().getLocale() + "'");
} }
Path localePath = Paths.get(mcMMO.getLocalesDirectory() + "locale_" + locale.toString() + ".properties"); Path localePath = Paths.get(mcMMO.getLocalesDirectory() + "locale_" + locale.toString() + ".properties");
Path overridePath = Paths.get(mcMMO.getLocalesDirectory() + OVERRIDE_FILE_NAME);
File overrideFile = overridePath.toFile();
if (Files.exists(localePath) && Files.isRegularFile(localePath)) { if (Files.exists(localePath) && Files.isRegularFile(localePath)) {
try (Reader localeReader = Files.newBufferedReader(localePath)) {
mcMMO.p.getLogger().log(Level.INFO, "Loading locale from {0}", localePath); File oldOverrideFile = localePath.toFile();
try {
//Copy the file
com.google.common.io.Files.copy(oldOverrideFile, overrideFile);
//Remove the old file now
oldOverrideFile.delete();
//Insert our helpful text
StringBuilder stringBuilder = new StringBuilder();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(overrideFile.getPath()))) {
// Open the file
String line;
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
LocalDateTime localDateTime = LocalDateTime.now();
stringBuilder.append("# mcMMO Locale Override File created on ").append(localDateTime.format(dateTimeFormatter)).append("\r\n"); //Empty file
stringBuilder.append(getLocaleHelpTextWithoutExamples()); //Add our helpful text
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try(FileWriter fileWriter = new FileWriter(overrideFile.getPath())) {
fileWriter.write(stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Use the new locale file
if (Files.exists(overridePath) && Files.isRegularFile(overridePath)) {
try (Reader localeReader = Files.newBufferedReader(overridePath)) {
mcMMO.p.getLogger().log(Level.INFO, "Loading locale from {0}", overridePath);
filesystemBundle = new PropertyResourceBundle(localeReader); filesystemBundle = new PropertyResourceBundle(localeReader);
} catch (IOException e) { } catch (IOException e) {
mcMMO.p.getLogger().log(Level.WARNING, "Failed to load locale from " + localePath, e); mcMMO.p.getLogger().log(Level.WARNING, "Failed to load locale from " + overridePath, e);
}
} else {
//Create a blank file and fill it in with some helpful text
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(overrideFile, true))) {
// Open the file to write the player
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
LocalDateTime localDateTime = LocalDateTime.now();
bufferedWriter.append("# mcMMO Locale Override File created on ").append(localDateTime.format(dateTimeFormatter)).append("\r\n"); //Empty file
String localeExplanation = getLocaleHelpText();
bufferedWriter.append(localeExplanation);
} catch (Exception e) {
e.printStackTrace();
} }
} }
bundle = ResourceBundle.getBundle(BUNDLE_ROOT, locale); bundle = ResourceBundle.getBundle(BUNDLE_ROOT, locale);
}
enBundle = ResourceBundle.getBundle(BUNDLE_ROOT, Locale.US); enBundle = ResourceBundle.getBundle(BUNDLE_ROOT, Locale.US);
} }
@NotNull
private static String getLocaleHelpText() {
String localeExplanation =
"# -- Are you looking to change the language of mcMMO but without editing it yourself? --\n" +
"\n" +
"# mcMMO has quite a few built in translations, you can choose which translation by editing config.yml with the appropriate locale code. The setting is `General.Locale` in config.yml\n" +
"# Odds are, if you speak a popular language on earth we already have a translation for it.\n" +
"# However our translations are done by the community, and update infrequently. (Please help us out <3)\n" +
"# We would love more people to help update our locales, submit any updated translation file to our GitHub or email it to me at business@neetgames.com\n" +
"# For a list of built in translations, view this link: https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" +
"\n" +
"\n" +
"# -- Using a built in translation -- \n" +
"# Assuming you read the above section, edit config.yml's General.Locale from en_US to the locale code that we support (see the above link), then reboot your server\n" +
"\n" +
"\n" +
"# -- Do you want to change the text in mcMMO? Including adding colors? ( Locale Override ) -- \n" +
"# First, a brief explanation.\n" +
"# Locales are the language files used by mcMMO, they also contain color codes and most of the styling used by mcMMO.\n" +
"# You can customize a locale outside of the JAR in version 2.1.51 and up.\n" +
"#\n" +
"# Locales can be overridden by editing this file\n" +
"# You can find the up to date current locale files here https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" +
"# The master file is en_US, if a translation is missing entries (as they often are) it will pull from the en_US file https://github.com/mcMMO-Dev/mcMMO/blob/master/src/main/resources/locale/locale_en_US.properties\n" +
"#\n" +
"# To override a locale, add entries to this file and copy ** only ** the strings you want to replace, otherwise you will not see any updated strings when mcMMO updates and will have to manually change them and read patch notes carefully.\n" +
"# If you wish to replace every line in some way, feel free to copy the entire contents of this file, just be advised that you will need to be on top of locale updates in mcMMO and follow our changelog closely.\n" +
"\n" +
"\n" +
"# WARNING: Locales only support ASCII and UTF16 characters at the moment, so you'll need to run special characters through a UTF16 converter (google it) to get them to work. This will be fixed in the future!\n" +
"# FIND KEYS HERE: On our github repo (en_US is our master file and has ALL the keys) -> https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" +
"# WARNING: Some keys in our master file are unused, make gratuitous use of Ctrl+F\n" +
"# HOW TO APPLY: You can either restart the server for these changes to take effect or run /mcreloadlocale.\n" +
"# -- Add Keys Below --\n" +
getExamples();
return localeExplanation;
}
@NotNull
private static String getExamples() {
return "This.Is.An.Example.Put.Locale.Keys.Here.One=&aExample text using hex color codes\n" +
"This.Is.An.Example.Put.Locale.Keys.Here.Two=[[DARK_AQUA]]Example text using our own color codes\n" +
"This.Is.An.Example.Put.Locale.Keys.Here.Three=Example text with no colors\n";
}
@NotNull
private static String getLocaleHelpTextWithoutExamples() {
String localeExplanation =
"# -- Are you looking to change the language of mcMMO but without editing it yourself? --\n" +
"\n" +
"# mcMMO has quite a few built in translations, you can choose which translation by editing config.yml with the appropriate locale code. The setting is `General.Locale` in config.yml\n" +
"# Odds are, if you speak a popular language on earth we already have a translation for it.\n" +
"# However our translations are done by the community, and update infrequently. (Please help us out <3)\n" +
"# We would love more people to help update our locales, submit any updated translation file to our GitHub or email it to me at business@neetgames.com\n" +
"# For a list of built in translations, view this link: https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" +
"\n" +
"\n" +
"# -- Using a built in translation -- \n" +
"# Assuming you read the above section, edit config.yml's General.Locale from en_US to the locale code that we support (see the above link), then reboot your server\n" +
"\n" +
"\n" +
"# -- Do you want to change the text in mcMMO? Including adding colors? ( Locale Override ) -- \n" +
"# First, a brief explanation.\n" +
"# Locales are the language files used by mcMMO, they also contain color codes and most of the styling used by mcMMO.\n" +
"# You can customize a locale outside of the JAR in version 2.1.51 and up.\n" +
"#\n" +
"# Locales can be overridden by editing this file\n" +
"# You can find the up to date current locale files here https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" +
"# The master file is en_US, if a translation is missing entries (as they often are) it will pull from the en_US file https://github.com/mcMMO-Dev/mcMMO/blob/master/src/main/resources/locale/locale_en_US.properties\n" +
"#\n" +
"# To override a locale, add entries to this file and copy ** only ** the strings you want to replace, otherwise you will not see any updated strings when mcMMO updates and will have to manually change them and read patch notes carefully.\n" +
"# If you wish to replace every line in some way, feel free to copy the entire contents of this file, just be advised that you will need to be on top of locale updates in mcMMO and follow our changelog closely.\n" +
"\n" +
"\n" +
"# WARNING: Locales only support ASCII and UTF16 characters at the moment, so you'll need to run special characters through a UTF16 converter (google it) to get them to work. This will be fixed in the future!\n" +
"# FIND KEYS HERE: On our github repo (en_US is our master file and has ALL the keys) -> https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" +
"# WARNING: Some keys in our master file are unused, make gratuitous use of Ctrl+F\n" +
"# HOW TO APPLY: You can either restart the server for these changes to take effect or run /mcreloadlocale.\n" +
"# -- Add Keys Below --\n";
return localeExplanation;
} }
public static String addColors(String input) { public static String addColors(String input) {

View File

@ -43,6 +43,7 @@ import com.gmail.nossr50.util.player.PlayerLevelUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.util.skills.SmeltingTracker; import com.gmail.nossr50.util.skills.SmeltingTracker;
import com.gmail.nossr50.util.upgrade.UpgradeManager; import com.gmail.nossr50.util.upgrade.UpgradeManager;
import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardManager;
@ -55,8 +56,10 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -87,6 +90,9 @@ public class mcMMO extends JavaPlugin {
private static ChatManager chatManager; private static ChatManager chatManager;
private static CommandManager commandManager; //ACF private static CommandManager commandManager; //ACF
private static TransientEntityTracker transientEntityTracker; private static TransientEntityTracker transientEntityTracker;
private @NotNull SkillTools skillTools;
private static boolean serverShutdownExecuted = false; private static boolean serverShutdownExecuted = false;
/* Adventure */ /* Adventure */
@ -147,21 +153,46 @@ public class mcMMO extends JavaPlugin {
public final static String PROJECTILE_ORIGIN_METAKEY = "mcMMO: Projectile Origin"; public final static String PROJECTILE_ORIGIN_METAKEY = "mcMMO: Projectile Origin";
public static FixedMetadataValue metadataValue; public static FixedMetadataValue metadataValue;
private long purgeTime = 2630000000L;
public static final String ULTRA_PERMISSONS = "UltraPermissons"; private GeneralConfig generalConfig;
private AdvancedConfig advancedConfig;
// private RepairConfig repairConfig;
// private SalvageConfig salvageConfig;
// private PersistentDataConfig persistentDataConfig;
// private ChatConfig chatConfig;
// private CoreSkillsConfig coreSkillsConfig;
// private RankConfig rankConfig;
// private TreasureConfig treasureConfig;
// private FishingTreasureConfig fishingTreasureConfig;
// private SoundConfig soundConfig;
public mcMMO() { public mcMMO() {
p = this; p = this;
} }
protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file)
{
super(loader, description, dataFolder, file);
}
/** /**
* Things to be run when the plugin is enabled. * Things to be run when the plugin is enabled.
*/ */
@Override @Override
public void onEnable() { public void onEnable() {
try { try {
setupFilePaths();
generalConfig = new GeneralConfig(getDataFolder()); //Load before skillTools
skillTools = new SkillTools(this); //Load after general config
//Init configs
advancedConfig = new AdvancedConfig(getDataFolder());
//Store this value so other plugins can check it //Store this value so other plugins can check it
isRetroModeEnabled = Config.getInstance().getIsRetroMode(); isRetroModeEnabled = generalConfig.getIsRetroMode();
//Platform Manager //Platform Manager
platformManager = new PlatformManager(); platformManager = new PlatformManager();
@ -177,7 +208,6 @@ public class mcMMO extends JavaPlugin {
upgradeManager = new UpgradeManager(); upgradeManager = new UpgradeManager();
setupFilePaths();
modManager = new ModManager(); modManager = new ModManager();
@ -203,7 +233,10 @@ public class mcMMO extends JavaPlugin {
getLogger().warning("mcMMO will not work properly alongside NoCheatPlus without CompatNoCheatPlus"); getLogger().warning("mcMMO will not work properly alongside NoCheatPlus without CompatNoCheatPlus");
} }
databaseManager = DatabaseManagerFactory.getDatabaseManager(); // One month in milliseconds
this.purgeTime = 2630000000L * generalConfig.getOldUsersCutoff();
databaseManager = DatabaseManagerFactory.getDatabaseManager(mcMMO.getUsersFilePath(), getLogger(), purgeTime, mcMMO.p.getAdvancedConfig().getStartingLevel());
//Check for the newer API and tell them what to do if its missing //Check for the newer API and tell them what to do if its missing
checkForOutdatedAPI(); checkForOutdatedAPI();
@ -243,7 +276,7 @@ public class mcMMO extends JavaPlugin {
placeStore = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager placeStore = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager
if (Config.getInstance().getPTPCommandWorldPermissions()) { if (generalConfig.getPTPCommandWorldPermissions()) {
Permissions.generateWorldTeleportPermissions(); Permissions.generateWorldTeleportPermissions();
} }
@ -254,11 +287,11 @@ public class mcMMO extends JavaPlugin {
//If anonymous statistics are enabled then use them //If anonymous statistics are enabled then use them
Metrics metrics; Metrics metrics;
if(Config.getInstance().getIsMetricsEnabled()) { if(generalConfig.getIsMetricsEnabled()) {
metrics = new Metrics(this, 3894); metrics = new Metrics(this, 3894);
metrics.addCustomChart(new SimplePie("version", () -> getDescription().getVersion())); metrics.addCustomChart(new SimplePie("version", () -> getDescription().getVersion()));
if(Config.getInstance().getIsRetroMode()) if(generalConfig.getIsRetroMode())
metrics.addCustomChart(new SimplePie("leveling_system", () -> "Retro")); metrics.addCustomChart(new SimplePie("leveling_system", () -> "Retro"));
else else
metrics.addCustomChart(new SimplePie("leveling_system", () -> "Standard")); metrics.addCustomChart(new SimplePie("leveling_system", () -> "Standard"));
@ -350,7 +383,7 @@ public class mcMMO extends JavaPlugin {
mcMMO.getPartyManager().saveParties(); // Save our parties mcMMO.getPartyManager().saveParties(); // Save our parties
//TODO: Needed? //TODO: Needed?
if(Config.getInstance().getScoreboardsEnabled()) if(generalConfig.getScoreboardsEnabled())
ScoreboardManager.teardownAll(); ScoreboardManager.teardownAll();
formulaManager.saveFormula(); formulaManager.saveFormula();
@ -360,7 +393,7 @@ public class mcMMO extends JavaPlugin {
e.printStackTrace(); e.printStackTrace();
} }
if (Config.getInstance().getBackupsEnabled()) { if (generalConfig.getBackupsEnabled()) {
// Remove other tasks BEFORE starting the Backup, or we just cancel it straight away. // Remove other tasks BEFORE starting the Backup, or we just cancel it straight away.
try { try {
ZipLibrary.mcMMOBackup(); ZipLibrary.mcMMOBackup();
@ -532,7 +565,7 @@ public class mcMMO extends JavaPlugin {
TreasureConfig.getInstance(); TreasureConfig.getInstance();
FishingTreasureConfig.getInstance(); FishingTreasureConfig.getInstance();
HiddenConfig.getInstance(); HiddenConfig.getInstance();
AdvancedConfig.getInstance(); mcMMO.p.getAdvancedConfig();
PotionConfig.getInstance(); PotionConfig.getInstance();
CoreSkillsConfig.getInstance(); CoreSkillsConfig.getInstance();
SoundConfig.getInstance(); SoundConfig.getInstance();
@ -592,7 +625,7 @@ public class mcMMO extends JavaPlugin {
private void registerCustomRecipes() { private void registerCustomRecipes() {
getServer().getScheduler().scheduleSyncDelayedTask(this, () -> { getServer().getScheduler().scheduleSyncDelayedTask(this, () -> {
if (Config.getInstance().getChimaeraEnabled()) { if (generalConfig.getChimaeraEnabled()) {
getServer().addRecipe(ChimaeraWing.getChimaeraWingRecipe()); getServer().addRecipe(ChimaeraWing.getChimaeraWingRecipe());
} }
}, 40); }, 40);
@ -603,7 +636,7 @@ public class mcMMO extends JavaPlugin {
long second = 20; long second = 20;
long minute = second * 60; long minute = second * 60;
long saveIntervalTicks = Math.max(minute, Config.getInstance().getSaveInterval() * minute); long saveIntervalTicks = Math.max(minute, generalConfig.getSaveInterval() * minute);
new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks); new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks);
@ -611,7 +644,7 @@ public class mcMMO extends JavaPlugin {
new CleanBackupsTask().runTaskAsynchronously(mcMMO.p); new CleanBackupsTask().runTaskAsynchronously(mcMMO.p);
// Old & Powerless User remover // Old & Powerless User remover
long purgeIntervalTicks = Config.getInstance().getPurgeInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; long purgeIntervalTicks = generalConfig.getPurgeInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR;
if (purgeIntervalTicks == 0) { if (purgeIntervalTicks == 0) {
new UserPurgeTask().runTaskLaterAsynchronously(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. new UserPurgeTask().runTaskLaterAsynchronously(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
@ -621,7 +654,7 @@ public class mcMMO extends JavaPlugin {
} }
// Automatically remove old members from parties // Automatically remove old members from parties
long kickIntervalTicks = Config.getInstance().getAutoPartyKickInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; long kickIntervalTicks = generalConfig.getAutoPartyKickInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR;
if (kickIntervalTicks == 0) { if (kickIntervalTicks == 0) {
new PartyAutoKickTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. new PartyAutoKickTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
@ -638,7 +671,7 @@ public class mcMMO extends JavaPlugin {
new ClearRegisteredXPGainTask().runTaskTimer(this, 60, 60); new ClearRegisteredXPGainTask().runTaskTimer(this, 60, 60);
} }
if(AdvancedConfig.getInstance().allowPlayerTips()) if(mcMMO.p.getAdvancedConfig().allowPlayerTips())
{ {
new NotifySquelchReminderTask().runTaskTimer(this, 60, ((20 * 60) * 60)); new NotifySquelchReminderTask().runTaskTimer(this, 60, ((20 * 60) * 60));
} }
@ -710,4 +743,20 @@ public class mcMMO extends JavaPlugin {
private static synchronized void setServerShutdown(boolean bool) { private static synchronized void setServerShutdown(boolean bool) {
serverShutdownExecuted = bool; serverShutdownExecuted = bool;
} }
public long getPurgeTime() {
return purgeTime;
}
public @NotNull SkillTools getSkillTools() {
return skillTools;
}
public @NotNull GeneralConfig getGeneralConfig() {
return generalConfig;
}
public @NotNull AdvancedConfig getAdvancedConfig() {
return advancedConfig;
}
} }

View File

@ -1,8 +1,8 @@
package com.gmail.nossr50.party; package com.gmail.nossr50.party;
import com.gmail.nossr50.commands.party.PartySubCommandType; import com.gmail.nossr50.commands.party.PartySubCommandType;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.StringUtils;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -17,7 +17,7 @@ public enum PartyFeature {
} }
public String getFeatureLockedLocaleString() { public String getFeatureLockedLocaleString() {
return LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Party.Feature.Locked." + StringUtils.getPrettyPartyFeatureString(this).replace(" ", ""), Config.getInstance().getPartyFeatureUnlockLevel(this))); return LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Party.Feature.Locked." + StringUtils.getPrettyPartyFeatureString(this).replace(" ", ""), mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(this)));
} }
public boolean hasPermission(Player player) { public boolean hasPermission(Player player) {

View File

@ -0,0 +1,845 @@
package com.gmail.nossr50.party;
import com.gmail.nossr50.datatypes.chat.ChatChannel;
import com.gmail.nossr50.datatypes.interactions.NotificationType;
import com.gmail.nossr50.datatypes.party.ItemShareType;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyLeader;
import com.gmail.nossr50.datatypes.party.ShareMode;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.party.McMMOPartyAllianceChangeEvent;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.sounds.SoundManager;
import com.gmail.nossr50.util.sounds.SoundType;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
public final class PartyManager {
private static final String partiesFilePath = mcMMO.getFlatFileDirectory() + "parties.yml";
private static final List<Party> parties = new ArrayList<>();
private static final File partyFile = new File(partiesFilePath);
private PartyManager() {}
/**
* Check if a party with a given name already exists.
*
* @param player The player to notify
* @param partyName The name of the party to check
* @return true if a party with that name exists, false otherwise
*/
public static boolean checkPartyExistence(Player player, String partyName) {
if (getParty(partyName) == null) {
return false;
}
player.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists", partyName));
return true;
}
/**
* Checks if the player can join a party, parties can have a size limit, although there is a permission to bypass this
* @param player player who is attempting to join the party
* @param targetParty the target party
* @return true if party is full and cannot be joined
*/
public static boolean isPartyFull(Player player, Party targetParty)
{
return !Permissions.partySizeBypass(player) && mcMMO.p.getGeneralConfig().getPartyMaxSize() >= 1 && targetParty.getOnlineMembers().size() >= mcMMO.p.getGeneralConfig().getPartyMaxSize();
}
/**
* Attempt to change parties or join a new party.
*
* @param mcMMOPlayer The player changing or joining parties
* @param newPartyName The name of the party being joined
* @return true if the party was joined successfully, false otherwise
*/
public static boolean changeOrJoinParty(McMMOPlayer mcMMOPlayer, String newPartyName) {
Player player = mcMMOPlayer.getPlayer();
if (mcMMOPlayer.inParty()) {
Party oldParty = mcMMOPlayer.getParty();
if (!handlePartyChangeEvent(player, oldParty.getName(), newPartyName, EventReason.CHANGED_PARTIES)) {
return false;
}
removeFromParty(mcMMOPlayer);
}
else return handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY);
return true;
}
/**
* Check if two online players are in the same party.
*
* @param firstPlayer The first player
* @param secondPlayer The second player
* @return true if they are in the same party, false otherwise
*/
public static boolean inSameParty(Player firstPlayer, Player secondPlayer) {
//Profile not loaded
if(UserManager.getPlayer(firstPlayer) == null)
{
return false;
}
//Profile not loaded
if(UserManager.getPlayer(secondPlayer) == null)
{
return false;
}
Party firstParty = UserManager.getPlayer(firstPlayer).getParty();
Party secondParty = UserManager.getPlayer(secondPlayer).getParty();
if (firstParty == null || secondParty == null) {
return false;
}
return firstParty.equals(secondParty);
}
public static boolean areAllies(Player firstPlayer, Player secondPlayer) {
//Profile not loaded
if(UserManager.getPlayer(firstPlayer) == null)
{
return false;
}
//Profile not loaded
if(UserManager.getPlayer(secondPlayer) == null)
{
return false;
}
Party firstParty = UserManager.getPlayer(firstPlayer).getParty();
Party secondParty = UserManager.getPlayer(secondPlayer).getParty();
if (firstParty == null || secondParty == null || firstParty.getAlly() == null || secondParty.getAlly() == null) {
return false;
}
return firstParty.equals(secondParty.getAlly()) && secondParty.equals(firstParty.getAlly());
}
/**
* Get the near party members.
*
* @param mcMMOPlayer The player to check
* @return the near party members
*/
public static List<Player> getNearMembers(McMMOPlayer mcMMOPlayer) {
List<Player> nearMembers = new ArrayList<>();
Party party = mcMMOPlayer.getParty();
if (party != null) {
Player player = mcMMOPlayer.getPlayer();
double range = mcMMO.p.getGeneralConfig().getPartyShareRange();
for (Player member : party.getOnlineMembers()) {
if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), member.getLocation(), range)) {
nearMembers.add(member);
}
}
}
return nearMembers;
}
public static List<Player> getNearVisibleMembers(McMMOPlayer mcMMOPlayer) {
List<Player> nearMembers = new ArrayList<>();
Party party = mcMMOPlayer.getParty();
if (party != null) {
Player player = mcMMOPlayer.getPlayer();
double range = mcMMO.p.getGeneralConfig().getPartyShareRange();
for (Player member : party.getVisibleMembers(player)) {
if (!player.equals(member)
&& member.isValid()
&& Misc.isNear(player.getLocation(), member.getLocation(), range)) {
nearMembers.add(member);
}
}
}
return nearMembers;
}
/**
* Get a list of all players in this player's party.
*
* @param player The player to check
* @return all the players in the player's party
*/
public static LinkedHashMap<UUID, String> getAllMembers(Player player) {
Party party = getParty(player);
return party == null ? new LinkedHashMap<>() : party.getMembers();
}
/**
* Get a list of all online players in this party.
*
* @param partyName The party to check
* @return all online players in this party
*/
public static List<Player> getOnlineMembers(String partyName) {
return getOnlineMembers(getParty(partyName));
}
/**
* Get a list of all online players in this party.
*
* @param player The player to check
* @return all online players in this party
*/
public static List<Player> getOnlineMembers(Player player) {
return getOnlineMembers(getParty(player));
}
private static List<Player> getOnlineMembers(Party party) {
return party == null ? new ArrayList<>() : party.getOnlineMembers();
}
/**
* Retrieve a party by its name
*
* @param partyName The party name
* @return the existing party, null otherwise
*/
public static Party getParty(String partyName) {
for (Party party : parties) {
if (party.getName().equalsIgnoreCase(partyName)) {
return party;
}
}
return null;
}
/**
* Retrieve a party by a members name
*
* @param playerName The members name
* @return the existing party, null otherwise
*/
@Deprecated
public static Party getPlayerParty(String playerName) {
for (Party party : parties) {
if (party.getMembers().containsKey(playerName)) {
return party;
}
}
return null;
}
/**
* Retrieve a party by a members uuid
*
* @param uuid The members uuid
* @return the existing party, null otherwise
*/
public static Party getPlayerParty(String playerName, UUID uuid) {
for (Party party : parties) {
LinkedHashMap<UUID, String> members = party.getMembers();
if (members.containsKey(uuid) || members.containsValue(playerName)) {
// Name changes
if (members.get(uuid) == null || !members.get(uuid).equals(playerName)) {
members.put(uuid, playerName);
}
return party;
}
}
return null;
}
/**
* Retrieve a party by member
*
* @param player The member
* @return the existing party, null otherwise
*/
public static Party getParty(Player player) {
//Profile not loaded
if(UserManager.getPlayer(player) == null)
{
return null;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
return mcMMOPlayer.getParty();
}
/**
* Get a list of all current parties.
*
* @return the list of parties.
*/
public static List<Party> getParties() {
return parties;
}
/**
* Remove a player from a party.
*
* @param player The player to remove
* @param party The party
*/
public static void removeFromParty(OfflinePlayer player, Party party) {
LinkedHashMap<UUID, String> members = party.getMembers();
String playerName = player.getName();
members.remove(player.getUniqueId());
if (player.isOnline()) {
party.getOnlineMembers().remove(player.getPlayer());
}
if (members.isEmpty()) {
parties.remove(party);
}
else {
// If the leaving player was the party leader, appoint a new leader from the party members
if (party.getLeader().getUniqueId().equals(player.getUniqueId())) {
setPartyLeader(members.keySet().iterator().next(), party);
}
informPartyMembersQuit(party, playerName);
}
}
/**
* Remove a player from a party.
*
* @param mcMMOPlayer The player to remove
*/
public static void removeFromParty(McMMOPlayer mcMMOPlayer) {
removeFromParty(mcMMOPlayer.getPlayer(), mcMMOPlayer.getParty());
processPartyLeaving(mcMMOPlayer);
}
/**
* Disband a party. Kicks out all members and removes the party.
*
* @param party The party to remove
*/
public static void disbandParty(Party party) {
//TODO: Potential issues with unloaded profile?
for (Player member : party.getOnlineMembers()) {
//Profile not loaded
if(UserManager.getPlayer(member) == null)
{
continue;
}
processPartyLeaving(UserManager.getPlayer(member));
}
// Disband the alliance between the disbanded party and it's ally
if (party.getAlly() != null) {
party.getAlly().setAlly(null);
}
parties.remove(party);
}
/**
* Create a new party
*
* @param mcMMOPlayer The player to add to the party
* @param partyName The party to add the player to
* @param password The password for this party, null if there was no password
*/
public static void createParty(McMMOPlayer mcMMOPlayer, String partyName, String password) {
Player player = mcMMOPlayer.getPlayer();
Party party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName.replace(".", ""), password);
if (password != null) {
player.sendMessage(LocaleLoader.getString("Party.Password.Set", password));
}
parties.add(party);
player.sendMessage(LocaleLoader.getString("Commands.Party.Create", party.getName()));
addToParty(mcMMOPlayer, party);
}
/**
* Check if a player can join a party
*
* @param player The player trying to join a party
* @param party The party
* @param password The password provided by the player
* @return true if the player can join the party
*/
public static boolean checkPartyPassword(Player player, Party party, String password) {
if (party.isLocked()) {
String partyPassword = party.getPassword();
if (partyPassword == null) {
player.sendMessage(LocaleLoader.getString("Party.Locked"));
return false;
}
if (password == null) {
player.sendMessage(LocaleLoader.getString("Party.Password.None"));
return false;
}
if (!password.equals(partyPassword)) {
player.sendMessage(LocaleLoader.getString("Party.Password.Incorrect"));
return false;
}
}
return true;
}
/**
* Accept a party invitation
*
* @param mcMMOPlayer The player to add to the party
*/
public static void joinInvitedParty(McMMOPlayer mcMMOPlayer) {
Party invite = mcMMOPlayer.getPartyInvite();
// Check if the party still exists, it might have been disbanded
if (!parties.contains(invite)) {
NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Party.Disband");
return;
}
/*
* Don't let players join a full party
*/
if(mcMMO.p.getGeneralConfig().getPartyMaxSize() > 0 && invite.getMembers().size() >= mcMMO.p.getGeneralConfig().getPartyMaxSize())
{
NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull.InviteAccept", invite.getName(), String.valueOf(mcMMO.p.getGeneralConfig().getPartyMaxSize()));
return;
}
NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Commands.Party.Invite.Accepted", invite.getName());
mcMMOPlayer.removePartyInvite();
addToParty(mcMMOPlayer, invite);
}
/**
* Accept a party alliance invitation
*
* @param mcMMOPlayer The player who accepts the alliance invite
*/
public static void acceptAllianceInvite(McMMOPlayer mcMMOPlayer) {
Party invite = mcMMOPlayer.getPartyAllianceInvite();
Player player = mcMMOPlayer.getPlayer();
// Check if the party still exists, it might have been disbanded
if (!parties.contains(invite)) {
player.sendMessage(LocaleLoader.getString("Party.Disband"));
return;
}
if (!handlePartyChangeAllianceEvent(player, mcMMOPlayer.getParty().getName(), invite.getName(), McMMOPartyAllianceChangeEvent.EventReason.FORMED_ALLIANCE)) {
return;
}
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.Accepted", invite.getName()));
mcMMOPlayer.removePartyAllianceInvite();
createAlliance(mcMMOPlayer.getParty(), invite);
}
public static void createAlliance(Party firstParty, Party secondParty) {
firstParty.setAlly(secondParty);
secondParty.setAlly(firstParty);
for (Player member : firstParty.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.Alliance.Formed", secondParty.getName()));
}
for (Player member : secondParty.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.Alliance.Formed", firstParty.getName()));
}
}
public static boolean disbandAlliance(Player player, Party firstParty, Party secondParty){
if (!handlePartyChangeAllianceEvent(player, firstParty.getName(), secondParty.getName(), McMMOPartyAllianceChangeEvent.EventReason.DISBAND_ALLIANCE)) {
return false;
}
PartyManager.disbandAlliance(firstParty, secondParty);
return true;
}
private static void disbandAlliance(Party firstParty, Party secondParty) {
firstParty.setAlly(null);
secondParty.setAlly(null);
for (Player member : firstParty.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.Alliance.Disband", secondParty.getName()));
}
for (Player member : secondParty.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.Alliance.Disband", firstParty.getName()));
}
}
/**
* Add a player to a party
*
* @param mcMMOPlayer The player to add to the party
* @param party The party
*/
public static void addToParty(McMMOPlayer mcMMOPlayer, Party party) {
Player player = mcMMOPlayer.getPlayer();
String playerName = player.getName();
informPartyMembersJoin(party, playerName);
mcMMOPlayer.setParty(party);
party.getMembers().put(player.getUniqueId(), player.getName());
party.getOnlineMembers().add(player);
}
/**
* Get the leader of a party.
*
* @param partyName The party name
* @return the leader of the party
*/
public static String getPartyLeaderName(String partyName) {
Party party = getParty(partyName);
return party == null ? null : party.getLeader().getPlayerName();
}
/**
* Set the leader of a party.
*
* @param uuid The uuid of the player to set as leader
* @param party The party
*/
public static void setPartyLeader(UUID uuid, Party party) {
OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(uuid);
UUID leaderUniqueId = party.getLeader().getUniqueId();
for (Player member : party.getOnlineMembers()) {
UUID memberUniqueId = member.getUniqueId();
if (memberUniqueId.equals(player.getUniqueId())) {
member.sendMessage(LocaleLoader.getString("Party.Owner.Player"));
}
else if (memberUniqueId.equals(leaderUniqueId)) {
member.sendMessage(LocaleLoader.getString("Party.Owner.NotLeader"));
}
else {
member.sendMessage(LocaleLoader.getString("Party.Owner.New", player.getName()));
}
}
party.setLeader(new PartyLeader(player.getUniqueId(), player.getName()));
}
/**
* Check if a player can invite others to his party.
*
* @return true if the player can invite
*/
public static boolean canInvite(McMMOPlayer mcMMOPlayer) {
Party party = mcMMOPlayer.getParty();
return !party.isLocked() || party.getLeader().getUniqueId().equals(mcMMOPlayer.getPlayer().getUniqueId());
}
/**
* Load party file.
*/
public static void loadParties() {
if (!partyFile.exists()) {
return;
}
// if (mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.ADD_UUIDS_PARTY)) {
// loadAndUpgradeParties();
// return;
// }
try {
YamlConfiguration partiesFile;
partiesFile = YamlConfiguration.loadConfiguration(partyFile);
ArrayList<Party> hasAlly = new ArrayList<>();
for (String partyName : partiesFile.getConfigurationSection("").getKeys(false)) {
Party party = new Party(partyName);
String[] leaderSplit = partiesFile.getString(partyName + ".Leader").split("[|]");
party.setLeader(new PartyLeader(UUID.fromString(leaderSplit[0]), leaderSplit[1]));
party.setPassword(partiesFile.getString(partyName + ".Password"));
party.setLocked(partiesFile.getBoolean(partyName + ".Locked"));
party.setLevel(partiesFile.getInt(partyName + ".Level"));
party.setXp(partiesFile.getInt(partyName + ".Xp"));
if (partiesFile.getString(partyName + ".Ally") != null) {
hasAlly.add(party);
}
party.setXpShareMode(ShareMode.getShareMode(partiesFile.getString(partyName + ".ExpShareMode", "NONE")));
party.setItemShareMode(ShareMode.getShareMode(partiesFile.getString(partyName + ".ItemShareMode", "NONE")));
for (ItemShareType itemShareType : ItemShareType.values()) {
party.setSharingDrops(itemShareType, partiesFile.getBoolean(partyName + ".ItemShareType." + itemShareType.toString(), true));
}
LinkedHashMap<UUID, String> members = party.getMembers();
for (String memberEntry : partiesFile.getStringList(partyName + ".Members")) {
String[] memberSplit = memberEntry.split("[|]");
members.put(UUID.fromString(memberSplit[0]), memberSplit[1]);
}
parties.add(party);
}
mcMMO.p.debug("Loaded (" + parties.size() + ") Parties...");
for (Party party : hasAlly) {
party.setAlly(PartyManager.getParty(partiesFile.getString(party.getName() + ".Ally")));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Save party file.
*/
public static void saveParties() {
mcMMO.p.debug("[Party Data] Saving...");
if (partyFile.exists()) {
if (!partyFile.delete()) {
mcMMO.p.getLogger().warning("Could not delete party file. Party saving failed!");
return;
}
}
YamlConfiguration partiesFile = new YamlConfiguration();
for (Party party : parties) {
String partyName = party.getName();
PartyLeader leader = party.getLeader();
partiesFile.set(partyName + ".Leader", leader.getUniqueId().toString() + "|" + leader.getPlayerName());
partiesFile.set(partyName + ".Password", party.getPassword());
partiesFile.set(partyName + ".Locked", party.isLocked());
partiesFile.set(partyName + ".Level", party.getLevel());
partiesFile.set(partyName + ".Xp", (int) party.getXp());
partiesFile.set(partyName + ".Ally", (party.getAlly() != null) ? party.getAlly().getName() : "");
partiesFile.set(partyName + ".ExpShareMode", party.getXpShareMode().toString());
partiesFile.set(partyName + ".ItemShareMode", party.getItemShareMode().toString());
for (ItemShareType itemShareType : ItemShareType.values()) {
partiesFile.set(partyName + ".ItemShareType." + itemShareType.toString(), party.sharingDrops(itemShareType));
}
List<String> members = new ArrayList<>();
for (Entry<UUID, String> memberEntry : party.getMembers().entrySet()) {
String memberUniqueId = memberEntry.getKey() == null ? "" : memberEntry.getKey().toString();
String memberName = memberEntry.getValue();
if (!members.contains(memberName)) {
members.add(memberUniqueId + "|" + memberName);
}
}
partiesFile.set(partyName + ".Members", members);
}
try {
partiesFile.save(partyFile);
}
catch (Exception e) {
e.printStackTrace();
}
}
// private static void loadAndUpgradeParties() {
// YamlConfiguration partiesFile = YamlConfiguration.loadConfiguration(partyFile);
//
// if (!partyFile.renameTo(new File(mcMMO.getFlatFileDirectory() + "parties.yml.converted"))) {
// mcMMO.p.getLogger().severe("Could not rename parties.yml to parties.yml.converted!");
// return;
// }
//
// ArrayList<Party> hasAlly = new ArrayList<>();
//
// for (String partyName : partiesFile.getConfigurationSection("").getKeys(false)) {
// Party party = new Party(partyName);
//
// String leaderName = partiesFile.getString(partyName + ".Leader");
// PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(leaderName, false);
//
// if (!profile.isLoaded()) {
// mcMMO.p.getLogger().warning("Could not find UUID in database for party leader " + leaderName + " in party " + partyName);
// continue;
// }
//
// UUID leaderUniqueId = profile.getUniqueId();
//
// party.setLeader(new PartyLeader(leaderUniqueId, leaderName));
// party.setPassword(partiesFile.getString(partyName + ".Password"));
// party.setLocked(partiesFile.getBoolean(partyName + ".Locked"));
// party.setLevel(partiesFile.getInt(partyName + ".Level"));
// party.setXp(partiesFile.getInt(partyName + ".Xp"));
//
// if (partiesFile.getString(partyName + ".Ally") != null) {
// hasAlly.add(party);
// }
//
// party.setXpShareMode(ShareMode.getShareMode(partiesFile.getString(partyName + ".ExpShareMode", "NONE")));
// party.setItemShareMode(ShareMode.getShareMode(partiesFile.getString(partyName + ".ItemShareMode", "NONE")));
//
// for (ItemShareType itemShareType : ItemShareType.values()) {
// party.setSharingDrops(itemShareType, partiesFile.getBoolean(partyName + ".ItemShareType." + itemShareType.toString(), true));
// }
//
// LinkedHashMap<UUID, String> members = party.getMembers();
//
// for (String memberName : partiesFile.getStringList(partyName + ".Members")) {
// PlayerProfile memberProfile = mcMMO.getDatabaseManager().loadPlayerProfile(memberName, false);
//
// if (!memberProfile.isLoaded()) {
// mcMMO.p.getLogger().warning("Could not find UUID in database for party member " + memberName + " in party " + partyName);
// continue;
// }
//
// UUID memberUniqueId = memberProfile.getUniqueId();
//
// members.put(memberUniqueId, memberName);
// }
//
// parties.add(party);
// }
//
// mcMMO.p.debug("Loaded (" + parties.size() + ") Parties...");
//
// for (Party party : hasAlly) {
// party.setAlly(PartyManager.getParty(partiesFile.getString(party.getName() + ".Ally")));
// }
//
// mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_UUIDS_PARTY);
// }
/**
* Handle party change event.
*
* @param player The player changing parties
* @param oldPartyName The name of the old party
* @param newPartyName The name of the new party
* @param reason The reason for changing parties
* @return true if the change event was successful, false otherwise
*/
public static boolean handlePartyChangeEvent(Player player, String oldPartyName, String newPartyName, EventReason reason) {
McMMOPartyChangeEvent event = new McMMOPartyChangeEvent(player, oldPartyName, newPartyName, reason);
mcMMO.p.getServer().getPluginManager().callEvent(event);
return !event.isCancelled();
}
/**
* Handle party alliance change event.
*
* @param player The player changing party alliances
* @param oldAllyName The name of the old ally
* @param newAllyName The name of the new ally
* @param reason The reason for changing allies
* @return true if the change event was successful, false otherwise
*/
public static boolean handlePartyChangeAllianceEvent(Player player, String oldAllyName, String newAllyName, McMMOPartyAllianceChangeEvent.EventReason reason) {
McMMOPartyAllianceChangeEvent event = new McMMOPartyAllianceChangeEvent(player, oldAllyName, newAllyName, reason);
mcMMO.p.getServer().getPluginManager().callEvent(event);
return !event.isCancelled();
}
/**
* Remove party data from the mcMMOPlayer.
*
* @param mcMMOPlayer The player to remove party data from.
*/
public static void processPartyLeaving(McMMOPlayer mcMMOPlayer) {
mcMMOPlayer.removeParty();
mcMMOPlayer.setChatMode(ChatChannel.NONE);
mcMMOPlayer.setItemShareModifier(10);
}
/**
* Notify party members when the party levels up.
*
* @param party The concerned party
* @param levelsGained The amount of levels gained
* @param level The current party level
*/
public static void informPartyMembersLevelUp(Party party, int levelsGained, int level) {
boolean levelUpSoundsEnabled = mcMMO.p.getGeneralConfig().getLevelUpSoundsEnabled();
for (Player member : party.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.LevelUp", levelsGained, level));
if (levelUpSoundsEnabled) {
SoundManager.sendSound(member, member.getLocation(), SoundType.LEVEL_UP);
}
}
}
/**
* Notify party members when a player joins.
*
* @param party The concerned party
* @param playerName The name of the player that joined
*/
private static void informPartyMembersJoin(Party party, String playerName) {
for (Player member : party.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.InformedOnJoin", playerName));
}
}
/**
* Notify party members when a party member quits.
*
* @param party The concerned party
* @param playerName The name of the player that left
*/
private static void informPartyMembersQuit(Party party, String playerName) {
for (Player member : party.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Party.InformedOnQuit", playerName));
}
}
}

View File

@ -1,6 +1,6 @@
package com.gmail.nossr50.party; package com.gmail.nossr50.party;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -12,7 +12,7 @@ public class PartyTeleportRecord {
public PartyTeleportRecord() { public PartyTeleportRecord() {
requestor = null; requestor = null;
enabled = true; enabled = true;
confirmRequired = Config.getInstance().getPTPCommandConfirmRequired(); confirmRequired = mcMMO.p.getGeneralConfig().getPTPCommandConfirmRequired();
timeout = 0; timeout = 0;
lastUse = 0; lastUse = 0;
} }

View File

@ -3,6 +3,7 @@ package com.gmail.nossr50.party;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.mcMMO;
import com.neetgames.mcmmo.experience.XPGainReason; import com.neetgames.mcmmo.experience.XPGainReason;
import com.neetgames.mcmmo.experience.XPGainSource; import com.neetgames.mcmmo.experience.XPGainSource;
import com.neetgames.mcmmo.party.Party; import com.neetgames.mcmmo.party.Party;
@ -38,7 +39,7 @@ public final class ShareHandler {
nearMembers.add(mmoPlayer.getPlayer()); nearMembers.add(mmoPlayer.getPlayer());
int partySize = nearMembers.size(); int partySize = nearMembers.size();
double shareBonus = Math.min(Config.getInstance().getPartyShareBonusBase() + (partySize * Config.getInstance().getPartyShareBonusIncrease()), Config.getInstance().getPartyShareBonusCap()); double shareBonus = Math.min(mcMMO.p.getGeneralConfig().getPartyShareBonusBase() + (partySize * mcMMO.p.getGeneralConfig().getPartyShareBonusIncrease()), mcMMO.p.getGeneralConfig().getPartyShareBonusCap());
float splitXp = (float) (xp / partySize * shareBonus); float splitXp = (float) (xp / partySize * shareBonus);
for (Player otherMember : nearMembers) { for (Player otherMember : nearMembers) {

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.runnables.backups; package com.gmail.nossr50.runnables.backups;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@ -48,11 +47,11 @@ public class CleanBackupsTask extends BukkitRunnable {
int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR); int year = cal.get(Calendar.YEAR);
if (isPast24Hours(date) && Config.getInstance().getKeepLast24Hours()) { if (isPast24Hours(date) && mcMMO.p.getGeneralConfig().getKeepLast24Hours()) {
// Keep all files from the last 24 hours // Keep all files from the last 24 hours
continue; continue;
} }
else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && Config.getInstance().getKeepDailyLastWeek()) { else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) {
// Keep daily backups of the past week // Keep daily backups of the past week
savedDays.add(dayOfWeek); savedDays.add(dayOfWeek);
continue; continue;
@ -60,7 +59,7 @@ public class CleanBackupsTask extends BukkitRunnable {
else { else {
List<Integer> savedWeeks = savedYearsWeeks.computeIfAbsent(year, k -> new ArrayList<>()); List<Integer> savedWeeks = savedYearsWeeks.computeIfAbsent(year, k -> new ArrayList<>());
if (!savedWeeks.contains(weekOfYear) && Config.getInstance().getKeepWeeklyPastMonth()) { if (!savedWeeks.contains(weekOfYear) && mcMMO.p.getGeneralConfig().getKeepWeeklyPastMonth()) {
// Keep one backup of each week // Keep one backup of each week
savedWeeks.add(weekOfYear); savedWeeks.add(weekOfYear);
continue; continue;

View File

@ -1,10 +1,10 @@
package com.gmail.nossr50.runnables.commands; package com.gmail.nossr50.runnables.commands;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.SkillTools;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@ -30,7 +30,7 @@ public class McrankCommandDisplayTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
if (useBoard && Config.getInstance().getScoreboardsEnabled()) { if (useBoard && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
displayBoard(); displayBoard();
} }
@ -47,13 +47,13 @@ public class McrankCommandDisplayTask extends BukkitRunnable {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Heading")); sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Heading"));
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Player", playerName)); sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Player", playerName));
for (PrimarySkillType skill : PrimarySkillType.NON_CHILD_SKILLS) { for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) {
// if (!skill.getPermissions(player)) { // if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, skill)) {
// continue; // continue;
// } // }
rank = skills.get(skill); rank = skills.get(skill);
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", skill.getName(), (rank == null ? LocaleLoader.getString("Commands.mcrank.Unranked") : rank))); sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), (rank == null ? LocaleLoader.getString("Commands.mcrank.Unranked") : rank)));
} }
rank = skills.get(null); rank = skills.get(null);

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.runnables.commands; package com.gmail.nossr50.runnables.commands;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@ -36,7 +35,7 @@ public class MctopCommandDisplayTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
if (useBoard && Config.getInstance().getScoreboardsEnabled()) { if (useBoard && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
displayBoard(); displayBoard();
} }
@ -62,10 +61,10 @@ public class MctopCommandDisplayTask extends BukkitRunnable {
} }
else { else {
if(sender instanceof Player) { if(sender instanceof Player) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", primarySkillType.getName())); sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill)));
} }
else { else {
sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", primarySkillType.getName()))); sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill))));
} }
} }

View File

@ -10,6 +10,7 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillTools;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@ -57,7 +58,7 @@ public class FormulaConversionTask extends BukkitRunnable {
private void editValues(PlayerProfile profile) { private void editValues(PlayerProfile profile) {
mcMMO.p.debug("========================================================================"); mcMMO.p.debug("========================================================================");
mcMMO.p.debug("Conversion report for " + profile.getPlayerName() + ":"); mcMMO.p.debug("Conversion report for " + profile.getPlayerName() + ":");
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
int oldLevel = profile.getSkillLevel(primarySkillType); int oldLevel = profile.getSkillLevel(primarySkillType);
int oldXPLevel = profile.getSkillXpLevel(primarySkillType); int oldXPLevel = profile.getSkillXpLevel(primarySkillType);
int totalOldXP = mcMMO.getFormulaManager().calculateTotalExperience(oldLevel, oldXPLevel); int totalOldXP = mcMMO.getFormulaManager().calculateTotalExperience(oldLevel, oldXPLevel);

View File

@ -1,6 +1,5 @@
package com.gmail.nossr50.runnables.database; package com.gmail.nossr50.runnables.database;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@ -13,7 +12,7 @@ public class UserPurgeTask extends BukkitRunnable {
lock.lock(); lock.lock();
mcMMO.getDatabaseManager().purgePowerlessUsers(); mcMMO.getDatabaseManager().purgePowerlessUsers();
if (Config.getInstance().getOldUsersCutoff() != -1) { if (mcMMO.p.getGeneralConfig().getOldUsersCutoff() != -1) {
mcMMO.getDatabaseManager().purgeOldUsers(); mcMMO.getDatabaseManager().purgeOldUsers();
} }
lock.unlock(); lock.unlock();

View File

@ -1,8 +1,8 @@
package com.gmail.nossr50.runnables.items; package com.gmail.nossr50.runnables.items;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.ChimaeraWing; import com.gmail.nossr50.util.ChimaeraWing;
import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
@ -36,13 +36,13 @@ public class ChimaeraWingWarmup extends BukkitRunnable {
ItemStack inHand = player.getInventory().getItemInMainHand(); ItemStack inHand = player.getInventory().getItemInMainHand();
if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < Config.getInstance().getChimaeraUseCost()) { if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < mcMMO.p.getGeneralConfig().getChimaeraUseCost()) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name"))); player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name")));
return; return;
} }
long recentlyHurt = mmoPlayer.getRecentlyHurtTimestamp(); long recentlyHurt = mmoPlayer.getRecentlyHurtTimestamp();
int hurtCooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown(); int hurtCooldown = mcMMO.p.getGeneralConfig().getChimaeraRecentlyHurtCooldown();
if (hurtCooldown > 0) { if (hurtCooldown > 0) {
int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);

Some files were not shown because too many files have changed in this diff Show More