Compare commits

..
36 Commits
Author SHA1 Message Date
BenCodez abd86834a6 Update version number to 6.18.2 2025-01-26 13:29:33 -06:00
BenCodez c6647d7cc3 Slight change to plugin messaging 2025-01-26 09:54:46 -06:00
BenCodez a3851f9bf2 Update version number to 6.18.2-SNAPSHOT 2025-01-25 20:37:57 -06:00
BenCodez a951aae0de Update version number to 6.18.1 2025-01-25 20:15:31 -06:00
BenCodez 826fc95131 Adjust encryption 2025-01-25 19:22:14 -06:00
BenCodez dea13f6ff1 Add log warning for disabled plugin message encryption on proxy 2025-01-25 18:24:39 -06:00
BenCodez bab55de93b Add warning when PluginMessageEncryption is disabled 2025-01-25 17:51:53 -06:00
BenCodez 1c112688b1 Add restart requirement notes for PluginMessageChannel and
PluginMessageEncryption

- Added note for PluginMessageChannel restart requirement
- Added note for PluginMessageEncryption restart requirement
- Instructed to copy secretkey.key file to all servers
- Ensured settings must match on all servers
- Updated `BungeeSettings.yml` and `bungeeconfig.yml` files
2025-01-25 16:59:27 -06:00
BenCodez bc0e82f68f Fix null check and correct config path
- Add null check for playerName in isPlayerOnline method
- Correct path for PluginMessageChannel in BungeeSettings
- Ensure playerName is not null before checking online status
- Update config annotation path in BungeeSettings
- Improve code robustness and prevent potential null pointer exceptions
2025-01-25 16:50:10 -06:00
BenCodez a82397a67f Update channel identifier creation to use lowercase values
- Split plugin message channel by colon
- Convert channel parts to lowercase
- Create MinecraftChannelIdentifier with lowercase values
- Register the new channel identifier
- Ensure compatibility with case-insensitive channels
- Improve robustness of channel handling
2025-01-25 16:12:33 -06:00
BenCodez b1ffce516c Add plugin message encryption support
- Add `PluginMessageEncryption` to config files
- Update `BungeeHandler` to handle encryption
- Modify `VotingPluginProxy` to support encrypted messages
- Implement encryption checks in `Config` classes
- Update `BungeeSettings` with encryption setting
- Ensure message encryption in `sendPluginMessage` method
2025-01-25 16:09:53 -06:00
BenCodez f48a008040 Add ability to change pluginmessage channel 2025-01-25 15:35:42 -06:00
BenCodez 90c8255894 Fix isSomeoneOnlineServer method to correctly check for online
players.
2025-01-25 12:36:14 -06:00
BenCodez 4001e865f5 Refactor plugin message handling in VotingPluginProxy
- Combine if-else statements for subchannel checks
- Add comment for unused "TimeChangeFinished" subchannel
- Add handling for "VoteUpdate" subchannel
- Add debug message for ignored plugin messages
- Improve code readability and maintainability
- Ensure proper message forwarding and logging
2025-01-24 17:32:55 -06:00
BenCodez 77b7659cb6 Fix for velocity 2025-01-24 16:24:26 -06:00
BenCodez bc073857f6 Test change for velocity 2025-01-24 16:21:02 -06:00
BenCodez 9c2a41c9b5 Fix reward path in AdminVoteVoteShopItem.java 2025-01-24 10:40:16 -06:00
BenCodez 972f5350a1 Change default second votesite 2025-01-22 08:09:46 -06:00
BenCodez 66df9d85da Improve javadoc commments for VotingPluginUser 2025-01-20 09:55:45 -06:00
Ben 4046dd9d7f Merge pull request #1412 from BlvckBytes/master
Added variable %sitename% to placeholders of Commands.Vote.Today.Line
2025-01-18 19:58:16 -06:00
Philip Hell d89aa6ccb2 Added variable %sitename% to placeholders of Commands.Vote.Today.Line 2025-01-19 02:50:28 +01:00
Ben 813ffed723 Merge pull request #1404 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-javadoc-plugin-3.11.2
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.11.1 to 3.11.2 in /VotingPlugin
2025-01-12 15:59:02 -06:00
BenCodez c0bc1b2730 Adjust when dev build warning is given 2025-01-10 19:25:37 -06:00
BenCodez 1217e63583 Changes to proxy handling 2025-01-09 08:46:45 -06:00
BenCodez cd6ed92e4f Rewrite backend on velocity to make it more universal with bungee 2025-01-09 08:12:29 -06:00
BenCodez 07c9eda769 Code cleanup 2024-12-31 15:39:51 -06:00
BenCodez ef0f73ba32 Fix a few issues on bungee related to internal changes 2024-12-31 15:29:53 -06:00
BenCodez 10b0fd3b11 Internal rewrites of bungee for universal proxy backend 2024-12-31 11:19:07 -06:00
BenCodez a4aa209aa7 Fix handling of previous months votes on certain dates 2024-12-31 11:17:45 -06:00
BenCodez 70af742083 Code cleanup 2024-12-29 21:42:00 -06:00
BenCodez 0463700037 Add permission check to sites not voted on 2024-12-27 11:08:30 -06:00
BenCodez 69d9c09b06 Increase default skull cache timing 2024-12-20 07:54:11 -06:00
BenCodez 4455cc96b9 Fix issue with no vote url set 2024-12-17 09:11:59 -06:00
BenCodez 0ee7c1f2e8 Adjustment to maven profile 2024-12-16 20:44:49 -06:00
BenCodez 4b3cc8c8e0 Update version number to 6.18.1-SNAPSHOT 2024-12-16 20:36:49 -06:00
dependabot[bot] bc49aae401 Bump org.apache.maven.plugins:maven-javadoc-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.11.1 to 3.11.2.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.11.1...maven-javadoc-plugin-3.11.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-09 06:39:01 +00:00
85 changed files with 6491 additions and 6175 deletions

No files matched your search

+11
View File
@@ -84,6 +84,17 @@ BungeeVotePartyRewards: {}
# This runs a one time command only
BungeeVotePartyGlobalCommands: []
# Default is vp:vp, can be changed to prevent potential exploits
# Must match on all servers
# This setting requires a restart
PluginMessageChannel: "vp:vp"
# Use this to encrypt the plugin messages
# Must be set on all servers the same
# Copy secretkey.key file to all servers (They all must match)
# This setting requires a restart
PluginMessageEncryption: false
####################################################################################
# Global mysql data handle for between server commmunications
# This is NOT required for bungee voting to work
+3 -3
View File
@@ -602,7 +602,7 @@ DefaultRewardBlackListedWorlds: []
# This setting only enables setting totals, not using them
# Enabling this is pretty safe and harmless with just this setting
# Essentially will just copy MonthTotal to MonthTotal-MONTH-YEAR
# Can use command /vote PreviousMonthsVoters after this is enabled
# Can use command /vote PreviousMonthstotals after this is enabled
StoreMonthTotalsWithDate: false
# Experimental
@@ -621,10 +621,10 @@ UseMonthDateTotalsAsPrimaryTotal: false
PreloadSkulls: true
# Number of miliseconds between skull caching
# Default about 3 seconds is good for most servers
# Default about 4 seconds is good for most servers
# Used to avoid rate limit, increase if needed
# If rate limit is hit caching will pause for 15 minutes
SkullLoadDelay: 3000
SkullLoadDelay: 4000
# Set a skull profile URL
# This is what gets used to cache skulls
+1 -1
View File
@@ -89,7 +89,7 @@ VoteSites:
Site2:
Enabled: false
Name: 'Site2'
ServiceSite: 'PlanetMinecraft.com'
ServiceSite: 'Crafty.gg'
VoteURL: 'link to vote URL here, used in /vote'
VoteDelay: 24
DisplayItem:
+11
View File
@@ -85,6 +85,17 @@ WhiteListedServers: []
# REDIS
BungeeMethod: PLUGINMESSAGING
# Default is vp:vp, can be changed to prevent potential exploits
# Must match on all servers
# This setting requires a restart
PluginMessageChannel: "vp:vp"
# Use this to encrypt the plugin messages
# Must be set on all servers the same
# Copy secretkey.key file to all servers (They all must match)
# This setting requires a restart
PluginMessageEncryption: false
# Use Redis for between server communication, set BungeeMethod to REDIS to use this
Redis:
Host: localhost
-2
View File
@@ -247,8 +247,6 @@ permissions:
description: Allows admincommands
VotingPlugin.Admin.Debug:
description: Permission to view debug info ingame
VotingPlugin.Signs.Create:
description: Allows access to create signs
VotingPlugin.TopVoter.Ignore:
description: Allows you to be exempt from top voter
VotingPlugin.NoRemind:
+7 -7
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.bencodez</groupId>
<artifactId>votingplugin</artifactId>
<version>6.18</version>
<version>6.18.2</version>
<packaging>jar</packaging>
<name>VotingPlugin</name>
<properties>
@@ -257,7 +257,7 @@
<dependency>
<groupId>com.bencodez</groupId>
<artifactId>advancedcore</artifactId>
<version>3.7.12</version>
<version>3.7.14-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
@@ -342,14 +342,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.11.1</version>
<version>3.11.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<phase>install</phase>
<phase>deploy</phase>
<configuration>
<sourcepath>
${project.basedir}/target/delombok</sourcepath>
@@ -372,7 +372,7 @@
<executions>
<execution>
<id>default-deploy</id>
<phase>install</phase>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
@@ -417,7 +417,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.11.1</version>
<version>3.11.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
@@ -559,7 +559,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.11.1</version>
<version>3.11.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
@@ -78,29 +78,6 @@ public class BungeeHandler implements Listener {
this.plugin = plugin;
}
public void close() {
if (socketHandler != null) {
socketHandler.closeConnection();
}
if (clientHandler != null) {
clientHandler.stopConnection();
}
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
if (globalDataHandler != null) {
globalDataHandler.getGlobalMysql().close();
}
}
/*
* @EventHandler public void onDateChange(DateChangedEvent event) { if
* (method.equals(BungeeMethod.PLUGINMESSAGING)) {
* plugin.getPluginMessaging().sendPluginMessage("timeupdate",
* plugin.getServerDataFile().getPrevMonth() + "//" +
* plugin.getServerDataFile().getPrevDay() + "//" +
* plugin.getServerDataFile().getPrevWeekDay()); } }
*/
public void checkGlobalData() {
HashMap<String, DataValue> data = globalDataHandler.getExact(plugin.getBungeeSettings().getServer());
// plugin.debug(data.toString());
@@ -131,19 +108,21 @@ public class BungeeHandler implements Listener {
}
if (forceUpdate) {
HashMap<String, DataValue> dataToSet = new HashMap<String, DataValue>();
HashMap<String, DataValue> dataToSet = new HashMap<>();
dataToSet.put("FinishedProcessing", new DataValueBoolean(true));
dataToSet.put("Processing", new DataValueBoolean(false));
globalDataHandler.setData(plugin.getBungeeSettings().getServer(), dataToSet);
}
}
public boolean checkGlobalDataTimeValue(DataValue data) {
if (data.isBoolean()) {
return data.getBoolean();
}
return Boolean.valueOf(data.getString());
}
/*
* @EventHandler public void onDateChange(DateChangedEvent event) { if
* (method.equals(BungeeMethod.PLUGINMESSAGING)) {
* plugin.getPluginMessaging().sendPluginMessage("timeupdate",
* plugin.getServerDataFile().getPrevMonth() + "//" +
* plugin.getServerDataFile().getPrevDay() + "//" +
* plugin.getServerDataFile().getPrevWeekDay()); } }
*/
public boolean checkGlobalDataTime(TimeType type, HashMap<String, DataValue> data) {
boolean isProcessing = false;
@@ -174,106 +153,24 @@ public class BungeeHandler implements Listener {
return isProcessing;
}
public void loadGlobalMysql() {
if (plugin.getBungeeSettings().isGloblalDataEnabled()) {
if (timer != null) {
timer.shutdown();
try {
timer.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.shutdownNow();
}
timer = Executors.newScheduledThreadPool(1);
timer.scheduleWithFixedDelay(new Runnable() {
public boolean checkGlobalDataTimeValue(DataValue data) {
if (data.isBoolean()) {
return data.getBoolean();
}
return Boolean.valueOf(data.getString());
}
@Override
public void run() {
checkGlobalData();
}
}, 60, 10, TimeUnit.SECONDS);
timer.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
globalDataHandler.setString(plugin.getBungeeSettings().getServer(), "LastOnline",
"" + LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli());
}
}, 1, 60, TimeUnit.MINUTES);
if (globalDataHandler != null) {
globalDataHandler.getGlobalMysql().close();
}
if (plugin.getBungeeSettings().isGloblalDataUseMainMySQL()
&& plugin.getStorageType().equals(UserStorage.MYSQL)) {
globalDataHandler = new GlobalDataHandler(
new GlobalMySQL("VotingPlugin_GlobalData", plugin.getMysql().getMysql()) {
@Override
public void warning(String text) {
plugin.getLogger().warning(text);
}
@Override
public void severe(String text) {
plugin.getLogger().severe(text);
}
@Override
public void debug(Exception e) {
plugin.debug(e);
}
@Override
public void debug(String text) {
plugin.debug(text);
}
@Override
public void info(String text) {
plugin.getLogger().info(text);
}
});
} else {
globalDataHandler = new GlobalDataHandler(
new GlobalMySQL("VotingPlugin_GlobalData", new MysqlConfigSpigot(
plugin.getBungeeSettings().getData().getConfigurationSection("GlobalData"))) {
@Override
public void warning(String text) {
plugin.getLogger().warning(text);
}
@Override
public void severe(String text) {
plugin.getLogger().severe(text);
}
@Override
public void debug(Exception e) {
plugin.debug(e);
}
@Override
public void debug(String text) {
plugin.debug(text);
}
@Override
public void info(String text) {
plugin.getLogger().info(text);
}
});
}
globalDataHandler.getGlobalMysql().alterColumnType("IgnoreTime", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("MONTH", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("WEEK", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("DAY", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("FinishedProcessing", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("Processing", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("LastUpdated", "MEDIUMTEXT");
globalDataHandler.getGlobalMysql().alterColumnType("ForceUpdate", "VARCHAR(5)");
plugin.getTimeChecker().setProcessingEnabled(false);
public void close() {
if (socketHandler != null) {
socketHandler.closeConnection();
}
if (clientHandler != null) {
clientHandler.stopConnection();
}
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
if (globalDataHandler != null) {
globalDataHandler.getGlobalMysql().close();
}
}
@@ -295,12 +192,12 @@ public class BungeeHandler implements Listener {
} else if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
plugin.getPluginMessaging().sendPluginMessage(subChannel, messageData);
} else if (method.equals(BungeeMethod.SOCKETS)) {
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
list.add(subChannel);
list.addAll(ArrayUtils.convert(messageData));
sendData(ArrayUtils.convert(list));
} else if (method.equals(BungeeMethod.REDIS)) {
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
list.add(subChannel);
list.addAll(ArrayUtils.convert(messageData));
redisHandler.sendMessage(plugin.getBungeeSettings().getRedisPrefix() + "VotingPlugin",
@@ -608,28 +505,28 @@ public class BungeeHandler implements Listener {
});
if (method.equals(BungeeMethod.MYSQL)) {
plugin.registerBungeeChannels("vp:vp");
plugin.registerBungeeChannels(plugin.getBungeeSettings().getPluginMessagingChannel());
} else if (method.equals(BungeeMethod.REDIS)) {
redisHandler = new RedisHandler(plugin.getBungeeSettings().getRedisHost(),
plugin.getBungeeSettings().getRedisPort(), plugin.getBungeeSettings().getRedisUsername(),
plugin.getBungeeSettings().getRedisPassword()) {
@Override
protected void onMessage(String channel, String[] message) {
plugin.getLogger().info(channel + ArrayUtils.makeStringList(ArrayUtils.convert(message)));
if (message.length > 0) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 1; i < message.length; i++) {
list.add(message[i]);
}
globalMessageHandler.onMessage(message[0], list);
public void debug(String message) {
if (plugin.getBungeeSettings().isBungeeDebug()) {
plugin.debug(message);
}
}
@Override
public void debug(String message) {
if (plugin.getBungeeSettings().isBungeeDebug()) {
plugin.debug(message);
protected void onMessage(String channel, String[] message) {
plugin.getLogger().info(channel + ArrayUtils.makeStringList(ArrayUtils.convert(message)));
if (message.length > 0) {
ArrayList<String> list = new ArrayList<>();
for (int i = 1; i < message.length; i++) {
list.add(message[i]);
}
globalMessageHandler.onMessage(message[0], list);
}
}
};
@@ -647,8 +544,12 @@ public class BungeeHandler implements Listener {
redisThread.start();
} else if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
plugin.registerBungeeChannels(plugin.getBungeeSettings().getPluginMessagingChannel());
plugin.registerBungeeChannels("vp:vp");
if (plugin.getBungeeSettings().isPluginMessageEncryption()) {
encryptionHandler = new EncryptionHandler(new File(plugin.getDataFolder(), "secretkey.key"));
plugin.getPluginMessaging().setEncryptionHandler(encryptionHandler);
}
bungeeVotePartyCurrent = plugin.getServerData().getBungeeVotePartyCurrent();
bungeeVotePartyRequired = plugin.getServerData().getBungeeVotePartyRequired();
@@ -895,6 +796,109 @@ public class BungeeHandler implements Listener {
}
public void loadGlobalMysql() {
if (plugin.getBungeeSettings().isGloblalDataEnabled()) {
if (timer != null) {
timer.shutdown();
try {
timer.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.shutdownNow();
}
timer = Executors.newScheduledThreadPool(1);
timer.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
checkGlobalData();
}
}, 60, 10, TimeUnit.SECONDS);
timer.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
globalDataHandler.setString(plugin.getBungeeSettings().getServer(), "LastOnline",
"" + LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli());
}
}, 1, 60, TimeUnit.MINUTES);
if (globalDataHandler != null) {
globalDataHandler.getGlobalMysql().close();
}
if (plugin.getBungeeSettings().isGloblalDataUseMainMySQL()
&& plugin.getStorageType().equals(UserStorage.MYSQL)) {
globalDataHandler = new GlobalDataHandler(
new GlobalMySQL("VotingPlugin_GlobalData", plugin.getMysql().getMysql()) {
@Override
public void debug(Exception e) {
plugin.debug(e);
}
@Override
public void debug(String text) {
plugin.debug(text);
}
@Override
public void info(String text) {
plugin.getLogger().info(text);
}
@Override
public void severe(String text) {
plugin.getLogger().severe(text);
}
@Override
public void warning(String text) {
plugin.getLogger().warning(text);
}
});
} else {
globalDataHandler = new GlobalDataHandler(
new GlobalMySQL("VotingPlugin_GlobalData", new MysqlConfigSpigot(
plugin.getBungeeSettings().getData().getConfigurationSection("GlobalData"))) {
@Override
public void debug(Exception e) {
plugin.debug(e);
}
@Override
public void debug(String text) {
plugin.debug(text);
}
@Override
public void info(String text) {
plugin.getLogger().info(text);
}
@Override
public void severe(String text) {
plugin.getLogger().severe(text);
}
@Override
public void warning(String text) {
plugin.getLogger().warning(text);
}
});
}
globalDataHandler.getGlobalMysql().alterColumnType("IgnoreTime", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("MONTH", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("WEEK", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("DAY", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("FinishedProcessing", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("Processing", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("LastUpdated", "MEDIUMTEXT");
globalDataHandler.getGlobalMysql().alterColumnType("ForceUpdate", "VARCHAR(5)");
plugin.getTimeChecker().setProcessingEnabled(false);
}
}
public void sendData(String... strings) {
clientHandler.sendMessage(strings);
}
@@ -117,7 +117,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
private ArrayList<CommandHandler> adminVoteCommand;
@Getter
private LinkedHashMap<java.util.UUID, ArrayList<String>> advancedTab = new LinkedHashMap<java.util.UUID, ArrayList<String>>();
private LinkedHashMap<java.util.UUID, ArrayList<String>> advancedTab = new LinkedHashMap<>();
@Getter
private BroadcastHandler broadcastHandler;
@@ -236,6 +236,17 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Getter
private UserManager votingPluginUserManager;
@Getter
private TimeQueueHandler timeQueueHandler;
@Getter
private ServiceSiteHandler serviceSiteHandler;
@Getter
private long lastBackgroundTaskTimeTaken = -1;
private boolean firstTimeLoaded = false;
public void addDirectlyDefinedRewards(DirectlyDefinedReward directlyDefinedReward) {
getRewardHandler().addDirectlyDefined(directlyDefinedReward);
}
@@ -249,6 +260,26 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
}
public void checkFirstTimeLoaded() {
if (!firstTimeLoaded) {
if (getGui().isChestVoteTopUseSkull()) {
int maxToLoad = 200;
for (TopVoter top : topVoter.keySet()) {
int num = 1;
Set<TopVoterPlayer> players = topVoter.get(top).keySet();
for (TopVoterPlayer p : players) {
if (num <= maxToLoad) {
getSkullCacheHandler().addToCache(p.getUuid(), p.getPlayerName());
}
num++;
}
}
}
}
firstTimeLoaded = true;
}
/**
* Check votifier.
*/
@@ -286,7 +317,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
public ArrayList<TopVoterPlayer> convertSet(Set<TopVoterPlayer> set) {
return new ArrayList<TopVoterPlayer>(set);
return new ArrayList<>(set);
}
@Override
@@ -297,7 +328,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
public LinkedHashMap<TopVoterPlayer, Integer> getTopVoter(TopVoter top) {
LinkedHashMap<TopVoterPlayer, Integer> top1 = topVoter.get(top);
if (top1 == null) {
top1 = new LinkedHashMap<TopVoterPlayer, Integer>();
top1 = new LinkedHashMap<>();
}
return top1;
}
@@ -355,16 +386,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
public ArrayList<VoteSite> getVoteSitesEnabled() {
ArrayList<VoteSite> sites = new ArrayList<VoteSite>();
for (VoteSite site : getVoteSites()) {
if (site.isEnabled()) {
sites.add(site);
}
}
return sites;
}
public String getVoteSiteName(boolean checkEnabled, String... urls) {
ArrayList<String> sites = getConfigVoteSites().getVoteSitesNames(checkEnabled);
@@ -397,6 +418,16 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
public ArrayList<VoteSite> getVoteSitesEnabled() {
ArrayList<VoteSite> sites = new ArrayList<>();
for (VoteSite site : getVoteSites()) {
if (site.isEnabled()) {
sites.add(site);
}
}
return sites;
}
public String getVoteSiteServiceSite(String name) {
ArrayList<String> sites = getConfigVoteSites().getVoteSitesNames(true);
if (name == null) {
@@ -406,10 +437,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
for (String siteName : sites) {
String URL = getConfigVoteSites().getServiceSite(siteName);
if (URL != null) {
if (URL.equalsIgnoreCase(name)) {
return URL;
}
if (name.equalsIgnoreCase(siteName)) {
if (URL.equalsIgnoreCase(name) || name.equalsIgnoreCase(siteName)) {
return URL;
}
}
@@ -438,6 +466,15 @@ public class VotingPluginMain extends AdvancedCorePlugin {
return false;
}
private void loadBungeeHandler() {
bungeeHandler = new BungeeHandler(this);
bungeeHandler.load();
if (getOptions().getServer().equalsIgnoreCase("PleaseSet")) {
getLogger().warning("Bungeecoord is true and server name is not set, bungeecoord features may not work");
}
}
public void loadDirectlyDefined() {
getRewardHandler().getDirectlyDefinedRewards().clear();
// AllSites reward
@@ -1015,6 +1052,10 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
private void loadVoteTimer() {
voteTimer = Executors.newSingleThreadScheduledExecutor();
}
/**
* Log vote.
*
@@ -1037,22 +1078,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
new VotingPluginMetrics().load(plugin);
}
private void loadVoteTimer() {
voteTimer = Executors.newSingleThreadScheduledExecutor();
}
@Getter
private TimeQueueHandler timeQueueHandler;
private void loadBungeeHandler() {
bungeeHandler = new BungeeHandler(this);
bungeeHandler.load();
if (getOptions().getServer().equalsIgnoreCase("PleaseSet")) {
getLogger().warning("Bungeecoord is true and server name is not set, bungeecoord features may not work");
}
}
@Override
public void onPostLoad() {
// auto conversion for Shop.yml
@@ -1115,23 +1140,23 @@ public class VotingPluginMain extends AdvancedCorePlugin {
});
topVoterHandler = new TopVoterHandler(this);
lastMonthTopVoter = new LinkedHashMap<TopVoterPlayer, Integer>();
previousMonthsTopVoters = new LinkedHashMap<YearMonth, LinkedHashMap<TopVoterPlayer, Integer>>();
lastMonthTopVoter = new LinkedHashMap<>();
previousMonthsTopVoters = new LinkedHashMap<>();
plugin.getBukkitScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
topVoterHandler.loadLastMonth();
debug("Loaded last month top voters");
topVoterHandler.loadPreviousMonthTopVoters();
}
});
topVoter = new LinkedHashMap<TopVoter, LinkedHashMap<TopVoterPlayer, Integer>>();
topVoter = new LinkedHashMap<>();
for (TopVoter top : TopVoter.values()) {
topVoter.put(top, new LinkedHashMap<TopVoterPlayer, Integer>());
topVoter.put(top, new LinkedHashMap<>());
}
voteToday = new LinkedHashMap<TopVoterPlayer, HashMap<VoteSite, LocalDateTime>>();
voteToday = new LinkedHashMap<>();
voteLog = new Logger(plugin, new File(plugin.getDataFolder() + File.separator + "Log", "votelog.txt"));
new AdminGUI(this).loadHook();
@@ -1299,7 +1324,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
plugin.getLogger().info("Enabled VotingPlugin " + plugin.getDescription().getVersion());
if (getProfile().contains("dev")) {
if (plugin.getDescription().getVersion().contains("SNAPSHOT")) {
plugin.getLogger().info(
"Using dev build, this is not a stable build, use at your own risk. Build number: " + buildNumber);
}
@@ -1350,9 +1375,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
@Getter
private ServiceSiteHandler serviceSiteHandler;
/*
* (non-Javadoc)
*
@@ -1370,9 +1392,8 @@ public class VotingPluginMain extends AdvancedCorePlugin {
if (!configFile.isOverrideVersionDisable()) {
Bukkit.getPluginManager().disablePlugin(this);
return;
} else {
plugin.getLogger().warning("Overriding version disable, beware of using this! This may cause issues!");
}
plugin.getLogger().warning("Overriding version disable, beware of using this! This may cause issues!");
}
setupFiles();
@@ -1580,9 +1601,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
plugin.debug("Loaded Files");
}
@Getter
private long lastBackgroundTaskTimeTaken = -1;
public void update() {
if (update || configFile.isAlwaysUpdate()) {
if (!updateStarted && plugin != null) {
@@ -1602,17 +1620,17 @@ public class VotingPluginMain extends AdvancedCorePlugin {
boolean extraBackgroundUpdate = configFile.isExtraBackgroundUpdate();
long startTime = System.currentTimeMillis();
LinkedHashMap<TopVoterPlayer, HashMap<VoteSite, LocalDateTime>> voteToday = new LinkedHashMap<TopVoterPlayer, HashMap<VoteSite, LocalDateTime>>();
LinkedHashMap<TopVoter, LinkedHashMap<TopVoterPlayer, Integer>> tempTopVoter = new LinkedHashMap<TopVoter, LinkedHashMap<TopVoterPlayer, Integer>>();
LinkedHashMap<TopVoterPlayer, HashMap<VoteSite, LocalDateTime>> voteToday = new LinkedHashMap<>();
LinkedHashMap<TopVoter, LinkedHashMap<TopVoterPlayer, Integer>> tempTopVoter = new LinkedHashMap<>();
ArrayList<TopVoter> topVotersToCheck = new ArrayList<TopVoter>();
ArrayList<TopVoter> topVotersToCheck = new ArrayList<>();
for (TopVoter top : TopVoter.values()) {
if (plugin == null) {
return;
}
if (plugin.getConfigFile().getLoadTopVoter(top)) {
topVotersToCheck.add(top);
tempTopVoter.put(top, new LinkedHashMap<TopVoterPlayer, Integer>());
tempTopVoter.put(top, new LinkedHashMap<>());
}
}
boolean topVoterIgnorePermissionUse = plugin.getConfigFile()
@@ -1629,61 +1647,59 @@ public class VotingPluginMain extends AdvancedCorePlugin {
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
if (!user.isBanned() && !blackList.contains(user.getPlayerName())) {
if (!topVoterIgnorePermissionUse || !user.isTopVoterIgnore()) {
for (TopVoter top : topVotersToCheck) {
int total = user.getTotal(top);
if (total > 0) {
tempTopVoter.get(top).put(user.getTopVoterPlayer(), total);
}
}
}
HashMap<VoteSite, LocalDateTime> times = new HashMap<VoteSite, LocalDateTime>();
for (Entry<VoteSite, Long> entry : user.getLastVotes().entrySet()) {
if (entry.getKey().isEnabled() && !entry.getKey().isHidden()) {
long time = entry.getValue();
if ((currentDay == MiscUtils.getInstance().getDayFromMili(time))
&& (LocalDateTime.now().getMonthValue() == MiscUtils
.getInstance().getMonthFromMili(time))
&& (LocalDateTime.now().getYear() == MiscUtils
.getInstance().getYearFromMili(time))) {
times.put(entry.getKey(),
LocalDateTime.ofInstant(Instant.ofEpochMilli(time),
ZoneId.systemDefault()));
}
}
}
if (times.keySet().size() > 0) {
voteToday.put(user.getTopVoterPlayer(), times);
}
}
if (extraBackgroundUpdate) {
if (user.isOnline()) {
user.offVote();
}
}
if (plugin != null) {
if (!plugin.getPlaceholders().getCacheLevel().onlineOnly()
|| user.isOnline()) {
plugin.getPlaceholders().onUpdate(user, false);
}
}
user.clearTempCache();
user = null;
}
} else {
if ((plugin == null) || !plugin.isEnabled()) {
return;
}
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
if (!user.isBanned() && !blackList.contains(user.getPlayerName())) {
if (!topVoterIgnorePermissionUse || !user.isTopVoterIgnore()) {
for (TopVoter top : topVotersToCheck) {
int total = user.getTotal(top);
if (total > 0) {
tempTopVoter.get(top).put(user.getTopVoterPlayer(), total);
}
}
}
HashMap<VoteSite, LocalDateTime> times = new HashMap<>();
for (Entry<VoteSite, Long> entry : user.getLastVotes().entrySet()) {
if (entry.getKey().isEnabled() && !entry.getKey().isHidden()) {
long time = entry.getValue();
if ((currentDay == MiscUtils.getInstance().getDayFromMili(time))
&& (LocalDateTime.now().getMonthValue() == MiscUtils
.getInstance().getMonthFromMili(time))
&& (LocalDateTime.now().getYear() == MiscUtils.getInstance()
.getYearFromMili(time))) {
times.put(entry.getKey(), LocalDateTime.ofInstant(
Instant.ofEpochMilli(time), ZoneId.systemDefault()));
}
}
}
if (times.keySet().size() > 0) {
voteToday.put(user.getTopVoterPlayer(), times);
}
}
if (extraBackgroundUpdate) {
if (user.isOnline()) {
user.offVote();
}
}
if (plugin != null) {
if (!plugin.getPlaceholders().getCacheLevel().onlineOnly()
|| user.isOnline()) {
plugin.getPlaceholders().onUpdate(user, false);
}
}
user.clearTempCache();
user = null;
}
}
cols.clear();
cols = null;
@@ -1725,36 +1741,14 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
}
private boolean firstTimeLoaded = false;
public void checkFirstTimeLoaded() {
if (!firstTimeLoaded) {
if (getGui().isChestVoteTopUseSkull()) {
int maxToLoad = 200;
for (TopVoter top : topVoter.keySet()) {
int num = 1;
Set<TopVoterPlayer> players = topVoter.get(top).keySet();
for (TopVoterPlayer p : players) {
if (num <= maxToLoad) {
getSkullCacheHandler().addToCache(p.getUuid(), p.getPlayerName());
}
num++;
}
}
}
}
firstTimeLoaded = true;
}
public void updateAdvancedCoreHook() {
getJavascriptEngine().put("VotingPlugin", this);
allowDownloadingFromSpigot(15358);
setConfigData(new YMLConfig(this, configFile.getData()) {
@Override
public void setValue(String path, Object value) {
configFile.setValue(path, value);
public void createSection(String key) {
configFile.createSection(key);
}
@Override
@@ -1763,8 +1757,8 @@ public class VotingPluginMain extends AdvancedCorePlugin {
}
@Override
public void createSection(String key) {
configFile.createSection(key);
public void setValue(String path, Object value) {
configFile.setValue(path, value);
}
});
if (bungeeSettings.isUseBungeecoord()) {
@@ -16,9 +16,8 @@ public class VotingPluginMetrics {
if (plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getFirstVoteRewardsPath())) {
return "True";
} else {
return "False";
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_everysite", new Callable<String>() {
@@ -28,9 +27,8 @@ public class VotingPluginMetrics {
if (plugin.getRewardHandler().hasRewards(plugin.getConfigVoteSites().getData(),
plugin.getConfigVoteSites().getEverySiteRewardPath())) {
return "True";
} else {
return "False";
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_allsites", new Callable<String>() {
@@ -40,9 +38,8 @@ public class VotingPluginMetrics {
if (plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getAllSitesRewardPath())) {
return "True";
} else {
return "False";
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_cumulative", new Callable<String>() {
@@ -51,14 +48,13 @@ public class VotingPluginMetrics {
public String call() throws Exception {
if (plugin.getSpecialRewardsConfig().getCumulativeVotes().size() == 0) {
return "False";
} else {
for (String cum : plugin.getSpecialRewardsConfig().getCumulativeVotes()) {
if (plugin.getSpecialRewardsConfig().getCumulativeRewardEnabled(Integer.parseInt(cum))) {
return "True";
}
}
return "False";
}
for (String cum : plugin.getSpecialRewardsConfig().getCumulativeVotes()) {
if (plugin.getSpecialRewardsConfig().getCumulativeRewardEnabled(Integer.parseInt(cum))) {
return "True";
}
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_voteparty", new Callable<String>() {
@@ -67,9 +63,8 @@ public class VotingPluginMetrics {
public String call() throws Exception {
if (!plugin.getSpecialRewardsConfig().isVotePartyEnabled()) {
return "False";
} else {
return "True";
}
return "True";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("placeholder_cache_level", new Callable<String>() {
@@ -85,14 +80,13 @@ public class VotingPluginMetrics {
public String call() throws Exception {
if (plugin.getSpecialRewardsConfig().getMilestoneVotes().size() == 0) {
return "False";
} else {
for (String milestone : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
if (plugin.getSpecialRewardsConfig().getMilestoneRewardEnabled(Integer.parseInt(milestone))) {
return "True";
}
}
return "False";
}
for (String milestone : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
if (plugin.getSpecialRewardsConfig().getMilestoneRewardEnabled(Integer.parseInt(milestone))) {
return "True";
}
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_anysitereward", new Callable<String>() {
@@ -102,9 +96,8 @@ public class VotingPluginMetrics {
if (plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getAnySiteRewardsPath())) {
return "True";
} else {
return "False";
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_votestreakday", new Callable<String>() {
@@ -186,9 +179,11 @@ public class VotingPluginMetrics {
int total = plugin.getUserManager().getAllUUIDs().size();
if (total > 800000) {
return ">800000";
} else if (total > 700000) {
}
if (total > 700000) {
return "700000-800000";
} else if (total > 600000) {
}
if (total > 600000) {
return "600000-700000";
} else if (total > 500000) {
return "500000-600000";
@@ -255,9 +250,8 @@ public class VotingPluginMetrics {
public String call() throws Exception {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
return "" + plugin.getBungeeHandler().getMethod().toString();
} else {
return "Disabled";
}
return "Disabled";
}
}));
if (plugin.getBungeeSettings().isUseBungeecoord()) {
@@ -18,7 +18,7 @@ import com.bencodez.votingplugin.VotingPluginMain;
public class BroadcastHandler {
private VotingPluginMain plugin;
private ScheduledExecutorService timer;
ConcurrentLinkedQueue<String> votedPlayers = new ConcurrentLinkedQueue<String>();
ConcurrentLinkedQueue<String> votedPlayers = new ConcurrentLinkedQueue<>();
public BroadcastHandler(VotingPluginMain plugin, int delay) {
this.plugin = plugin;
@@ -39,11 +39,11 @@ public class BroadcastHandler {
playersText += ", ";
}
}
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("numberofplayers", "" + size);
placeholders.put("players", playersText);
bc = PlaceholderUtils.replacePlaceHolder(bc, placeholders);
ArrayList<Player> players = new ArrayList<Player>();
ArrayList<Player> players = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
if (!plugin.getVotingPluginUserManager().getVotingPluginUser(p).getDisableBroadcast()) {
players.add(p);
@@ -5,14 +5,18 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.bencodez.votingplugin.bungee.proxy.VotingPluginProxyConfig;
import lombok.Getter;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
public class Config {
public class Config implements VotingPluginProxyConfig {
private VotingPluginBungee bungee;
@Getter
private Configuration data;
@@ -21,72 +25,28 @@ public class Config {
this.bungee = bungee;
}
public String getRedisHost() {
return getData().getString("Redis.Host", "");
}
public int getRedisPort() {
return getData().getInt("Redis.Port", 6379);
}
public String getRedisUsername() {
return getData().getString("Redis.Username", "");
}
public String getRedisPrefix() {
return getData().getString("Redis.Prefix", "");
}
public String getRedisPassword() {
return getData().getString("Redis.Password", "");
public Map<String, Object> configToMap(Configuration config) {
Map<String, Object> map = new HashMap<>();
if (config != null) {
config.getKeys().forEach(key -> map.put(key, config.get(key)));
}
return map;
}
public boolean getAllowUnJoined() {
return getData().getBoolean("AllowUnJoined", false);
}
public List<String> getBlockedServers() {
return getData().getStringList("BlockedServers");
}
public List<String> getWhiteListedServers() {
return getData().getStringList("WhiteListedServers");
}
public boolean getBroadcast() {
return getData().getBoolean("Broadcast", false);
}
public boolean getStoreMonthTotalsWithDate() {
return getData().getBoolean("StoreMonthTotalsWithDate", false);
}
public boolean getUseMonthDateTotalsAsPrimaryTotal() {
return getData().getBoolean("UseMonthDateTotalsAsPrimaryTotal", false);
}
public String getBedrockPlayerPrefix() {
return getData().getString("BedrockPlayerPrefix", ".");
}
public boolean getOnlineMode() {
return getData().getBoolean("OnlineMode", true);
}
public boolean getTimeChangeFailSafeBypass() {
return getData().getBoolean("TimeChangeFailSafeBypass", false);
public List<String> getBlockedServers() {
return getData().getStringList("BlockedServers");
}
public boolean getUUIDLookup() {
return getData().getBoolean("UUIDLookup", true);
}
public boolean getGlobalDataEnabled() {
return getData().getBoolean("GlobalData.Enabled", false);
}
public boolean getGlobalDataUseMainMySQL() {
return getData().getBoolean("GlobalData.UseMainMySQL", true);
public boolean getBroadcast() {
return getData().getBoolean("Broadcast", false);
}
public String getBungeeHost() {
@@ -105,98 +65,90 @@ public class Config {
return getData().getInt("BungeeServer.Port", 1297);
}
public int getLimitVotePoints() {
return getData().getInt("LimitVotePoints", -1);
}
public boolean getDebug() {
return getData().getBoolean("Debug", false);
}
public boolean getMultiProxySupport() {
return getData().getBoolean("MultiProxySupport", false);
}
public int getMaxAmountOfVotesPerDay() {
return getData().getInt("MaxAmountOfVotesPerDay", -1);
}
public int getMultiProxySocketHostPort() {
return getData().getInt("MultiProxySocketHost.Port", 1297);
}
public String getMultiProxySocketHostHost() {
return getData().getString("MultiProxySocketHost.Host", "");
}
public boolean getMultiProxyOneGlobalReward() {
return getData().getBoolean("MultiProxyOneGlobalReward", false);
}
public Configuration getMultiProxyServersConfiguration(String s) {
return getData().getSection("MultiProxyServers." + s);
}
public Collection<String> getMultiProxyServers() {
return getData().getSection("MultiProxyServers").getKeys();
}
public boolean getPrimaryServer() {
return getData().getBoolean("PrimaryServer", false);
}
public String getFallBack() {
return getData().getString("FallBackServer", "");
}
public int getPointsOnVote() {
return getData().getInt("PointsOnVote", 1);
public boolean getGlobalDataEnabled() {
return getData().getBoolean("GlobalData.Enabled", false);
}
public boolean getSendVotesToAllServers() {
return getData().getBoolean("SendVotesToAllServers");
public boolean getGlobalDataUseMainMySQL() {
return getData().getBoolean("GlobalData.UseMainMySQL", true);
}
public Configuration getSpigotServerConfiguration(String s) {
return getData().getSection("SpigotServers." + s);
public int getLimitVotePoints() {
return getData().getInt("LimitVotePoints", -1);
}
public Collection<String> getSpigotServers() {
return getData().getSection("SpigotServers").getKeys();
}
public boolean getWaitForUserOnline() {
return getData().getBoolean("WaitForUserOnline", false);
}
public boolean getVotePartyEnabled() {
return getData().getBoolean("VoteParty.Enabled", false);
}
public boolean getVotePartySendToAllServers() {
return getData().getBoolean("VoteParty.SendToAllServers", true);
}
public int getVotePartyVotesRequired() {
return getData().getInt("VoteParty.VotesRequired", 100);
}
public int getVotePartyIncreaseVotesRequired() {
return getData().getInt("VoteParty.IncreaseVotesRequired", 0);
}
public int getVoteCacheTime() {
return getData().getInt("VoteCacheTime", -1);
}
public String getVotePartyBroadcast() {
return getData().getString("VoteParty.Broadcast", "");
public int getMaxAmountOfVotesPerDay() {
return getData().getInt("MaxAmountOfVotesPerDay", -1);
}
public String getMultiProxyMethod() {
return getData().getString("MultiProxyMethod", "SOCKET");
}
public boolean getMultiProxyOneGlobalReward() {
return getData().getBoolean("MultiProxyOneGlobalReward", false);
}
public String getMultiProxyRedisHost() {
return getData().getString("MultiProxyRedis.Host", "");
}
public String getMultiProxyRedisPassword() {
return getData().getString("MultiProxyRedis.Password", "");
}
public int getMultiProxyRedisPort() {
return getData().getInt("MultiProxyRedis.Port", 6379);
}
public boolean getMultiProxyRedisUseExistingConnection() {
return getData().getBoolean("MultiProxyRedis.UseExistingConnection", false);
}
public String getMultiProxyRedisUsername() {
return getData().getString("MultiProxyRedis.Username", "");
}
public Collection<String> getMultiProxyServers() {
return getData().getSection("MultiProxyServers").getKeys();
}
public Map<String, Object> getMultiProxyServersConfiguration(String s) {
return configToMap(getData().getSection("MultiProxyServers." + s));
}
public String getMultiProxySocketHostHost() {
return getData().getString("MultiProxySocketHost.Host", "");
}
public int getMultiProxySocketHostPort() {
return getData().getInt("MultiProxySocketHost.Port", 1297);
}
public boolean getMultiProxySupport() {
return getData().getBoolean("MultiProxySupport", false);
}
public boolean getOnlineMode() {
return getData().getBoolean("OnlineMode", true);
}
public int getPointsOnVote() {
return getData().getInt("PointsOnVote", 1);
}
public boolean getPrimaryServer() {
return getData().getBoolean("PrimaryServer", false);
}
public String getProxyServerName() {
return getData().getString("ProxyServerName", "SOCKET");
}
@@ -205,32 +157,100 @@ public class Config {
return getData().getStringList("ProxyServers");
}
public boolean getMultiProxyRedisUseExistingConnection() {
return getData().getBoolean("MultiProxyRedis.UseExistingConnection", false);
public String getRedisHost() {
return getData().getString("Redis.Host", "");
}
public List<String> getVotePartyServersToSend() {
return getData().getStringList("VoteParty.ServersToSend");
public String getRedisPassword() {
return getData().getString("Redis.Password", "");
}
public int getRedisPort() {
return getData().getInt("Redis.Port", 6379);
}
public String getRedisPrefix() {
return getData().getString("Redis.Prefix", "");
}
public String getRedisUsername() {
return getData().getString("Redis.Username", "");
}
public boolean getSendVotesToAllServers() {
return getData().getBoolean("SendVotesToAllServers");
}
public Map<String, Object> getSpigotServerConfiguration(String s) {
return configToMap(getData().getSection("SpigotServers." + s));
}
public Collection<String> getSpigotServers() {
return getData().getSection("SpigotServers").getKeys();
}
public boolean getStoreMonthTotalsWithDate() {
return getData().getBoolean("StoreMonthTotalsWithDate", false);
}
public boolean getTimeChangeFailSafeBypass() {
return getData().getBoolean("TimeChangeFailSafeBypass", false);
}
public int getTimeHourOffSet() {
return getData().getInt("TimeHourOffSet");
}
public String getTimeZone() {
return getData().getString("TimeZone", "");
}
public boolean getUseMonthDateTotalsAsPrimaryTotal() {
return getData().getBoolean("UseMonthDateTotalsAsPrimaryTotal", false);
}
public boolean getUUIDLookup() {
return getData().getBoolean("UUIDLookup", true);
}
public int getVoteCacheTime() {
return getData().getInt("VoteCacheTime", -1);
}
public String getVotePartyBroadcast() {
return getData().getString("VoteParty.Broadcast", "");
}
public List<String> getVotePartyBungeeCommands() {
return getData().getStringList("VoteParty.BungeeCommands");
}
public String getMultiProxyRedisHost() {
return getData().getString("MultiProxyRedis.Host", "");
public boolean getVotePartyEnabled() {
return getData().getBoolean("VoteParty.Enabled", false);
}
public int getMultiProxyRedisPort() {
return getData().getInt("MultiProxyRedis.Port", 6379);
public int getVotePartyIncreaseVotesRequired() {
return getData().getInt("VoteParty.IncreaseVotesRequired", 0);
}
public String getMultiProxyRedisUsername() {
return getData().getString("MultiProxyRedis.Username", "");
public boolean getVotePartySendToAllServers() {
return getData().getBoolean("VoteParty.SendToAllServers", true);
}
public String getMultiProxyRedisPassword() {
return getData().getString("MultiProxyRedis.Password", "");
public List<String> getVotePartyServersToSend() {
return getData().getStringList("VoteParty.ServersToSend");
}
public int getVotePartyVotesRequired() {
return getData().getInt("VoteParty.VotesRequired", 100);
}
public boolean getWaitForUserOnline() {
return getData().getBoolean("WaitForUserOnline", false);
}
public List<String> getWhiteListedServers() {
return getData().getStringList("WhiteListedServers");
}
public void load() {
@@ -264,4 +284,14 @@ public class Config {
}
}
@Override
public String getPluginMessageChannel() {
return getData().getString("PluginMessageChannel", "vp:vp");
}
@Override
public boolean getPluginMessageEncryption() {
return getData().getBoolean("PluginMessageEncryption", false);
}
}
@@ -20,7 +20,7 @@ public class NonVotedPlayersCache {
}
public void addPlayer(ProxiedPlayer proxiedPlayer) {
if (!bungee.getMysql().containsKeyQuery(proxiedPlayer.getUniqueId().toString())) {
if (!bungee.getVotingPluginProxy().getProxyMySQL().containsKeyQuery(proxiedPlayer.getUniqueId().toString())) {
addPlayer(proxiedPlayer.getUniqueId().toString(), proxiedPlayer.getName());
}
}
@@ -32,7 +32,7 @@ public class NonVotedPlayersCache {
}
public void addPlayerCheck(String uuid, String playerName) {
if (!bungee.getMysql().containsKeyQuery(uuid)) {
if (!bungee.getVotingPluginProxy().getProxyMySQL().containsKeyQuery(uuid)) {
addPlayer(uuid, playerName);
}
}
@@ -45,7 +45,7 @@ public class NonVotedPlayersCache {
} else {
String uuid = getData().getString("NonVotedPlayers." + player + ".UUID", "");
if (!uuid.isEmpty()) {
if (bungee.getMysql().containsKeyQuery(uuid)) {
if (bungee.getVotingPluginProxy().getProxyMySQL().containsKeyQuery(uuid)) {
remove(player);
}
} else {
@@ -21,28 +21,11 @@ public class VoteCache {
this.bungee = bungee;
}
public int getVotePartyCurrentVotes() {
return getData().getInt("VoteParty.CurrentVotes", 0);
}
public int getVotePartyInreaseVotesRequired() {
return getData().getInt("VoteParty.IncreaseVotes", 0);
}
public void setVotePartyCurrentVotes(int amount) {
getData().set("VoteParty.CurrentVotes", amount);
}
public void setVotePartyInreaseVotesRequired(int amount) {
getData().set("VoteParty.IncreaseVotes", amount);
}
public void setVotePartyCache(String server, int amount) {
getData().set("VoteParty.Cache." + server, amount);
}
public int getVotePartyCache(String server) {
return getData().getInt("VoteParty.Cache." + server, 0);
public void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
Configuration section = getData().getSection("TimedVoteCache." + num);
section.set("Name", voteTimedQueue.getName());
section.set("Service", voteTimedQueue.getService());
section.set("Time", voteTimedQueue.getTime());
}
public void addVote(String server, int num, OfflineBungeeVote voteData) {
@@ -55,13 +38,6 @@ public class VoteCache {
section.set("Text", voteData.getText());
}
public void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
Configuration section = getData().getSection("TimedVoteCache." + num);
section.set("Name", voteTimedQueue.getName());
section.set("Service", voteTimedQueue.getService());
section.set("Time", voteTimedQueue.getTime());
}
public void addVoteOnline(String player, int num, OfflineBungeeVote voteData) {
Configuration section = getData().getSection("OnlineCache." + player + "." + num);
section.set("Name", voteData.getPlayerName());
@@ -75,6 +51,7 @@ public class VoteCache {
public void clearData() {
getData().set("VoteCache", null);
getData().set("OnlineCache", null);
getData().set("TimedVoteCache", null);
save();
}
@@ -94,14 +71,6 @@ public class VoteCache {
return getData().getSection("VoteCache").getKeys();
}
public Configuration getTimedVoteCache(String key) {
return getData().getSection("TimedVoteCache." + key);
}
public Collection<String> getTimedVoteCache() {
return getData().getSection("TimedVoteCache").getKeys();
}
public Collection<String> getServerVotes(String server) {
return getData().getSection("VoteCache." + server).getKeys();
}
@@ -110,13 +79,33 @@ public class VoteCache {
return getData().getSection("VoteCache." + server + "." + num);
}
public Collection<String> getTimedVoteCache() {
return getData().getSection("TimedVoteCache").getKeys();
}
public Configuration getTimedVoteCache(String key) {
return getData().getSection("TimedVoteCache." + key);
}
public int getVotePartyCache(String server) {
return getData().getInt("VoteParty.Cache." + server, 0);
}
public int getVotePartyCurrentVotes() {
return getData().getInt("VoteParty.CurrentVotes", 0);
}
public int getVotePartyInreaseVotesRequired() {
return getData().getInt("VoteParty.IncreaseVotes", 0);
}
public void load() {
if (!bungee.getDataFolder().exists()) {
bungee.getDataFolder().mkdir();
}
File yamlFile = new File(bungee.getDataFolder(), "votecache.yml");
File file = new File(bungee.getDataFolder(), "votecache.json");
if (!file.exists()) {
@@ -136,10 +125,10 @@ public class VoteCache {
} catch (IOException e) {
e.printStackTrace();
}
save();
}
try {
data = ConfigurationProvider.getProvider(JsonConfiguration.class)
.load(new File(bungee.getDataFolder(), "votecache.json"));
@@ -157,4 +146,16 @@ public class VoteCache {
}
}
public void setVotePartyCache(String server, int amount) {
getData().set("VoteParty.Cache." + server, amount);
}
public void setVotePartyCurrentVotes(int amount) {
getData().set("VoteParty.CurrentVotes", amount);
}
public void setVotePartyInreaseVotesRequired(int amount) {
getData().set("VoteParty.IncreaseVotes", amount);
}
}
@@ -28,7 +28,7 @@ public class VoteEventBungee implements net.md_5.bungee.api.plugin.Listener {
vote.setServiceName(serviceSite);
}
plugin.vote(vote.getUsername(), serviceSite, true, true, 0, null, null);
plugin.getVotingPluginProxy().vote(vote.getUsername(), serviceSite, true, true, 0, null, null);
}
});
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
package com.bencodez.votingplugin.bungee;
import com.bencodez.advancedcore.api.time.TimeType;
import com.bencodez.votingplugin.bungee.proxy.VotingPluginProxyCommand;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.TextComponent;
@@ -17,82 +17,9 @@ public class VotingPluginBungeeCommand extends Command {
@Override
public void execute(CommandSender sender, String[] args) {
if (sender.hasPermission("votingplugin.admin")) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("reload")) {
bungee.reload(false);
sender.sendMessage(new TextComponent("Reloading VotingPluginBungee"));
}
if (args[0].equalsIgnoreCase("reloadmysql")) {
bungee.reload(true);
sender.sendMessage(new TextComponent("Reloading VotingPluginBungee with MySQL"));
}
if (args[0].equalsIgnoreCase("vote")) {
if (args.length >= 2) {
String user = args[1];
String site = args[2];
bungee.vote(user, site, false, true, 0, null, null);
sender.sendMessage(new TextComponent("Sending vote"));
}
}
if (args[0].equalsIgnoreCase("forcetimechange")) {
if (args.length >= 2) {
bungee.getBungeeTimeChecker().forceChanged(TimeType.getTimeType(args[1]));
sender.sendMessage(new TextComponent("Triggering time change: " + args[1]));
}
}
if (args[0].equalsIgnoreCase("status")) {
if (bungee.getMethod().equals(BungeeMethod.SOCKETS)) {
sender.sendMessage(new TextComponent(
"&aChecking status, waiting for response, check console, method: sockets"));
bungee.status(sender);
} else if (bungee.getMethod().equals(BungeeMethod.PLUGINMESSAGING)) {
sender.sendMessage(new TextComponent(
"&aChecking status, waiting for response, check console, method: plugin messaging"));
bungee.status(sender);
bungee.sendServerNameMessage();
} else if (bungee.getMethod().equals(BungeeMethod.REDIS)) {
sender.sendMessage(new TextComponent(
"&aChecking status, waiting for response, check console, method: redis"));
bungee.status(sender);
bungee.sendServerNameMessage();
} else {
sender.sendMessage(
new TextComponent("&aNot using socket/pluginmessage/redis method, command unavailable"));
}
}
if (args[0].equalsIgnoreCase("multiproxystatus")) {
bungee.getMultiProxyHandler().sendMultiProxyServerMessage("Status");
sender.sendMessage(new TextComponent("Sending status message"));
}
if (args[0].equalsIgnoreCase("help")) {
TextComponent[] msg = new TextComponent[7];
msg[0] = new TextComponent("&avotingpluginbungee reload - Reload plugin");
msg[1] = new TextComponent("&avotingpluginbungee reloadmysql - Reload plugin including mysql");
msg[2] = new TextComponent("&avotingpluginbungee vote (player) (servicesite) - Send bungee vote");
msg[3] = new TextComponent("&avotingpluginbungee status - Check socket connection status");
msg[4] = new TextComponent("&avotingpluginbungee forcetimechange (timetype) - Force a time change");
msg[5] = new TextComponent("&avotingpluginbungee voteparty force - Force a vote party");
msg[6] = new TextComponent(
"&avotingpluginbungee voteparty setvotecount (number) - Set current vote party votes");
sender.sendMessage(msg);
}
if (args[0].equalsIgnoreCase("voteparty")) {
if (args.length > 1) {
if (args[1].equalsIgnoreCase("Force")) {
bungee.setCurrentVotePartyVotes(bungee.getCurrentVotePartyVotesRequired());
bungee.checkVoteParty();
sender.sendMessage(new TextComponent("Vote party forced"));
}
if (args.length > 2) {
if (args[1].equalsIgnoreCase("SetVoteCount")) {
if (isInt(args[2])) {
bungee.setCurrentVotePartyVotes(Integer.parseInt(args[2]));
sender.sendMessage(new TextComponent("Set current vote party votes to " + args[2]));
}
}
}
}
}
String result = new VotingPluginProxyCommand(bungee.getVotingPluginProxy()).execute(args);
if (result != null) {
sender.sendMessage(new TextComponent(result.replace("&", "§")));
}
} else {
sender.sendMessage(new TextComponent("&cYou do not have permission to do this!"));
@@ -16,20 +16,6 @@ import com.bencodez.votingplugin.bungee.BungeeMessageData;
import lombok.Getter;
public abstract class MultiProxyHandler {
public abstract boolean getMultiProxySupportEnabled();
public abstract EncryptionHandler getEncryptionHandler();
public abstract File getPluginDataFolder();
public abstract void setEncryptionHandler(EncryptionHandler encryptionHandler);
public abstract void logInfo(String msg);
public abstract boolean getDebug();
public abstract String getVersion();
private HashMap<String, ClientHandler> multiproxyClientHandles;
private SocketHandler multiproxySocketHandler;
@@ -41,19 +27,9 @@ public abstract class MultiProxyHandler {
}
public void sendMultiProxyServerMessage(String... messageData) {
if (getMultiProxyMethod().equals(MultiProxyMethod.SOCKETS)) {
for (ClientHandler h : multiproxyClientHandles.values()) {
h.sendMessage(messageData);
}
} else if (getMultiProxyMethod().equals(MultiProxyMethod.REDIS)) {
for (String server : getProxyServers()) {
multiProxyRedis.sendMessage("VotingPluginProxy_" + server, messageData);
}
}
}
public abstract void addNonVotedPlayerCache(String string, String string2);
public abstract List<String> getProxyServers();
public abstract void clearVote(String string);
public void close() {
if (multiproxySocketHandler != null) {
@@ -65,6 +41,44 @@ public abstract class MultiProxyHandler {
}
}
public abstract boolean getDebug();
public abstract EncryptionHandler getEncryptionHandler();
public abstract MultiProxyMethod getMultiProxyMethod();
public abstract String getMultiProxyPassword();
public abstract String getMultiProxyRedisHost();
public abstract int getMultiProxyRedisPort();
public abstract boolean getMultiProxyRedisUseExistingConnection();
public abstract String getMultiProxyServerName();
public abstract Collection<String> getMultiProxyServers();
public abstract MultiProxyServerSocketConfiguration getMultiProxyServersConfiguration(String s);
public abstract String getMultiProxySocketHostHost();
public abstract int getMultiProxySocketHostPort();
public abstract boolean getMultiProxySupportEnabled();
public abstract String getMultiProxyUsername();
public abstract File getPluginDataFolder();
public abstract boolean getPrimaryServer();
public abstract List<String> getProxyServers();
public abstract RedisHandler getRedisHandler();
public abstract String getVersion();
public void loadMultiProxySupport() {
if (getMultiProxySupportEnabled()) {
if (getMultiProxyMethod().equals(MultiProxyMethod.SOCKETS)) {
@@ -117,7 +131,7 @@ public abstract class MultiProxyHandler {
}
});
multiproxyClientHandles = new HashMap<String, ClientHandler>();
multiproxyClientHandles = new HashMap<>();
for (String s : getMultiProxyServers()) {
MultiProxyServerSocketConfiguration d = getMultiProxyServersConfiguration(s);
multiproxyClientHandles.put(s,
@@ -131,6 +145,13 @@ public abstract class MultiProxyHandler {
multiProxyRedis = new RedisHandler(getMultiProxyRedisHost(), getMultiProxyRedisPort(),
getMultiProxyUsername(), getMultiProxyPassword()) {
@Override
public void debug(String message) {
if (getDebug()) {
logInfo("MultiProxyRedis: " + message);
}
}
@Override
public void onMessage(String channel, String[] data) {
if (data.length > 0) {
@@ -158,13 +179,6 @@ public abstract class MultiProxyHandler {
}
}
}
@Override
public void debug(String message) {
if (getDebug()) {
logInfo("MultiProxyRedis: " + message);
}
}
};
}
@@ -182,48 +196,31 @@ public abstract class MultiProxyHandler {
}
}
public abstract void runAsnc(Runnable runnable);
public abstract MultiProxyMethod getMultiProxyMethod();
public abstract RedisHandler getRedisHandler();
public abstract boolean getMultiProxyRedisUseExistingConnection();
public abstract String getMultiProxyPassword();
public abstract String getMultiProxyUsername();
public abstract String getMultiProxyServerName();
public abstract int getMultiProxyRedisPort();
public abstract String getMultiProxyRedisHost();
public abstract boolean getPrimaryServer();
public void login(String uuid, String playerName) {
if (!getMultiProxySupportEnabled()) {
return;
}
if (getPrimaryServer()) {
if (!getMultiProxySupportEnabled() || getPrimaryServer()) {
return;
}
sendMultiProxyServerMessage("Login", uuid, playerName);
}
public abstract int getMultiProxySocketHostPort();
public abstract void logInfo(String msg);
public abstract String getMultiProxySocketHostHost();
public abstract void runAsnc(Runnable runnable);
public abstract MultiProxyServerSocketConfiguration getMultiProxyServersConfiguration(String s);
public void sendMultiProxyServerMessage(String... messageData) {
if (getMultiProxyMethod().equals(MultiProxyMethod.SOCKETS)) {
for (ClientHandler h : multiproxyClientHandles.values()) {
h.sendMessage(messageData);
}
} else if (getMultiProxyMethod().equals(MultiProxyMethod.REDIS)) {
for (String server : getProxyServers()) {
multiProxyRedis.sendMessage("VotingPluginProxy_" + server, messageData);
}
}
}
public abstract Collection<String> getMultiProxyServers();
public abstract void setEncryptionHandler(EncryptionHandler encryptionHandler);
public abstract void triggerVote(String player, String service, boolean realVote, boolean timeQueue, long queueTime,
BungeeMessageData text, String uuid);
public abstract void addNonVotedPlayerCache(String string, String string2);
public abstract void clearVote(String string);
}
@@ -1,9 +1,9 @@
package com.bencodez.votingplugin.bungee.global.multiproxy;
public interface MultiProxyServerSocketConfiguration {
String getServerName();
String getHost();
int getPort();
String getServerName();
}
@@ -1,21 +1,22 @@
package com.bencodez.votingplugin.bungee.global.multiproxy;
import net.md_5.bungee.config.Configuration;
import java.util.Map;
public class MultiProxyServerSocketConfigurationBungee implements MultiProxyServerSocketConfiguration {
private String server;
private String host;
private String host = "";
private int port;
public MultiProxyServerSocketConfigurationBungee(String s, Configuration config) {
public MultiProxyServerSocketConfigurationBungee(String s, Map<String, Object> config) {
server = s;
host = config.getString("Host", "");
port = config.getInt("Port", 1234);
}
@Override
public String getServerName() {
return server;
if (config.containsKey("Host")) {
host = (String) config.get("Host");
}
if (config.containsKey("Port")) {
port = (int) config.get("Port");
} else {
port = 1298;
}
}
@Override
@@ -28,4 +29,9 @@ public class MultiProxyServerSocketConfigurationBungee implements MultiProxyServ
return port;
}
@Override
public String getServerName() {
return server;
}
}
@@ -15,11 +15,6 @@ public class MultiProxyServerSocketConfigurationVelocity implements MultiProxySe
}
@Override
public String getServerName() {
return server;
}
@Override
public String getHost() {
return host;
@@ -30,4 +25,9 @@ public class MultiProxyServerSocketConfigurationVelocity implements MultiProxySe
return port;
}
@Override
public String getServerName() {
return server;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
package com.bencodez.votingplugin.bungee.proxy;
import com.bencodez.advancedcore.api.time.TimeType;
import com.bencodez.votingplugin.bungee.BungeeMethod;
public class VotingPluginProxyCommand {
private VotingPluginProxy plugin;
public VotingPluginProxyCommand(VotingPluginProxy plugin) {
this.plugin = plugin;
}
/**
* Execute the command and return a message as a String.
*
* @param args Command arguments
* @return The resulting message to send
*/
public String execute(String[] args) {
if (args.length == 0)
return "&cPlease provide a valid command. Use 'help' to view all commands.";
switch (args[0].toLowerCase()) {
case "reload":
plugin.reloadCore(false);
return "&aReloading VotingPlugin";
case "reloadmysql":
plugin.reloadCore(true);
return "&aReloading VotingPlugin including MySQL";
case "vote":
if (args.length >= 3) {
String user = args[1];
String site = args[2];
plugin.vote(user, site, false, true, 0, null, null);
return "&aVote sent for " + user + " on " + site;
}
return "&cUsage: vote <player> <site>";
case "forcetimechange":
if (args.length >= 2) {
plugin.getBungeeTimeChecker().forceChanged(TimeType.getTimeType(args[1]));
return "&aTriggered time change to " + args[1];
}
return "&cUsage: forcetimechange <TimeType>";
case "status":
return handleStatusCommand();
case "multiproxystatus":
plugin.getMultiProxyHandler().sendMultiProxyServerMessage("Status");
return "&aSent status message across multi-proxy";
case "help":
return getHelpMessage();
case "voteparty":
return handleVotePartyCommand(args);
default:
return "&cUnknown command. Use 'help' to view all commands.";
}
}
private String handleStatusCommand() {
BungeeMethod method = plugin.getMethod();
switch (method) {
case SOCKETS:
plugin.status();
return "&aChecking status via sockets. Check console for details.";
case PLUGINMESSAGING:
case REDIS:
plugin.status();
plugin.sendServerNameMessage();
return "&aChecking status with method: " + method.toString().toLowerCase();
default:
return "&cStatus command unavailable for the current connection method.";
}
}
private String handleVotePartyCommand(String[] args) {
if (args.length > 1) {
if ("force".equalsIgnoreCase(args[1])) {
plugin.setCurrentVotePartyVotes(plugin.getCurrentVotePartyVotesRequired());
plugin.checkVoteParty();
return "&aVote party forced";
} else if ("setvotecount".equalsIgnoreCase(args[1]) && args.length > 2 && isInt(args[2])) {
plugin.setCurrentVotePartyVotes(Integer.parseInt(args[2]));
return "&aSet current vote party votes to " + args[2];
} else {
return "&cInvalid usage. Use 'help' for correct syntax.";
}
}
return "&cUsage: voteparty <force/setvotecount>";
}
private String getHelpMessage() {
StringBuilder helpBuilder = new StringBuilder("&aVotingPlugin Commands:\n");
helpBuilder.append("/votingplugin reload - Reload the plugin\n");
helpBuilder.append("/votingplugin reloadmysql - Reload the plugin including MySQL\n");
helpBuilder.append("/votingplugin vote <player> <site> - Send a vote\n");
helpBuilder.append("/votingplugin forcetimechange <TimeType> - Force a time change\n");
helpBuilder.append("/votingplugin status - Check connection status\n");
helpBuilder.append("/votingplugin multiproxystatus - Send status message across proxies\n");
helpBuilder.append("/votingplugin voteparty <force/setvotecount> - Trigger or modify vote party\n");
return helpBuilder.toString();
}
private boolean isInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
@@ -0,0 +1,127 @@
package com.bencodez.votingplugin.bungee.proxy;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public interface VotingPluginProxyConfig {
public boolean getAllowUnJoined();
public String getBedrockPlayerPrefix();
public List<String> getBlockedServers();
public boolean getBroadcast();
public String getBungeeHost();
public boolean getBungeeManageTotals();
public String getBungeeMethod();
public int getBungeePort();
public String getPluginMessageChannel();
public boolean getPluginMessageEncryption();
public boolean getDebug();
public String getFallBack();
public boolean getGlobalDataEnabled();
public boolean getGlobalDataUseMainMySQL();
public int getLimitVotePoints();
public int getMaxAmountOfVotesPerDay();
public String getMultiProxyMethod();
public boolean getMultiProxyOneGlobalReward();
public String getMultiProxyRedisHost();
public String getMultiProxyRedisPassword();
public int getMultiProxyRedisPort();
public boolean getMultiProxyRedisUseExistingConnection();
public String getMultiProxyRedisUsername();
public Collection<String> getMultiProxyServers();
public Map<String, Object> getMultiProxyServersConfiguration(String s);
public String getMultiProxySocketHostHost();
public int getMultiProxySocketHostPort();
public boolean getMultiProxySupport();
public boolean getOnlineMode();
public int getPointsOnVote();
public boolean getPrimaryServer();
public String getProxyServerName();
public List<String> getProxyServers();
public String getRedisHost();
public String getRedisPassword();
public int getRedisPort();
public String getRedisPrefix();
public String getRedisUsername();
public boolean getSendVotesToAllServers();
public Map<String, Object> getSpigotServerConfiguration(String s);
public Collection<String> getSpigotServers();
public boolean getStoreMonthTotalsWithDate();
public boolean getTimeChangeFailSafeBypass();
public int getTimeHourOffSet();
public String getTimeZone();
public boolean getUseMonthDateTotalsAsPrimaryTotal();
public boolean getUUIDLookup();
public int getVoteCacheTime();
public String getVotePartyBroadcast();
public List<String> getVotePartyBungeeCommands();
public boolean getVotePartyEnabled();
public int getVotePartyIncreaseVotesRequired();
public boolean getVotePartySendToAllServers();
public List<String> getVotePartyServersToSend();
public int getVotePartyVotesRequired();
public boolean getWaitForUserOnline();
public List<String> getWhiteListedServers();
public void load();
public void save();
}
@@ -2,16 +2,18 @@ package com.bencodez.votingplugin.bungee.velocity;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import com.bencodez.simpleapi.file.velocity.VelocityYMLFile;
import com.bencodez.votingplugin.bungee.proxy.VotingPluginProxyConfig;
import ninja.leaping.configurate.ConfigurationNode;
public class Config extends VelocityYMLFile {
public class Config extends VelocityYMLFile implements VotingPluginProxyConfig {
public Config(File file) {
super(file);
@@ -21,44 +23,20 @@ public class Config extends VelocityYMLFile {
return getBoolean(getNode("AllowUnJoined"), false);
}
public List<String> getBlockedServers() {
return getStringList(getNode("BlockedServers"), new ArrayList<String>());
public String getBedrockPlayerPrefix() {
return getString(getNode("BedrockPlayerPrefix"), ".");
}
public List<String> getWhiteListedServers() {
return getStringList(getNode("WhiteListedServers"), new ArrayList<String>());
public List<String> getBlockedServers() {
return getStringList(getNode("BlockedServers"), new ArrayList<>());
}
public boolean getBroadcast() {
return getBoolean(getNode("Broadcast"), false);
}
public boolean getOnlineMode() {
return getBoolean(getNode("OnlineMode"), true);
}
public boolean getTimeChangeFailSafeBypass() {
return getBoolean(getNode("TimeChangeFailSafeBypass"), false);
}
public boolean getStoreMonthTotalsWithDate() {
return getBoolean(getNode("StoreMonthTotalsWithDate"), false);
}
public boolean getUseMonthDateTotalsAsPrimaryTotal() {
return getBoolean(getNode("UseMonthDateTotalsAsPrimaryTotal"), false);
}
public boolean getUUIDLookup() {
return getBoolean(getNode("UUIDLookup"), true);
}
public boolean getGlobalDataEnabled() {
return getBoolean(getNode("GlobalData", "Enabled"), false);
}
public boolean getGlobalDataUseMainMySQL() {
return getBoolean(getNode("GlobalData", "UseMainMySQL"), true);
public String getBungeeHost() {
return getString(getNode("BungeeServer", "Host"), "");
}
public boolean getBungeeManageTotals() {
@@ -69,46 +47,10 @@ public class Config extends VelocityYMLFile {
return getString(getNode("BungeeMethod"), "PLUGINMESSAGING");
}
public String getRedisHost() {
return getString(getNode("Redis", "Host"), "");
}
public int getRedisPort() {
return getInt(getNode("Redis", "Port"), 6379);
}
public int getLimitVotePoints() {
return getInt(getNode("LimitVotePoints"), -1);
}
public String getRedisUsername() {
return getString(getNode("Redis", "Username"), "");
}
public String getRedisPrefix() {
return getString(getNode("Redis", "Prefix"), "");
}
public String getRedisPassword() {
return getString(getNode("Redis", "Password"), "");
}
public String getBungeeHost() {
return getString(getNode("BungeeServer", "Host"), "");
}
public int getBungeePort() {
return getInt(getNode("BungeeServer", "Port"), 1297);
}
public int getMaxAmountOfVotesPerDay() {
return getInt(getNode("MaxAmountOfVotesPerDay"), -1);
}
public int getVoteCacheTime() {
return getInt(getNode("VoteCacheTime"), -1);
}
public boolean getDebug() {
return getBoolean(getNode("Debug"), false);
}
@@ -117,84 +59,66 @@ public class Config extends VelocityYMLFile {
return getString(getNode("FallBackServer"), "");
}
public ConfigurationNode getMysqlNode() {
return getNode("MySQL");
public boolean getGlobalDataEnabled() {
return getBoolean(getNode("GlobalData", "Enabled"), false);
}
public int getPointsOnVote() {
return getInt(getNode("PointsOnVote"), 1);
public boolean getGlobalDataUseMainMySQL() {
return getBoolean(getNode("GlobalData", "UseMainMySQL"), true);
}
public boolean getSendVotesToAllServers() {
return getBoolean(getNode("SendVotesToAllServers"), true);
public int getLimitVotePoints() {
return getInt(getNode("LimitVotePoints"), -1);
}
public boolean getVotePartyEnabled() {
return getBoolean(getVotePartyNode().getNode("Enabled"), false);
public int getMaxAmountOfVotesPerDay() {
return getInt(getNode("MaxAmountOfVotesPerDay"), -1);
}
public ConfigurationNode getVotePartyNode() {
return getNode("VoteParty");
}
public boolean getVotePartySendToAllServers() {
return getBoolean(getVotePartyNode().getNode("SendToAllServers"), false);
}
public int getVotePartyVotesRequired() {
return getInt(getVotePartyNode().getNode("VotesRequired"), 100);
}
public int getVotePartyIncreaseVotesRequired() {
return getInt(getVotePartyNode().getNode("IncreaseVotesRequired"), 0);
}
public String getVotePartyBroadcast() {
return getString(getVotePartyNode().getNode("Broadcast"), "");
}
public List<String> getVotePartyServersToSend() {
return getStringList(getVotePartyNode().getNode("ServersToSend"), new ArrayList<String>());
}
public List<String> getVotePartyBungeeCommands() {
return getStringList(getVotePartyNode().getNode("BungeeCommands"), new ArrayList<String>());
}
public ConfigurationNode getSpigotServerConfiguration(String s) {
return getNode("SpigotServers", s);
}
public @NonNull Collection<? extends ConfigurationNode> getSpigotServers() {
return getNode("SpigotServers").getChildrenMap().values();
}
public boolean getWaitForUserOnline() {
return getBoolean(getNode("WaitForUserOnline"), false);
}
public boolean getMultiProxySupport() {
return getBoolean(getNode("MultiProxySupport"), false);
public String getMultiProxyMethod() {
return getString(getNode("MultiProxyMethod"), "SOCKET");
}
public boolean getMultiProxyOneGlobalReward() {
return getBoolean(getNode("MultiProxyOneGlobalReward"), false);
}
public boolean getPrimaryServer() {
return getBoolean(getNode("PrimaryServer"), false);
public String getMultiProxyRedisHost() {
return getString(getNode("MultiProxyRedis", "Host"), "");
}
public String getBedrockPlayerPrefix() {
return getString(getNode("BedrockPlayerPrefix"), ".");
public String getMultiProxyRedisPassword() {
return getString(getNode("MultiProxyRedis", "Password"), "");
}
public ConfigurationNode getMultiProxyServers(String s) {
return getNode("MultiProxyServers", s);
public int getMultiProxyRedisPort() {
return getInt(getNode("MultiProxyRedis", "Port"), 6379);
}
public @NonNull Collection<? extends ConfigurationNode> getMultiProxyServers() {
return getNode("MultiProxyServers").getChildrenMap().values();
public boolean getMultiProxyRedisUseExistingConnection() {
return getBoolean(getNode("MultiProxyRedis", "UseExistingConnection"), false);
}
public String getMultiProxyRedisUsername() {
return getString(getNode("MultiProxyRedis", "Username"), "");
}
public @NonNull List<String> getMultiProxyServers() {
return getChildrenAsList(getNode("MultiProxyServers"));
}
public List<String> getChildrenAsList(ConfigurationNode config) {
List<String> children = new ArrayList<>();
if (config != null) {
for (Map.Entry<Object, ? extends ConfigurationNode> entry : config.getChildrenMap().entrySet()) {
children.add(entry.getKey().toString());
}
}
return children;
}
public Map<String, Object> getMultiProxyServersConfiguration(String s) {
return configToMap(getNode("MultiProxyServers", s));
}
public String getMultiProxySocketHostHost() {
@@ -205,8 +129,24 @@ public class Config extends VelocityYMLFile {
return getInt(getNode("MultiProxySocketHost", "Port"), 1297);
}
public String getMultiProxyMethod() {
return getString(getNode("MultiProxyMethod"), "SOCKET");
public boolean getMultiProxySupport() {
return getBoolean(getNode("MultiProxySupport"), false);
}
public ConfigurationNode getMysqlNode() {
return getNode("MySQL");
}
public boolean getOnlineMode() {
return getBoolean(getNode("OnlineMode"), true);
}
public int getPointsOnVote() {
return getInt(getNode("PointsOnVote"), 1);
}
public boolean getPrimaryServer() {
return getBoolean(getNode("PrimaryServer"), false);
}
public String getProxyServerName() {
@@ -214,27 +154,135 @@ public class Config extends VelocityYMLFile {
}
public List<String> getProxyServers() {
return getStringList(getNode("ProxyServers"), new ArrayList<String>());
return getStringList(getNode("ProxyServers"), new ArrayList<>());
}
public boolean getMultiProxyRedisUseExistingConnection() {
return getBoolean(getNode("MultiProxyRedis", "UseExistingConnection"), false);
public String getRedisHost() {
return getString(getNode("Redis", "Host"), "");
}
public String getMultiProxyRedisHost() {
return getString(getNode("MultiProxyRedis", "Host"), "");
public String getRedisPassword() {
return getString(getNode("Redis", "Password"), "");
}
public int getMultiProxyRedisPort() {
return getInt(getNode("MultiProxyRedis", "Port"), 6379);
public int getRedisPort() {
return getInt(getNode("Redis", "Port"), 6379);
}
public String getMultiProxyRedisUsername() {
return getString(getNode("MultiProxyRedis", "Username"), "");
public String getRedisPrefix() {
return getString(getNode("Redis", "Prefix"), "");
}
public String getMultiProxyRedisPassword() {
return getString(getNode("MultiProxyRedis", "Password"), "");
public String getRedisUsername() {
return getString(getNode("Redis", "Username"), "");
}
public boolean getSendVotesToAllServers() {
return getBoolean(getNode("SendVotesToAllServers"), true);
}
public Map<String, Object> getSpigotServerConfiguration(String s) {
return configToMap(getNode("SpigotServers", s));
}
public Map<String, Object> configToMap(ConfigurationNode config) {
Map<String, Object> map = new HashMap<>();
if (config != null) {
for (Map.Entry<Object, ? extends ConfigurationNode> entry : config.getChildrenMap().entrySet()) {
map.put(entry.getKey().toString(), entry.getValue().getValue());
}
}
return map;
}
public @NonNull List<String> getSpigotServers() {
return getChildrenAsList(getNode("SpigotServers"));
}
public boolean getStoreMonthTotalsWithDate() {
return getBoolean(getNode("StoreMonthTotalsWithDate"), false);
}
public boolean getTimeChangeFailSafeBypass() {
return getBoolean(getNode("TimeChangeFailSafeBypass"), false);
}
public boolean getUseMonthDateTotalsAsPrimaryTotal() {
return getBoolean(getNode("UseMonthDateTotalsAsPrimaryTotal"), false);
}
public boolean getUUIDLookup() {
return getBoolean(getNode("UUIDLookup"), true);
}
public int getVoteCacheTime() {
return getInt(getNode("VoteCacheTime"), -1);
}
public String getVotePartyBroadcast() {
return getString(getVotePartyNode().getNode("Broadcast"), "");
}
public List<String> getVotePartyBungeeCommands() {
return getStringList(getVotePartyNode().getNode("BungeeCommands"), new ArrayList<>());
}
public boolean getVotePartyEnabled() {
return getBoolean(getVotePartyNode().getNode("Enabled"), false);
}
public int getVotePartyIncreaseVotesRequired() {
return getInt(getVotePartyNode().getNode("IncreaseVotesRequired"), 0);
}
public ConfigurationNode getVotePartyNode() {
return getNode("VoteParty");
}
public boolean getVotePartySendToAllServers() {
return getBoolean(getVotePartyNode().getNode("SendToAllServers"), false);
}
public List<String> getVotePartyServersToSend() {
return getStringList(getVotePartyNode().getNode("ServersToSend"), new ArrayList<>());
}
public int getVotePartyVotesRequired() {
return getInt(getVotePartyNode().getNode("VotesRequired"), 100);
}
public boolean getWaitForUserOnline() {
return getBoolean(getNode("WaitForUserOnline"), false);
}
public List<String> getWhiteListedServers() {
return getStringList(getNode("WhiteListedServers"), new ArrayList<>());
}
@Override
public int getTimeHourOffSet() {
return getInt(getNode("TimeHourOffSet"), 0);
}
@Override
public String getTimeZone() {
return getString(getNode("TimeZone"), "");
}
@Override
public void load() {
// TODO Auto-generated method stub
}
@Override
public String getPluginMessageChannel() {
return getString(getNode("PluginMessageChannel"), "vp:vp");
}
@Override
public boolean getPluginMessageEncryption() {
return getBoolean(getNode("PluginMessageEncryption"), false);
}
}
@@ -15,7 +15,7 @@ public class NonVotedPlayersCache extends VelocityJSONFile {
}
public void addPlayer(Player player) {
if (!plugin.getMysql().containsKeyQuery(player.getUniqueId().toString())) {
if (!plugin.getVotingPluginProxy().getProxyMySQL().containsKeyQuery(player.getUniqueId().toString())) {
addPlayer(player.getUniqueId().toString(), player.getUsername());
}
}
@@ -27,7 +27,7 @@ public class NonVotedPlayersCache extends VelocityJSONFile {
}
public void addPlayerCheck(String uuid, String playerName) {
if (!plugin.getMysql().containsKeyQuery(uuid)) {
if (!plugin.getVotingPluginProxy().getProxyMySQL().containsKeyQuery(uuid)) {
addPlayer(uuid, playerName);
}
}
@@ -40,7 +40,7 @@ public class NonVotedPlayersCache extends VelocityJSONFile {
} else {
String uuid = getNode("NonVotedPlayers", player, "UUID").getString("");
if (!uuid.isEmpty()) {
if (plugin.getMysql().containsKeyQuery(uuid)) {
if (plugin.getVotingPluginProxy().getProxyMySQL().containsKeyQuery(uuid)) {
remove(player);
}
} else {
@@ -15,28 +15,10 @@ public class VoteCache extends VelocityJSONFile {
super(file);
}
public int getVotePartyCurrentVotes() {
return getInt(getNode("VoteParty").getNode("CurrentVotes"), 0);
}
public int getVotePartyInreaseVotesRequired() {
return getInt(getNode("VoteParty").getNode("IncreaseVotes"), 0);
}
public void setVotePartyCurrentVotes(int amount) {
getNode("VoteParty").getNode("CurrentVotes").setValue(amount);
}
public void setVotePartyInreaseVotesRequired(int amount) {
getNode("VoteParty").getNode("IncreaseVotes").setValue(amount);
}
public void setVotePartyCache(String server, int amount) {
getNode("VoteParty").getNode("Cache").getNode(server).setValue(amount);
}
public int getVotePartyCache(String server) {
return getNode("VoteParty").getNode("Cache").getNode(server).getInt(0);
public void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
getNode("TimedVoteCache", "" + num, "Name").setValue(voteTimedQueue.getName());
getNode("TimedVoteCache", "" + num, "Service").setValue(voteTimedQueue.getService());
getNode("TimedVoteCache", "" + num, "Time").setValue(voteTimedQueue.getTime());
}
public void addVote(String server, int num, OfflineBungeeVote voteData) {
@@ -49,12 +31,6 @@ public class VoteCache extends VelocityJSONFile {
getNode("VoteCache", server, "" + num, "Text").setValue(voteData.getText());
}
public void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
getNode("TimedVoteCache", "" + num, "Name").setValue(voteTimedQueue.getName());
getNode("TimedVoteCache", "" + num, "Service").setValue(voteTimedQueue.getService());
getNode("TimedVoteCache", "" + num, "Time").setValue(voteTimedQueue.getTime());
}
public void addVoteOnline(String player, int num, OfflineBungeeVote voteData) {
getNode("OnlineCache", player, "" + num, "Name").setValue(voteData.getPlayerName());
@@ -68,6 +44,7 @@ public class VoteCache extends VelocityJSONFile {
public void clearData() {
getNode("VoteCache").setValue(null);
getNode("OnlineCache").setValue(null);
getNode("TimedVoteCache").setValue(null);
save();
}
@@ -75,10 +52,6 @@ public class VoteCache extends VelocityJSONFile {
return getKeys(getNode("OnlineCache", name));
}
public ConfigurationNode getTimedVoteCache(String name) {
return getNode("TimedVoteCache", name);
}
public ConfigurationNode getOnlineVotes(String name, String num) {
return getNode("OnlineCache", name, num);
}
@@ -91,10 +64,6 @@ public class VoteCache extends VelocityJSONFile {
return getKeys(getNode("VoteCache"));
}
public Collection<String> getTimedVoteCache() {
return getKeys(getNode("TimedVoteCache"));
}
public Collection<String> getServerVotes(String server) {
return getKeys(getNode("VoteCache", server));
}
@@ -103,4 +72,36 @@ public class VoteCache extends VelocityJSONFile {
return getNode("VoteCache", server, num);
}
public Collection<String> getTimedVoteCache() {
return getKeys(getNode("TimedVoteCache"));
}
public ConfigurationNode getTimedVoteCache(String name) {
return getNode("TimedVoteCache", name);
}
public int getVotePartyCache(String server) {
return getNode("VoteParty").getNode("Cache").getNode(server).getInt(0);
}
public int getVotePartyCurrentVotes() {
return getInt(getNode("VoteParty").getNode("CurrentVotes"), 0);
}
public int getVotePartyInreaseVotesRequired() {
return getInt(getNode("VoteParty").getNode("IncreaseVotes"), 0);
}
public void setVotePartyCache(String server, int amount) {
getNode("VoteParty").getNode("Cache").getNode(server).setValue(amount);
}
public void setVotePartyCurrentVotes(int amount) {
getNode("VoteParty").getNode("CurrentVotes").setValue(amount);
}
public void setVotePartyInreaseVotesRequired(int amount) {
getNode("VoteParty").getNode("IncreaseVotes").setValue(amount);
}
}
@@ -9,7 +9,7 @@ public class VoteEventVelocity {
public VoteEventVelocity(VotingPluginVelocity plugin) {
this.plugin = plugin;
}
@Subscribe
public void onVotifierEvent(VotifierEvent event) {
final String serviceSiteVote = event.getVote().getServiceName();
@@ -24,7 +24,7 @@ public class VoteEventVelocity {
serviceSite = "Empty";
}
plugin.vote(name, serviceSite, true, false, 0, null, null);
plugin.getVotingPluginProxy().vote(name, serviceSite, true, false, 0, null, null);
}
});
File diff suppressed because it is too large. Load diff
@@ -1,12 +1,10 @@
package com.bencodez.votingplugin.bungee.velocity;
import com.bencodez.advancedcore.api.time.TimeType;
import com.bencodez.votingplugin.bungee.BungeeMethod;
import com.bencodez.votingplugin.bungee.proxy.VotingPluginProxyCommand;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.command.SimpleCommand;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
public class VotingPluginVelocityCommand implements SimpleCommand {
private VotingPluginVelocity plugin;
@@ -21,89 +19,16 @@ public class VotingPluginVelocityCommand implements SimpleCommand {
// Get the arguments after the command alias
String[] args = invocation.arguments();
if (args.length > 0) {
if (args[0].equalsIgnoreCase("reload")) {
plugin.reload(false);
source.sendMessage(Component.text("Reloading VotingPluginBungee").color(NamedTextColor.AQUA));
}
if (args[0].equalsIgnoreCase("reloadmysql")) {
plugin.reload(true);
source.sendMessage(Component.text("Reloading VotingPluginBungee MySQL").color(NamedTextColor.AQUA));
}
if (args[0].equalsIgnoreCase("vote")) {
if (args.length >= 2) {
String user = args[1];
String site = args[2];
plugin.vote(user, site, false, true, 0, null, null);
source.sendMessage(Component.text("Sending vote").color(NamedTextColor.AQUA));
}
}
if (args[0].equalsIgnoreCase("forcetimechange")) {
if (args.length >= 2) {
plugin.getBungeeTimeChecker().forceChanged(TimeType.getTimeType(args[1]));
source.sendMessage(Component.text("Triggering time change: " + args[1]).color(NamedTextColor.AQUA));
}
}
if (args[0].equalsIgnoreCase("status")) {
if (plugin.getMethod().equals(BungeeMethod.SOCKETS)) {
source.sendMessage(
Component.text("Checking status, waiting for response, check console, method: sockets")
.color(NamedTextColor.AQUA));
plugin.status();
} else if (plugin.getMethod().equals(BungeeMethod.PLUGINMESSAGING)) {
source.sendMessage(Component
.text("Checking status, waiting for response, check console, method: pluginmessaging")
.color(NamedTextColor.AQUA));
plugin.status();
plugin.sendServerNameMessage();
} else if (plugin.getMethod().equals(BungeeMethod.REDIS)) {
source.sendMessage(
Component.text("Checking status, waiting for response, check console, method: redis")
.color(NamedTextColor.AQUA));
plugin.status();
plugin.sendServerNameMessage();
} else {
source.sendMessage(Component.text("Not using socket/pluginmessage method, command unavailable")
.color(NamedTextColor.AQUA));
}
}
if (args[0].equalsIgnoreCase("multiproxystatus")) {
plugin.getMultiProxyHandler().sendMultiProxyServerMessage("Status");
source.sendMessage(Component.text("Sending status message").color(NamedTextColor.AQUA));
}
if (args[0].equalsIgnoreCase("help")) {
String[] msg = new String[7];
msg[0] = "votingpluginbungee reload - Reload plugin";
msg[1] = "votingpluginbungee reloadmysql - Reload plugin including mysql";
msg[2] = "votingpluginbungee vote (player) (servicesite) - Send bungee vote";
msg[3] = "votingpluginbungee status - Check socket connection status";
msg[4] = "&avotingpluginbungee forcetimechange (timetype) - Force a time change";
msg[5] = "&avotingpluginbungee voteparty force - Force a vote party";
msg[6] = "&avotingpluginbungee voteparty setvotecount (number) - Set current vote party votes";
for (String m : msg) {
source.sendMessage(Component.text(m).color(NamedTextColor.AQUA));
}
}
if (args[0].equalsIgnoreCase("voteparty")) {
if (args.length > 1) {
if (args[1].equalsIgnoreCase("Force")) {
plugin.setCurrentVotePartyVotes(plugin.getCurrentVotePartyVotesRequired());
plugin.checkVoteParty();
source.sendMessage(Component.text("Vote party forced").color(NamedTextColor.AQUA));
}
if (args.length > 2) {
if (args[1].equalsIgnoreCase("SetVoteCount")) {
if (isInt(args[2])) {
plugin.setCurrentVotePartyVotes(Integer.parseInt(args[2]));
source.sendMessage(Component.text("Set current vote party votes to " + args[2])
.color(NamedTextColor.AQUA));
}
}
}
}
}
String result = new VotingPluginProxyCommand(plugin.getVotingPluginProxy()).execute(args);
if (result != null) {
source.sendMessage(Component.text(result));
}
}
@Override
public boolean hasPermission(final Invocation invocation) {
return invocation.source().hasPermission("votingpluginbungee.admin");
}
public boolean isInt(String st) {
@@ -119,9 +44,4 @@ public class VotingPluginVelocityCommand implements SimpleCommand {
return false;
}
}
@Override
public boolean hasPermission(final Invocation invocation) {
return invocation.source().hasPermission("votingpluginbungee.admin");
}
}
@@ -100,32 +100,6 @@ public class CommandLoader {
this.plugin = plugin;
}
public void processSlotClick(Player player, VotingPluginUser user, String slot) {
if (MessageAPI.startsWithIgnoreCase(slot, "url")) {
new VoteURL(plugin, player, user, true).open();
} else if (MessageAPI.startsWithIgnoreCase(slot, "next")) {
new VoteNext(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "last")) {
new VoteLast(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "total")) {
new VoteTotal(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "top")) {
new VoteTopVoter(plugin, player, user, TopVoter.getDefault(), 1).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "today")) {
new VoteToday(plugin, player, user, 1).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "help")) {
player.performCommand("vote help");
} else if (MessageAPI.startsWithIgnoreCase(slot, "shop")) {
new VoteShop(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "lastmonth")) {
new VoteTopVoterLastMonth(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "best")) {
new VoteBest(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "streak")) {
new VoteStreak(plugin, player, user).open(GUIMethod.CHEST);
}
}
/**
* @return the adminPerm
*/
@@ -233,8 +207,6 @@ public class CommandLoader {
if (handle.hasPerm(player)) {
// plugin.debug("has perm");
return true;
} else {
// plugin.debug("no perm " + cmd);
}
}
}
@@ -246,8 +218,6 @@ public class CommandLoader {
if (handle.hasPerm(player)) {
// plugin.debug("has perm");
return true;
} else {
// plugin.debug("no perm " + cmd);
}
}
}
@@ -271,7 +241,7 @@ public class CommandLoader {
* Load admin vote command.
*/
private void loadAdminVoteCommand() {
plugin.setAdminVoteCommand(new ArrayList<CommandHandler>());
plugin.setAdminVoteCommand(new ArrayList<>());
plugin.getAdminVoteCommand().add(new CommandHandler(plugin, new String[] { "CurrentPluginTime" },
"VotingPlugin.Commands.AdminVote.CurrentPluginTime|" + adminPerm, "Current plugin time") {
@@ -287,13 +257,6 @@ public class CommandLoader {
.add(new PlayerCommandHandler(plugin, new String[] { "User", "(player)", "SetPoints", "(number)" },
"VotingPlugin.Commands.AdminVote.SetPoints|" + adminPerm, "Set players voting points") {
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.setPoints(Integer.parseInt(args[3]));
sender.sendMessage(MessageAPI.colorize("&cSet " + args[1] + " points to " + args[3]));
}
@Override
public void executeAll(CommandSender sender, String[] args) {
int num = Integer.parseInt(args[3]);
@@ -309,6 +272,13 @@ public class CommandLoader {
}
sender.sendMessage(MessageAPI.colorize("&cDone setting all players points to " + args[3]));
}
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.setPoints(Integer.parseInt(args[3]));
sender.sendMessage(MessageAPI.colorize("&cSet " + args[1] + " points to " + args[3]));
}
});
plugin.getAdminVoteCommand()
@@ -383,7 +353,7 @@ public class CommandLoader {
@Override
public void execute(CommandSender sender, String[] args) {
sendMessage(sender, "&cStarting...");
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<Integer> nums = new ArrayList<>();
for (String str : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
try {
@@ -471,18 +441,6 @@ public class CommandLoader {
.add(new PlayerCommandHandler(plugin, new String[] { "User", "(player)", "AddPoints", "(number)" },
"VotingPlugin.Commands.AdminVote.AddPoints|" + adminPerm, "Add to players voting points") {
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
synchronized (pointLock) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.cache();
int newTotal = 0;
newTotal = user.addPoints(Integer.parseInt(args[3]));
sender.sendMessage(MessageAPI.colorize("&cGave " + args[1] + " " + args[3] + " points"
+ ", " + args[1] + " now has " + newTotal + " points"));
}
}
@Override
public void executeAll(CommandSender sender, String[] args) {
int num = Integer.parseInt(args[3]);
@@ -499,6 +457,18 @@ public class CommandLoader {
}
sender.sendMessage(MessageAPI.colorize("&cGave " + "all players" + " " + args[3] + " points"));
}
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
synchronized (pointLock) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.cache();
int newTotal = 0;
newTotal = user.addPoints(Integer.parseInt(args[3]));
sender.sendMessage(MessageAPI.colorize("&cGave " + args[1] + " " + args[3] + " points"
+ ", " + args[1] + " now has " + newTotal + " points"));
}
}
});
plugin.getAdminVoteCommand()
@@ -1033,15 +1003,6 @@ public class CommandLoader {
new String[] { "User", "(player)", "AddMilestoneCount", "(number)" },
"VotingPlugin.Commands.AdminVote.AddMilestoneCount|" + adminPerm, "Add milestonecount") {
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.setMilestoneCount(user.getMilestoneCount() + Integer.parseInt(args[3]));
plugin.getSpecialRewards().checkMilestone(user, null,
plugin.getBungeeSettings().isUseBungeecoord());
sender.sendMessage(MessageAPI.colorize("&cAdded milestonecount for " + args[1]));
}
@Override
public void executeAll(CommandSender sender, String[] args) {
int toAdd = Integer.parseInt(args[3]);
@@ -1057,6 +1018,15 @@ public class CommandLoader {
}
sender.sendMessage(MessageAPI.colorize("&cFinished adding milestonecount for all players"));
}
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.setMilestoneCount(user.getMilestoneCount() + Integer.parseInt(args[3]));
plugin.getSpecialRewards().checkMilestone(user, null,
plugin.getBungeeSettings().isUseBungeecoord());
sender.sendMessage(MessageAPI.colorize("&cAdded milestonecount for " + args[1]));
}
});
plugin.getAdminVoteCommand()
@@ -1077,13 +1047,6 @@ public class CommandLoader {
"VotingPlugin.Commands.AdminVote.ClearGottenMilestones|" + adminPerm,
"Clears received milestones") {
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.setHasGottenMilestone(new HashMap<String, Boolean>());
sender.sendMessage(MessageAPI.colorize("&cClearing gotten milestones for " + args[1]));
}
@Override
public void executeAll(CommandSender sender, String[] args) {
String path = "GottenMileStones";
@@ -1098,6 +1061,13 @@ public class CommandLoader {
sender.sendMessage(
MessageAPI.colorize("&cFinished clearing gotten milestones for all players"));
}
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
user.setHasGottenMilestone(new HashMap<>());
sender.sendMessage(MessageAPI.colorize("&cClearing gotten milestones for " + args[1]));
}
});
plugin.getAdminVoteCommand().add(new CommandHandler(plugin, new String[] { "Vote", "(player)", "All" },
@@ -1830,8 +1800,7 @@ public class CommandLoader {
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager()
.getAllKeys(UserStorage.value(args[1]));
Queue<Entry<UUID, ArrayList<Column>>> players = new LinkedList<Entry<UUID, ArrayList<Column>>>(
cols.entrySet());
Queue<Entry<UUID, ArrayList<Column>>> players = new LinkedList<>(cols.entrySet());
ArrayList<String> uuids = plugin.getUserManager().getAllUUIDs();
while (players.size() > 0) {
@@ -1882,7 +1851,7 @@ public class CommandLoader {
* Load aliases.
*/
public void loadAliases() {
commands = new HashMap<String, CommandHandler>();
commands = new HashMap<>();
if (!plugin.getConfigFile().isLoadCommandAliases()) {
return;
}
@@ -1997,7 +1966,7 @@ public class CommandLoader {
@Override
public void onClick(ClickEvent clickEvent) {
Player player = clickEvent.getPlayer();
ArrayList<String> voteSites = new ArrayList<String>();
ArrayList<String> voteSites = new ArrayList<>();
for (VoteSite voteSite : plugin.getVoteSitesEnabled()) {
voteSites.add(voteSite.getKey());
}
@@ -2090,7 +2059,7 @@ public class CommandLoader {
* Load tab complete.
*/
public void loadTabComplete() {
ArrayList<String> sites = new ArrayList<String>();
ArrayList<String> sites = new ArrayList<>();
for (VoteSite site : plugin.getVoteSitesEnabled()) {
sites.add(site.getKey());
}
@@ -2099,7 +2068,7 @@ public class CommandLoader {
@Override
public void reload() {
ArrayList<String> sites = new ArrayList<String>();
ArrayList<String> sites = new ArrayList<>();
for (VoteSite site : plugin.getVoteSitesEnabled()) {
sites.add(site.getKey());
}
@@ -2111,7 +2080,7 @@ public class CommandLoader {
}
});
ArrayList<String> topVoter = new ArrayList<String>();
ArrayList<String> topVoter = new ArrayList<>();
for (TopVoter top : TopVoter.values()) {
topVoter.add(top.toString());
}
@@ -2120,7 +2089,7 @@ public class CommandLoader {
@Override
public void reload() {
ArrayList<String> topVoter = new ArrayList<String>();
ArrayList<String> topVoter = new ArrayList<>();
for (TopVoter top : TopVoter.values()) {
topVoter.add(top.toString());
}
@@ -2137,7 +2106,7 @@ public class CommandLoader {
@Override
public void reload() {
ArrayList<String> sites = new ArrayList<String>();
ArrayList<String> sites = new ArrayList<>();
for (String str : plugin.getShopFile().getShopIdentifiers()) {
sites.add(str);
}
@@ -2154,7 +2123,7 @@ public class CommandLoader {
* Load vote command.
*/
private void loadVoteCommand() {
plugin.setVoteCommand(new ArrayList<CommandHandler>());
plugin.setVoteCommand(new ArrayList<>());
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders()) {
plugin.getVoteCommand().add(new CommandHandler(plugin, new String[] { "SetPrimaryAccount", "(player)" },
"VotingPlugin.Commands.Vote.SetPrimaryAccount|" + modPerm, "Set primary account", false) {
@@ -2277,7 +2246,7 @@ public class CommandLoader {
if (identifier != null) {
if (limitPass) {
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("identifier", identifier);
placeholders.put("points", "" + points);
placeholders.put("limit", "" + limit);
@@ -2579,7 +2548,7 @@ public class CommandLoader {
@Override
public void execute(CommandSender sender, String[] args) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
int daily = 0;
int weekly = 0;
@@ -2724,7 +2693,7 @@ public class CommandLoader {
if (cPlayer.getPoints() >= pointsToGive) {
user.addPoints(pointsToGive);
cPlayer.removePoints(pointsToGive);
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("transfer", "" + pointsToGive);
placeholders.put("touser", "" + user.getPlayerName());
placeholders.put("fromuser", "" + cPlayer.getPlayerName());
@@ -2788,8 +2757,7 @@ public class CommandLoader {
for (String ident : plugin.getConfigFile().getCustomCommands()) {
ConfigurationSection section = plugin.getConfigFile().getCustomCommands(ident);
@SuppressWarnings("unchecked")
String[] args = ArrayUtils
.convert((ArrayList<String>) section.getList("Args", new ArrayList<String>()));
String[] args = ArrayUtils.convert((ArrayList<String>) section.getList("Args", new ArrayList<>()));
plugin.getVoteCommand().add(new CommandHandler(plugin, args, section.getString("Permission", ""),
section.getString("HelpMessage", "")) {
@@ -2797,7 +2765,7 @@ public class CommandLoader {
@Override
public void execute(CommandSender sender, String[] args) {
sendMessage(sender, section.getString("Message", ""));
for (String str : (ArrayList<String>) section.getList("Commands", new ArrayList<String>())) {
for (String str : (ArrayList<String>) section.getList("Commands", new ArrayList<>())) {
plugin.getBukkitScheduler().runTask(plugin, new Runnable() {
@Override
@@ -2851,6 +2819,32 @@ public class CommandLoader {
}
}
public void processSlotClick(Player player, VotingPluginUser user, String slot) {
if (MessageAPI.startsWithIgnoreCase(slot, "url")) {
new VoteURL(plugin, player, user, true).open();
} else if (MessageAPI.startsWithIgnoreCase(slot, "next")) {
new VoteNext(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "last")) {
new VoteLast(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "total")) {
new VoteTotal(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "top")) {
new VoteTopVoter(plugin, player, user, TopVoter.getDefault(), 1).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "today")) {
new VoteToday(plugin, player, user, 1).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "help")) {
player.performCommand("vote help");
} else if (MessageAPI.startsWithIgnoreCase(slot, "shop")) {
new VoteShop(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "lastmonth")) {
new VoteTopVoterLastMonth(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "best")) {
new VoteBest(plugin, player, user).open(GUIMethod.CHEST);
} else if (MessageAPI.startsWithIgnoreCase(slot, "streak")) {
new VoteStreak(plugin, player, user).open(GUIMethod.CHEST);
}
}
/**
* Sets the commands.
*
@@ -40,7 +40,7 @@ public class CommandAliases implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
ArrayList<String> argsNew = new ArrayList<String>();
ArrayList<String> argsNew = new ArrayList<>();
argsNew.add(cmdHandle.getArgs()[0]);
for (String arg : args) {
argsNew.add(arg);
@@ -48,7 +48,7 @@ public class CommandAliases implements CommandExecutor {
plugin.debug("Attempting cmd...");
plugin.debug("Inputed args: " + ArrayUtils.makeStringList(argsNew));
ArrayList<CommandHandler> handles = new ArrayList<CommandHandler>();
ArrayList<CommandHandler> handles = new ArrayList<>();
if (adminCommand) {
handles.addAll(plugin.getAdminVoteCommand());
} else {
@@ -91,11 +91,9 @@ public class CommandAliases implements CommandExecutor {
// invalid command
if (adminCommand) {
sender.sendMessage(
MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandAdminVote()));
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandAdminVote()));
} else {
sender.sendMessage(
MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandVote()));
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandVote()));
}
return true;
}
@@ -49,7 +49,7 @@ public class AdminGUI {
* @return ArrayList of buttons
*/
public ArrayList<BInventoryButton> adminGUIButtons() {
ArrayList<BInventoryButton> buttons = new ArrayList<BInventoryButton>();
ArrayList<BInventoryButton> buttons = new ArrayList<>();
buttons.add(new BInventoryButton("&cVoteSites",
new String[] { "&cOnly enabled sites are listed in this section", "&cMiddle Click to create" },
new ItemStack(Material.STONE)) {
@@ -241,7 +241,7 @@ public class AdminGUI {
BInventory inv = new BInventory("VoteSites");
int count = 0;
for (VoteSite voteSite : plugin.getVoteSites()) {
ArrayList<String> lore = new ArrayList<String>();
ArrayList<String> lore = new ArrayList<>();
lore.add("Enabled: " + voteSite.isEnabled());
lore.add("Priority: " + voteSite.getPriority());
@@ -251,17 +251,17 @@ public class AdminGUI {
lore.add("VoteDelay: " + voteSite.getVoteDelay());
lore.add("VoteDelayMin: " + voteSite.getVoteDelayMin());
inv.addButton(count, new BInventoryButton(voteSite.getKey(), ArrayUtils.convert(lore),
new ItemStack(Material.STONE)) {
inv.addButton(count,
new BInventoryButton(voteSite.getKey(), ArrayUtils.convert(lore), new ItemStack(Material.STONE)) {
@Override
public void onClick(ClickEvent event) {
@Override
public void onClick(ClickEvent event) {
Player player = event.getWhoClicked();
openAdminGUIVoteSiteSite(player, voteSite);
Player player = event.getWhoClicked();
openAdminGUIVoteSiteSite(player, voteSite);
}
});
}
});
count++;
}
inv.openInventory(player);
@@ -281,7 +281,7 @@ public class AdminGUI {
@Override
public void onClick(ClickEvent event) {
ArrayList<String> playerNames = new ArrayList<String>();
ArrayList<String> playerNames = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
playerNames.add(p.getName());
}
@@ -302,8 +302,8 @@ public class AdminGUI {
});
}
}
}, ArrayUtils.convert(playerNames)).usingMethod(InputMethod.INVENTORY)
.allowCustomOption(true).request(event.getWhoClicked());
}, ArrayUtils.convert(playerNames)).usingMethod(InputMethod.INVENTORY).allowCustomOption(true)
.request(event.getWhoClicked());
}
});
@@ -35,7 +35,7 @@ public class AdminVoteHelp extends GUIHandler {
*/
public ArrayList<TextComponent> adminHelp(CommandSender sender, int page) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<TextComponent> msg = new ArrayList<TextComponent>();
ArrayList<TextComponent> msg = new ArrayList<>();
ArrayList<TextComponent> text = adminHelpText(sender);
int maxPage = text.size() / pagesize;
@@ -61,8 +61,8 @@ public class AdminVoteHelp extends GUIHandler {
* @return the array list
*/
public ArrayList<TextComponent> adminHelpText(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<TextComponent>();
HashMap<String, TextComponent> unsorted = new HashMap<String, TextComponent>();
ArrayList<TextComponent> msg = new ArrayList<>();
HashMap<String, TextComponent> unsorted = new HashMap<>();
boolean requirePerms = plugin.getConfigFile().isFormatCommandsVoteHelpRequirePermission();
@@ -71,7 +71,7 @@ public class AdminVoteHelp extends GUIHandler {
unsorted.put(cmdHandle.getHelpLineCommand("/adminvote"), cmdHandle.getHelpLine("/adminvote"));
}
}
ArrayList<String> unsortedList = new ArrayList<String>();
ArrayList<String> unsortedList = new ArrayList<>();
unsortedList.addAll(unsorted.keySet());
Collections.sort(unsortedList, String.CASE_INSENSITIVE_ORDER);
for (String cmd : unsortedList) {
@@ -40,7 +40,7 @@ public class AdminVotePerms extends GUIHandler {
}
public String[] listPerms(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
for (CommandHandler handle : plugin.getVoteCommand()) {
if (sender instanceof Player) {
@@ -100,7 +100,7 @@ public class AdminVotePerms extends GUIHandler {
maxPage++;
}
ArrayList<String> text = new ArrayList<String>();
ArrayList<String> text = new ArrayList<>();
text.add("&c&lCommand : Permissions " + page + "/" + maxPage);
@@ -115,10 +115,10 @@ public class AdminVotePerms extends GUIHandler {
public ArrayList<String> listPerms(CommandSender sender, String player, int page) {
Player p = Bukkit.getPlayer(player);
ArrayList<String> text = new ArrayList<String>();
ArrayList<String> text = new ArrayList<>();
if (p != null) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
for (CommandHandler handle : plugin.getVoteCommand()) {
if (handle.hasPerm(p)) {
@@ -180,7 +180,7 @@ public class AdminVotePerms extends GUIHandler {
}
public String[] listPermsDev(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
msg.add("Command");
msg.add(" Permissions (seperated by |");
msg.add(" Help messasge");
@@ -48,7 +48,7 @@ public class AdminVotePlaceholders extends GUIHandler {
msg = "votingplugin_" + identifier + "";
}
Layout layout = new Layout(new ArrayList<String>(Arrays.asList("[Json]")));
Layout layout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
layout.replaceTextComponent("[Json]", BookUtil.TextBuilder.of(identifier).color(ChatColor.AQUA)
.onHover(BookUtil.HoverAction.showText(msg)).build());
book.addLayout(layout);
@@ -66,7 +66,7 @@ public class AdminVotePlaceholders extends GUIHandler {
msg = "votingplugin_" + identifier + "";
}
Layout layout = new Layout(new ArrayList<String>(Arrays.asList("[Json]")));
Layout layout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
layout.replaceTextComponent("[Json]", BookUtil.TextBuilder.of(identifier).color(ChatColor.AQUA)
.onHover(BookUtil.HoverAction.showText(msg)).build());
book.addLayout(layout);
@@ -79,7 +79,7 @@ public class AdminVotePlaceholders extends GUIHandler {
@Override
public void onChat(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
msg.add("&cPlaceholders:");
for (PlaceHolder<VotingPluginUser> placeholder : plugin.getPlaceholders().getPlaceholders()) {
String identifier = placeholder.getIdentifier().toLowerCase();
@@ -45,7 +45,7 @@ public class AdminVotePlaceholdersPlayer extends GUIHandler {
}
String value = placeholder.placeholderRequest(user, identifier);
String msg = identifier + " = " + value;
Layout layout = new Layout(new ArrayList<String>(Arrays.asList("[Json]")));
Layout layout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
layout.replaceTextComponent("[Json]", BookUtil.TextBuilder.of(msg).color(ChatColor.AQUA)
.onHover(BookUtil.HoverAction.showText(value)).build());
book.addLayout(layout);
@@ -60,7 +60,7 @@ public class AdminVotePlaceholdersPlayer extends GUIHandler {
String value = placeholder.placeholderRequest(identifier);
String msg = identifier + " = " + value;
Layout layout = new Layout(new ArrayList<String>(Arrays.asList("[Json]")));
Layout layout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
layout.replaceTextComponent("[Json]", BookUtil.TextBuilder.of(msg).color(ChatColor.AQUA)
.onHover(BookUtil.HoverAction.showText(value)).build());
book.addLayout(layout);
@@ -70,7 +70,7 @@ public class AdminVotePlaceholdersPlayer extends GUIHandler {
@Override
public void onChat(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
msg.add("&cPlaceholders:");
VotingPluginUser placeholderUser = user;
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders() && user.hasPrimaryAccount()) {
@@ -52,7 +52,7 @@ public class AdminVoteCumulative extends GUIHandler {
@Override
public void onClick(ClickEvent clickEvent) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<Integer> nums = new ArrayList<>();
for (String num : plugin.getSpecialRewardsConfig().getCumulativeVotes()) {
if (MessageAPI.isInt(num)) {
nums.add(Integer.parseInt(num));
@@ -63,7 +63,6 @@ public class AdminVoteCumulativeRemove extends GUIHandler {
}
}.open();
}
});
}
@@ -63,7 +63,6 @@ public class AdminVoteMilestoneRemove extends GUIHandler {
}
}.open();
}
});
}
@@ -52,7 +52,7 @@ public class AdminVoteMilestones extends GUIHandler {
@Override
public void onClick(ClickEvent clickEvent) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<Integer> nums = new ArrayList<>();
for (String num : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
if (MessageAPI.isInt(num)) {
nums.add(Integer.parseInt(num));
@@ -141,7 +141,7 @@ public class AdminVoteVoteShopItem extends GUIHandler {
@Override
public void onClick(ClickEvent clickEvent) {
RewardEditGUI.getInstance().openRewardGUI(clickEvent.getPlayer(),
plugin.getRewardHandler().getDirectlyDefined("CHEST.Shop." + identifier + ".Rewards"));
plugin.getRewardHandler().getDirectlyDefined("Shop." + identifier + ".Rewards"));
}
});
@@ -31,11 +31,11 @@ public class VoteBest extends GUIHandler {
@Override
public ArrayList<String> getChat(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
msg.add(plugin.getConfigFile().getFormatCommandsVoteBestTitle());
msg.addAll(plugin.getConfigFile().getFormatCommandsVoteBestLines());
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("HighestDailyTotal", "" + user.getHighestDailyTotal());
placeholders.put("HighestWeeklyTotal", "" + user.getHighestWeeklyTotal());
placeholders.put("HighestMonthlyTotal", "" + user.getHighestMonthlyTotal());
@@ -64,7 +64,7 @@ public class VoteGUI extends GUIHandler {
}
} else if (slot.equalsIgnoreCase("today")) {
String[] today = new VoteToday(plugin, player, user, 1).voteTodayGUI();
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
if (today.length > 0) {
for (int i = today.length - 1; i < today.length && list.size() < 10 && i >= 0; i--) {
list.add(today[i]);
@@ -151,7 +151,8 @@ public class VoteGUI extends GUIHandler {
String cmd = plugin.getGui().getChestVoteGUISlotCommand(slot);
if (cmd.equalsIgnoreCase("none")) {
return;
} else if (!cmd.equals("")) {
}
if (!cmd.equals("")) {
event.runSync(new Runnable() {
@Override
@@ -34,8 +34,8 @@ public class VoteHelp extends GUIHandler {
}
public ArrayList<TextComponent> helpText(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<TextComponent>();
HashMap<String, TextComponent> unsorted = new HashMap<String, TextComponent>();
ArrayList<TextComponent> msg = new ArrayList<>();
HashMap<String, TextComponent> unsorted = new HashMap<>();
boolean requirePerms = plugin.getConfigFile().isFormatCommandsVoteHelpRequirePermission();
@@ -54,7 +54,7 @@ public class VoteHelp extends GUIHandler {
plugin.getConfigFile().getFormatCommandsVoteHelpLine(), hoverColor));
}
}
ArrayList<String> unsortedList = new ArrayList<String>();
ArrayList<String> unsortedList = new ArrayList<>();
unsortedList.addAll(unsorted.keySet());
Collections.sort(unsortedList, String.CASE_INSENSITIVE_ORDER);
for (String cmd : unsortedList) {
@@ -65,8 +65,8 @@ public class VoteHelp extends GUIHandler {
}
public ArrayList<TextComponent> helpTextLegacy(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<TextComponent>();
HashMap<String, TextComponent> unsorted = new HashMap<String, TextComponent>();
ArrayList<TextComponent> msg = new ArrayList<>();
HashMap<String, TextComponent> unsorted = new HashMap<>();
boolean requirePerms = plugin.getConfigFile().isFormatCommandsVoteHelpRequirePermission();
@@ -76,7 +76,7 @@ public class VoteHelp extends GUIHandler {
cmdHandle.getHelpLine("/vote", plugin.getConfigFile().getFormatCommandsVoteHelpLine()));
}
}
ArrayList<String> unsortedList = new ArrayList<String>();
ArrayList<String> unsortedList = new ArrayList<>();
unsortedList.addAll(unsorted.keySet());
Collections.sort(unsortedList, String.CASE_INSENSITIVE_ORDER);
for (String cmd : unsortedList) {
@@ -108,8 +108,8 @@ public class VoteHelp extends GUIHandler {
public ArrayList<TextComponent> voteHelpText(CommandSender sender) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<TextComponent> msg = new ArrayList<TextComponent>();
ArrayList<TextComponent> text = new ArrayList<TextComponent>();
ArrayList<TextComponent> msg = new ArrayList<>();
ArrayList<TextComponent> text = new ArrayList<>();
if (NMSManager.getInstance().isVersion("1.12")) {
text = helpTextLegacy(sender);
} else {
@@ -33,7 +33,7 @@ public class VoteLast extends GUIHandler {
@Override
public ArrayList<String> getChat(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
String playerName = user.getPlayerName();
@@ -80,10 +80,10 @@ public class VoteLast extends GUIHandler {
PlaceholderUtils
.replacePlaceHolder(
PlaceholderUtils.replacePlaceHolder(
PlaceholderUtils
.replacePlaceHolder(plugin.getGui()
PlaceholderUtils.replacePlaceHolder(
plugin.getGui()
.getChestVoteURLURLText(),
"voteurl", site.getVoteURL()),
"voteurl", site.getVoteURL()),
"sitename", site.getDisplayName()),
"player", player.getName()));
@@ -37,7 +37,7 @@ public class VoteNext extends GUIHandler {
@Override
public ArrayList<String> getChat(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
String playerName = user.getPlayerName();
@@ -64,7 +64,7 @@ public class VoteNext extends GUIHandler {
// add colors/config options
for (VoteSite site : plugin.getVoteSitesEnabled()) {
if (!site.isHidden()) {
Layout nextLayout = new Layout(new ArrayList<String>(Arrays.asList("[Json]")));
Layout nextLayout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
nextLayout.replaceTextComponent("[Json]",
BookUtil.TextBuilder.of(book.colorize(site.getDisplayName()))
.onClick(BookUtil.ClickAction.openUrl(site.getVoteURLJsonStrip()))
@@ -93,10 +93,13 @@ public class VoteNext extends GUIHandler {
siteNameDisplay = site.getDisplayName();
}
inv.addButton(inv.getNextSlot(),
new UpdatingBInventoryButton(plugin, site.getItem().setName(siteNameDisplay)
.setLore(PlaceholderUtils.replacePlaceHolder(
plugin.getGui().getChestVoteNextLine(), "time", user.voteCommandNextInfo(site)))
.setAmountNone(1), 1000, 1000) {
new UpdatingBInventoryButton(plugin,
site.getItem().setName(siteNameDisplay)
.setLore(PlaceholderUtils.replacePlaceHolder(
plugin.getGui().getChestVoteNextLine(), "time",
user.voteCommandNextInfo(site)))
.setAmountNone(1),
1000, 1000) {
@Override
public void onClick(ClickEvent clickEvent) {
@@ -127,7 +127,7 @@ public class VoteShop extends GUIHandler {
if (limitPass) {
if (!plugin.getShopFile().isVoteShopRequireConfirmation(identifier)) {
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("identifier",
plugin.getShopFile().getShopIdentifierIdentifierName(identifier));
placeholders.put("points", "" + points);
@@ -56,7 +56,7 @@ public class VoteShopConfirm extends GUIHandler {
user.cache();
int points = plugin.getShopFile().getShopIdentifierCost(identifier);
int limit = plugin.getShopFile().getShopIdentifierLimit(identifier);
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("identifier", identifier);
placeholders.put("points", "" + points);
placeholders.put("limit", "" + limit);
@@ -32,11 +32,11 @@ public class VoteStreak extends GUIHandler {
@Override
public ArrayList<String> getChat(CommandSender sender) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
msg.add(plugin.getConfigFile().getFormatCommandsVoteStreakTitle());
msg.addAll(plugin.getConfigFile().getFormatCommandsVoteStreakLines());
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("DailyStreak", "" + user.getDayVoteStreak());
placeholders.put("WeeklyStreak", "" + user.getWeekVoteStreak());
placeholders.put("MonthlyStreak", "" + user.getMonthVoteStreak());
@@ -44,7 +44,7 @@ public class VoteToday extends GUIHandler {
if (page < 1) {
page = 1;
}
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
String[] voteToday = voteToday();
int maxPage = voteToday.length / pagesize;
@@ -52,7 +52,7 @@ public class VoteToday extends GUIHandler {
maxPage++;
}
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("page", "" + page);
placeholders.put("maxpage", "" + maxPage);
@@ -91,7 +91,7 @@ public class VoteToday extends GUIHandler {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(plugin.getConfigFile().getFormatTimeFormat());
String timeString = plugin.getVoteToday().get(user).get(voteSite).format(formatter);
String msg = plugin.getGui().getChestVoteTodayLine();
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("VoteSite", voteSite.getDisplayName());
placeholders.put("Time", timeString);
msg = PlaceholderUtils.replacePlaceHolder(msg, placeholders);
@@ -146,15 +146,16 @@ public class VoteToday extends GUIHandler {
}
public String[] voteToday() {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
for (TopVoterPlayer user : plugin.getVoteToday().keySet()) {
for (VoteSite voteSite : plugin.getVoteToday().get(user).keySet()) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(plugin.getConfigFile().getFormatTimeFormat());
String timeString = plugin.getVoteToday().get(user).get(voteSite).format(formatter);
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesite", voteSite.getKey());
placeholders.put("sitename", voteSite.getDisplayName());
placeholders.put("time", timeString);
msg.add(PlaceholderUtils.replacePlaceHolder(plugin.getConfigFile().getFormatCommandsVoteTodayLine(),
placeholders));
@@ -167,7 +168,7 @@ public class VoteToday extends GUIHandler {
}
public String[] voteTodayGUI() {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
for (TopVoterPlayer user : plugin.getVoteToday().keySet()) {
LocalDateTime mostRecent = null;
@@ -181,9 +182,10 @@ public class VoteToday extends GUIHandler {
if (mostRecent != null) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(plugin.getConfigFile().getFormatTimeFormat());
String timeString = mostRecent.format(formatter);
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesite", mostRecentSite.getKey());
placeholders.put("sitename", mostRecentSite.getDisplayName());
placeholders.put("time", timeString);
msg.add(PlaceholderUtils.replacePlaceHolder(plugin.getConfigFile().getFormatCommandsVoteTodayLine(),
placeholders));
@@ -56,7 +56,7 @@ public class VoteTopVoter extends GUIHandler {
default:
break;
}
return new ArrayList<String>();
return new ArrayList<>();
}
@Override
@@ -85,7 +85,7 @@ public class VoteTopVoter extends GUIHandler {
ConfigurationSection customization = plugin.getGui().getChestVoteTopCustomization();
boolean customzationEnabled = false;
Queue<Integer> playerSlots = new ConcurrentLinkedQueue<Integer>();
Queue<Integer> playerSlots = new ConcurrentLinkedQueue<>();
if (customization != null) {
customzationEnabled = customization.getBoolean("Enabled");
List<Integer> customizationPlayerSlots = customization.getIntegerList("PlayerSlots");
@@ -109,7 +109,7 @@ public class VoteTopVoter extends GUIHandler {
playerItem = new ItemBuilder(Material.valueOf(plugin.getGui().getChestVoteTopPlayerItemMaterial()));
}
playerItem.setLore(new ArrayList<String>());
playerItem.setLore(new ArrayList<>());
BInventoryButton button = new BInventoryButton(playerItem
.setName(plugin.getGui().getChestVoteTopItemName())
@@ -65,7 +65,7 @@ public class VoteTopVoterLastMonth extends GUIHandler {
playerItem = new ItemBuilder(Material.valueOf(plugin.getGui().getChestVoteTopPlayerItemMaterial()));
}
playerItem.setLore(new ArrayList<String>());
playerItem.setLore(new ArrayList<>());
inv.addButton(new BInventoryButton(playerItem.setName(plugin.getGui().getChestVoteTopItemName())
.addLoreLine(plugin.getGui().getChestVoteTopItemLore()).addPlaceholder("position", "" + pos)
@@ -43,6 +43,10 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
return null;
}
public void next(int index) {
}
@Override
public void onBook(Player player) {
// TODO
@@ -52,10 +56,6 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
public void onChat(CommandSender sender) {
}
public void next(int index) {
}
@Override
public void onChest(Player player) {
@@ -70,22 +70,19 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
}
player.sendMessage(ChatColor.RED + "Can't open previous months, no data");
return;
} else {
if (yearMonthList.size() > index) {
yearMonth = yearMonthList.get(index);
} else {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data for requested index");
return;
}
}
if (yearMonthList.size() <= index) {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data for requested index");
return;
}
yearMonth = yearMonthList.get(index);
Set<Entry<TopVoterPlayer, Integer>> users = null;
if (plugin.getPreviousMonthsTopVoters().containsKey(yearMonth)) {
users = plugin.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
} else {
if (!plugin.getPreviousMonthsTopVoters().containsKey(yearMonth)) {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data");
return;
}
users = plugin.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
BInventory inv = new BInventory(plugin.getGui().getChestVoteTopName());
inv.addPlaceholder("topvoter", yearMonth.toString());
@@ -103,7 +100,7 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
playerItem = new ItemBuilder(Material.valueOf(plugin.getGui().getChestVoteTopPlayerItemMaterial()));
}
playerItem.setLore(new ArrayList<String>());
playerItem.setLore(new ArrayList<>());
inv.addButton(new BInventoryButton(playerItem.setName(plugin.getGui().getChestVoteTopItemName())
.addLoreLine(plugin.getGui().getChestVoteTopItemLore()).addPlaceholder("position", "" + pos)
@@ -32,7 +32,7 @@ public class VoteTotal extends GUIHandler {
@Override
public ArrayList<String> getChat(CommandSender arg0) {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
int daily = user.getTotal(TopVoter.Daily);
int weekly = user.getTotal(TopVoter.Weekly);
@@ -56,7 +56,7 @@ public class VoteURL extends GUIHandler {
}
public ArrayList<String> getChat(CommandSender sender, boolean bypassCanVote) {
ArrayList<String> sites = new ArrayList<String>();
ArrayList<String> sites = new ArrayList<>();
List<String> title = plugin.getConfigFile().getFormatCommandsVoteText();
if (title != null) {
@@ -89,7 +89,7 @@ public class VoteURL extends GUIHandler {
}
}
if (user != null) {
HashMap<String, String> phs = new HashMap<String, String>();
HashMap<String, String> phs = new HashMap<>();
phs.put("DailyTotal", "" + user.getTotal(TopVoter.Daily));
phs.put("WeekTotal", "" + user.getTotal(TopVoter.Weekly));
phs.put("MonthTotal", "" + user.getTotal(TopVoter.Monthly));
@@ -229,7 +229,7 @@ public class VoteURL extends GUIHandler {
Player player = event.getPlayer();
if (player != null) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("voteurl", voteSite.getVoteURL());
placeholders.put("sitename", voteSite.getDisplayName());
placeholders.put("player", player.getName());
@@ -32,9 +32,9 @@ public class AdminVoteTabCompleter implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) {
List<String> tab = new ArrayList<String>();
List<String> tab = new ArrayList<>();
Set<String> cmds = new HashSet<String>();
Set<String> cmds = new HashSet<>();
cmds.addAll(AdvancedCoreTabCompleteHandler.getInstance().getTabCompleteOptions(plugin.getAdminVoteCommand(),
sender, args, args.length - 1));
@@ -39,7 +39,7 @@ public class AliasesTabCompleter implements TabCompleter {
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] argsIn) {
ArrayList<String> msgArray = new ArrayList<String>();
ArrayList<String> msgArray = new ArrayList<>();
msgArray.add("");
for (String arg : argsIn) {
msgArray.add(arg);
@@ -47,11 +47,11 @@ public class AliasesTabCompleter implements TabCompleter {
String[] args = ArrayUtils.convert(msgArray);
ArrayList<String> tab = new ArrayList<String>();
ArrayList<String> tab = new ArrayList<>();
Set<String> cmds = new HashSet<String>();
Set<String> cmds = new HashSet<>();
ArrayList<CommandHandler> cmdHandlers = new ArrayList<CommandHandler>();
ArrayList<CommandHandler> cmdHandlers = new ArrayList<>();
if (adminCommand) {
cmdHandlers.addAll(plugin.getAdminVoteCommand());
@@ -33,12 +33,12 @@ public class VoteTabCompleter implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) {
ArrayList<String> tab = new ArrayList<String>();
ArrayList<String> tab = new ArrayList<>();
Set<String> cmds = new HashSet<String>();
Set<String> cmds = new HashSet<>();
cmds.addAll(AdvancedCoreTabCompleteHandler.getInstance().getTabCompleteOptions(plugin.getVoteCommand(), sender, args,
args.length - 1));
cmds.addAll(AdvancedCoreTabCompleteHandler.getInstance().getTabCompleteOptions(plugin.getVoteCommand(), sender,
args, args.length - 1));
for (String str : cmds) {
if (MessageAPI.startsWithIgnoreCase(str, args[args.length - 1])) {
@@ -39,6 +39,14 @@ public class BungeeSettings extends YMLFile {
@Getter
private String RedisUsername = "";
@ConfigDataString(path = "PluginMessageChannel")
@Getter
private String pluginMessagingChannel = "vp:vp";
@ConfigDataBoolean(path = "PluginMessageEncryption")
@Getter
private boolean pluginMessageEncryption = false;
@ConfigDataString(path = "Redis.Prefix")
@Getter
private String RedisPrefix = "";
@@ -117,7 +125,7 @@ public class BungeeSettings extends YMLFile {
@ConfigDataListString(path = "BungeeVotePartyGlobalCommands")
@Getter
private ArrayList<String> bungeeVotePartyGlobalCommands = new ArrayList<String>();
private ArrayList<String> bungeeVotePartyGlobalCommands = new ArrayList<>();
public BungeeSettings(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "BungeeSettings.yml"));
@@ -121,15 +121,15 @@ public class Config extends YMLFile {
@ConfigDataListString(path = "DisabledCommands")
@Getter
private ArrayList<String> disabledCommands = new ArrayList<String>();
private ArrayList<String> disabledCommands = new ArrayList<>();
@ConfigDataListString(path = "DisabledDefaultPermissions")
@Getter
private ArrayList<String> disabledDefaultPermissions = new ArrayList<String>();
private ArrayList<String> disabledDefaultPermissions = new ArrayList<>();
@ConfigDataListString(path = "CachedPlaceholders")
@Getter
private ArrayList<String> cachedPlaceholders = new ArrayList<String>();
private ArrayList<String> cachedPlaceholders = new ArrayList<>();
@ConfigDataBoolean(path = "DisableInteractEvent")
@Getter
@@ -337,45 +337,15 @@ public class Config extends YMLFile {
@ConfigDataListString(path = "VotingBroadcastBlacklist")
@Getter
private ArrayList<String> votingBroadcastBlacklist = new ArrayList<String>();
public Config(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "Config.yml"));
}
/**
* Gets the black list.
*
* @return the black list
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getBlackList() {
return (ArrayList<String>) getData().getList("BlackList", new ArrayList<String>());
}
private ArrayList<String> votingBroadcastBlacklist = new ArrayList<>();
@ConfigDataKeys(path = "CustomCommands")
@Getter
private Set<String> customCommands = new HashSet<String>();
private Set<String> customCommands = new HashSet<>();
@ConfigDataKeys(path = "CustomPlaceholderReturns")
@Getter
private Set<String> customPlaceholderReturns = new HashSet<String>();
public Set<String> getCustomPlaceholderReturns(String placeholder) {
Set<String> str = getData().getConfigurationSection("CustomPlaceholderReturns." + placeholder).getKeys(false);
if (str == null) {
str = new HashSet<String>();
}
return str;
}
public String getCustomPlaceholderReturns(String placeholder, String returnString) {
return getData().getString("CustomPlaceholderReturns." + placeholder + "." + returnString, "");
}
public ConfigurationSection getCustomCommands(String ident) {
return getData().getConfigurationSection("CustomCommands." + ident);
}
private Set<String> customPlaceholderReturns = new HashSet<>();
@ConfigDataString(path = "Format.BroadcastMsg")
@Getter
@@ -395,7 +365,7 @@ public class Config extends YMLFile {
@ConfigDataListString(path = "Format.Commands.Vote.Best.Lines")
@Getter
private ArrayList<String> formatCommandsVoteBestLines = new ArrayList<String>();
private ArrayList<String> formatCommandsVoteBestLines = new ArrayList<>();
@ConfigDataString(path = "Format.Commands.Vote.Best.Title")
@Getter
@@ -441,10 +411,6 @@ public class Config extends YMLFile {
@Getter
private String placeholderCacheLevelString = "AUTO";
public PlaceholderCacheLevel getPlaceholderCacheLevel() {
return PlaceholderCacheLevel.getCache(getPlaceholderCacheLevelString());
}
@ConfigDataString(path = "Format.Commands.Vote.Next.Layout")
@Getter
private String formatCommandsVoteNextLayout = "&3%SiteName%: &6%info%";
@@ -453,69 +419,10 @@ public class Config extends YMLFile {
@Getter
private String formatCommandsVoteNextTitle = "&3&l%player% Next Votes:";
/**
* Gets the commands vote party.
*
* @return the commands vote party
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteParty() {
ArrayList<String> msg = new ArrayList<String>();
msg.add("&cCurrently at &6%Votes%&c, &6%NeededVotes% &cmore votes to go to reach &6%VotesRequired%");
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Party", msg);
}
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteStreakLines() {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Streak.Lines", new ArrayList<String>());
}
@ConfigDataString(path = "Format.Commands.Vote.Streak.Title")
@Getter
private String formatCommandsVoteStreakTitle = "&3&l%player% Vote Streak";
/**
* Gets the commands vote text.
*
* @return the commands vote text
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteText() {
ArrayList<String> str = new ArrayList<String>();
str.add("&4&lVote for our server!");
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Text", str);
}
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteTotal() {
ArrayList<String> list = (ArrayList<String>) getData().getList("Format.Commands.Vote.Total",
new ArrayList<String>());
if (list.isEmpty()) {
list.add("&3&l%player% Total Votes:");
list.add("&3&lDaily Total: &6&l%DailyTotal%");
list.add("&3&lWeekly Total: &6&l%WeeklyTotal%");
list.add("&3&lMonthly Total: &6&l%MonthlyTotal%");
list.add("&3&lAllTime Total: &6&l%AllTimeTotal%");
}
return list;
}
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteTotalAll() {
ArrayList<String> list = (ArrayList<String>) getData().getList("Format.Commands.Vote.TotalAll",
new ArrayList<String>());
if (list.isEmpty()) {
list.add("&3&lServer Total Votes:");
list.add("&3&lDaily Total: &6&l%DailyTotal%");
list.add("&3&lWeekly Total: &6&l%WeeklyTotal%");
list.add("&3&lMonthly Total: &6&l%MonthlyTotal%");
list.add("&3&lAllTime Total: &6&l%AllTimeTotal%");
}
return list;
}
@ConfigDataString(path = "Format.Commands.Vote.Sites")
@Getter
private String formatCommandsVoteURLS = "&4%num%: &c&l%SiteName% - &c%url%";
@@ -567,9 +474,11 @@ public class Config extends YMLFile {
@ConfigDataString(path = "Format.Signs.TopVoterSign.Line2")
@Getter
private String formatSignTopVoterSignLine2 = "#%position%";
@ConfigDataString(path = "Format.Signs.TopVoterSign.Line3")
@Getter
private String formatSignTopVoterSignLine3 = "%player%";
@ConfigDataString(path = "Format.Signs.TopVoterSign.Line4")
@Getter
private String formatSignTopVoterSignLine4 = "%votes% Votes";
@@ -609,40 +518,13 @@ public class Config extends YMLFile {
@ConfigDataString(path = "Format.InvalidCommand.Vote")
@Getter
private String formatInvalidCommandVote = "&4No valid arguments, see /vote help!";
@ConfigDataString(path = "Format.InvalidCommand.AdminVote")
@Getter
private String formatInvalidCommandAdminVote = "&4No valid arguments, see /adminvote help!";
/**
* Gets the vote help.
*
* @return the vote help
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatVoteHelp() {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Help.Lines", new ArrayList<String>());
}
@ConfigDataBoolean(path = "GiveDefaultPermission")
@Getter
private boolean giveDefaultPermission = true;
public boolean getLoadTopVoter(TopVoter top) {
switch (top) {
case AllTime:
return isLoadTopVoterAllTime();
case Daily:
return isLoadTopVoterDaily();
case Monthly:
return isLoadTopVoterMonthly();
case Weekly:
return isLoadTopVoterWeekly();
default:
return false;
}
}
@ConfigDataBoolean(path = "LoadTopVoter.AllTime")
@Getter
private boolean loadTopVoterAllTime = true;
@@ -681,7 +563,7 @@ public class Config extends YMLFile {
@ConfigDataListString(path = "RequestAPI.DisabledMethods")
@Getter
private ArrayList<String> requestAPIDisabledMethods = new ArrayList<String>();
private ArrayList<String> requestAPIDisabledMethods = new ArrayList<>();
@ConfigDataBoolean(path = "StoreTopVoters.Daily")
@Getter
@@ -715,6 +597,127 @@ public class Config extends YMLFile {
@Getter
private boolean voteRemindingRemindOnlyOnce = false;
@ConfigDataString(path = "VoteTopDefault")
@Getter
private String voteTopDefault = "Monthly";
public Config(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "Config.yml"));
}
/**
* Gets the black list.
*
* @return the black list
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getBlackList() {
return (ArrayList<String>) getData().getList("BlackList", new ArrayList<>());
}
public ConfigurationSection getCustomCommands(String ident) {
return getData().getConfigurationSection("CustomCommands." + ident);
}
public Set<String> getCustomPlaceholderReturns(String placeholder) {
Set<String> str = getData().getConfigurationSection("CustomPlaceholderReturns." + placeholder).getKeys(false);
if (str == null) {
str = new HashSet<>();
}
return str;
}
public String getCustomPlaceholderReturns(String placeholder, String returnString) {
return getData().getString("CustomPlaceholderReturns." + placeholder + "." + returnString, "");
}
/**
* Gets the commands vote party.
*
* @return the commands vote party
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteParty() {
ArrayList<String> msg = new ArrayList<>();
msg.add("&cCurrently at &6%Votes%&c, &6%NeededVotes% &cmore votes to go to reach &6%VotesRequired%");
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Party", msg);
}
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteStreakLines() {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Streak.Lines", new ArrayList<>());
}
/**
* Gets the commands vote text.
*
* @return the commands vote text
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteText() {
ArrayList<String> str = new ArrayList<>();
str.add("&4&lVote for our server!");
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Text", str);
}
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteTotal() {
ArrayList<String> list = (ArrayList<String>) getData().getList("Format.Commands.Vote.Total", new ArrayList<>());
if (list.isEmpty()) {
list.add("&3&l%player% Total Votes:");
list.add("&3&lDaily Total: &6&l%DailyTotal%");
list.add("&3&lWeekly Total: &6&l%WeeklyTotal%");
list.add("&3&lMonthly Total: &6&l%MonthlyTotal%");
list.add("&3&lAllTime Total: &6&l%AllTimeTotal%");
}
return list;
}
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteTotalAll() {
ArrayList<String> list = (ArrayList<String>) getData().getList("Format.Commands.Vote.TotalAll",
new ArrayList<>());
if (list.isEmpty()) {
list.add("&3&lServer Total Votes:");
list.add("&3&lDaily Total: &6&l%DailyTotal%");
list.add("&3&lWeekly Total: &6&l%WeeklyTotal%");
list.add("&3&lMonthly Total: &6&l%MonthlyTotal%");
list.add("&3&lAllTime Total: &6&l%AllTimeTotal%");
}
return list;
}
/**
* Gets the vote help.
*
* @return the vote help
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatVoteHelp() {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Help.Lines", new ArrayList<>());
}
public boolean getLoadTopVoter(TopVoter top) {
switch (top) {
case AllTime:
return isLoadTopVoterAllTime();
case Daily:
return isLoadTopVoterDaily();
case Monthly:
return isLoadTopVoterMonthly();
case Weekly:
return isLoadTopVoterWeekly();
default:
return false;
}
}
public PlaceholderCacheLevel getPlaceholderCacheLevel() {
return PlaceholderCacheLevel.getCache(getPlaceholderCacheLevelString());
}
/**
* Gets the rewards.
*
@@ -724,10 +727,6 @@ public class Config extends YMLFile {
return "VoteReminding.Rewards";
}
@ConfigDataString(path = "VoteTopDefault")
@Getter
private String voteTopDefault = "Monthly";
@Override
public void loadValues() {
new AnnotationHandler().load(getData(), this);
@@ -14,8 +14,8 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.rewards.DirectlyDefinedReward;
import com.bencodez.simpleapi.file.YMLFile;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.file.YMLFile;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
@@ -138,6 +138,10 @@ public class ConfigVoteSites extends YMLFile {
return getData(site).getConfigurationSection("Item");
}
public String getPermissionToView(String siteName) {
return getData(siteName).getString("PermissionToView", "");
}
/**
* Gets the priority.
*
@@ -168,10 +172,6 @@ public class ConfigVoteSites extends YMLFile {
return getData(siteName).getString("ServiceSite");
}
public int getVoteDelayDailyHour(String siteName) {
return getData(siteName).getInt("VoteDelayDailyHour", 0);
}
/**
* Gets the vote delay.
*
@@ -182,6 +182,10 @@ public class ConfigVoteSites extends YMLFile {
return getData(siteName).getDouble("VoteDelay", 24);
}
public int getVoteDelayDailyHour(String siteName) {
return getData(siteName).getInt("VoteDelayDailyHour", 0);
}
public double getVoteDelayMin(String siteName) {
return getData(siteName).getDouble("VoteDelayMin", 0);
}
@@ -239,7 +243,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the vote sites load
*/
public ArrayList<VoteSite> getVoteSitesLoad() {
ArrayList<VoteSite> voteSites = new ArrayList<VoteSite>();
ArrayList<VoteSite> voteSites = new ArrayList<>();
ArrayList<String> voteSiteNames = getVoteSitesNames(true);
if (voteSiteNames != null) {
for (String site : voteSiteNames) {
@@ -276,7 +280,7 @@ public class ConfigVoteSites extends YMLFile {
}
public ArrayList<String> getVoteSitesNames(boolean checkEnabled) {
ArrayList<String> siteNames = new ArrayList<String>();
ArrayList<String> siteNames = new ArrayList<>();
if (getData().isConfigurationSection("VoteSites")) {
siteNames = ArrayUtils.convert(getData().getConfigurationSection("VoteSites").getKeys(false));
}
@@ -298,10 +302,6 @@ public class ConfigVoteSites extends YMLFile {
return siteNames;
}
public String getPermissionToView(String siteName) {
return getData(siteName).getString("PermissionToView", "");
}
/**
* Gets the vote URL.
*
@@ -309,7 +309,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the vote URL
*/
public String getVoteURL(String siteName) {
return getData(siteName).getString("VoteURL");
return getData(siteName).getString("VoteURL", "");
}
public boolean getWaitUntilVoteDelay(String siteName) {
@@ -7,8 +7,8 @@ import java.util.Set;
import org.bukkit.configuration.ConfigurationSection;
import com.bencodez.simpleapi.file.YMLFile;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.file.YMLFile;
import com.bencodez.simpleapi.file.annotation.AnnotationHandler;
import com.bencodez.simpleapi.file.annotation.ConfigDataBoolean;
import com.bencodez.simpleapi.file.annotation.ConfigDataConfigurationSection;
@@ -50,7 +50,7 @@ public class GUI extends YMLFile {
@ConfigDataListString(path = "BOOK.VoteURLBookGUI.TopLayout")
@Getter
private ArrayList<String> bookVoteURLBookGUITopLayout = new ArrayList<String>();
private ArrayList<String> bookVoteURLBookGUITopLayout = new ArrayList<>();
@ConfigDataString(path = "BOOK.VoteURLBookGUI.Title")
@Getter
@@ -134,11 +134,6 @@ public class GUI extends YMLFile {
private VotingPluginMain plugin;
public GUI(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "GUI.yml"));
this.plugin = plugin;
}
@ConfigDataConfigurationSection(path = "CHEST.BackButton")
@Getter
private ConfigurationSection CHESTBackButton;
@@ -163,58 +158,14 @@ public class GUI extends YMLFile {
@Getter
private String chestVoteGUIName = "&cVoteGUI: &c&l%player%";
/**
* Gets the vote GUI slot command.
*
* @param slot the slot
* @return the vote GUI slot command
*/
public String getChestVoteGUISlotCommand(String slot) {
return getData().getString("CHEST.VoteGUI." + slot + ".Command", "");
}
public ConfigurationSection getChestGUIExtraItemsItem(String gui, String item) {
return getData().getConfigurationSection("CHEST." + gui + ".ExtraItems." + item);
}
/**
* Gets the vote GUI slot lore.
*
* @param slot the slot
* @return the vote GUI slot lore
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getChestVoteGUISlotLore(String slot) {
return (ArrayList<String>) getData().getList("CHEST.VoteGUI." + slot + ".Item.Lore", new ArrayList<String>());
}
public String getChestVoteGUISlotRewardsPath(String slot, String lastPath) {
return "CHEST.VoteGUI." + slot + "." + lastPath;
}
@ConfigDataKeys(path = "CHEST.VoteGUI")
@Getter
private Set<String> chestVoteGUISlots = new HashSet<String>();
public ConfigurationSection getChestVoteGUISlotSection(String slot) {
return getData().getConfigurationSection("CHEST.VoteGUI." + slot + ".Item");
}
private Set<String> chestVoteGUISlots = new HashSet<>();
@ConfigDataConfigurationSection(path = "CHEST.VoteTop.Customization")
@Getter
private ConfigurationSection chestVoteTopCustomization;
/**
* Gets the vote GUI slot slot.
*
* @param slot the slot
* @return the vote GUI slot slot
*/
public int getChestVoteGUISlotSlot(String slot) {
return getData().getInt("CHEST.VoteGUI." + slot + ".Slot", -1);
}
@ConfigDataBoolean(path = "CHEST.VoteLast.BackButton")
@Getter
private boolean chestVoteLastBackButton = false;
@@ -239,10 +190,6 @@ public class GUI extends YMLFile {
@Getter
private String chestVoteNextLine = "%time%";
public String getChestVoteNextCustomSiteNamesDisplays(String site) {
return getData().getString("CHEST.VoteNext.CustomSiteNamesDisplays." + site, "");
}
@ConfigDataString(path = "CHEST.VoteRewardName")
@Getter
private String chestVoteRewardName = "VoteReward";
@@ -321,7 +268,7 @@ public class GUI extends YMLFile {
@ConfigDataListString(path = "CHEST.VoteTop.SwitchItem.TopVoters")
@Getter
private ArrayList<String> chestVoteTopSwitchItemTopVoters = new ArrayList<String>();
private ArrayList<String> chestVoteTopSwitchItemTopVoters = new ArrayList<>();
@ConfigDataConfigurationSection(path = "CHEST.VoteTotal.AllTimeTotal.Item")
@Getter
@@ -335,22 +282,6 @@ public class GUI extends YMLFile {
@Getter
private ConfigurationSection chestVoteTotalDayTotalItem;
public ConfigurationSection getChestVoteTotalItem(TopVoter top) {
switch (top) {
case AllTime:
return getChestVoteTotalAllTimeTotalItem();
case Daily:
return getChestVoteTotalDayTotalItem();
case Monthly:
return getChestVoteTotalMonthTotalItem();
case Weekly:
return getChestVoteTotalWeekTotalItem();
default:
return getChestVoteTotalAllTimeTotalItem();
}
}
@ConfigDataConfigurationSection(path = "CHEST.VoteTotal.MonthTotal.Item")
@Getter
private ConfigurationSection chestVoteTotalMonthTotalItem;
@@ -393,18 +324,7 @@ public class GUI extends YMLFile {
@ConfigDataKeys(path = "CHEST.VoteURL.ExtraItems")
@Getter
private Set<String> chestVoteURLExtraItems = new HashSet<String>();
public ConfigurationSection getChestVoteURLExtraItemsItem(String item) {
return getData().getConfigurationSection("CHEST.VoteURL.ExtraItems." + item);
}
public Set<String> getChestGUIExtraItems(String gui) {
if (getData().isConfigurationSection("CHEST." + gui + ".ExtraItems")) {
return getData().getConfigurationSection("CHEST." + gui + ".ExtraItems").getKeys(false);
}
return new HashSet<String>();
}
private Set<String> chestVoteURLExtraItems = new HashSet<>();
@ConfigDataString(path = "CHEST.VoteURL.SiteName")
@Getter
@@ -438,6 +358,86 @@ public class GUI extends YMLFile {
@Getter
private boolean chestVoteURLViewAllUrlsButtonEnabled = false;
public GUI(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "GUI.yml"));
this.plugin = plugin;
}
public Set<String> getChestGUIExtraItems(String gui) {
if (getData().isConfigurationSection("CHEST." + gui + ".ExtraItems")) {
return getData().getConfigurationSection("CHEST." + gui + ".ExtraItems").getKeys(false);
}
return new HashSet<>();
}
public ConfigurationSection getChestGUIExtraItemsItem(String gui, String item) {
return getData().getConfigurationSection("CHEST." + gui + ".ExtraItems." + item);
}
/**
* Gets the vote GUI slot command.
*
* @param slot the slot
* @return the vote GUI slot command
*/
public String getChestVoteGUISlotCommand(String slot) {
return getData().getString("CHEST.VoteGUI." + slot + ".Command", "");
}
/**
* Gets the vote GUI slot lore.
*
* @param slot the slot
* @return the vote GUI slot lore
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getChestVoteGUISlotLore(String slot) {
return (ArrayList<String>) getData().getList("CHEST.VoteGUI." + slot + ".Item.Lore", new ArrayList<>());
}
public String getChestVoteGUISlotRewardsPath(String slot, String lastPath) {
return "CHEST.VoteGUI." + slot + "." + lastPath;
}
public ConfigurationSection getChestVoteGUISlotSection(String slot) {
return getData().getConfigurationSection("CHEST.VoteGUI." + slot + ".Item");
}
/**
* Gets the vote GUI slot slot.
*
* @param slot the slot
* @return the vote GUI slot slot
*/
public int getChestVoteGUISlotSlot(String slot) {
return getData().getInt("CHEST.VoteGUI." + slot + ".Slot", -1);
}
public String getChestVoteNextCustomSiteNamesDisplays(String site) {
return getData().getString("CHEST.VoteNext.CustomSiteNamesDisplays." + site, "");
}
public ConfigurationSection getChestVoteTotalItem(TopVoter top) {
switch (top) {
case AllTime:
return getChestVoteTotalAllTimeTotalItem();
case Daily:
return getChestVoteTotalDayTotalItem();
case Monthly:
return getChestVoteTotalMonthTotalItem();
case Weekly:
return getChestVoteTotalWeekTotalItem();
default:
return getChestVoteTotalAllTimeTotalItem();
}
}
public ConfigurationSection getChestVoteURLExtraItemsItem(String item) {
return getData().getConfigurationSection("CHEST.VoteURL.ExtraItems." + item);
}
@Override
public void loadValues() {
new AnnotationHandler().load(getData(), this);
@@ -48,11 +48,54 @@ public class ShopFile extends YMLFile {
private VotingPluginMain plugin;
@ConfigDataBoolean(path = "VoteShop.BackButton")
@Getter
private boolean voteShopBackButton = true;
@ConfigDataBoolean(path = "VoteShop.ReopenGUIOnPurchase")
@Getter
private boolean voteShopReopenGUIOnPurchase = true;
@ConfigDataBoolean(path = "VoteShop.Enabled")
@Getter
private boolean voteShopEnabled = true;
@ConfigDataString(path = "VoteShop.Name")
@Getter
private String voteShopName = "VoteShop";
@ConfigDataKeys(path = "ExtraItems")
@Getter
private Set<String> voteShopExtraItems = new HashSet<>();
public ShopFile(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "Shop.yml"));
this.plugin = plugin;
}
public void convertFromGUIFile() {
// booleans
setValue("VoteShop.Enabled", plugin.getGui().getData().getBoolean("CHEST.VoteShopEnabled"));
setValue("VoteShop.BackButton", plugin.getGui().getData().getBoolean("CHEST.VoteShopBackButton"));
setValue("VoteShop.HideLimitReached", plugin.getGui().getData().getBoolean("CHEST.VoteShopHideLimitedReached"));
setValue("VoteShop.RequireConfirmation",
plugin.getGui().getData().getBoolean("CHEST.VoteShopRequireConfirmation"));
setValue("VoteShop.ReopenGUIOnPurchase",
plugin.getGui().getData().getBoolean("CHEST.VoteShopReopenGUIOnPurchase"));
// strings
setValue("VoteShop.Name", plugin.getGui().getData().getString("CHEST.VoteShopName"));
setValue("VoteShop.LimitReached", plugin.getGui().getData().getString("CHEST.VoteShopLimitReached"));
setValue("VoteShop.Disabled", plugin.getGui().getData().getString("CHEST.VoteShopDisabled"));
// sections
setValue("Shop", plugin.getGui().getData().getConfigurationSection("CHEST.Shop"));
setValue("ExtraItems", plugin.getGui().getData().getConfigurationSection("CHEST.VoteShopExtraItems"));
setValue("ShopConfirmPurchase", plugin.getGui().getData().getConfigurationSection("CHEST.ShopConfirmPurchase"));
saveData();
}
public void createShop(String value) {
ConfigurationSection shopData = getData().createSection("Shop." + value);
shopData.set("Identifier_Name", value);
@@ -69,6 +112,10 @@ public class ShopFile extends YMLFile {
saveData();
}
public ConfigurationSection getGUIVoteShopExtraItems(String item) {
return getData().getConfigurationSection("ExtraItems." + item);
}
public int getShopIdentifierCost(String identifier) {
return getData().getInt("Shop." + identifier + ".Cost");
}
@@ -90,21 +137,13 @@ public class ShopFile extends YMLFile {
if (shop != null) {
return shop.getKeys(false);
}
return new HashSet<String>();
return new HashSet<>();
}
public ConfigurationSection getShopIdentifierSection(String identifier) {
return getData().getConfigurationSection("Shop." + identifier);
}
@ConfigDataBoolean(path = "VoteShop.BackButton")
@Getter
private boolean voteShopBackButton = true;
@ConfigDataBoolean(path = "VoteShop.ReopenGUIOnPurchase")
@Getter
private boolean voteShopReopenGUIOnPurchase = true;
public boolean getVoteShopCloseGUI(String shop) {
return getData().getBoolean("Shop." + shop + ".CloseGUI", true);
}
@@ -113,14 +152,6 @@ public class ShopFile extends YMLFile {
return getData().getBoolean("Shop." + shop + ".HideOnNoPermission", true);
}
@ConfigDataBoolean(path = "VoteShop.Enabled")
@Getter
private boolean voteShopEnabled = true;
@ConfigDataString(path = "VoteShop.Name")
@Getter
private String voteShopName = "VoteShop";
public boolean getVoteShopNotBuyable(String shop) {
return getData().getBoolean("Shop." + shop + ".NotBuyable", false);
}
@@ -146,14 +177,6 @@ public class ShopFile extends YMLFile {
return getData().getBoolean("Shop." + shop + ".Reset.Weekly", false);
}
public ConfigurationSection getGUIVoteShopExtraItems(String item) {
return getData().getConfigurationSection("ExtraItems." + item);
}
@ConfigDataKeys(path = "ExtraItems")
@Getter
private Set<String> voteShopExtraItems = new HashSet<String>();
public boolean isVoteShopRequireConfirmation(String identifier) {
return getData().getBoolean("Shop." + identifier + ".RequireConfirmation", isVoteShopRequireConfirmation());
}
@@ -168,29 +191,6 @@ public class ShopFile extends YMLFile {
plugin.saveResource("Shop.yml", true);
}
public void convertFromGUIFile() {
// booleans
setValue("VoteShop.Enabled", plugin.getGui().getData().getBoolean("CHEST.VoteShopEnabled"));
setValue("VoteShop.BackButton", plugin.getGui().getData().getBoolean("CHEST.VoteShopBackButton"));
setValue("VoteShop.HideLimitReached", plugin.getGui().getData().getBoolean("CHEST.VoteShopHideLimitedReached"));
setValue("VoteShop.RequireConfirmation",
plugin.getGui().getData().getBoolean("CHEST.VoteShopRequireConfirmation"));
setValue("VoteShop.ReopenGUIOnPurchase",
plugin.getGui().getData().getBoolean("CHEST.VoteShopReopenGUIOnPurchase"));
// strings
setValue("VoteShop.Name", plugin.getGui().getData().getString("CHEST.VoteShopName"));
setValue("VoteShop.LimitReached", plugin.getGui().getData().getString("CHEST.VoteShopLimitReached"));
setValue("VoteShop.Disabled", plugin.getGui().getData().getString("CHEST.VoteShopDisabled"));
// sections
setValue("Shop", plugin.getGui().getData().getConfigurationSection("CHEST.Shop"));
setValue("ExtraItems", plugin.getGui().getData().getConfigurationSection("CHEST.VoteShopExtraItems"));
setValue("ShopConfirmPurchase", plugin.getGui().getData().getConfigurationSection("CHEST.ShopConfirmPurchase"));
saveData();
}
public void removeShop(String value) {
getData().set("Shop." + value, null);
saveData();
@@ -78,11 +78,11 @@ public class SpecialRewardsConfig extends YMLFile {
@ConfigDataListInt(path = "VoteParty.VoteReminderAtVotes")
@Getter
private ArrayList<Integer> votePartyVoteReminderAtVotes = new ArrayList<Integer>();
private ArrayList<Integer> votePartyVoteReminderAtVotes = new ArrayList<>();
@ConfigDataListString(path = "VoteParty.GlobalRandomCommand")
@Getter
private ArrayList<String> votePartyGlobalRandomCommand = new ArrayList<String>();
private ArrayList<String> votePartyGlobalRandomCommand = new ArrayList<>();
@Getter
private String votePartyRewardsPath = "VoteParty.Rewards";
@@ -103,119 +103,29 @@ public class SpecialRewardsConfig extends YMLFile {
@Getter
private double voteStreakRequirementWeek = 50;
public SpecialRewardsConfig(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "SpecialRewards.yml"));
this.plugin = plugin;
}
public boolean getCumulativeRewardEnabled(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".Enabled");
}
public String getCumulativeRewardsPath(int cumulative) {
return "Cumulative." + cumulative + ".Rewards";
}
public List<Integer> getCumulativeBlackList(int cumulative) {
return getData().getIntegerList("Cumulative." + cumulative + ".BlackList");
}
public boolean getCumulativeRecurring(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".Recurring", true);
}
@ConfigDataKeys(path = "Cumulative")
@Getter
private Set<String> cumulativeVotes = new HashSet<String>();
@Deprecated
public boolean getCumulativeVotesInSameDay(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameDay");
}
@Deprecated
public boolean getCumulativeVotesInSameMonth(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameMonth");
}
@Deprecated
public boolean getCumulativeVotesInSameWeek(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameWeek");
}
public String getCumulativeVotesTotal(int cumulative) {
String str = getData().getString("Cumulative." + cumulative + ".TotalToUse", "");
if (str.isEmpty()) {
if (getCumulativeVotesInSameMonth(cumulative)) {
return TopVoter.Monthly.toString();
} else if (getCumulativeVotesInSameWeek(cumulative)) {
return TopVoter.Weekly.toString();
} else if (getCumulativeVotesInSameDay(cumulative)) {
return TopVoter.Daily.toString();
}
}
return str;
}
public String getDailyAwardRewardsPath(String path) {
return "DailyAwards." + path + ".Rewards";
}
private Set<String> cumulativeVotes = new HashSet<>();
@ConfigDataKeys(path = "DailyAwards")
@Getter
private Set<String> dailyPossibleRewardPlaces = new HashSet<String>();
/**
* Gets the milestone reward enabled.
*
* @param milestones the milestones
* @return the milestone reward enabled
*/
public boolean getMilestoneRewardEnabled(int milestones) {
return getData().getBoolean("MileStones." + milestones + ".Enabled");
}
/**
* Gets the milestone rewards.
*
* @param milestones the milestones
* @return the milestone rewards
*/
public String getMilestoneRewardsPath(int milestones) {
return "MileStones." + milestones + ".Rewards";
}
private Set<String> dailyPossibleRewardPlaces = new HashSet<>();
@ConfigDataKeys(path = "MileStones")
@Getter
private Set<String> milestoneVotes = new HashSet<String>();
public String getMonthlyAwardRewardsPath(String path) {
return "MonthlyAwards." + path + ".Rewards";
}
/**
* Gets the monthly possible reward places.
*
* @return the monthly possible reward places
*/
public Set<String> getMonthlyPossibleRewardPlaces() {
try {
return getData().getConfigurationSection("MonthlyAwards").getKeys(false);
} catch (Exception ex) {
return new HashSet<String>();
}
}
private Set<String> milestoneVotes = new HashSet<>();
@ConfigDataBoolean(path = "ResetMilestonesMonthly")
@Getter
private boolean resetMilestonesMonthly = false;
@ConfigDataString(path = "VoteParty.Broadcast")
@Getter
private String votePartyBroadcast = "";
@ConfigDataListString(path = "VoteParty.GlobalCommands", secondPath = "VoteParty.Commands")
@Getter
private ArrayList<String> votePartyGlobalCommands = new ArrayList<String>();
private ArrayList<String> votePartyGlobalCommands = new ArrayList<>();
@ConfigDataBoolean(path = "VoteParty.CountFakeVotes")
@Getter
@@ -242,14 +152,6 @@ public class SpecialRewardsConfig extends YMLFile {
@Getter
private int votePartyIncreaseVotesRequired = 0;
public int getVotePartyIncreaseVotesRequiredWithTypo() {
int increase = getVotePartyIncreaseVotesRequired();
if (increase > 0) {
return increase;
}
return getVotePartyIncreaseVotesRquired();
}
@ConfigDataBoolean(path = "VoteParty.OnlyOncePerDay")
@Getter
private boolean votePartyOnlyOncePerDay = false;
@@ -273,11 +175,115 @@ public class SpecialRewardsConfig extends YMLFile {
@ConfigDataInt(path = "VoteParty.UserVotesRequired")
@Getter
private int votePartyUserVotesRequired = 0;
@ConfigDataInt(path = "VoteParty.VotesRequired")
@Getter
private int votePartyVotesRequired = 0;
@ConfigDataKeys(path = "WeeklyAwards")
@Getter
private Set<String> weeklyPossibleRewardPlaces = new HashSet<>();
public SpecialRewardsConfig(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "SpecialRewards.yml"));
this.plugin = plugin;
}
public List<Integer> getCumulativeBlackList(int cumulative) {
return getData().getIntegerList("Cumulative." + cumulative + ".BlackList");
}
public boolean getCumulativeRecurring(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".Recurring", true);
}
public boolean getCumulativeRewardEnabled(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".Enabled");
}
public String getCumulativeRewardsPath(int cumulative) {
return "Cumulative." + cumulative + ".Rewards";
}
@Deprecated
public boolean getCumulativeVotesInSameDay(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameDay");
}
@Deprecated
public boolean getCumulativeVotesInSameMonth(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameMonth");
}
@Deprecated
public boolean getCumulativeVotesInSameWeek(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameWeek");
}
public String getCumulativeVotesTotal(int cumulative) {
String str = getData().getString("Cumulative." + cumulative + ".TotalToUse", "");
if (str.isEmpty()) {
if (getCumulativeVotesInSameMonth(cumulative)) {
return TopVoter.Monthly.toString();
}
if (getCumulativeVotesInSameWeek(cumulative)) {
return TopVoter.Weekly.toString();
}
if (getCumulativeVotesInSameDay(cumulative)) {
return TopVoter.Daily.toString();
}
}
return str;
}
public String getDailyAwardRewardsPath(String path) {
return "DailyAwards." + path + ".Rewards";
}
/**
* Gets the milestone reward enabled.
*
* @param milestones the milestones
* @return the milestone reward enabled
*/
public boolean getMilestoneRewardEnabled(int milestones) {
return getData().getBoolean("MileStones." + milestones + ".Enabled");
}
/**
* Gets the milestone rewards.
*
* @param milestones the milestones
* @return the milestone rewards
*/
public String getMilestoneRewardsPath(int milestones) {
return "MileStones." + milestones + ".Rewards";
}
public String getMonthlyAwardRewardsPath(String path) {
return "MonthlyAwards." + path + ".Rewards";
}
/**
* Gets the monthly possible reward places.
*
* @return the monthly possible reward places
*/
public Set<String> getMonthlyPossibleRewardPlaces() {
try {
return getData().getConfigurationSection("MonthlyAwards").getKeys(false);
} catch (Exception ex) {
return new HashSet<>();
}
}
public int getVotePartyIncreaseVotesRequiredWithTypo() {
int increase = getVotePartyIncreaseVotesRequired();
if (increase > 0) {
return increase;
}
return getVotePartyIncreaseVotesRquired();
}
public boolean getVoteStreakRewardEnabled(String type, String s) {
return getData().getBoolean("VoteStreak." + type + "." + s + ".Enabled");
}
@@ -292,9 +298,9 @@ public class SpecialRewardsConfig extends YMLFile {
if (set != null) {
return set;
}
return new HashSet<String>();
return new HashSet<>();
} catch (Exception ex) {
return new HashSet<String>();
return new HashSet<>();
}
}
@@ -302,10 +308,6 @@ public class SpecialRewardsConfig extends YMLFile {
return "WeeklyAwards." + path + ".Rewards";
}
@ConfigDataKeys(path = "WeeklyAwards")
@Getter
private Set<String> weeklyPossibleRewardPlaces = new HashSet<String>();
@Override
public void loadValues() {
new AnnotationHandler().load(getData(), this);
@@ -29,27 +29,18 @@ public class CoolDownCheck implements Listener {
private VotingPluginMain plugin;
private HashMap<UUID, ScheduledFuture<?>> perSiteTasks = new HashMap<UUID, ScheduledFuture<?>>();
private HashMap<UUID, ScheduledFuture<?>> perSiteTasks = new HashMap<>();
private HashMap<UUID, ScheduledFuture<?>> allSiteTasks = new HashMap<UUID, ScheduledFuture<?>>();
public CoolDownCheck(VotingPluginMain plugin) {
this.plugin = plugin;
this.timer = Executors.newScheduledThreadPool(1);
}
private HashMap<UUID, ScheduledFuture<?>> allSiteTasks = new HashMap<>();
@Getter
private ScheduledExecutorService timer;
private boolean cooldownCheckEnabled = false;
public void checkEnabled() {
if (!plugin.getConfigFile().isDisableCoolDownCheck() && plugin.getRewardHandler()
.hasRewards(plugin.getSpecialRewardsConfig().getData(), "VoteCoolDownEndedReward")) {
cooldownCheckEnabled = true;
} else {
cooldownCheckEnabled = false;
}
public CoolDownCheck(VotingPluginMain plugin) {
this.plugin = plugin;
this.timer = Executors.newScheduledThreadPool(1);
}
public void check(UUID uuid) {
@@ -60,25 +51,6 @@ public class CoolDownCheck implements Listener {
check(user);
}
public void checkPerSite(UUID uuid) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
if (!user.isOnline()) {
user.dontCache();
}
checkPerSite(user);
}
public void vote(VotingPluginUser user, VoteSite site) {
if (cooldownCheckEnabled) {
schedule(user, true);
}
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
user.setCoolDownCheckSite(site, Boolean.FALSE);
schedulePerSite(user, true);
}
}
public synchronized void check(VotingPluginUser user) {
boolean coolDownCheck = user.getCoolDownCheck();
if (coolDownCheck) {
@@ -93,6 +65,48 @@ public class CoolDownCheck implements Listener {
}
}
public void checkAllVoteSite(VoteSite site) {
plugin.getLogger().info("Checking vote cooldown rewards for all players: " + site.getKey());
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
checkPerSite(user);
user.clearTempCache();
user = null;
}
}
}
cols.clear();
cols = null;
plugin.getLogger().info("Finished checking vote cooldown rewards for all players: " + site.getKey());
}
public void checkEnabled() {
if (!plugin.getConfigFile().isDisableCoolDownCheck() && plugin.getRewardHandler()
.hasRewards(plugin.getSpecialRewardsConfig().getData(), "VoteCoolDownEndedReward")) {
cooldownCheckEnabled = true;
} else {
cooldownCheckEnabled = false;
}
}
public void checkPerSite(UUID uuid) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
if (!user.isOnline()) {
user.dontCache();
}
checkPerSite(user);
}
public synchronized void checkPerSite(VotingPluginUser user) {
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
HashMap<String, Boolean> coolDownChecks = user.getCoolDownCheckSiteList();
@@ -117,6 +131,74 @@ public class CoolDownCheck implements Listener {
}
public void load() {
plugin.addUserStartup(new UserStartup() {
@Override
public void onFinish() {
}
@Override
public void onStart() {
}
@Override
public void onStartUp(AdvancedCoreUser advancedcoreUser) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(advancedcoreUser);
user.dontCache();
if (cooldownCheckEnabled) {
check(user);
}
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
checkPerSite(user);
}
}
});
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteCoolDownEndEvent event) {
plugin.getRewardHandler().giveReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
"VoteCoolDownEndedReward", new RewardOptions());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteSiteCoolDownEndEvent event) {
plugin.getRewardHandler().giveReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
new RewardOptions().addPlaceholder("sitename", event.getSite().getDisplayName()).addPlaceholder("url",
event.getSite().getVoteURL(false)));
}
public void schedule(VotingPluginUser user, boolean force) {
if (user.getSitesVotedOn() > 0 || force) {
final UUID uuid = UUID.fromString(user.getUUID());
long time = user.getNextTimeAllSitesAvailable();
if (allSiteTasks.containsKey(uuid)) {
allSiteTasks.get(uuid).cancel(false);
allSiteTasks.remove(uuid);
}
if (time > 0) {
user.setCoolDownCheck(true);
ScheduledFuture<?> scheduledFuture = timer.schedule(new Runnable() {
@Override
public void run() {
if (plugin != null && plugin.isEnabled()) {
check(uuid);
}
}
}, time + 2, TimeUnit.SECONDS);
allSiteTasks.put(uuid, scheduledFuture);
} else {
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling cooldown check");
}
}
}
public void schedulePerSite(VotingPluginUser user, boolean force) {
if (user.getSitesVotedOn() > 0 || force) {
final UUID uuid = UUID.fromString(user.getUUID());
@@ -143,97 +225,15 @@ public class CoolDownCheck implements Listener {
}
}
public void schedule(VotingPluginUser user, boolean force) {
if (user.getSitesVotedOn() > 0 || force) {
final UUID uuid = UUID.fromString(user.getUUID());
long time = user.getNextTimeAllSitesAvailable();
if (allSiteTasks.containsKey(uuid)) {
allSiteTasks.get(uuid).cancel(false);
allSiteTasks.remove(uuid);
}
if (time > 0) {
user.setCoolDownCheck(true);
ScheduledFuture<?> scheduledFuture = timer.schedule(new Runnable() {
@Override
public void run() {
if (plugin != null && plugin.isEnabled()) {
check(uuid);
}
}
}, time + 2, TimeUnit.SECONDS);
allSiteTasks.put(uuid, scheduledFuture);
} else {
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling cooldown check");
}
public void vote(VotingPluginUser user, VoteSite site) {
if (cooldownCheckEnabled) {
schedule(user, true);
}
}
public void load() {
plugin.addUserStartup(new UserStartup() {
@Override
public void onStartUp(AdvancedCoreUser advancedcoreUser) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(advancedcoreUser);
user.dontCache();
if (cooldownCheckEnabled) {
check(user);
}
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
checkPerSite(user);
}
}
@Override
public void onStart() {
}
@Override
public void onFinish() {
}
});
}
public void checkAllVoteSite(VoteSite site) {
plugin.getLogger().info("Checking vote cooldown rewards for all players: " + site.getKey());
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
checkPerSite(user);
user.clearTempCache();
user = null;
}
}
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
user.setCoolDownCheckSite(site, Boolean.FALSE);
schedulePerSite(user, true);
}
cols.clear();
cols = null;
plugin.getLogger().info("Finished checking vote cooldown rewards for all players: " + site.getKey());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteCoolDownEndEvent event) {
plugin.getRewardHandler().giveReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
"VoteCoolDownEndedReward", new RewardOptions());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteSiteCoolDownEndEvent event) {
plugin.getRewardHandler().giveReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
new RewardOptions().addPlaceholder("sitename", event.getSite().getDisplayName()).addPlaceholder("url",
event.getSite().getVoteURL(false)));
}
}
@@ -38,54 +38,6 @@ public class ServerData {
}
}
public void setShopConverted(boolean value) {
getData().set("VoteShopConverted", value);
saveData();
}
public boolean isVoteShopConverted() {
return getData().getBoolean("VoteShopConverted");
}
public void updatePlaceholders() {
boolean data = getData().getBoolean("AutoCacheUpdated", false);
if (!data) {
List<String> placeholders = getAutoCachedPlaceholder();
for (int i = 0; i < placeholders.size(); i++) {
placeholders.set(i, placeholders.get(i).toLowerCase());
}
setAutoCachedPlaceholder(placeholders);
getData().set("AutoCacheUpdated", true);
saveData();
}
}
public void addVoteShopPurchase(String ident) {
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
}
public void setVoteShopPurchases(String ident, int amount) {
getData().set("VoteShopPurchases." + ident, amount);
saveData();
}
public int getVoteShopPurchases(String ident) {
return getData().getInt("VoteShopPurchases." + ident);
}
public void setAutoCachedPlaceholder(List<String> placeholders) {
getData().set("AutoCachePlaceholders", placeholders);
saveData();
}
public List<String> getAutoCachedPlaceholder() {
return getData().getStringList("AutoCachePlaceholders");
}
public List<String> getDisabledReminders() {
return getData().getStringList("DisabledReminders");
}
public synchronized void addServiceSite(String site) {
ArrayList<String> l = getServiceSites();
if (!getServiceSites().contains(site)) {
@@ -116,6 +68,34 @@ public class ServerData {
getSignSkullLocation("" + count), getSignData("" + count), getSignPosition("" + count)));
}
public void addTimeVoted(int num, VoteTimeQueue vote) {
getData().set("TimedVoteCache." + num + ".Name", vote.getName());
getData().set("TimedVoteCache." + num + ".Service", vote.getService());
getData().set("TimedVoteCache." + num + ".Time", vote.getTime());
saveData();
}
public void addVoteShopPurchase(String ident) {
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
}
public void clearTimedVoteCache() {
getData().set("TimedVoteCache", null);
saveData();
}
public List<String> getAutoCachedPlaceholder() {
return getData().getStringList("AutoCachePlaceholders");
}
public int getBungeeVotePartyCurrent() {
return getData().getInt("BungeeVotePartyCurrent");
}
public int getBungeeVotePartyRequired() {
return getData().getInt("BungeeVotePartyRequired");
}
/**
* Gets the data.
*
@@ -130,9 +110,13 @@ public class ServerData {
return data;
}
public List<String> getDisabledReminders() {
return getData().getStringList("DisabledReminders");
}
@SuppressWarnings("unchecked")
public ArrayList<String> getServiceSites() {
return (ArrayList<String>) getData().getList("ServiceSites", new ArrayList<String>());
return (ArrayList<String>) getData().getList("ServiceSites", new ArrayList<>());
}
/**
@@ -176,7 +160,7 @@ public class ServerData {
try {
return getData().getConfigurationSection("Signs").getKeys(false);
} catch (Exception ex) {
return new HashSet<String>();
return new HashSet<>();
}
}
@@ -195,10 +179,25 @@ public class ServerData {
getData().getDouble("Signs." + sign + ".Skull.Z"));
}
public Set<String> getTimedVoteCacheKeys() {
if (getData().isConfigurationSection("TimedVoteCache")) {
return getData().getConfigurationSection("TimedVoteCache").getKeys(false);
}
return new HashSet<>();
}
public ConfigurationSection getTimedVoteCacheSection(String num) {
return getData().getConfigurationSection("TimedVoteCache." + num);
}
public int getVotePartyExtraRequired() {
return getData().getInt("VotePartyExtraRequired", 0);
}
public int getVoteShopPurchases(String ident) {
return getData().getInt("VoteShopPurchases." + ident);
}
public boolean isLastVotePartySameDay() {
int num = getData().getInt("LastVoteParty", 0);
if (num == plugin.getTimeChecker().getTime().getDayOfYear()) {
@@ -216,6 +215,10 @@ public class ServerData {
return false;
}
public boolean isVoteShopConverted() {
return getData().getBoolean("VoteShopConverted");
}
/**
* Next sign number.
*
@@ -268,11 +271,40 @@ public class ServerData {
plugin.getServerDataFile().saveData();
}
public void saveDisabledReminders(ArrayList<UUID> disabledReminders) {
ArrayList<String> uuids = new ArrayList<>();
for (UUID uuid : disabledReminders) {
uuids.add(uuid.toString());
}
getData().set("DisabledReminders", uuids);
saveData();
}
public void setAutoCachedPlaceholder(List<String> placeholders) {
getData().set("AutoCachePlaceholders", placeholders);
saveData();
}
public void setBungeeVotePartyCurrent(int current) {
getData().set("BungeeVotePartyCurrent", current);
saveData();
}
public void setBungeeVotePartyRequired(int required) {
getData().set("BungeeVotePartyRequired", required);
saveData();
}
public void setServiceSites(ArrayList<String> list) {
getData().set("ServiceSites", list);
saveData();
}
public void setShopConverted(boolean value) {
getData().set("VoteShopConverted", value);
saveData();
}
public void setSign(String count, Location location, Location skullLocation, String data, int position) {
getData().set("Signs." + count + ".World", location.getWorld().getName());
@@ -312,6 +344,11 @@ public class ServerData {
saveData();
}
public void setVoteShopPurchases(String ident, int amount) {
getData().set("VoteShopPurchases." + ident, amount);
saveData();
}
public void updateLastVoteParty() {
getData().set("LastVoteParty", plugin.getTimeChecker().getTime().getDayOfYear());
saveData();
@@ -323,31 +360,17 @@ public class ServerData {
saveData();
}
public int getBungeeVotePartyCurrent() {
return getData().getInt("BungeeVotePartyCurrent");
}
public int getBungeeVotePartyRequired() {
return getData().getInt("BungeeVotePartyRequired");
}
public void setBungeeVotePartyCurrent(int current) {
getData().set("BungeeVotePartyCurrent", current);
saveData();
}
public void setBungeeVotePartyRequired(int required) {
getData().set("BungeeVotePartyRequired", required);
saveData();
}
public void saveDisabledReminders(ArrayList<UUID> disabledReminders) {
ArrayList<String> uuids = new ArrayList<String>();
for (UUID uuid : disabledReminders) {
uuids.add(uuid.toString());
public void updatePlaceholders() {
boolean data = getData().getBoolean("AutoCacheUpdated", false);
if (!data) {
List<String> placeholders = getAutoCachedPlaceholder();
for (int i = 0; i < placeholders.size(); i++) {
placeholders.set(i, placeholders.get(i).toLowerCase());
}
setAutoCachedPlaceholder(placeholders);
getData().set("AutoCacheUpdated", true);
saveData();
}
getData().set("DisabledReminders", uuids);
saveData();
}
/**
@@ -356,28 +379,4 @@ public class ServerData {
public void updateValues() {
setVersion();
}
public void addTimeVoted(int num, VoteTimeQueue vote) {
getData().set("TimedVoteCache." + num + ".Name", vote.getName());
getData().set("TimedVoteCache." + num + ".Service", vote.getService());
getData().set("TimedVoteCache." + num + ".Time", vote.getTime());
saveData();
}
public Set<String> getTimedVoteCacheKeys() {
if (getData().isConfigurationSection("TimedVoteCache")) {
return getData().getConfigurationSection("TimedVoteCache").getKeys(false);
} else {
return new HashSet<String>();
}
}
public ConfigurationSection getTimedVoteCacheSection(String num) {
return getData().getConfigurationSection("TimedVoteCache." + num);
}
public void clearTimedVoteCache() {
getData().set("TimedVoteCache", null);
saveData();
}
}
@@ -55,7 +55,7 @@ public class PlayerPostVoteEvent extends Event {
@Getter
@Setter
private VoteSite voteSite;
@Getter
@Setter
private long voteTime = 0;
@@ -64,7 +64,8 @@ public class PlayerPostVoteEvent extends Event {
@Setter
private VotingPluginUser votingPluginUser;
public PlayerPostVoteEvent(VoteSite voteSite, VotingPluginUser user, boolean realVote, boolean forceBungee, long voteTime) {
public PlayerPostVoteEvent(VoteSite voteSite, VotingPluginUser user, boolean realVote, boolean forceBungee,
long voteTime) {
super(true);
this.user = user;
this.voteSite = voteSite;
@@ -86,7 +86,7 @@ public class PlayerVoteListener implements Listener {
if (!plugin.getConfigFile().isDisableNoServiceSiteMessage()) {
plugin.getLogger().warning("No voting site with the service site: '" + event.getServiceSite() + "'");
ArrayList<String> services = new ArrayList<String>();
ArrayList<String> services = new ArrayList<>();
for (VoteSite site : plugin.getVoteSites()) {
services.add(site.getServiceSite());
}
@@ -117,13 +117,12 @@ public class PlayerVoteListener implements Listener {
if (!event.isRealVote()) {
plugin.getLogger().info(user.getPlayerName() + " did a not real vote, bypassing WaitUntilVoteDelay");
} else {
if (user.hasPermission("VotingPlugin.BypassWaitUntilVoteDelay")) {
plugin.getLogger()
.info(user.getPlayerName() + " has bypass permission for WaitUntilVoteDelay, bypassing");
} else {
if (!user.hasPermission("VotingPlugin.BypassWaitUntilVoteDelay")) {
plugin.getLogger().info(user.getPlayerName() + " must wait until votedelay is over, ignoring vote");
return;
}
plugin.getLogger()
.info(user.getPlayerName() + " has bypass permission for WaitUntilVoteDelay, bypassing");
}
}
@@ -132,7 +132,7 @@ public class VoteSite {
} else {
String bc = MessageAPI.colorize(plugin.getConfigFile().getFormatBroadCastMsg());
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", playerName);
placeholders.put("nickname",
(user.getPlayer() != null) ? user.getPlayer().getDisplayName() : user.getPlayerName());
@@ -142,7 +142,7 @@ public class VoteSite {
placeholders.put("neededvotes", "" + plugin.getVoteParty().getNeededVotes());
bc = PlaceholderUtils.replacePlaceHolder(bc, placeholders);
bc = PlaceholderUtils.replacePlaceHolders(user.getOfflinePlayer(), bc);
ArrayList<Player> players = new ArrayList<Player>();
ArrayList<Player> players = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
if (!plugin.getVotingPluginUserManager().getVotingPluginUser(p).getDisableBroadcast()) {
players.add(p);
@@ -164,9 +164,8 @@ public class VoteSite {
plugin.getLogger().warning("Invalid display item section in site: " + key);
return new ItemBuilder(Material.STONE, 1).setName("&cInvalid display item for site: " + key)
.setLore("&cInvalid display item for site: " + key);
} else {
return new ItemBuilder(item);
}
return new ItemBuilder(item);
}
public ConfigurationSection getSiteData() {
@@ -180,12 +179,11 @@ public class VoteSite {
public String getVoteURL(boolean json) {
if (!plugin.getConfigFile().isFormatCommandsVoteForceLinks() || !json || MessageAPI.containsJson(voteURL)) {
return voteURL;
} else {
if (!voteURL.startsWith("http")) {
return "[Text=\"" + voteURL + "\",url=\"http://" + voteURL + "\"]";
}
return "[Text=\"" + voteURL + "\",url=\"" + voteURL + "\"]";
}
if (!voteURL.startsWith("http")) {
return "[Text=\"" + voteURL + "\",url=\"http://" + voteURL + "\"]";
}
return "[Text=\"" + voteURL + "\",url=\"" + voteURL + "\"]";
}
public String getVoteURLJsonStrip() {
@@ -44,7 +44,8 @@ public class MVdWPlaceholders {
.getVotingPluginUser(event.getOfflinePlayer());
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders()
&& user.hasPrimaryAccount()) {
user = plugin.getVotingPluginUserManager().getVotingPluginUser(user.getPrimaryAccount());
user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(user.getPrimaryAccount());
}
return place.placeholderRequest(user,
event.getPlaceholder().substring("VotingPlugin_".length()));
@@ -55,7 +56,8 @@ public class MVdWPlaceholders {
}
for (final NonPlayerPlaceHolder<VotingPluginUser> place : plugin.getPlaceholders().getNonPlayerPlaceholders()) {
for (final NonPlayerPlaceHolder<VotingPluginUser> place : plugin.getPlaceholders()
.getNonPlayerPlaceholders()) {
String str = place.getIdentifier();
if (!str.endsWith("_")) {
PlaceholderAPI.registerPlaceholder(VotingPluginMain.plugin, "VotingPlugin_" + str,
@@ -41,35 +41,52 @@ import lombok.Getter;
public class PlaceHolders {
@Getter
private ArrayList<NonPlayerPlaceHolder<VotingPluginUser>> nonPlayerPlaceholders = new ArrayList<NonPlayerPlaceHolder<VotingPluginUser>>();
private ArrayList<NonPlayerPlaceHolder<VotingPluginUser>> nonPlayerPlaceholders = new ArrayList<>();
@Getter
private ArrayList<PlaceHolder<VotingPluginUser>> placeholders = new ArrayList<PlaceHolder<VotingPluginUser>>();
private ArrayList<PlaceHolder<VotingPluginUser>> placeholders = new ArrayList<>();
private VotingPluginMain plugin;
private ArrayList<String> cachedPlaceholders = new ArrayList<>();
private ConcurrentLinkedQueue<String> placeholdersToSetCacheOn = new ConcurrentLinkedQueue<>();
@Getter
private PlaceholderCacheLevel cacheLevel;
public PlaceHolders(VotingPluginMain plugin) {
this.plugin = plugin;
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
}
public void reload() {
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
onUpdate();
if (!cacheLevel.equals(PlaceholderCacheLevel.NONE)) {
for (Player player : Bukkit.getOnlinePlayers()) {
onUpdate(plugin.getVotingPluginUserManager().getVotingPluginUser(player), player.isOnline());
public void checkNonCachedPlaceholders() {
while (!placeholdersToSetCacheOn.isEmpty()) {
String toCache = placeholdersToSetCacheOn.poll().toLowerCase();
if (toCache.startsWith("votingplugin")) {
toCache = toCache.substring("votingplugin_".length());
}
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.matches(toCache)) {
* placeholder.setUseCache(true, toCache); cachedPlaceholders.add(toCache);
* plugin.getServerData().addAutoCachedPlaceholder(toCache);
* plugin.extraDebug("Auto Caching placeholder " + toCache); }
*
* }
*/
for (PlaceHolder<VotingPluginUser> placeholder : placeholders) {
if (placeholder.matches(toCache)) {
placeholder.setUseCache(true, toCache);
cachedPlaceholders.add(toCache);
plugin.getServerData().addAutoCachedPlaceholder(toCache);
plugin.extraDebug("Auto Caching placeholder " + toCache);
}
}
}
}
private ArrayList<String> cachedPlaceholders = new ArrayList<String>();
private ConcurrentLinkedQueue<String> placeholdersToSetCacheOn = new ConcurrentLinkedQueue<String>();
@Getter
private PlaceholderCacheLevel cacheLevel;
public String getPlaceHolder(OfflinePlayer p, String identifier) {
return getPlaceHolder(p, identifier, true);
}
@@ -96,19 +113,25 @@ public class PlaceHolders {
identifier = identifier.replaceAll("custom_", "");
}
if (custom && plugin.getConfigFile().getCustomPlaceholderReturns().contains(identifier)) {
String str = getPlaceholderValue(p, identifier, javascript, true, useCache);
String returnStr = plugin.getConfigFile().getCustomPlaceholderReturns(identifier, str);
if (!returnStr.isEmpty()) {
return returnStr;
}
return str;
} else {
if (!custom || !plugin.getConfigFile().getCustomPlaceholderReturns().contains(identifier)) {
return getPlaceholderValue(p, identifier, javascript, forceProcess, useCache);
}
String str = getPlaceholderValue(p, identifier, javascript, true, useCache);
String returnStr = plugin.getConfigFile().getCustomPlaceholderReturns(identifier, str);
if (!returnStr.isEmpty()) {
return returnStr;
}
return str;
}
public String getPlaceHolder(Player p, String identifier) {
if (plugin.getConfigFile().isUseJavascriptPlaceholders()) {
identifier = PlaceholderUtils.replaceJavascript(p, identifier);
}
return getPlaceHolder(p, identifier, false);
}
public String getPlaceholderValue(OfflinePlayer p, String identifier, boolean javascript, boolean forceProcess,
boolean useCache) {
if (plugin.getConfigFile().isUseJavascriptPlaceholders() && javascript && p != null) {
@@ -161,77 +184,74 @@ public class PlaceHolders {
try {
if (placeholder.matches(identifier)) {
if (placeholder instanceof CalculatingPlaceholder<?>) {
if (useCache) {
CalculatingPlaceholder<VotingPluginUser> cPlaceholder = (CalculatingPlaceholder<VotingPluginUser>) placeholder;
if (placeholder.isUsesCache() && placeholder.isCached(identifier)) {
ConcurrentHashMap<UUID, String> cache = placeholder.getCache().get(identifier);
if (cache.containsKey(p.getUniqueId())) {
if (cPlaceholder.getCacheData().containsKey(user.getJavaUUID())) {
return cPlaceholder.placeholderRequest(user, identifier);
}
return cache.get(p.getUniqueId());
} else if (!forceProcess) {
schedulePlaceholderCheck(user);
return "...";
}
}
if (forceProcess) {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return placeholder.placeholderRequest(user, identifier);
} else {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return ".";
}
} else {
if (!useCache) {
return placeholder.placeholderRequest(user, identifier);
}
CalculatingPlaceholder<VotingPluginUser> cPlaceholder = (CalculatingPlaceholder<VotingPluginUser>) placeholder;
if (placeholder.isUsesCache() && placeholder.isCached(identifier)) {
ConcurrentHashMap<UUID, String> cache = placeholder.getCache().get(identifier);
if (cache.containsKey(p.getUniqueId())) {
if (cPlaceholder.getCacheData().containsKey(user.getJavaUUID())) {
return cPlaceholder.placeholderRequest(user, identifier);
}
return cache.get(p.getUniqueId());
} else if (!forceProcess) {
schedulePlaceholderCheck(user);
return "...";
}
}
if (forceProcess) {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return placeholder.placeholderRequest(user, identifier);
} else {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return ".";
}
}
if (!useCache) {
return placeholder.placeholderRequest(user, identifier);
}
if (placeholder.isUsesCache() && placeholder.isCached(identifier)) {
ConcurrentHashMap<UUID, String> cache = placeholder.getCache().get(identifier);
if (cache.containsKey(p.getUniqueId())) {
return cache.get(p.getUniqueId());
} else if (!forceProcess) {
schedulePlaceholderCheck(user);
return "...";
}
}
if (forceProcess) {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return placeholder.placeholderRequest(user, identifier);
} else {
if (useCache) {
if (placeholder.isUsesCache() && placeholder.isCached(identifier)) {
ConcurrentHashMap<UUID, String> cache = placeholder.getCache().get(identifier);
if (cache.containsKey(p.getUniqueId())) {
return cache.get(p.getUniqueId());
} else if (!forceProcess) {
schedulePlaceholderCheck(user);
return "...";
}
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
if (forceProcess) {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return placeholder.placeholderRequest(user, identifier);
} else {
if (getCacheLevel().shouldCache()) {
if (!placeholdersToSetCacheOn.contains(identifier)
&& !cachedPlaceholders.contains(identifier)) {
placeholdersToSetCacheOn.add(identifier);
schedulePlaceholderCheck(user);
}
}
return ".";
}
} else {
return placeholder.placeholderRequest(user, identifier);
}
return ".";
}
}
} catch (Exception e) {
@@ -243,13 +263,6 @@ public class PlaceHolders {
return "Not a valid placeholder";
}
public String getPlaceHolder(Player p, String identifier) {
if (plugin.getConfigFile().isUseJavascriptPlaceholders()) {
identifier = PlaceholderUtils.replaceJavascript(p, identifier);
}
return getPlaceHolder(p, identifier, false);
}
public void load() {
placeholders.clear();
nonPlayerPlaceholders.clear();
@@ -499,7 +512,7 @@ public class PlaceHolders {
return plugin.getConfigFile().getFormatCommandsVoteNextInfoCanVote();
}
long smallest = -1;
HashMap<Long, VoteSite> times = new HashMap<Long, VoteSite>();
HashMap<Long, VoteSite> times = new HashMap<>();
for (VoteSite site : plugin.getVoteSitesEnabled()) {
long t = user.voteNextDurationTime(site);
if (smallest == -1) {
@@ -531,6 +544,12 @@ public class PlaceHolders {
for (final VoteSite voteSite : plugin.getVoteSitesEnabled()) {
placeholders.add(new CalculatingPlaceholder<VotingPluginUser>("Next_" + voteSite.getKey()) {
@Override
public String placeholderDataRequest(VotingPluginUser user, String identifier) {
long time = user.getTime(voteSite);
return "" + time;
}
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
if (getCacheData().containsKey(user.getJavaUUID())) {
@@ -542,12 +561,6 @@ public class PlaceHolders {
}
return user.voteCommandNextInfo(voteSite);
}
@Override
public String placeholderDataRequest(VotingPluginUser user, String identifier) {
long time = user.getTime(voteSite);
return "" + time;
}
}.withDescription("How long until user can vote on " + voteSite.getKey()).updateDataKey("LastVotes"));
placeholders.add(new PlaceHolder<VotingPluginUser>("Last_" + voteSite.getKey()) {
@@ -1064,7 +1077,7 @@ public class PlaceHolders {
}
}.withDescription("Time until plugin time month changes"));
Set<String> placeholdersSet = new HashSet<String>();
Set<String> placeholdersSet = new HashSet<>();
placeholdersSet.addAll(plugin.getConfigFile().getCachedPlaceholders());
if (getCacheLevel().equals(PlaceholderCacheLevel.AUTO)) {
placeholdersSet.addAll(plugin.getServerData().getAutoCachedPlaceholder());
@@ -1142,16 +1155,6 @@ public class PlaceHolders {
});
}
public void onVotePartyUpdate() {
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.isUsesCache()) { if
* (placeholder.getIdentifier().startsWith("VoteParty")) { for (String ident :
* placeholder.getCache().keySet()) { placeholder.getCache().put(ident,
* placeholder.placeholderRequest(ident)); } } } }
*/
}
public void onBungeeVotePartyUpdate() {
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
@@ -1172,6 +1175,22 @@ public class PlaceHolders {
}
}
public void onUpdate() {
checkNonCachedPlaceholders();
for (Player p : Bukkit.getOnlinePlayers()) {
onUpdate(plugin.getVotingPluginUserManager().getVotingPluginUser(p), true);
}
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.isUsesCache()) { for (String ident :
* placeholder.getCache().keySet()) { if (ident != null) { String str =
* placeholder.placeholderRequest(ident); if (str != null) {
* placeholder.getCache().put(ident, str); } } else {
* plugin.debug("ident null: " + placeholder.getIdentifier()); } } } }
*/
}
public void onUpdate(VotingPluginUser user, boolean login) {
for (PlaceHolder<VotingPluginUser> placeholder : placeholders) {
if (placeholder.isUsesCache()) {
@@ -1201,30 +1220,23 @@ public class PlaceHolders {
}
}
public void checkNonCachedPlaceholders() {
while (!placeholdersToSetCacheOn.isEmpty()) {
String toCache = placeholdersToSetCacheOn.poll().toLowerCase();
if (toCache.startsWith("votingplugin")) {
toCache = toCache.substring("votingplugin_".length());
}
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.matches(toCache)) {
* placeholder.setUseCache(true, toCache); cachedPlaceholders.add(toCache);
* plugin.getServerData().addAutoCachedPlaceholder(toCache);
* plugin.extraDebug("Auto Caching placeholder " + toCache); }
*
* }
*/
for (PlaceHolder<VotingPluginUser> placeholder : placeholders) {
if (placeholder.matches(toCache)) {
placeholder.setUseCache(true, toCache);
cachedPlaceholders.add(toCache);
plugin.getServerData().addAutoCachedPlaceholder(toCache);
plugin.extraDebug("Auto Caching placeholder " + toCache);
}
}
public void onVotePartyUpdate() {
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.isUsesCache()) { if
* (placeholder.getIdentifier().startsWith("VoteParty")) { for (String ident :
* placeholder.getCache().keySet()) { placeholder.getCache().put(ident,
* placeholder.placeholderRequest(ident)); } } } }
*/
}
public void reload() {
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
onUpdate();
if (!cacheLevel.equals(PlaceholderCacheLevel.NONE)) {
for (Player player : Bukkit.getOnlinePlayers()) {
onUpdate(plugin.getVotingPluginUserManager().getVotingPluginUser(player), player.isOnline());
}
}
}
@@ -1238,20 +1250,4 @@ public class PlaceHolders {
}
});
}
public void onUpdate() {
checkNonCachedPlaceholders();
for (Player p : Bukkit.getOnlinePlayers()) {
onUpdate(plugin.getVotingPluginUserManager().getVotingPluginUser(p), true);
}
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.isUsesCache()) { for (String ident :
* placeholder.getCache().keySet()) { if (ident != null) { String str =
* placeholder.placeholderRequest(ident); if (str != null) {
* placeholder.getCache().put(ident, str); } } else {
* plugin.debug("ident null: " + placeholder.getIdentifier()); } } } }
*/
}
}
@@ -13,10 +13,7 @@ public enum PlaceholderCacheLevel {
}
public boolean onlineOnly() {
if (this == AUTOALL) {
return false;
}
if (this == SPECIFICALL) {
if ((this == AUTOALL) || (this == SPECIFICALL)) {
return false;
}
return true;
@@ -29,13 +29,13 @@ public class VotingPluginExpansion extends PlaceholderExpansion {
return "1.6";
}
@Override
public boolean persist() {
return true;
}
@Override
public String onRequest(OfflinePlayer p, String indendifier) {
return plugin.getPlaceholders().getPlaceHolder(p, indendifier);
}
@Override
public boolean persist() {
return true;
}
}
@@ -15,9 +15,35 @@ import lombok.Getter;
public class ServiceSiteHandler {
@Getter
private HashMap<String, String> serviceSites = new HashMap<String, String>();
private HashMap<String, String> serviceSites = new HashMap<>();
private VotingPluginMain plugin;
public ServiceSiteHandler(VotingPluginMain plugin) {
this.plugin = plugin;
loadFromGithub();
for (Entry<String, String> entry : serviceSites.entrySet()) {
plugin.extraDebug(entry.getKey() + " - " + entry.getValue());
}
}
public boolean contains(String service) {
for (Entry<String, String> entry : serviceSites.entrySet()) {
if (entry.getKey().equalsIgnoreCase(service)) {
return true;
}
}
return false;
}
public void loadFromGithub() {
try {
readFromWeb("https://github.com/BenCodez/VotingPlugin/wiki/Minecraft-Server-Lists");
} catch (IOException e) {
e.printStackTrace();
}
}
public String match(String service) {
for (Entry<String, String> entry : serviceSites.entrySet()) {
if (entry.getKey().equalsIgnoreCase(service)) {
@@ -36,15 +62,6 @@ public class ServiceSiteHandler {
return service;
}
public ServiceSiteHandler(VotingPluginMain plugin) {
this.plugin = plugin;
loadFromGithub();
for (Entry<String, String> entry : serviceSites.entrySet()) {
plugin.extraDebug(entry.getKey() + " - " + entry.getValue());
}
}
public void readFromWeb(String webURL) throws IOException {
serviceSites.clear();
URL url = new URL(webURL);
@@ -77,21 +94,4 @@ public class ServiceSiteHandler {
}
}
public void loadFromGithub() {
try {
readFromWeb("https://github.com/BenCodez/VotingPlugin/wiki/Minecraft-Server-Lists");
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean contains(String service) {
for (Entry<String, String> entry : serviceSites.entrySet()) {
if (entry.getKey().equalsIgnoreCase(service)) {
return true;
}
}
return false;
}
}
@@ -70,7 +70,7 @@ public class SignHandler {
setData(data);
this.position = position;
setValid(true);
lines = new ArrayList<String>();
lines = new ArrayList<>();
checkValidSign();
playerName = "";
}
@@ -174,7 +174,7 @@ public class SignHandler {
* Update lines.
*/
public void updateLines() {
lines = new ArrayList<String>();
lines = new ArrayList<>();
checkValidSign();
if (position != 0) {
String line1 = plugin.getConfigFile().getFormatSignTopVoterSignLine1();
@@ -22,7 +22,7 @@ public class Signs {
public Signs(VotingPluginMain plugin) {
this.plugin = plugin;
this.signs = new ArrayList<SignHandler>();
this.signs = new ArrayList<>();
}
/**
@@ -45,7 +45,7 @@ public class Signs {
* Load signs.
*/
public void loadSigns() {
setSigns(new ArrayList<SignHandler>());
setSigns(new ArrayList<>());
for (String sign : plugin.getServerData().getSigns()) {
// plugin.getLogger().info("Loading sign " + sign);
getSigns().add(new SignHandler(plugin, sign, plugin.getServerData().getSignLocation(sign),
@@ -29,6 +29,23 @@ public class SpecialRewards {
this.plugin = plugin;
}
public void bungeeAllSitesCheck(VotingPluginUser user, int numberOfVotes, int num) {
if (plugin.getBungeeSettings().isGiveExtraAllSitesRewards()) {
int numberOfSites = plugin.getVoteSitesEnabled().size();
if (numberOfVotes >= numberOfSites * 2) {
if (num > numberOfSites) {
if (num % numberOfSites == 0) {
// should give extra allsites?
if (user.checkAllVotes()) {
plugin.debug("Giving extra allsites reward from bungee");
giveAllSitesRewards(user, user.isOnline(), true);
}
}
}
}
}
}
public boolean checkAllSites(VotingPluginUser user, boolean forceBungee) {
boolean checkAllVotes = user.checkAllVotes();
if (checkAllVotes
@@ -49,23 +66,6 @@ public class SpecialRewards {
return checkAllVotes;
}
public void bungeeAllSitesCheck(VotingPluginUser user, int numberOfVotes, int num) {
if (plugin.getBungeeSettings().isGiveExtraAllSitesRewards()) {
int numberOfSites = plugin.getVoteSitesEnabled().size();
if (numberOfVotes >= numberOfSites * 2) {
if (num > numberOfSites) {
if (num % numberOfSites == 0) {
// should give extra allsites?
if (user.checkAllVotes()) {
plugin.debug("Giving extra allsites reward from bungee");
giveAllSitesRewards(user, user.isOnline(), true);
}
}
}
}
}
}
public boolean checkAlmostAllSites(VotingPluginUser user, boolean forceBungee) {
boolean checkAllVotes = user.checkAlmostAllVotes();
plugin.extraDebug("Checking almostallsites reward: " + checkAllVotes + "/" + user.getSitesNotVotedOn());
@@ -206,7 +206,7 @@ public class SpecialRewards {
}
}
if (plugin.getConfigFile().isPreventRepeatMilestones()) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<Integer> nums = new ArrayList<>();
for (String str : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
try {
@@ -13,11 +13,52 @@ import com.bencodez.votingplugin.user.VotingPluginUser;
public class VoteTester {
private VotingPluginMain plugin;
public VoteTester(VotingPluginMain plugin) {
this.plugin = plugin;
}
private VotingPluginMain plugin;
public void generatePlayers(int numberOfPlayers) {
if (plugin.getOptions().getDebug().isDebug()) {
int num = 1;
String salt = getSaltString();
Random random = new Random();
for (int i = 0; i < numberOfPlayers; i++) {
UUID uuid = UUID.randomUUID();
if (!plugin.getUserManager().userExist(uuid)) {
String playerName = salt + num;
if (!plugin.getUserManager().userExist(playerName)) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid,
playerName);
user.dontCache();
user.setPoints(random.nextInt(100));
for (TopVoter top : TopVoter.values()) {
user.setTotal(top, random.nextInt(1000));
}
user.setMilestoneCount(random.nextInt(100));
user.setPlayerName(playerName);
user.updateName(true);
num++;
plugin.debug("Generated user " + uuid.toString() + "/" + playerName);
}
}
}
}
}
private String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 12) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
public void testRewards(int amount, String name, String rewardName) {
plugin.getVoteTimer().submit(new Runnable() {
@@ -25,7 +66,7 @@ public class VoteTester {
@Override
public void run() {
long time1 = System.currentTimeMillis();
ArrayList<Long> timesPerReward = new ArrayList<Long>();
ArrayList<Long> timesPerReward = new ArrayList<>();
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(name);
Reward reward = plugin.getRewardHandler().getReward(rewardName);
int rewardsGiven = 0;
@@ -57,44 +98,24 @@ public class VoteTester {
}
private String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 12) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
public void testSpam(int amount, String name, String site) {
for (int i = 0; i < amount; i++) {
plugin.getBukkitScheduler().runTaskAsynchronously(plugin, new Runnable() {
}
@Override
public void run() {
plugin.getVoteTimer().submit(new Runnable() {
public void generatePlayers(int numberOfPlayers) {
if (plugin.getOptions().getDebug().isDebug()) {
int num = 1;
String salt = getSaltString();
Random random = new Random();
for (int i = 0; i < numberOfPlayers; i++) {
UUID uuid = UUID.randomUUID();
if (!plugin.getUserManager().userExist(uuid)) {
String playerName = salt + num;
if (!plugin.getUserManager().userExist(playerName)) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid,
playerName);
user.dontCache();
user.setPoints(random.nextInt(100));
for (TopVoter top : TopVoter.values()) {
user.setTotal(top, random.nextInt(1000));
@Override
public void run() {
PlayerVoteEvent voteEvent = new PlayerVoteEvent(plugin.getVoteSite(site, false), name,
plugin.getVoteSiteServiceSite(site), false);
plugin.getServer().getPluginManager().callEvent(voteEvent);
}
user.setMilestoneCount(random.nextInt(100));
user.setPlayerName(playerName);
user.updateName(true);
num++;
plugin.debug("Generated user " + uuid.toString() + "/" + playerName);
}
});
}
}
});
}
}
@@ -104,7 +125,7 @@ public class VoteTester {
@Override
public void run() {
long time1 = System.currentTimeMillis();
ArrayList<Long> timesPerVote = new ArrayList<Long>();
ArrayList<Long> timesPerVote = new ArrayList<>();
for (int i = 0; i < amount; i++) {
long start1 = System.currentTimeMillis();
PlayerVoteEvent voteEvent = new PlayerVoteEvent(plugin.getVoteSite(site, false), name,
@@ -131,25 +152,4 @@ public class VoteTester {
}
public void testSpam(int amount, String name, String site) {
for (int i = 0; i < amount; i++) {
plugin.getBukkitScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
plugin.getVoteTimer().submit(new Runnable() {
@Override
public void run() {
PlayerVoteEvent voteEvent = new PlayerVoteEvent(plugin.getVoteSite(site, false), name,
plugin.getVoteSiteServiceSite(site), false);
plugin.getServer().getPluginManager().callEvent(voteEvent);
}
});
}
});
}
}
}
@@ -19,7 +19,7 @@ import lombok.Getter;
public class TimeQueueHandler implements Listener {
@Getter
private Queue<VoteTimeQueue> timeChangeQueue = new ConcurrentLinkedQueue<VoteTimeQueue>();
private Queue<VoteTimeQueue> timeChangeQueue = new ConcurrentLinkedQueue<>();
private VotingPluginMain plugin;
@@ -28,38 +28,11 @@ public class TimeQueueHandler implements Listener {
load();
}
public void processQueue() {
while (getTimeChangeQueue().size() > 0) {
VoteTimeQueue vote = getTimeChangeQueue().remove();
PlayerVoteEvent voteEvent = new PlayerVoteEvent(
plugin.getVoteSite(plugin.getVoteSiteName(true, vote.getService()), true), vote.getName(),
vote.getService(), true);
voteEvent.setTime(voteEvent.getTime());
plugin.getServer().getPluginManager().callEvent(voteEvent);
if (voteEvent.isCancelled()) {
plugin.debug("Vote cancelled");
return;
}
}
}
public void addVote(String voteUsername, String voteSiteName) {
timeChangeQueue.add(new VoteTimeQueue(voteUsername, voteSiteName,
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void postTimeChange(DateChangedEvent event) {
plugin.getVoteTimer().schedule(new Runnable() {
@Override
public void run() {
processQueue();
}
}, 5, TimeUnit.SECONDS);
}
public void load() {
for (String str : plugin.getServerData().getTimedVoteCacheKeys()) {
ConfigurationSection data = plugin.getServerData().getTimedVoteCacheSection(str);
@@ -76,6 +49,33 @@ public class TimeQueueHandler implements Listener {
}, 120, TimeUnit.SECONDS);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void postTimeChange(DateChangedEvent event) {
plugin.getVoteTimer().schedule(new Runnable() {
@Override
public void run() {
processQueue();
}
}, 5, TimeUnit.SECONDS);
}
public void processQueue() {
while (getTimeChangeQueue().size() > 0) {
VoteTimeQueue vote = getTimeChangeQueue().remove();
PlayerVoteEvent voteEvent = new PlayerVoteEvent(
plugin.getVoteSite(plugin.getVoteSiteName(true, vote.getService()), true), vote.getName(),
vote.getService(), true);
voteEvent.setTime(voteEvent.getTime());
plugin.getServer().getPluginManager().callEvent(voteEvent);
if (voteEvent.isCancelled()) {
plugin.debug("Vote cancelled");
return;
}
}
}
public void save() {
if (!timeChangeQueue.isEmpty()) {
int num = 0;
@@ -27,10 +27,26 @@ public enum TopVoter {
return AllTime;
}
public static TopVoter of(TimeType type) {
switch (type) {
case DAY:
return Daily;
case MONTH:
return Monthly;
case WEEK:
return Weekly;
default:
return null;
}
}
public static TopVoter[] valuesMinusAllTime() {
return new TopVoter[] { TopVoter.Daily, TopVoter.Weekly, TopVoter.Monthly };
}
@Getter
private ArrayList<TopVoter> switchItems = new ArrayList<>();
public String getColumnName() {
switch (this) {
case AllTime:
@@ -63,15 +79,14 @@ public enum TopVoter {
}
}
@Getter
private ArrayList<TopVoter> switchItems = new ArrayList<TopVoter>();
public String getName() {
if (this.equals(TopVoter.Monthly)) {
return VotingPluginMain.plugin.getConfigFile().getFormatTopVoterMonthly();
} else if (this.equals(TopVoter.Weekly)) {
}
if (this.equals(TopVoter.Weekly)) {
return VotingPluginMain.plugin.getConfigFile().getFormatTopVoterWeekly();
} else if (this.equals(TopVoter.Daily)) {
}
if (this.equals(TopVoter.Daily)) {
return VotingPluginMain.plugin.getConfigFile().getFormatTopVoterDaily();
} else {
return VotingPluginMain.plugin.getConfigFile().getFormatTopVoterAllTime();
@@ -79,7 +94,7 @@ public enum TopVoter {
}
public TopVoter next() {
ArrayList<TopVoter> list = new ArrayList<TopVoter>();
ArrayList<TopVoter> list = new ArrayList<>();
if (switchItems != null && !switchItems.isEmpty()) {
list.addAll(switchItems);
} else {
@@ -110,7 +125,7 @@ public enum TopVoter {
}
public TopVoter prev() {
ArrayList<TopVoter> list = new ArrayList<TopVoter>();
ArrayList<TopVoter> list = new ArrayList<>();
if (switchItems != null && !switchItems.isEmpty()) {
list.addAll(switchItems);
} else {
@@ -138,17 +153,4 @@ public enum TopVoter {
}
return TopVoter.AllTime;
}
public static TopVoter of(TimeType type) {
switch (type) {
case DAY:
return Daily;
case MONTH:
return Monthly;
case WEEK:
return Weekly;
default:
return null;
}
}
}
@@ -44,10 +44,84 @@ public class TopVoterHandler implements Listener {
this.plugin = plugin;
}
public boolean bungeeHandleResets() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
if (plugin.getBungeeSettings().isGloblalDataEnabled()) {
return true;
}
}
return false;
}
public String getGottenMilestonesPath() {
if (plugin.getBungeeSettings().isPerServerMilestones()) {
return plugin.getBungeeSettings().getServerNameStorage() + "_" + "GottenMilestones";
}
return "GottenMileStones";
}
public LinkedHashMap<TopVoterPlayer, Integer> getMonthlyTopVotersAtTime(LocalDateTime atTime) {
// int limitSize = plugin.getConfigFile().getMaxiumNumberOfTopVotersToLoad();
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
LinkedHashMap<TopVoterPlayer, Integer> topVoter = new LinkedHashMap<>();
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
int total = user.getTotal(TopVoter.Monthly, atTime);
if (total > 0) {
topVoter.put(user.getTopVoterPlayer(), total);
}
}
}
}
return sortByValues(topVoter, false);
}
public ArrayList<String> getTopVoterBlackList() {
return plugin.getConfigFile().getBlackList();
}
public LinkedHashMap<TopVoterPlayer, Integer> getTopVotersOfMonth(YearMonth month,
HashMap<UUID, ArrayList<Column>> cols) {
LinkedHashMap<TopVoterPlayer, Integer> totals = new LinkedHashMap<>();
LocalDateTime atTime = month.atDay(15).atTime(0, 0);
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuid),
false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
int total = 0;
total = user.getTotal(TopVoter.Monthly, atTime);
if (total > 0) {
totals.put(user.getTopVoterPlayer(), total);
}
user.clearTempCache();
}
}
return sortByValues(totals, false);
}
/**
* Top voters weekly.
*
@@ -55,7 +129,7 @@ public class TopVoterHandler implements Listener {
*/
public String[] getTopVotersWeekly() {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
ArrayList<TopVoterPlayer> users = plugin.convertSet(plugin.getTopVoter(TopVoter.Weekly).keySet());
for (int i = 0; i < users.size(); i++) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine().replace("%num%", "" + (i + 1))
@@ -68,7 +142,7 @@ public class TopVoterHandler implements Listener {
}
private HashMap<Integer, String> handlePlaces(Set<String> places) {
HashMap<Integer, String> place = new HashMap<Integer, String>();
HashMap<Integer, String> place = new HashMap<>();
for (String p : places) {
String[] data = p.split("-");
try {
@@ -87,6 +161,45 @@ public class TopVoterHandler implements Listener {
return place;
}
public void loadLastMonth() {
if (plugin.getGui().isLastMonthGUI()) {
plugin.getLastMonthTopVoter().clear();
LinkedHashMap<TopVoterPlayer, Integer> totals = new LinkedHashMap<>();
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
LocalDateTime lastMonthTime = plugin.getTimeChecker().getTime().minusMonths(1);
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
int total = 0;
if (plugin.getConfigFile().isUseMonthDateTotalsAsPrimaryTotal()) {
total = user.getTotal(TopVoter.Monthly, lastMonthTime);
} else {
total = user.getLastMonthTotal();
}
if (total > 0) {
totals.put(user.getTopVoterPlayer(), total);
}
user.clearTempCache();
}
}
}
cols.clear();
cols = null;
plugin.getLastMonthTopVoter().putAll(sortByValues(totals, false));
plugin.debug("Loaded last month top voters");
}
}
public void loadPreviousMonthTopVoters() {
if (plugin.getConfigFile().isStoreMonthTotalsWithDate()) {
@@ -100,10 +213,9 @@ public class TopVoterHandler implements Listener {
String month = data[1];
if (MessageAPI.isInt(year)) {
YearMonth yearMonth = YearMonth.of(Integer.parseInt(year), Month.valueOf(month));
if (yearMonth.atDay(now.getDayOfMonth()).atTime(23, 59).isBefore(now)) {
if (yearMonth.isBefore(YearMonth.of(now.getYear(), now.getMonth()))) {
plugin.debug("Loading previous month top voters of " + yearMonth.toString());
plugin.getPreviousMonthsTopVoters().put(yearMonth,
new LinkedHashMap<TopVoterPlayer, Integer>());
plugin.getPreviousMonthsTopVoters().put(yearMonth, new LinkedHashMap<>());
}
}
}
@@ -155,71 +267,6 @@ public class TopVoterHandler implements Listener {
}
}
public LinkedHashMap<TopVoterPlayer, Integer> getTopVotersOfMonth(YearMonth month,
HashMap<UUID, ArrayList<Column>> cols) {
LinkedHashMap<TopVoterPlayer, Integer> totals = new LinkedHashMap<TopVoterPlayer, Integer>();
LocalDateTime atTime = month.atDay(15).atTime(0, 0);
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuid),
false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
int total = 0;
total = user.getTotal(TopVoter.Monthly, atTime);
if (total > 0) {
totals.put(user.getTopVoterPlayer(), total);
}
user.clearTempCache();
}
}
return sortByValues(totals, false);
}
public void loadLastMonth() {
if (plugin.getGui().isLastMonthGUI()) {
plugin.getLastMonthTopVoter().clear();
LinkedHashMap<TopVoterPlayer, Integer> totals = new LinkedHashMap<TopVoterPlayer, Integer>();
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
LocalDateTime lastMonthTime = plugin.getTimeChecker().getTime().minusMonths(1);
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
int total = 0;
if (plugin.getConfigFile().isUseMonthDateTotalsAsPrimaryTotal()) {
total = user.getTotal(TopVoter.Monthly, lastMonthTime);
} else {
total = user.getLastMonthTotal();
}
if (total > 0) {
totals.put(user.getTopVoterPlayer(), total);
}
user.clearTempCache();
}
}
}
cols.clear();
cols = null;
plugin.getLastMonthTopVoter().putAll(sortByValues(totals, false));
plugin.debug("Loaded last month top voters");
}
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onDateChanged(DateChangedEvent event) {
plugin.setUpdate(true);
@@ -575,43 +622,26 @@ public class TopVoterHandler implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public void resetMilestoneCount() {
plugin.getUserManager().removeAllKeyValues("MilestoneCount", DataType.INTEGER);
}
public void resetGottenMilestones() {
plugin.getUserManager().removeAllKeyValues(getGottenMilestonesPath(), DataType.STRING);
}
public String getGottenMilestonesPath() {
if (plugin.getBungeeSettings().isPerServerMilestones()) {
return plugin.getBungeeSettings().getServerNameStorage() + "_" + "GottenMilestones";
}
return "GottenMileStones";
}
public void resetVoteShopLimit(String shopIdent) {
plugin.getUserManager().removeAllKeyValues("VoteShopLimit" + shopIdent, DataType.INTEGER);
public void resetMilestoneCount() {
plugin.getUserManager().removeAllKeyValues("MilestoneCount", DataType.INTEGER);
}
public void resetTotals(TopVoter topVoter) {
plugin.getUserManager().removeAllKeyValues(topVoter.getColumnName(), DataType.INTEGER);
}
public boolean bungeeHandleResets() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
if (plugin.getBungeeSettings().isGloblalDataEnabled()) {
return true;
}
}
return false;
public void resetVoteShopLimit(String shopIdent) {
plugin.getUserManager().removeAllKeyValues("VoteShopLimit" + shopIdent, DataType.INTEGER);
}
public LinkedHashMap<TopVoterPlayer, Integer> sortByValues(LinkedHashMap<TopVoterPlayer, Integer> map,
final boolean order) {
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<Entry<TopVoterPlayer, Integer>>(map.entrySet());
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(map.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<TopVoterPlayer, Integer>>() {
@@ -623,19 +653,17 @@ public class TopVoterHandler implements Listener {
return result;
}
return o2.getKey().getLastVoteTime().compareTo(o1.getKey().getLastVoteTime());
} else {
int result = (o2.getValue()).compareTo(o1.getValue());
if (result != 0) {
return result;
}
return o1.getKey().getLastVoteTime().compareTo(o2.getKey().getLastVoteTime());
}
int result = (o2.getValue()).compareTo(o1.getValue());
if (result != 0) {
return result;
}
return o1.getKey().getLastVoteTime().compareTo(o2.getKey().getLastVoteTime());
}
});
// Maintaining insertion order with the help of LinkedList
LinkedHashMap<TopVoterPlayer, Integer> sortedMap = new LinkedHashMap<TopVoterPlayer, Integer>();
LinkedHashMap<TopVoterPlayer, Integer> sortedMap = new LinkedHashMap<>();
for (Entry<TopVoterPlayer, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
@@ -662,7 +690,7 @@ public class TopVoterHandler implements Listener {
file.setup();
file.header("Saving top voters for " + top.toString() + ", file also contains other top voter info as backup");
for (TopVoter cTop : TopVoter.values()) {
ArrayList<String> topVoters = new ArrayList<String>();
ArrayList<String> topVoters = new ArrayList<>();
int cTotal = 0;
try {
ArrayList<Integer> nums = plugin.getUserManager().getNumbersInColumn(cTop.getColumnName());
@@ -694,8 +722,8 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVoterAllTime(int page) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> topVoters = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
@@ -733,8 +761,8 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVoterDaily(int page) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> topVoters = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
@@ -772,8 +800,8 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVoterMonthly(int page) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> topVoters = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
@@ -809,9 +837,8 @@ public class TopVoterHandler implements Listener {
* @return the string[]
*/
public String[] topVotersAllTime() {
ArrayList<String> msg = new ArrayList<String>();
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<Entry<TopVoterPlayer, Integer>>(
plugin.getTopVoter(TopVoter.AllTime).entrySet());
ArrayList<String> msg = new ArrayList<>();
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoter(TopVoter.AllTime).entrySet());
int i = 0;
for (Entry<TopVoterPlayer, Integer> entry : list) {
String line = "%num%: %player%, %votes%";
@@ -838,7 +865,7 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVotersDaily() {
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
ArrayList<TopVoterPlayer> users = plugin.convertSet(plugin.getTopVoter(TopVoter.Daily).keySet());
for (int i = 0; i < users.size(); i++) {
String line = "%num%: %player%, %votes%";
@@ -862,9 +889,8 @@ public class TopVoterHandler implements Listener {
* @return the string[]
*/
public String[] topVotersMonthly() {
ArrayList<String> msg = new ArrayList<String>();
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<Entry<TopVoterPlayer, Integer>>(
plugin.getTopVoter(TopVoter.Monthly).entrySet());
ArrayList<String> msg = new ArrayList<>();
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoter(TopVoter.Monthly).entrySet());
int i = 0;
for (Entry<TopVoterPlayer, Integer> entry : list) {
String line = "%num%: %player%, %votes%";
@@ -892,8 +918,8 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVoterWeekly(int page) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> topVoters = new ArrayList<String>();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
@@ -923,37 +949,6 @@ public class TopVoterHandler implements Listener {
return ArrayUtils.convert(msg);
}
public LinkedHashMap<TopVoterPlayer, Integer> getMonthlyTopVotersAtTime(LocalDateTime atTime) {
// int limitSize = plugin.getConfigFile().getMaxiumNumberOfTopVotersToLoad();
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
LinkedHashMap<TopVoterPlayer, Integer> topVoter = new LinkedHashMap<TopVoterPlayer, Integer>();
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
int total = user.getTotal(TopVoter.Monthly, atTime);
if (total > 0) {
topVoter.put(user.getTopVoterPlayer(), total);
}
}
}
}
return sortByValues(topVoter, false);
}
public synchronized void updateTopVoters(
LinkedHashMap<TopVoter, LinkedHashMap<TopVoterPlayer, Integer>> tempTopVoter) {
@@ -962,7 +957,7 @@ public class TopVoterHandler implements Listener {
LinkedHashMap<TopVoterPlayer, Integer> map = entry.getValue();
map = sortByValues(map, false);
if (limitSize > 0) {
ArrayList<TopVoterPlayer> listKeys = new ArrayList<TopVoterPlayer>(map.keySet());
ArrayList<TopVoterPlayer> listKeys = new ArrayList<>(map.keySet());
if (listKeys.size() > limitSize) {
for (int i = listKeys.size() - 1; i >= 0 && i >= limitSize; i--) {
map.remove(listKeys.get(i));
@@ -74,6 +74,24 @@ public class UserManager {
manager.addKey(new UserDataKeyInt(getGottenAlmostAllSitesDayPath()));
}
public ArrayList<String> getAllUUIDs() {
return plugin.getUserManager().getAllUUIDs();
}
public String getCoolDownCheckPath() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
return "CoolDownCheck_" + plugin.getBungeeSettings().getServerNameStorage();
}
return "CoolDownCheck";
}
public String getCoolDownCheckSitePath() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
return "CoolDownCheck_" + plugin.getBungeeSettings().getServerNameStorage() + "_Sites";
}
return "CoolDownCheck" + "_Sites";
}
public String getGottenAllSitesDayPath() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
return "AllSitesLast_" + plugin.getBungeeSettings().getServerNameStorage();
@@ -88,22 +106,6 @@ public class UserManager {
return "AlmostAllSitesLast";
}
public String getCoolDownCheckSitePath() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
return "CoolDownCheck_" + plugin.getBungeeSettings().getServerNameStorage() + "_Sites";
} else {
return "CoolDownCheck" + "_Sites";
}
}
public String getCoolDownCheckPath() {
if (plugin.getBungeeSettings().isUseBungeecoord()) {
return "CoolDownCheck_" + plugin.getBungeeSettings().getServerNameStorage();
} else {
return "CoolDownCheck";
}
}
public String getMonthTotalsWithDatePath() {
LocalDateTime cTime = plugin.getTimeChecker().getTime();
return getMonthTotalsWithDatePath(cTime);
@@ -113,19 +115,10 @@ public class UserManager {
return "MonthTotal-" + cTime.getMonth().toString() + "-" + cTime.getYear();
}
public ArrayList<String> getAllUUIDs() {
return plugin.getUserManager().getAllUUIDs();
}
public VotingPluginUser getVotingPluginUser(com.bencodez.advancedcore.api.user.AdvancedCoreUser user) {
return new VotingPluginUser(plugin, user);
}
@SuppressWarnings("deprecation")
public VotingPluginUser getVotingPluginUser(UUID uuid, String playerName) {
return new VotingPluginUser(plugin, uuid, playerName);
}
public VotingPluginUser getVotingPluginUser(OfflinePlayer player) {
return getVotingPluginUser(player.getUniqueId(), player.getName());
}
@@ -149,6 +142,11 @@ public class UserManager {
return new VotingPluginUser(plugin, uuid, loadName);
}
@SuppressWarnings("deprecation")
public VotingPluginUser getVotingPluginUser(UUID uuid, String playerName) {
return new VotingPluginUser(plugin, uuid, playerName);
}
public void purgeOldPlayersNoData() {
if (plugin.getOptions().isPurgeOldData() && plugin.getConfigFile().isPurgeNoDataOnStartup()) {
plugin.addUserStartup(new UserStartup() {
@@ -207,8 +205,9 @@ public class UserManager {
} else if (days > daysOld) {
if (user.getTotal(TopVoter.AllTime) == 0 && user.getMilestoneCount() == 0
&& user.getTotal(TopVoter.Monthly) == 0 && user.getTotal(TopVoter.Weekly) == 0
&& user.getTotal(TopVoter.Daily) == 0)
&& user.getTotal(TopVoter.Daily) == 0) {
plugin.debug("Removing " + user.getUUID() + " because of no data purge");
}
user.remove();
}
File diff suppressed because it is too large. Load diff
@@ -53,7 +53,7 @@ public class VoteParty implements Listener {
String uuid = user.getUUID();
ArrayList<String> voted = getVotedUsers();
if (voted == null) {
voted = new ArrayList<String>();
voted = new ArrayList<>();
}
if (!voted.contains(uuid)) {
voted.add(uuid);
@@ -62,11 +62,8 @@ public class VoteParty implements Listener {
}
public void check(VotingPluginUser user, boolean forceBungee) {
if (getTotalVotes() < getVotesRequired()) {
return;
}
if (plugin.getSpecialRewardsConfig().isVotePartyOnlyOncePerDay()
&& plugin.getServerData().isLastVotePartySameDay()) {
if ((getTotalVotes() < getVotesRequired()) || (plugin.getSpecialRewardsConfig().isVotePartyOnlyOncePerDay()
&& plugin.getServerData().isLastVotePartySameDay())) {
return;
}
if (plugin.getSpecialRewardsConfig().isVotePartyOnlyOncePerWeek()
@@ -98,6 +95,25 @@ public class VoteParty implements Listener {
}
public void checkVoteReminder(VotingPluginUser user) {
if (!user.isVanished()) {
int neededVotes = getNeededVotes();
for (Integer num1 : plugin.getSpecialRewardsConfig().getVotePartyVoteReminderAtVotes()) {
int num = num1.intValue();
if (neededVotes == num) {
String broadcastMessage = plugin.getSpecialRewardsConfig().getVotePartyVoteReminderBroadcast();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesrequired", "" + neededVotes);
MiscUtils.getInstance()
.broadcast(PlaceholderUtils.replacePlaceHolder(broadcastMessage, placeholders));
}
}
}
}
/**
* Command vote party.
*
@@ -109,7 +125,7 @@ public class VoteParty implements Listener {
int votesRequired = getVotesRequired();
int votes = getTotalVotes();
int neededVotes = votesRequired - votes;
HashMap<String, String> placeholders = new HashMap<String, String>();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("votesrequired", "" + votesRequired);
placeholders.put("neededvotes", "" + neededVotes);
placeholders.put("votes", "" + votes);
@@ -137,6 +153,18 @@ public class VoteParty implements Listener {
return neededVotes;
}
public String getRandomPlayerName() {
ArrayList<String> allPlayers = new ArrayList<>();
for (Player players : Bukkit.getOnlinePlayers()) {
allPlayers.add(players.getName());
}
if (allPlayers.size() == 0) {
return "No Player";
}
int random = new Random().nextInt(allPlayers.size());
return allPlayers.get(random);
}
/**
* Gets the total votes.
*
@@ -157,7 +185,7 @@ public class VoteParty implements Listener {
if (list != null) {
return list;
}
return new ArrayList<String>();
return new ArrayList<>();
}
public int getVotesRequired() {
@@ -186,18 +214,6 @@ public class VoteParty implements Listener {
.setServer(useBungee).send(user);
}
public String getRandomPlayerName() {
ArrayList<String> allPlayers = new ArrayList<String>();
for (Player players : Bukkit.getOnlinePlayers()) {
allPlayers.add(players.getName());
}
if (allPlayers.size() == 0) {
return "No Player";
}
int random = new Random().nextInt(allPlayers.size());
return allPlayers.get(random);
}
public void giveRewards(VotingPluginUser orgUser, boolean forceBungee) {
MiscUtils.getInstance().broadcast(plugin.getSpecialRewardsConfig().getVotePartyBroadcast());
@@ -230,7 +246,7 @@ public class VoteParty implements Listener {
if (plugin.getSpecialRewardsConfig().isVotePartyGiveAllPlayers()) {
plugin.debug("Trying to give all players vote party");
ArrayList<String> alreadyGotten = new ArrayList<String>();
ArrayList<String> alreadyGotten = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
VotingPluginUser user;
if (orgUser != null && orgUser.getJavaUUID().equals(p.getUniqueId())) {
@@ -316,19 +332,19 @@ public class VoteParty implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public void resetVotePartyCount() {
plugin.getUserManager().removeAllKeyValues("VotePartyVotes", DataType.INTEGER);
}
public void reset(boolean override) {
if (override) {
setTotalVotes(0);
}
setVotedUsers(new ArrayList<String>());
setVotedUsers(new ArrayList<>());
resetVotePartyCount();
}
public void resetVotePartyCount() {
plugin.getUserManager().removeAllKeyValues("VotePartyVotes", DataType.INTEGER);
}
/**
* Sets the total votes.
*
@@ -349,25 +365,6 @@ public class VoteParty implements Listener {
plugin.getServerData().saveData();
}
public void checkVoteReminder(VotingPluginUser user) {
if (!user.isVanished()) {
int neededVotes = getNeededVotes();
for (Integer num1 : plugin.getSpecialRewardsConfig().getVotePartyVoteReminderAtVotes()) {
int num = num1.intValue();
if (neededVotes == num) {
String broadcastMessage = plugin.getSpecialRewardsConfig().getVotePartyVoteReminderBroadcast();
HashMap<String, String> placeholders = new HashMap<String, String>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesrequired", "" + neededVotes);
MiscUtils.getInstance()
.broadcast(PlaceholderUtils.replacePlaceHolder(broadcastMessage, placeholders));
}
}
}
}
public synchronized void vote(VotingPluginUser user, boolean realVote, boolean forceBungee) {
if (plugin.getSpecialRewardsConfig().isVotePartyEnabled()) {
if (plugin.getSpecialRewardsConfig().isVotePartyCountFakeVotes() || realVote) {
@@ -30,41 +30,12 @@ public class VoteReminding {
private ScheduledExecutorService timer;
@Getter
private ConcurrentHashMap<UUID, Boolean> remindersEnabled = new ConcurrentHashMap<UUID, Boolean>();
private ConcurrentHashMap<UUID, Boolean> remindersEnabled = new ConcurrentHashMap<>();
public VoteReminding(VotingPluginMain plugin) {
this.plugin = plugin;
}
public void loadReminds() {
List<String> uuidsStr = plugin.getServerData().getDisabledReminders();
for (String str : uuidsStr) {
remindersEnabled.put(UUID.fromString(str), Boolean.FALSE);
}
plugin.getTimer().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
saveReminds();
}
}, 24, 24, TimeUnit.HOURS);
}
public void saveReminds() {
ArrayList<UUID> remindersDisabled = new ArrayList<UUID>();
for (Entry<UUID, Boolean> entry : remindersEnabled.entrySet()) {
if (remindersEnabled.containsKey(entry.getKey())) {
if (!remindersEnabled.get(entry.getKey()).booleanValue()) {
remindersDisabled.add(entry.getKey());
}
}
}
plugin.getServerData().saveDisabledReminders(remindersDisabled);
}
/**
* Check remind.
*
@@ -117,6 +88,22 @@ public class VoteReminding {
}
}
public void loadReminds() {
List<String> uuidsStr = plugin.getServerData().getDisabledReminders();
for (String str : uuidsStr) {
remindersEnabled.put(UUID.fromString(str), Boolean.FALSE);
}
plugin.getTimer().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
saveReminds();
}
}, 24, 24, TimeUnit.HOURS);
}
/**
* Run remind.
*
@@ -136,26 +123,6 @@ public class VoteReminding {
}
}
public boolean shouldRemind(VotingPluginUser user) {
if (remindersEnabled.containsKey(user.getJavaUUID())) {
if (!remindersEnabled.get(user.getJavaUUID()).booleanValue()) {
return false;
}
}
if (user.shouldBeReminded()) {
boolean hasPermAll = user.hasPermission("VotingPlugin.Login.RemindVotes.All");
if (hasPermAll) {
return user.canVoteAll();
} else {
return user.canVoteAny();
}
} else {
plugin.debug(user.getUUID() + " no need to remind because player has VotingPlugin.NoRemind");
return false;
}
}
public void runRemindLogin(VotingPluginUser user) {
if (plugin.getConfigFile().isVoteRemindingEnabled()) {
if (user.hasPermission("VotingPlugin.Login.RemindVotes") || user.hasPermission("VotingPlugin.Player")) {
@@ -178,4 +145,35 @@ public class VoteReminding {
}
}
}
public void saveReminds() {
ArrayList<UUID> remindersDisabled = new ArrayList<>();
for (Entry<UUID, Boolean> entry : remindersEnabled.entrySet()) {
if (remindersEnabled.containsKey(entry.getKey())) {
if (!remindersEnabled.get(entry.getKey()).booleanValue()) {
remindersDisabled.add(entry.getKey());
}
}
}
plugin.getServerData().saveDisabledReminders(remindersDisabled);
}
public boolean shouldRemind(VotingPluginUser user) {
if (remindersEnabled.containsKey(user.getJavaUUID())) {
if (!remindersEnabled.get(user.getJavaUUID()).booleanValue()) {
return false;
}
}
if (!user.shouldBeReminded()) {
plugin.debug(user.getUUID() + " no need to remind because player has VotingPlugin.NoRemind");
return false;
}
boolean hasPermAll = user.hasPermission("VotingPlugin.Login.RemindVotes.All");
if (hasPermAll) {
return user.canVoteAll();
}
return user.canVoteAny();
}
}