Ignore this

This commit is contained in:
Morten 2015-09-25 18:03:10 +02:00
parent 59d1a949c4
commit 1c995b14e8
411 changed files with 16317 additions and 12613 deletions

11
.gitignore vendored
View File

@ -39,3 +39,14 @@ zBench
zMyst
zSotanna
zSotanna2
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.fdt
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.fdx
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.fnm
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.frq
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.nrm
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.prx
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.tii
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/_0.tis
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments.gen
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments_1
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/write.lock

BIN
Art/Carl.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 KiB

View File

@ -20,6 +20,7 @@
<element id="module-output" name="Mineplex.Database" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jooq-3.5.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-dbcp2-2.0.1.jar" path-in-jar="/" />
<element id="module-output" name="Mineplex.PlayerCache" />
</root>
</artifact>
</component>

View File

@ -1,5 +1,5 @@
<component name="ArtifactManager">
<artifact name="Mineplex.Hub:test">
<artifact build-on-make="true" name="Mineplex.Hub:test">
<output-path>$PROJECT_DIR$/../Testing/Hub/plugins</output-path>
<root id="root">
<element id="artifact" artifact-name="Mineplex.Hub:jar" />

View File

@ -0,0 +1,24 @@
<component name="ArtifactManager">
<artifact type="jar" build-on-make="true" name="Mineplex.Votifier:jar">
<output-path>$PROJECT_DIR$/out/artifacts/</output-path>
<root id="archive" name="MineplexVotifier.jar">
<element id="module-output" name="Mineplex.Votifier" />
<element id="module-output" name="Mineplex.Core" />
<element id="module-output" name="Mineplex.Core.Common" />
<element id="module-output" name="Mineplex.ServerData" />
<element id="module-output" name="Mineplex.ServerMonitor" />
<element id="module-output" name="Mineplex.Database" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-dbcp2-2.0.1.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-io-2.4.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-logging-1.1.1.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-pool2-2.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-codec-1.6.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/gson-2.2.1.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/httpclient-4.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/httpcore-4.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jedis-2.4.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jooq-3.5.2.jar" path-in-jar="/" />
<element id="file-copy" path="$PROJECT_DIR$/Mineplex.Votifier/plugin.yml" />
</root>
</artifact>
</component>

View File

@ -4,6 +4,7 @@
<option name="DEFAULT_COMPILER" value="Javac" />
<excludeFromCompile>
<directory url="file://$PROJECT_DIR$/Nautilus.Game.PvP" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.ServerMonitor" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.Game.Clans" includeSubdirectories="true" />
</excludeFromCompile>
<resourceExtensions />

View File

@ -1,11 +0,0 @@
<component name="libraryTable">
<library name="bukkit">
<CLASSES>
<root url="jar://$PROJECT_DIR$/Libraries/bukkit.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/Libraries/bukkit.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -17,6 +17,7 @@
<module fileurl="file://$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" filepath="$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.ServerData/Mineplex.ServerData.iml" filepath="$PROJECT_DIR$/Mineplex.ServerData/Mineplex.ServerData.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.ServerMonitor/Mineplex.ServerMonitor.iml" filepath="$PROJECT_DIR$/Mineplex.ServerMonitor/Mineplex.ServerMonitor.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Votifier/Mineplex.Votifier.iml" filepath="$PROJECT_DIR$/Mineplex.Votifier/Mineplex.Votifier.iml" />
<module fileurl="file://$PROJECT_DIR$/Nautilus.Game.Arcade/Nautilus.Game.Arcade.iml" filepath="$PROJECT_DIR$/Nautilus.Game.Arcade/Nautilus.Game.Arcade.iml" group="Game" />
</modules>
</component>

View File

@ -86,6 +86,9 @@
<fileset dir="../Mineplex.ServerData/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.PlayerCache/bin">
<include name="**/*.class"/>
</fileset>
<zipfileset src="../Libraries/jooq-3.5.2.jar" />
<zipfileset src="../Libraries/httpclient-4.2.jar" />
@ -152,6 +155,9 @@
<fileset dir="../Mineplex.Database/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.PlayerCache/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.ServerData/bin">
<include name="**/*.class"/>
</fileset>
@ -198,6 +204,9 @@
<fileset dir="../Mineplex.ServerData/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.PlayerCache/bin">
<include name="**/*.class"/>
</fileset>
<zipfileset src="../Libraries/jooq-3.5.2.jar" />
<zipfileset src="../Libraries/httpclient-4.2.jar" />
@ -234,6 +243,9 @@
<fileset dir="../Mineplex.ServerData/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.PlayerCache/bin">
<include name="**/*.class"/>
</fileset>
<zipfileset src="../Libraries/jooq-3.5.2.jar" />
<zipfileset src="../Libraries/httpclient-4.2.jar" />
@ -440,6 +452,34 @@
</jar>
<copy file="../bin/TaskConverter.jar" todir="../../Testing/ChestConverter/"/>
</target>
<target name ="PetConverter" description="PetConverter">
<jar jarfile="../bin/PetConverter.jar">
<fileset dir="../Mineplex.Core.Common/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.PetConverter/bin">
<include name="**/*.class"/>
</fileset>
<zipfileset src="../Libraries/mysql.zip" />
<manifest>
<attribute name="Main-Class"
value="mineplex.chestConverter.PetConverter"/>
</manifest>
<zipfileset src="../Libraries/httpclient-4.2.jar" />
<zipfileset src="../Libraries/httpcore-4.2.jar" />
<zipfileset src="../Libraries/httpclient-cache-4.2.jar" />
<zipfileset src="../Libraries/httpmime-4.2.jar" />
<zipfileset src="../Libraries/gson-2.2.1.jar" />
<zipfileset src="../Libraries/craftbukkit.jar" />
<zipfileset src="../Libraries/commons-logging-1.1.1.jar" />
<zipfileset src="../Libraries/commons-codec-1.6.jar" />
<zipfileset src="../Libraries/commons-pool2-2.2.jar" />
</jar>
<copy file="../bin/PetConverter.jar" todir="../../Testing/PetConverter/"/>
</target>
<target name ="Queuer" description="Queuer">
<jar jarfile="../bin/Queuer.jar">
<fileset dir="../Mineplex.Core.Common/bin">

Binary file not shown.

View File

@ -1,5 +1,6 @@
package mineplex.bungee.motd;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@ -7,9 +8,13 @@ import java.util.Random;
import java.util.concurrent.TimeUnit;
import mineplex.serverdata.Region;
import mineplex.serverdata.data.BungeeServer;
import mineplex.serverdata.data.DataRepository;
import mineplex.serverdata.redis.RedisDataRepository;
import mineplex.serverdata.servers.ConnectionData;
import mineplex.serverdata.servers.ServerManager;
import mineplex.serverdata.servers.ConnectionData.ConnectionType;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
@ -20,6 +25,8 @@ public class MotdManager implements Listener, Runnable
private Plugin _plugin;
private DataRepository<GlobalMotd> _repository;
private DataRepository<GlobalMotd> _secondRepository;
private Region _region;
private Random _random = new Random();
private String _firstLine = " §b§l§m §8§l§m[ §r §9§lMineplex§r §f§lGames§r §8§l§m ]§b§l§m §r";
@ -28,6 +35,7 @@ public class MotdManager implements Listener, Runnable
public MotdManager(Plugin plugin)
{
_plugin = plugin;
_region = !new File("eu.dat").exists() ? Region.US : Region.EU;
_plugin.getProxy().getScheduler().schedule(_plugin, this, 5L, 30L, TimeUnit.SECONDS);
_plugin.getProxy().getPluginManager().registerListener(_plugin, this);
@ -38,12 +46,21 @@ public class MotdManager implements Listener, Runnable
if (new File("updateMOTD.dat").exists())
{
List<String> lines = new ArrayList<String>();
lines.add(" §f§l◄ §6§lNEW §f§l▬ §c§lSSM/SG/SW Teams§f§l ▬ §c§lMPS Update §f§l►");
//lines.add(" §d§lRank Sale §a§l40% Off");
//lines.add(" §f§l◄§c§lMAINTENANCE§f§l►");
if (_region == Region.US)
_secondRepository = new RedisDataRepository<GlobalMotd>(new ConnectionData("10.81.1.156", 6379, ConnectionType.MASTER, "ServerStatus"), new ConnectionData("10.81.1.156", 6377, ConnectionType.SLAVE, "ServerStatus"),
Region.ALL, GlobalMotd.class, "globalMotd");
else
_secondRepository = new RedisDataRepository<GlobalMotd>(new ConnectionData("10.33.53.16", 6379, ConnectionType.MASTER, "ServerStatus"), new ConnectionData("10.33.53.16", 6377, ConnectionType.SLAVE, "ServerStatus"),
Region.ALL, GlobalMotd.class, "globalMotd");
updateMainMotd(" §b§l§m §8§l§m[ §r §9§lMineplex§r §f§lGames§r §8§l§m ]§b§l§m §r", lines);
//String motdLine = "§f§l◄ §c§lMaintenance§f§l ►";
//String motdLine = "§f§l◄ §a§lCarl the Creeper§f§l ►";
String motdLine = " §b§l◄§f§lNEW GAME§b§l► §f§l◄§b§lEVOLUTION§f§l► §b§l◄§f§lNEW GAME§b§l►";
//String motdLine = " §f§l◄ §a§lCarl the Creeper§f§l ▬ §c§l75% OFF SALE§f§l ►";
//String motdLine = " §d§lRank Sale §a§l40% Off");
//String motdLine = " §f§l◄§c§lMAINTENANCE§f§l►");
updateMainMotd(" §b§l§m §8§l§m[ §r §9§lMineplex§r §f§lGames§r §8§l§m ]§b§l§m §r", motdLine);
System.out.println("Updated Bungee MOTD");
}
}
@ -78,9 +95,14 @@ public class MotdManager implements Listener, Runnable
* Update the main {@link GlobalMotd} determining the MOTD for Bungee instances.
* @param motdLines - the lines to update the MOTD to.
*/
public void updateMainMotd(String headline, List<String> motdLines)
public void updateMainMotd(String headline, String motdLine)
{
List<String> motdLines = new ArrayList<String>();
motdLines.add(motdLine);
_repository.addElement(new GlobalMotd("MainMotd", headline, motdLines));
_secondRepository.addElement(new GlobalMotd("MainMotd", headline, motdLines));
}
public List<String> getMotdLines()

View File

@ -1,6 +1,5 @@
package mineplex.bungee.playerStats;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@ -19,7 +18,6 @@ public class PlayerStats implements Listener, Runnable
private Plugin _plugin;
private PlayerStatsRepository _repository;
private PlayerCache _playerCache = new PlayerCache();
private HashSet<UUID> _retrievingPlayerInfo = new HashSet<UUID>();
public PlayerStats(Plugin plugin)
@ -52,7 +50,7 @@ public class PlayerStats implements Listener, Runnable
boolean addOrUpdatePlayer = false;
playerInfo = _playerCache.getPlayer(uuid);
playerInfo = PlayerCache.getInstance().getPlayer(uuid);
if (playerInfo == null)
{
@ -80,11 +78,11 @@ public class PlayerStats implements Listener, Runnable
}
else
playerInfo = updatedPlayerInfo;
_playerCache.addPlayer(playerInfo);
}
playerInfo.setSessionId(_repository.updatePlayerStats(playerInfo.getId(), ipInfo.id));
playerInfo.updateLoginTime();
PlayerCache.getInstance().addPlayer(playerInfo);
}
finally
{
@ -105,13 +103,13 @@ public class PlayerStats implements Listener, Runnable
PlayerInfo playerInfo = null;
playerInfo = _playerCache.getPlayer(uuid);
playerInfo = PlayerCache.getInstance().getPlayer(uuid);
int timeout = 5;
while (playerInfo == null && _retrievingPlayerInfo.contains(uuid) && timeout <= 5)
{
playerInfo = _playerCache.getPlayer(uuid);
playerInfo = PlayerCache.getInstance().getPlayer(uuid);
if (playerInfo != null)
break;
@ -130,6 +128,7 @@ public class PlayerStats implements Listener, Runnable
timeout++;
}
System.out.println(playerInfo.getName() + ":" + playerInfo.getSessionId());
_repository.updatePlayerSession(playerInfo.getSessionId());
}
});
@ -138,6 +137,6 @@ public class PlayerStats implements Listener, Runnable
@Override
public void run()
{
_playerCache.clean();
PlayerCache.getInstance().clean();
}
}

View File

@ -0,0 +1,27 @@
package mineplex.bungee.playerTracker;
import mineplex.serverdata.commands.CommandCallback;
import mineplex.serverdata.commands.PlayerJoinCommand;
import mineplex.serverdata.commands.ServerCommand;
public class PlayerJoinHandler implements CommandCallback
{
private PlayerTracker _playerTracker;
public PlayerJoinHandler(PlayerTracker playerTracker)
{
_playerTracker = playerTracker;
}
@SuppressWarnings("deprecation")
@Override
public void run(ServerCommand command)
{
if (command instanceof PlayerJoinCommand)
{
PlayerJoinCommand joinCommand = (PlayerJoinCommand)command;
_playerTracker.kickPlayerIfOnline(joinCommand.getUuid());
}
}
}

View File

@ -1,19 +1,25 @@
package mineplex.bungee.playerTracker;
import java.io.File;
import java.util.HashSet;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import mineplex.serverdata.Region;
import mineplex.serverdata.commands.ServerCommandManager;
import mineplex.serverdata.data.DataRepository;
import mineplex.serverdata.data.PlayerStatus;
import mineplex.serverdata.redis.RedisDataRepository;
import mineplex.serverdata.servers.ServerManager;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
public class PlayerTracker implements Listener
public class PlayerTracker implements Listener, Runnable
{
// Default period before status expiry (8 hours)
private static final int DEFAULT_STATUS_TIMEOUT = 60 * 60 * 8;
@ -21,6 +27,8 @@ public class PlayerTracker implements Listener
// Repository storing player status' across network.
private DataRepository<PlayerStatus> _repository;
private HashSet<String> _onlineUUIDs = new HashSet<String>();
private Plugin _plugin;
public PlayerTracker(Plugin plugin)
@ -28,11 +36,14 @@ public class PlayerTracker implements Listener
_plugin = plugin;
_plugin.getProxy().getPluginManager().registerListener(_plugin, this);
_plugin.getProxy().getScheduler().schedule(_plugin, this, 1L, 1L, TimeUnit.MINUTES);
Region region = !new File("eu.dat").exists() ? Region.US : Region.EU;
_repository = new RedisDataRepository<PlayerStatus>(ServerManager.getMasterConnection(), ServerManager.getSlaveConnection(),
region, PlayerStatus.class, "playerStatus");
ServerCommandManager.getInstance().registerCommandType("PlayerJoinCommand", mineplex.serverdata.commands.PlayerJoinCommand.class, new PlayerJoinHandler(this));
System.out.println("Initialized PlayerTracker.");
}
@ -56,8 +67,45 @@ public class PlayerTracker implements Listener
{
public void run()
{
_repository.removeElement(event.getPlayer().getName());
_repository.removeElement(event.getPlayer().getName().toLowerCase());
}
});
_onlineUUIDs.remove(event.getPlayer().getUniqueId());
}
@EventHandler
public void playerConnect(final PostLoginEvent event)
{
_onlineUUIDs.add(event.getPlayer().getUniqueId().toString());
}
@Override
public void run()
{
HashSet<String> onlineUUIDs = new HashSet<String>();
for (ProxiedPlayer player : _plugin.getProxy().getPlayers())
{
onlineUUIDs.add(player.getUniqueId().toString());
}
_onlineUUIDs = onlineUUIDs;
}
public boolean isPlayerOnline(String uuid)
{
return _onlineUUIDs.contains(uuid);
}
public void kickPlayerIfOnline(String uuid)
{
if (_onlineUUIDs.contains(uuid))
{
ProxiedPlayer player = _plugin.getProxy().getPlayer(UUID.fromString(uuid));
if (player != null)
player.disconnect("You have logged in from another location.");
}
}
}

View File

@ -10,6 +10,7 @@
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value=""/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${BUILD_FILES}/common.xml"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>

View File

@ -1,11 +1,20 @@
package mineplex.chestConverter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
@ -18,8 +27,23 @@ public class ChestConverter
private static Logger _logger = Logger.getLogger("Converter");
private static String _connectionString = "jdbc:mysql://db.mineplex.com:3306/Account?allowMultiQueries=true";
private static String _userName = "MilitaryPolice";
private static String _password = "CUPr6Wuw2Rus$qap";
private static Connection _connection;
public static void main (String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
try
{
FileHandler fileHandler = new FileHandler("converter.log", true);
@ -39,71 +63,137 @@ public class ChestConverter
e1.printStackTrace();
}
_repository = new ChestConverterRepository();
int lastId = 18279475;
int count = 50000;
int numOfRowsProcessed = lastId;
int limit = 50000;
HashSet<AccountStat> accountStats = new HashSet<AccountStat>();
HashMap<String, Integer> tasks = _repository.getTaskList();
try
while (true)
{
while (true)
accountStats.clear();
try
{
long time = System.currentTimeMillis();
HashMap<String, List<Integer>> playerMap = new HashMap<String, List<Integer>>();
Statement statement = null;
List<AccountTask> taskList = _repository.getTasks(lastId, count);
if (taskList != null && taskList.size() > 0)
try
{
for (AccountTask task : taskList)
{
if (!playerMap.containsKey(task.UUID))
playerMap.put(task.UUID, new ArrayList<Integer>());
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
playerMap.get(task.UUID).add(tasks.get(task.Task));
statement = _connection.createStatement();
if (task.Id > lastId)
lastId = task.Id;
}
statement.execute("SELECT accountId, statId, value FROM Account.accountStats LIMIT " + limit + ";");
_repository.incrementClients(playerMap);
try
ResultSet resultSet = statement.getResultSet();
while (resultSet.next())
{
numOfRowsProcessed += count;
log("Natural sleep. " + count + " took " + (System.currentTimeMillis() - time) / 1000 + " seconds. Count = " + + numOfRowsProcessed);
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
accountStats.add(new AccountStat(resultSet.getInt(1), resultSet.getInt(2), resultSet.getInt(3)));
}
}
else if (numOfRowsProcessed > 17000000)
catch (Exception exception)
{
System.out.println("Count : " + numOfRowsProcessed);
_logger.info("Count : " + numOfRowsProcessed);
break;
exception.printStackTrace();
}
else
finally
{
System.out.println("No greater than 17 mil");
_logger.info("No greater than 17 mil");
System.out.println("Count : " + numOfRowsProcessed);
_logger.info("Count : " + numOfRowsProcessed);
if (statement != null)
{
try
{
statement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
if (accountStats.size() == 0)
{
System.out.println("No accounts.");
return;
}
PreparedStatement updateStatement = null;
PreparedStatement insertStatement = null;
Statement deleteStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
_connection.setAutoCommit(true);
updateStatement = _connection.prepareStatement("UPDATE accountStat SET value = value + ? WHERE accountId = ? AND statId = ? AND value < ?;");
for (AccountStat stat : accountStats)
{
updateStatement.setLong(1, stat.value);
updateStatement.setInt(2, stat.accountId);
updateStatement.setInt(3, stat.statId);
updateStatement.setLong(4, stat.value);
updateStatement.addBatch();
}
int[] rowsAffected = updateStatement.executeBatch();
_connection.setAutoCommit(false);
int i = 0;
int count = 0;
log("Updated rows - " + limit);
insertStatement = _connection.prepareStatement("INSERT IGNORE accountStat(accountId, statId, value) VALUES (?, ?, ?);");
for (AccountStat stat : accountStats)
{
if (rowsAffected[i] < 1)
{
insertStatement.setInt(1, stat.accountId);
insertStatement.setInt(2, stat.statId);
insertStatement.setLong(3, stat.value);
insertStatement.addBatch();
count++;
}
i++;
}
insertStatement.executeBatch();
log("Inserted rows - " + count);
deleteStatement = _connection.createStatement();
deleteStatement.executeUpdate("DELETE FROM accountStats LIMIT " + limit + ";");
_connection.commit();
log("Deleted rows - " + limit);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (statement != null)
{
try
{
statement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{
_logger.info(e.getMessage());
}
finally
{
System.out.println("Count : " + numOfRowsProcessed);
_logger.info("Count : " + numOfRowsProcessed);
catch (Exception e)
{
_logger.info(e.getMessage());
}
}
}

View File

@ -8,6 +8,7 @@ import mineplex.core.common.util.UtilPlayer;
public enum Rank
{
//Staff
LT("LT", ChatColor.DARK_RED),
OWNER("Owner", ChatColor.DARK_RED),
DEVELOPER("Dev", ChatColor.RED),
@ -22,35 +23,47 @@ public enum Rank
EVENT("Event", ChatColor.WHITE),
//Staff ^^
//Media
YOUTUBE("YouTube", ChatColor.RED),
YOUTUBE_SMALL("MooTube", ChatColor.DARK_PURPLE),
TWITCH("Twitch", ChatColor.DARK_PURPLE),
LEGEND("Legend", ChatColor.GREEN),
HERO("Hero", ChatColor.LIGHT_PURPLE),
ULTRA("Ultra", ChatColor.AQUA),
//Player
LEGEND("Legend", ChatColor.GREEN, true),
HERO("Hero", ChatColor.LIGHT_PURPLE, true),
ULTRA("Ultra", ChatColor.AQUA, true),
ALL("", ChatColor.WHITE);
private ChatColor Color;
private ChatColor _color;
private boolean _donor;
public String Name;
Rank(String name, ChatColor color)
{
Color = color;
_color = color;
Name = name;
_donor = false;
}
public boolean Has(Rank rank)
Rank(String name, ChatColor color, boolean donor)
{
return Has(null, rank, false);
_color = color;
Name = name;
_donor = donor;
}
public boolean Has(Player player, Rank rank, boolean inform)
public boolean has(Rank rank)
{
return Has(player, rank, null, inform);
return has(null, rank, false);
}
public boolean Has(Player player, Rank rank, Rank[] specific, boolean inform)
public boolean has(Player player, Rank rank, boolean inform)
{
return has(player, rank, null, inform);
}
public boolean has(Player player, Rank rank, Rank[] specific, boolean inform)
{
//Specific Rank
if (specific != null)
@ -79,7 +92,7 @@ public enum Rank
return false;
}
public String GetTag(boolean bold, boolean uppercase)
public String getTag(boolean bold, boolean uppercase)
{
if (Name.equalsIgnoreCase("ALL"))
return "";
@ -88,12 +101,17 @@ public enum Rank
if (uppercase)
name = Name.toUpperCase();
if (bold) return Color + C.Bold + name;
else return Color + name;
if (bold) return _color + C.Bold + name;
else return _color + name;
}
public ChatColor GetColor()
public ChatColor getColor()
{
return Color;
return _color;
}
public boolean isDonor()
{
return _donor;
}
}

View File

@ -0,0 +1,24 @@
package mineplex.core.common.structs;
import org.bukkit.Material;
public class ItemContainer
{
public Material Type;
public byte Data;
public String Name;
public ItemContainer(Material type, byte data, String name)
{
Type = type;
Data = data;
Name = name;
}
public ItemContainer(int id, byte data, String name)
{
Type = Material.getMaterial(id);
Data = data;
Name = name;
}
}

View File

@ -95,15 +95,15 @@ public class F
public static String help(String cmd, String body, Rank rank)
{
return rank.GetColor() + cmd + " " + C.mBody + body + " " + rank(rank);
return rank.getColor() + cmd + " " + C.mBody + body + " " + rank(rank);
}
public static String rank(Rank rank)
{
if (rank == Rank.ALL)
return rank.GetColor() + "Player";
return rank.getColor() + "Player";
return rank.GetTag(false, false);
return rank.getTag(false, false);
}
public static String value(String variable, String value)

View File

@ -70,6 +70,11 @@ public class MapUtil
QuickChangeBlockAt(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), setTo);
}
public static void QuickChangeBlockAt(Location location, Material setTo, byte data)
{
QuickChangeBlockAt(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), setTo, data);
}
public static void QuickChangeBlockAt(Location location, int id, byte data)
{
QuickChangeBlockAt(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), id,

View File

@ -5,10 +5,8 @@ import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
@ -251,6 +249,25 @@ public class UtilAlg
return bestLoc;
}
public static Location findFurthest(Location mid, ArrayList<Location> locs)
{
Location bestLoc = null;
double bestDist = 0;
for (Location loc : locs)
{
double dist = UtilMath.offset(mid, loc);
if (bestLoc == null || dist > bestDist)
{
bestLoc = loc;
bestDist = dist;
}
}
return bestLoc;
}
public static boolean isInPyramid(Vector a, Vector b, double angleLimit)
{
return (Math.abs(GetPitch(a) - GetPitch(b)) < angleLimit) && (Math.abs(GetYaw(a) - GetYaw(b)) < angleLimit);
@ -298,6 +315,42 @@ public class UtilAlg
return bestLoc;
}
public static Location getLocationAwayFromOtherLocations(ArrayList<Location> locs, ArrayList<Location> players)
{
Location bestLoc = null;
double bestDist = 0;
for (Location loc : locs)
{
double closest = -1;
for (Location player : players)
{
//Different Worlds
if (!player.getWorld().equals(loc.getWorld()))
continue;
double dist = UtilMath.offsetSquared(player, loc);
if (closest == -1 || dist < closest)
{
closest = dist;
}
}
if (closest == -1)
continue;
if (bestLoc == null || closest > bestDist)
{
bestLoc = loc;
bestDist = closest;
}
}
return bestLoc;
}
public static Location getLocationNearPlayers(ArrayList<Location> locs, ArrayList<Player> players, ArrayList<Player> dontOverlap)
{
Location bestLoc = null;
@ -353,4 +406,21 @@ public class UtilAlg
return bestLoc;
}
public static Location getNearestCornerLocation(Location near, Block block)
{
ArrayList<Location> corners = new ArrayList<Location>();
corners.add(block.getLocation().clone());
corners.add(block.getLocation().clone().add(.999, 0, 0));
corners.add(block.getLocation().clone().add(.999, 0, .999));
corners.add(block.getLocation().clone().add(0, 0, .999));
corners.add(block.getLocation().clone().add(0, .999, 0));
corners.add(block.getLocation().clone().add(.999, .999, 0));
corners.add(block.getLocation().clone().add(.999, .999, .999));
corners.add(block.getLocation().clone().add(0, .999, .999));
return UtilAlg.findClosest(near, corners);
}
}

View File

@ -4,26 +4,32 @@ import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.server.v1_7_R4.AxisAlignedBB;
import net.minecraft.server.v1_7_R4.EntityBat;
import net.minecraft.server.v1_7_R4.EntityCreature;
import net.minecraft.server.v1_7_R4.EntityEnderDragon;
import net.minecraft.server.v1_7_R4.EntityHuman;
import net.minecraft.server.v1_7_R4.EntityInsentient;
import net.minecraft.server.v1_7_R4.EntityLiving;
import net.minecraft.server.v1_7_R4.EntityTrackerEntry;
import net.minecraft.server.v1_7_R4.Navigation;
import net.minecraft.server.v1_7_R4.PacketPlayOutEntityHeadRotation;
import net.minecraft.server.v1_7_R4.PathfinderGoal;
import net.minecraft.server.v1_7_R4.PathfinderGoalLookAtPlayer;
import net.minecraft.server.v1_7_R4.PathfinderGoalMoveTowardsRestriction;
import net.minecraft.server.v1_7_R4.PathfinderGoalRandomLookaround;
import net.minecraft.server.v1_7_R4.PathfinderGoalSelector;
import net.minecraft.server.v1_7_R4.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_7_R4.CraftWorld;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftCreature;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftLivingEntity;
import org.bukkit.entity.Creature;
@ -32,8 +38,7 @@ import org.bukkit.entity.EntityType;
import org.bukkit.entity.Giant;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftCreature;
import org.bukkit.craftbukkit.v1_7_R4.CraftWorld;
import org.bukkit.util.Vector;
public class UtilEnt
{
@ -491,10 +496,14 @@ public class UtilEnt
public static boolean isGrounded(Entity ent)
{
if (ent instanceof CraftEntity)
return ((CraftEntity)ent).getHandle().onGround;
AxisAlignedBB box = ((CraftEntity)ent).getHandle().boundingBox;
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.1, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.1, box.f);
return UtilBlock.solid(ent.getLocation().getBlock().getRelative(BlockFace.DOWN));
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true;
}
return false;
}
public static void PlayDamageSound(LivingEntity damagee)
@ -582,6 +591,36 @@ public class UtilEnt
return false;
}
public static boolean CreatureLook(Entity ent, Entity target)
{
return CreatureLook(ent, target instanceof LivingEntity ? ((LivingEntity) target).getEyeLocation() : target.getLocation());
}
public static boolean CreatureLook(Entity ent, Location target)
{
Vector vec = UtilAlg.getTrajectory(ent.getLocation(), target);
return CreatureLook(ent, UtilAlg.GetPitch(vec), UtilAlg.GetYaw(vec));
}
public static boolean CreatureLook(Entity ent, float pitch, float yaw)
{
if (!(ent instanceof LivingEntity))
return false;
EntityLiving ec = ((CraftLivingEntity) ent).getHandle();
Location loc = ent.getLocation();
ec.setPositionRotation(loc.getX(), loc.getY(), loc.getZ(), yaw, pitch);
ec.al = true;
EntityTrackerEntry entry = (EntityTrackerEntry) ((WorldServer) ec.world).tracker.trackedEntities.get(ec.getId());
entry.broadcast(new PacketPlayOutEntityHeadRotation(ec, (byte) (ec.yaw * 256.0F / 360.0F)));
return true;
}
public static void CreatureMove(Entity ent, Location target, float speed)
{
if (!(ent instanceof Creature))

View File

@ -1,5 +1,7 @@
package mineplex.core.common.util;
import net.minecraft.server.v1_7_R4.PacketPlayOutEntityDestroy;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.FireworkEffect.Type;
@ -8,6 +10,7 @@ import org.bukkit.craftbukkit.v1_7_R4.CraftWorld;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftFirework;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.util.Vector;
@ -69,4 +72,28 @@ public class UtilFirework
{
playFirework(loc, FireworkEffect.builder().flicker(flicker).withColor(color).with(type).trail(trail).build());
}
public static void packetPlayFirework(Player player, Location loc, Type type, Color color, boolean flicker, boolean trail)
{
Firework firework = (Firework) loc.getWorld().spawn(loc, Firework.class);
FireworkEffect effect = FireworkEffect.builder().flicker(flicker).withColor(color).with(type).trail(trail).build();
FireworkMeta data = (FireworkMeta) firework.getFireworkMeta();
data.clearEffects();
data.setPower(1);
data.addEffect(effect);
firework.setFireworkMeta(data);
((CraftFirework) firework).getHandle().expectedLifespan = 1;
PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy(firework.getEntityId());
for (Player viewing : UtilServer.getPlayers())
{
if (player == viewing)
continue;
UtilPlayer.sendPacket(viewing, packet);
}
}
}

View File

@ -4,22 +4,24 @@ import java.util.AbstractMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import mineplex.core.common.structs.ItemContainer;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class UtilItem
{
public static LinkedList<Entry<Material, Byte>> matchItem(Player caller, String items, boolean inform)
public static LinkedList<ItemContainer> matchItem(Player caller, String items, boolean inform)
{
LinkedList<Entry<Material, Byte>> matchList = new LinkedList<Entry<Material, Byte>>();
LinkedList<ItemContainer> matchList = new LinkedList<ItemContainer>();
String failList = "";
//Mass Search
for (String cur : items.split(","))
{
Entry<Material, Byte> match = searchItem(caller, cur, inform);
ItemContainer match = searchItem(caller, cur, inform);
if (match != null)
matchList.add(match);
@ -40,21 +42,27 @@ public class UtilItem
return matchList;
}
public static Entry<Material, Byte> searchItem(Player caller, String args, boolean inform)
public static ItemContainer searchItem(Player caller, String args, boolean inform)
{
LinkedList<Entry<Material, Byte>> matchList = new LinkedList<Entry<Material, Byte>>();
LinkedList<ItemContainer> matchList = new LinkedList<ItemContainer>();
for (Material cur : Material.values())
{
String[] arg = args.split(":");
//Get Selected Name
String name = null;
if (arg.length > 2)
name = arg[2].replaceAll("_", " ");
//By Name
if (cur.toString().equalsIgnoreCase(args))
return new AbstractMap.SimpleEntry<Material, Byte>(cur, (byte)0);
return new ItemContainer(cur, (byte)0, name);
if (cur.toString().toLowerCase().contains(args.toLowerCase()))
matchList.add(new AbstractMap.SimpleEntry<Material, Byte>(cur, (byte)0));
matchList.add(new ItemContainer(cur, (byte)0, name));
//By ID:Data
String[] arg = args.split(":");
//By ID:Data:Name
//ID
int id = 0;
@ -83,7 +91,7 @@ public class UtilItem
continue;
}
return new AbstractMap.SimpleEntry<Material, Byte>(cur, data);
return new ItemContainer(cur, data, name);
}
//No / Non-Unique
@ -102,8 +110,9 @@ public class UtilItem
if (matchList.size() > 0)
{
String matchString = "";
for (Entry<Material, Byte> cur : matchList)
matchString += F.elem(cur.getKey().toString()) + ", ";
for (ItemContainer cur : matchList)
matchString += F.elem(cur.Type.toString()) + ", ";
if (matchString.length() > 1)
matchString = matchString.substring(0 , matchString.length() - 2);

View File

@ -85,5 +85,11 @@ public class UtilMath
return Math.random() * d;
}
public static <T> T randomElement(T[] array) {
if (array.length == 0)
return null;
return array[random.nextInt(array.length)];
}
}

View File

@ -6,20 +6,23 @@ import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import net.minecraft.server.v1_7_R4.EntityPlayer;
import net.minecraft.server.v1_7_R4.Packet;
import net.minecraft.server.v1_7_R4.PlayerConnection;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_7_R4.event.CraftEventFactory;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_7_R4.Packet;
import net.minecraft.server.v1_7_R4.PlayerConnection;
public class UtilPlayer
{
private static boolean hasIntersection(Vector3D p1, Vector3D p2, Vector3D min, Vector3D max)
@ -609,6 +612,18 @@ public class UtilPlayer
return false;
}
public static InventoryView swapToInventory(Player player, Inventory inv) {
EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle();
if (nmsPlayer.activeContainer != nmsPlayer.defaultContainer)
{
// Do this so that other inventories know their time is over.
CraftEventFactory.handleInventoryCloseEvent(nmsPlayer);
nmsPlayer.m();
}
return player.openInventory(inv);
}
/*
public void setListName(Player player, CoreClient client)
{

View File

@ -6,23 +6,23 @@ public class UtilSkull
{
public static byte getSkullData(Entity entity)
{
if (entity instanceof Skeleton)
{
Skeleton sk = ((Skeleton) entity);
if (sk.getSkeletonType() == Skeleton.SkeletonType.WITHER)
return 1;
else return 0;
}
else if (entity instanceof Zombie || entity instanceof Giant)
{
if (entity == null)
return 0;
return getSkullData(entity.getType());
}
public static byte getSkullData(EntityType type)
{
if (type == EntityType.SKELETON)
return 0;
if (type == EntityType.WITHER)
return 1;
if (type == EntityType.ZOMBIE || type == EntityType.GIANT)
return 2;
}
else if (entity instanceof Creeper)
{
if (type == EntityType.CREEPER)
return 4;
}
else
return 3;
return 3;
}
public static boolean isPlayerHead(byte data)
@ -31,52 +31,54 @@ public class UtilSkull
}
public static String getPlayerHeadName(Entity entity)
{
return getPlayerHeadName(entity.getType());
}
public static String getPlayerHeadName(EntityType entity)
{
String name = "MHF_Alex";
// order is important for some of these
if (entity instanceof Blaze)
if (entity == EntityType.BLAZE)
name = "MHF_Blaze";
else if (entity instanceof CaveSpider)
else if (entity == EntityType.CAVE_SPIDER)
name = "MHF_CaveSpider";
else if (entity instanceof Spider)
else if (entity == EntityType.SPIDER)
name = "MHF_Spider";
else if (entity instanceof Chicken)
else if (entity == EntityType.CHICKEN)
name = "MHF_Chicken";
else if (entity instanceof MushroomCow)
else if (entity == EntityType.MUSHROOM_COW)
name = "MHF_MushroomCow";
else if (entity instanceof Cow)
else if (entity == EntityType.COW)
name = "MHF_Cow";
else if (entity instanceof Creeper)
else if (entity == EntityType.CREEPER)
name = "MHF_Creeper";
else if (entity instanceof Enderman)
else if (entity == EntityType.ENDERMAN)
name = "MHF_Enderman";
else if (entity instanceof Ghast)
else if (entity == EntityType.GHAST)
name = "MHF_Ghast";
else if (entity instanceof Golem)
else if (entity == EntityType.IRON_GOLEM)
name = "MHF_Golem";
else if (entity instanceof PigZombie)
else if (entity == EntityType.PIG_ZOMBIE)
name = "MHF_PigZombie";
else if (entity instanceof MagmaCube)
else if (entity == EntityType.MAGMA_CUBE)
name = "MHF_LavaSlime";
else if (entity instanceof Slime)
else if (entity == EntityType.SLIME)
name = "MHF_Slime";
else if (entity instanceof Ocelot)
else if (entity == EntityType.OCELOT)
name = "MHF_Ocelot";
else if (entity instanceof PigZombie)
name = "MHF_PigZombie";
else if (entity instanceof Pig)
else if (entity == EntityType.PIG)
name = "MHF_Pig";
else if (entity instanceof Sheep)
name = "MHF_Pig";
else if (entity instanceof Squid)
else if (entity == EntityType.SHEEP)
name = "MHF_Sheep";
else if (entity == EntityType.SQUID)
name = "MHF_Squid";
else if (entity instanceof HumanEntity)
else if (entity == EntityType.PLAYER)
name = "MHF_Steve";
else if (entity instanceof Villager)
else if (entity == EntityType.VILLAGER)
name = "MHF_Villager";
return name;
}
}

View File

@ -2,6 +2,8 @@ package mineplex.core.common.util;
import java.util.Collection;
import org.apache.commons.lang.WordUtils;
public class UtilText {
public static <T> String listToString(Collection<T> inputList, boolean comma) {
String out = "";
@ -84,4 +86,13 @@ public class UtilText {
return false;
}
public static String[] wrap(String text, int lineLength)
{
return wrap(text, lineLength, true);
}
public static String[] wrap(String text, int lineLength, boolean wrapLongerWords) {
return WordUtils.wrap(text, lineLength, "\00D0", wrapLongerWords).split("\00D0");
}
}

View File

@ -14,5 +14,6 @@
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/craftbukkit.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core.Common"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/NoCheatPlus.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.PlayerCache"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -1,5 +1,6 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7

View File

@ -20,5 +20,6 @@
<orderEntry type="library" name="commons-dbcp2" level="project" />
<orderEntry type="module" module-name="Classpath.Dummy" />
<orderEntry type="library" name="NoCheatPlus" level="project" />
<orderEntry type="module" module-name="Mineplex.PlayerCache" />
</component>
</module>

View File

@ -22,7 +22,7 @@ public class TablistFix extends MiniPlugin
// This is sort of experimental!
@EventHandler(priority = EventPriority.MONITOR)
public void onJoin(PlayerJoinEvent event)
{
{/*
final Player player = event.getPlayer();
runSyncLater(new Runnable()
{
@ -49,5 +49,6 @@ public class TablistFix extends MiniPlugin
}
}
}, 20L);
*/
}
}

View File

@ -1,33 +0,0 @@
package mineplex.core.account;
import java.util.UUID;
import mineplex.serverdata.data.Data;
public class AccountCache implements Data
{
private UUID _uuid;
private Integer _id;
public AccountCache(UUID uuid, int id)
{
_uuid = uuid;
_id = id;
}
public UUID getUUID()
{
return _uuid;
}
public int getId()
{
return _id;
}
@Override
public String getDataId()
{
return _uuid.toString();
}
}

View File

@ -1,12 +1,14 @@
package mineplex.core.account;
import mineplex.core.common.Rank;
import mineplex.serverdata.Utility;
import org.bukkit.entity.Player;
public class CoreClient
{
private int _accountId = -1;
private long _networkSessionLoginTime;
private String _name;
private String _disguisedAs;
private Player _player;
@ -18,6 +20,7 @@ public class CoreClient
{
_player = player;
_name = player.getName();
_networkSessionLoginTime = Utility.currentTimeMillis();
}
public CoreClient(String name)
@ -58,6 +61,9 @@ public class CoreClient
public Rank GetRank()
{
if (_rank == null)
_rank = Rank.ALL;
return _rank;
}
@ -66,6 +72,11 @@ public class CoreClient
_rank = rank;
}
public long getNetworkSessionLoginTime()
{
return _networkSessionLoginTime;
}
public String getDisguisedAs()
{
return _disguisedAs;
@ -95,4 +106,9 @@ public class CoreClient
public void setDisguised(boolean disguised) {
this._disguised = disguised;
}
public void setNetworkSessionLoginTime(long loginTime)
{
_networkSessionLoginTime = loginTime;
}
}

View File

@ -2,6 +2,7 @@ package mineplex.core.account;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
@ -21,10 +22,8 @@ import mineplex.core.common.util.UtilPlayer;
import mineplex.core.timing.TimingManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.serverdata.Region;
import mineplex.serverdata.data.BungeeServer;
import mineplex.serverdata.redis.RedisDataRepository;
import mineplex.serverdata.servers.ServerManager;
import mineplex.playerCache.PlayerCache;
import mineplex.playerCache.PlayerInfo;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
@ -47,9 +46,9 @@ public class CoreClientManager extends MiniPlugin
private AccountRepository _repository;
private NautHashMap<String, CoreClient> _clientList;
private HashSet<String> _duplicateLoginGlitchPreventionList;
private RedisDataRepository<AccountCache> _accountCacheRepository;
private NautHashMap<String, ILoginProcessor> _loginProcessors = new NautHashMap<String, ILoginProcessor>();
private LinkedList<IQuerylessLoginProcessor> _querylessLoginProcessors = new LinkedList<IQuerylessLoginProcessor>();
private Object _clientLock = new Object();
@ -64,9 +63,6 @@ public class CoreClientManager extends MiniPlugin
_repository = new AccountRepository(plugin, webServer);
_clientList = new NautHashMap<String, CoreClient>();
_duplicateLoginGlitchPreventionList = new HashSet<String>();
_accountCacheRepository = new RedisDataRepository<AccountCache>(ServerManager.getMasterConnection(), ServerManager.getSlaveConnection(),
Region.ALL, AccountCache.class, "accountCache");
}
public AccountRepository getRepository()
@ -124,7 +120,14 @@ public class CoreClientManager extends MiniPlugin
if(client.getDisguisedAs().equalsIgnoreCase(name))
return client;
}
return _clientList.get(name);
CoreClient client = _clientList.get(name);
if (client == null)
{
client = new CoreClient(name);
}
return client;
}
}
@ -138,6 +141,16 @@ public class CoreClientManager extends MiniPlugin
return Bukkit.getOnlinePlayers().size() + Math.max(0, _clientsConnecting.get());
}
/**
* Get the databse account id for a player. Requires the player is online
* @param player
* @return
*/
public int getAccountId(Player player)
{
return Get(player).getAccountId();
}
@EventHandler(priority = EventPriority.LOWEST)
public void AsyncLogin(AsyncPlayerPreLoginEvent event)
{
@ -173,7 +186,7 @@ public class CoreClientManager extends MiniPlugin
_clientsProcessing.decrementAndGet();
}
if (Bukkit.hasWhitelist() && !Get(event.getName()).GetRank().Has(Rank.MODERATOR))
if (Bukkit.hasWhitelist() && !Get(event.getName()).GetRank().has(Rank.MODERATOR))
{
for (OfflinePlayer player : Bukkit.getWhitelistedPlayers())
{
@ -207,7 +220,16 @@ public class CoreClientManager extends MiniPlugin
UUID uuid = loadUUIDFromDB(playerName);
if (uuid == null)
uuid = UUIDFetcher.getUUIDOf(playerName);
{
try
{
uuid = UUIDFetcher.getUUIDOf(playerName);
}
catch (Exception exception)
{
System.out.println("Error fetching uuid from mojang : " + exception.getMessage());
}
}
String response = "";
@ -224,13 +246,21 @@ public class CoreClientManager extends MiniPlugin
CoreClient client = Add(playerName);
client.SetRank(Rank.valueOf(token.Rank));
client.setAccountId(_repository.login(_loginProcessors, uuid.toString(), client.GetPlayerName()));
client.setAccountId(_repository.login(_loginProcessors, _querylessLoginProcessors, uuid.toString(), client.GetPlayerName()));
// JSON sql response
Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response, uuid));
if (client.getAccountId() > 0)
_accountCacheRepository.addElement(new AccountCache(uuid, client.getAccountId()), 60 * 60 * 6);
{
PlayerInfo playerInfo = PlayerCache.getInstance().getPlayer(uuid);
if (playerInfo != null)
{
playerInfo.setAccountId(client.getAccountId());
PlayerCache.getInstance().addPlayer(playerInfo);
}
}
}
catch (Exception exception)
{
@ -264,7 +294,7 @@ public class CoreClientManager extends MiniPlugin
{
public void run()
{
client.setAccountId(_repository.login(_loginProcessors, uuid.toString(), client.GetPlayerName()));
client.setAccountId(_repository.login(_loginProcessors, _querylessLoginProcessors, uuid.toString(), client.GetPlayerName()));
_clientLoginLock.remove(client.GetPlayerName());
}
});
@ -301,17 +331,15 @@ public class CoreClientManager extends MiniPlugin
TimingManager.stop(client.GetPlayerName() + " LoadClient Total.");
System.out.println(client.GetPlayerName() + "'s account id = " + client.getAccountId());
if (client.getAccountId() > 0)
{
try
PlayerInfo playerInfo = PlayerCache.getInstance().getPlayer(uuid);
if (playerInfo != null)
{
_accountCacheRepository.addElement(new AccountCache(uuid, client.getAccountId()), 60 * 60 * 6);
}
catch (Exception e)
{
e.printStackTrace();
client.setNetworkSessionLoginTime(playerInfo.getLoginTime());
playerInfo.setAccountId(client.getAccountId());
PlayerCache.getInstance().addPlayer(playerInfo);
}
}
@ -342,7 +370,7 @@ public class CoreClientManager extends MiniPlugin
// Reserved Slot Check
if (Bukkit.getOnlinePlayers().size() >= Bukkit.getServer().getMaxPlayers())
{
if (client.GetRank().Has(event.getPlayer(), Rank.ULTRA, false))
if (client.GetRank().has(event.getPlayer(), Rank.ULTRA, false))
{
event.allow();
event.setResult(PlayerLoginEvent.Result.ALLOWED);
@ -485,7 +513,9 @@ public class CoreClientManager extends MiniPlugin
clientIterator.remove();
if (clientPlayer != null)
{
_plugin.getServer().getPluginManager().callEvent(new ClientUnloadEvent(clientPlayer.getName()));
}
}
}
}
@ -508,17 +538,17 @@ public class CoreClientManager extends MiniPlugin
_loginProcessors.put(processor.getName(), processor);
}
public void addStoredProcedureLoginProcessor(IQuerylessLoginProcessor processor)
{
_querylessLoginProcessors.add(processor);
}
public boolean hasRank(Player player, Rank rank)
{
CoreClient client = Get(player);
if (client == null)
return false;
return client.GetRank().Has(rank);
}
public int getCachedClientAccountId(UUID uuid)
{
return _accountCacheRepository.getElement(uuid.toString()).getId();
return client.GetRank().has(rank);
}
}

View File

@ -0,0 +1,6 @@
package mineplex.core.account;
public interface IQuerylessLoginProcessor
{
public void processLogin(String playerName, int accountId);
}

View File

@ -29,7 +29,7 @@ public class UpdateRank extends CommandBase<CoreClientManager>
if (Plugin.Get(caller).GetRank() == Rank.JNR_DEV && !testServer)
{
F.main(Plugin.getName(), F.elem(Rank.JNR_DEV.GetTag(true, true)) + "s are only permitted to set ranks on test servers!");
F.main(Plugin.getName(), F.elem(Rank.JNR_DEV.getTag(true, true)) + "s are only permitted to set ranks on test servers!");
return;
}
@ -60,9 +60,9 @@ public class UpdateRank extends CommandBase<CoreClientManager>
final Rank rank = tempRank;
if (rank == Rank.ADMIN || rank == Rank.YOUTUBE || rank == Rank.TWITCH || rank == Rank.MODERATOR || rank == Rank.HELPER || rank == Rank.ALL || rank == Rank.MAPDEV || rank == Rank.SNR_MODERATOR || rank == Rank.JNR_DEV || rank == Rank.DEVELOPER)
if (rank == Rank.ADMIN || rank == Rank.YOUTUBE || rank == Rank.TWITCH || rank == Rank.MODERATOR || rank == Rank.JNR_DEV || rank == Rank.HELPER || rank == Rank.ALL || rank == Rank.MAPDEV || rank == Rank.SNR_MODERATOR)
{
if (!testServer && rank.Has(Rank.ADMIN) && !Plugin.hasRank(caller, Rank.LT))
if (!testServer && rank.has(Rank.ADMIN) && !Plugin.hasRank(caller, Rank.LT))
{
UtilPlayer.message(caller, F.main(Plugin.getName(), ChatColor.RED + "" + ChatColor.BOLD + "Insufficient privileges!"));
return;

View File

@ -6,6 +6,7 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
@ -14,6 +15,7 @@ import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.account.ILoginProcessor;
import mineplex.core.account.IQuerylessLoginProcessor;
import mineplex.core.account.repository.token.LoginToken;
import mineplex.core.account.repository.token.RankUpdateToken;
import mineplex.core.common.Rank;
@ -55,7 +57,7 @@ public class AccountRepository extends RepositoryBase
//executeUpdate(CREATE_ACCOUNT_TABLE);
}
public int login(NautHashMap<String, ILoginProcessor> loginProcessors, String uuid, String name)
public int login(NautHashMap<String, ILoginProcessor> loginProcessors, LinkedList<IQuerylessLoginProcessor> querylessLoginProcessors, String uuid, String name)
{
int accountId = -1;
try (
@ -145,6 +147,11 @@ public class AccountRepository extends RepositoryBase
loginProcessor.processLoginResultSet(name, accountId, statement.getResultSet());
statement.getMoreResults();
}
for (IQuerylessLoginProcessor loginProcessor : querylessLoginProcessors)
{
loginProcessor.processLogin(name, accountId);
}
}
catch (Exception exception)
{
@ -186,7 +193,7 @@ public class AccountRepository extends RepositoryBase
}, new ColumnVarChar("name", 100, name));
if (uuids.size() > 0)
return uuids.get(uuids.size() - 1);
return uuids.get(0);
else
return null;
}

View File

@ -662,11 +662,53 @@ public enum Achievement
new int[]{20},
AchievementCategory.BOMB_LOBBERS),
BOMB_LOBBERS_SNIPER("Sniper", 10000,
BOMB_LOBBERS_SNIPER("Sniper", 1000,
new String[]{"Bomb Lobbers.Direct Hit"},
new String[]{"Get 50 direct hits"},
new int[]{50},
AchievementCategory.BOMB_LOBBERS)
AchievementCategory.BOMB_LOBBERS),
EVOLUTION_WINS("Expert Evolver", 1200,
new String[]{"Evolution.Wins"},
new String[]{"Win 20 games of Evolution"},
new int[]{20},
AchievementCategory.EVOLUTION),
EVOLUTION_NO_DEATHS("Perfect Game", 2000,
new String[]{"Evolution.NoDeaths"},
new String[]{"Win a game without dying"},
new int[]{1},
AchievementCategory.EVOLUTION),
EVOLUTION_STEALTH("Stealth Mastah", 1000,
new String[]{"Evolution.Stealth"},
new String[]{"Win without taking any", "damage while evolving"},
new int[]{1},
AchievementCategory.EVOLUTION),
EVOLUTION_RAMPAGE("Rampage", 800,
new String[]{"Evolution.Rampage"},
new String[]{"Get 3 kills within 5 seconds", "of each other"},
new int[]{1},
AchievementCategory.EVOLUTION),
EVOLUTION_MELEE("Melee Monster", 1000,
new String[]{"Evolution.MeleeOnly"},
new String[]{"Win without using any abilities"},
new int[]{1},
AchievementCategory.EVOLUTION),
EVOLUTION_SKILLS("Ability Assassin", 1000,
new String[]{"Evolution.AbilityOnly"},
new String[]{"Win without any melee attacks"},
new int[]{1},
AchievementCategory.EVOLUTION),
EVOLUTION_EVOLVEKILL("No Evolve 5 U", 800,
new String[]{"Evolution.EvolveKill"},
new String[]{"Kill 25 people while they", "Are trying to evolve"},
new int[]{25},
AchievementCategory.EVOLUTION)
;

View File

@ -2,9 +2,6 @@ package mineplex.core.achievement;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
@ -12,10 +9,14 @@ import mineplex.core.common.util.UtilTime;
import mineplex.core.stats.PlayerStats;
import mineplex.core.stats.StatsManager;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public enum AchievementCategory
{
GLOBAL("Global", null,
new StatDisplay[] { StatDisplay.GEMS_EARNED, null, new StatDisplay("Games Played", "GamesPlayed"), StatDisplay.TIME_IN_GAME },
new StatDisplay[] { StatDisplay.GEMS_EARNED, null, new StatDisplay("Games Played", "GamesPlayed"), StatDisplay.TIME_IN_GAME, null,
new StatDisplay("Daily Rewards", "DailyReward"), new StatDisplay("Times Voted", "DailyVote"), null, new StatDisplay("Chests Opened", "Treasure.Old", "Treasure.Ancient", "Treasure.Mythical") },
Material.EMERALD, 0, GameCategory.GLOBAL, "None"),
BRIDGES("The Bridges", null,
@ -28,7 +29,7 @@ public enum AchievementCategory
SKYWARS("Skywars",null,
new StatDisplay[]{StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED},
Material.FEATHER, 5, GameCategory.SURVIVAL, "Destructor Kit"),
Material.FEATHER, 0, GameCategory.SURVIVAL, "Destructor Kit"),
UHC("Ultra Hardcore", null,
new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED },
@ -122,7 +123,11 @@ public enum AchievementCategory
BOMB_LOBBERS("Bomb Lobbers", null,
new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED },
Material.FIREBALL, 0, GameCategory.ARCADE, "Waller Kit");
Material.FIREBALL, 0, GameCategory.ARCADE, "Waller Kit"),
EVOLUTION("Evolution", null,
new StatDisplay[] {StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED},
Material.MONSTER_EGG, 0, GameCategory.ARCADE, "Harvester Kit");
private String _name;
private String[] _statsToPull;
@ -202,7 +207,7 @@ public enum AchievementCategory
String displayName = _statDisplays[i].getDisplayName();
// Skip showing Losses, Kills, Deaths for other players
if (!clientManager.Get(player).GetRank().Has(Rank.MODERATOR) && !player.equals(target) && (displayName.contains("Losses") || displayName.contains("Kills") || displayName.contains("Deaths") || displayName.equals("Time In Game") || displayName.equals("Games Played")))
if (!clientManager.Get(player).GetRank().has(Rank.MODERATOR) && !player.equals(target) && (displayName.contains("Losses") || displayName.contains("Kills") || displayName.contains("Deaths") || displayName.equals("Time In Game") || displayName.equals("Games Played")))
continue;
int statNumber = 0;

View File

@ -137,15 +137,6 @@ public class AchievementManager extends MiniPlugin
_log.remove(event.getPlayer().getName());
}
@EventHandler
public void playerJoin(PlayerJoinEvent event)
{
if (_giveInterfaceItem)
{
giveInterfaceItem(event.getPlayer());
}
}
public void clearLog(Player player)
{
_log.remove(player.getName());
@ -161,22 +152,7 @@ public class AchievementManager extends MiniPlugin
_giveInterfaceItem = giveInterfaceItem;
}
public void giveInterfaceItem(Player player)
{
if (!UtilGear.isMat(player.getInventory().getItem(_interfaceSlot), Material.SKULL_ITEM))
{
ItemStack item = ItemStackFactory.Instance.CreateStack(Material.SKULL_ITEM, (byte) 3, 1, ChatColor.RESET + C.cGreen + "/stats");
SkullMeta meta = ((SkullMeta) item.getItemMeta());
meta.setOwner(player.getName());
item.setItemMeta(meta);
player.getInventory().setItem(_interfaceSlot, item);
UtilInv.Update(player);
}
}
@EventHandler
/*@EventHandler
public void openShop(PlayerInteractEvent event)
{
if (!_shopEnabled)
@ -188,7 +164,7 @@ public class AchievementManager extends MiniPlugin
openShop(event.getPlayer());
}
}
}*/
public boolean hasCategory(Player player, Achievement[] required)
{
@ -211,15 +187,15 @@ public class AchievementManager extends MiniPlugin
if (sender.getName().equalsIgnoreCase("B2_mp"))
return 101;
if (rank.Has(Rank.MODERATOR))
if (rank.has(Rank.MODERATOR))
level = Math.max(level, 5);
if (rank.Has(Rank.SNR_MODERATOR))
if (rank.has(Rank.SNR_MODERATOR))
level = Math.max(level, 15);
if (rank.Has(Rank.JNR_DEV))
if (rank.has(Rank.JNR_DEV))
level = Math.max(level, 25);
if (rank.Has(Rank.ADMIN))
if (rank.has(Rank.ADMIN))
level = Math.max(level, 30 + get(sender, Achievement.GLOBAL_GEM_HUNTER).getLevel());
if (rank.Has(Rank.OWNER))
if (rank.has(Rank.OWNER))
level = Math.max(level, 50 + get(sender, Achievement.GLOBAL_GEM_HUNTER).getLevel());
if (sender.getName().equalsIgnoreCase("Phinary"))

View File

@ -17,7 +17,7 @@ public class StatsCommand extends CommandBase<AchievementManager>
@Override
public void Execute(Player caller, String[] args)
{
if (args == null || args.length == 0)
if (args.length == 0)
{
Plugin.openShop(caller);
}

View File

@ -57,11 +57,10 @@ public class AchievementMainPage extends ShopPageBase<AchievementManager, Achiev
ArrayList<String> lore = new ArrayList<String>();
lore.add(" ");
category.addStats(getClientManager(), _statsManager, lore, category == AchievementCategory.GLOBAL ? 5 : 2,
category.addStats(getClientManager(), _statsManager, lore, category == AchievementCategory.GLOBAL ? 10 : 2,
getPlayer(), _target);
lore.add(" ");
addAchievements(category, lore, 9);
lore.add(" ");
lore.add(ChatColor.RESET + "Click for more details!");
ShopItem shopItem = new ShopItem(category.getIcon(), category.getIconData(), C.Bold + category.getFriendlyName(),
@ -100,5 +99,8 @@ public class AchievementMainPage extends ShopPageBase<AchievementManager, Achiev
achievementCount++;
}
}
if (achievementCount > 0)
lore.add(" ");
}
}

View File

@ -259,7 +259,7 @@ public class AntiHack extends MiniPlugin
//Inform
for (Player admin : UtilServer.getPlayers())
if (_clientManager.Get(admin).GetRank().Has(Rank.MODERATOR) && _preferences.Get(admin).ShowMacReports)
if (_clientManager.Get(admin).GetRank().has(Rank.MODERATOR) && _preferences.Get(admin).ShowMacReports)
{
UtilPlayer.message(admin, "#" + total + ": " + C.cRed + C.Bold + player.getName() + " suspected for " + type + ".");
}
@ -335,7 +335,7 @@ public class AntiHack extends MiniPlugin
boolean handled = false;
for (Player staff : UtilServer.getPlayers())
{
if (_clientManager.Get(staff).GetRank().Has(Rank.MODERATOR))
if (_clientManager.Get(staff).GetRank().has(Rank.MODERATOR))
{
UtilPlayer.message(staff, C.cAqua + C.Scramble + "A" + ChatColor.RESET + C.cRed + C.Bold + " MAC > " + ChatColor.RESET + C.cYellow + report);
UtilPlayer.message(staff, C.cAqua + C.Scramble + "A" + ChatColor.RESET + C.cRed + C.Bold + " MAC > " + ChatColor.RESET + C.cGold + player.getName() + C.cYellow + " has extreme violation. Please investigate.");

View File

@ -13,7 +13,7 @@ public class AntiHackRepository
{
private String _serverName;
private static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS AntiHack_Kick_Log (id INT NOT NULL AUTO_INCREMENT, updated LONG, playerName VARCHAR(256), motd VARCHAR(56), gameType VARCHAR(56), map VARCHAR(256), serverName VARCHAR(256), report VARCHAR(256), ping VARCHAR(25), PRIMARY KEY (id));";
//private static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS AntiHack_Kick_Log (id INT NOT NULL AUTO_INCREMENT, updated LONG, playerName VARCHAR(256), motd VARCHAR(56), gameType VARCHAR(56), map VARCHAR(256), serverName VARCHAR(256), report VARCHAR(256), ping VARCHAR(25), PRIMARY KEY (id));";
private static String UPDATE_PLAYER_OFFENSES = "INSERT INTO AntiHack_Kick_Log (updated, playerName, motd, gameType, map, serverName, report, ping) VALUES (now(), ?, ?, ?, ?, ?, ?, ?);";
public AntiHackRepository(String serverName)
@ -23,32 +23,6 @@ public class AntiHackRepository
public void initialize()
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
{
// Create table
preparedStatement = connection.prepareStatement(CREATE_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public void saveOffense(final Player player, final String motd, final String game, final String map, final String report)

View File

@ -0,0 +1,159 @@
package mineplex.core.bonuses;
import java.util.List;
import org.bukkit.ChatColor;
import mineplex.core.common.util.C;
public class BonusAmount
{
private int _gems;
private int _coins;
private int _gold;
private int _bonusGems;
private int _bonusCoins;
private int _bonusGold;
private int _experience;
private int _bonusExperience;
private int _tickets;
public BonusAmount()
{
}
public int getGems()
{
return _gems;
}
public void setGems(int gems)
{
_gems = gems;
}
public int getCoins()
{
return _coins;
}
public void setCoins(int coins)
{
_coins = coins;
}
public int getGold()
{
return _gold;
}
public void setGold(int gold)
{
_gold = gold;
}
public int getBonusGems()
{
return _bonusGems;
}
public void setBonusGems(int bonusGems)
{
_bonusGems = bonusGems;
}
public int getBonusCoins()
{
return _bonusCoins;
}
public void setBonusCoins(int bonusCoins)
{
_bonusCoins = bonusCoins;
}
public int getBonusGold()
{
return _bonusGold;
}
public void setBonusGold(int bonusGold)
{
_bonusGold = bonusGold;
}
public int getTotalGems()
{
return getGems() + getBonusGems();
}
public int getTotalCoins()
{
return getCoins() + getBonusCoins();
}
public int getTotalGold()
{
return getGold() + getBonusGold();
}
public int getExperience()
{
return _experience;
}
public void setExperience(int experience)
{
_experience = experience;
}
public int getBonusExperience()
{
return _bonusExperience;
}
public void setBonusExperience(int bonusExperience)
{
_bonusExperience = bonusExperience;
}
public int getTotalExperience()
{
return getExperience() + getBonusExperience();
}
public int getTickets()
{
return _tickets;
}
public void setTickets(int tickets)
{
_tickets = tickets;
}
public boolean isGreaterThanZero()
{
return _bonusCoins > 0 || _coins > 0 || _bonusGems > 0 || _gems > 0 || _gold > 0 || _bonusGold > 0;
}
public void addLore(List<String> lore)
{
lore.add(C.cYellow + "Rewards");
addLore(lore, getTickets(), 0, "Carl Spin Ticket" + (getTickets() > 1 ? "s" : ""));
addLore(lore, getCoins(), getBonusCoins(), "Coins");
addLore(lore, getGems(), getBonusGems(), "Gems");
addLore(lore, getGold(), getBonusGold(), "Gold");
addLore(lore, getExperience(), getBonusExperience(), "Experience");
}
private void addLore(List<String> lore, int amount, int bonus, String suffix)
{
if (amount > 0)
lore.add(" " + C.cWhite + amount + " " + suffix);
// if (bonus > 0)
// lore.add(C.cYellow + "Streak Bonus: " + C.cWhite + bonus + " " + suffix);
}
}

View File

@ -0,0 +1,127 @@
package mineplex.core.bonuses;
import java.sql.Date;
import java.sql.Timestamp;
import mineplex.core.hologram.Hologram;
import mineplex.database.tables.records.BonusRecord;
public class BonusClientData
{
private Hologram _hologram;
private int _accountId;
private Timestamp _dailyTime;
private Date _rankTime;
private Date _voteTime;
private int _dailyStreak;
private int _maxDailyStreak;
private int _voteStreak;
private int _maxVoteStreak;
private int _tickets;
public BonusClientData()
{
_accountId = -1;
}
public void setAccountId(Integer value)
{
_accountId = value;
}
public Integer getAccountId()
{
return _accountId;
}
public void setDailyTime(Timestamp value)
{
_dailyTime = value;
}
public Timestamp getDailyTime()
{
return _dailyTime;
}
public void setRankTime(Date value)
{
_rankTime = value;
}
public Date getRankTime()
{
return _rankTime;
}
public void setVoteTime(Date value)
{
_voteTime = value;
}
public Date getVoteTime()
{
return _voteTime;
}
public void setDailyStreak(Integer value)
{
_dailyStreak = value;
}
public Integer getDailyStreak()
{
return _dailyStreak;
}
public void setMaxDailyStreak(Integer value)
{
_maxDailyStreak = value;
}
public Integer getMaxDailyStreak()
{
return _maxDailyStreak;
}
public void setVoteStreak(Integer value)
{
_voteStreak = value;
}
public Integer getVoteStreak()
{
return _voteStreak;
}
public void setMaxVoteStreak(Integer value)
{
_maxVoteStreak = value;
}
public Integer getMaxVoteStreak()
{
return _maxVoteStreak;
}
public void setTickets(Integer value)
{
_tickets = value;
}
public Integer getTickets()
{
return _tickets;
}
public Hologram getHologram()
{
return _hologram;
}
public void setHologram(Hologram hologram)
{
_hologram = hologram;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,446 @@
package mineplex.core.bonuses;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Map;
import com.sun.org.apache.xpath.internal.operations.Bool;
import mineplex.core.bonuses.gui.SpinGui;
import mineplex.core.common.Pair;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnInt;
import mineplex.core.donation.DonationManager;
import mineplex.core.recharge.Recharge;
import mineplex.database.Tables;
import mineplex.database.tables.records.BonusRecord;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.Record2;
import org.jooq.SQLDialect;
import org.jooq.TableField;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
public class BonusRepository extends RepositoryBase
{
private static String CREATE_BONUS_TABLE = "CREATE TABLE IF NOT EXISTS bonus (accountId INT NOT NULL AUTO_INCREMENT, dailytime TIMESTAMP NULL DEFAULT NULL, ranktime DATE NULL DEFAULT NULL, PRIMARY KEY (accountId), FOREIGN KEY (accountId) REFERENCES accounts(id));";
private BonusManager _manager;
private DonationManager _donationManager;
public BonusRepository(JavaPlugin plugin, BonusManager bonusManager, DonationManager donationManager)
{
super(plugin, DBPool.ACCOUNT);
_manager = bonusManager;
_donationManager = donationManager;
}
public BonusRecord loadRecord(String playerName, int accountId)
{
DSLContext create = jooq();
BonusRecord record = create.selectFrom(Tables.bonus).where(Tables.bonus.accountId.eq(accountId)).fetchOne();
if (record == null)
{
// Need to create new record!
record = create.newRecord(Tables.bonus);
record.setAccountId(accountId);
record.setDailyStreak(0);
record.setMaxDailyStreak(0);
record.setVoteStreak(0);
record.setMaxVoteStreak(0);
record.setTickets(0);
record.store(); // Todo - is this necessary?
}
System.out.println("Loaded record. Daily time: " + record.getDailytime());
return record;
}
public BonusClientData loadData(final int accountId, ResultSet resultSet) throws SQLException
{
BonusClientData clientData = new BonusClientData();
clientData.setAccountId(accountId);
boolean foundClient = false;
while (resultSet.next())
{
foundClient = true;
clientData.setDailyTime(resultSet.getTimestamp(2));
clientData.setRankTime(resultSet.getDate(3));
clientData.setVoteTime(resultSet.getDate(4));
clientData.setDailyStreak(resultSet.getInt(5));
clientData.setMaxDailyStreak(resultSet.getInt(6));
clientData.setVoteStreak(resultSet.getInt(7));
clientData.setMaxVoteStreak(resultSet.getInt(8));
clientData.setTickets(resultSet.getInt(9));
}
if (!foundClient)
{
_manager.runAsync(new Runnable()
{
@Override
public void run()
{
executeInsert("INSERT IGNORE INTO bonus (accountId) VALUES (" + accountId + ")", null);
}
});
}
return clientData;
}
public void getDailyStreakRecord(Callback<StreakRecord> callback)
{
getStreakRecord(Tables.bonus.maxDailyStreak, callback);
}
public void getVoteStreakRecord(Callback<StreakRecord> callback)
{
getStreakRecord(Tables.bonus.maxVoteStreak, callback);
}
private void getStreakRecord(final TableField<BonusRecord, Integer> field, final Callback<StreakRecord> callback)
{
Bukkit.getScheduler().runTaskAsynchronously(_manager.getPlugin(), new Runnable()
{
@Override
public void run()
{
final Record2<String, Integer> record = jooq().select(Tables.accounts.name, field)
.from(Tables.bonus.join(Tables.accounts).on(Tables.bonus.accountId.eq(Tables.accounts.id)))
.orderBy(field.desc()).limit(1).fetchOne();
Bukkit.getScheduler().runTask(_manager.getPlugin(), new Runnable()
{
@Override
public void run()
{
if (record.value1() != null && record.value2() != null)
{
callback.run(new StreakRecord(record.value1(), record.value2()));
}
}
});
}
});
}
public void attemptAddTickets(final int accountId, final BonusClientData client, final int tickets, final Callback<Boolean> callback)
{
if (client.getTickets() + tickets < 0)
callback.run(false);
Bukkit.getScheduler().runTaskAsynchronously(_manager.getPlugin(), new Runnable()
{
@Override
public void run()
{
try
{
DSLContext create = DSL.using(DBPool.ACCOUNT, SQLDialect.MYSQL);
create.update(Tables.bonus).set(Tables.bonus.tickets, Tables.bonus.tickets.add(tickets)).
where(Tables.bonus.accountId.eq(accountId)).execute();
final int newTickets = create.select(Tables.bonus.tickets).from(Tables.bonus).where(Tables.bonus.accountId.eq(accountId)).fetchOne().value1();
Bukkit.getScheduler().runTask(_manager.getPlugin(), new Runnable()
{
@Override
public void run()
{
client.setTickets(newTickets);
callback.run(true);
}
});
}
catch (Exception e)
{
e.printStackTrace();
callback.run(false);
}
}
});
}
public void attemptDailyBonus(final Player player, final Callback<Boolean> result)
{
final int accountId = _manager.getClientManager().Get(player).getAccountId();
final int coins = 0;
final int gems = 0;
/*
* if (coins == 0 && gems == 0) { result.accept(false); return; }
*/
final JavaPlugin plug = _manager.getPlugin();
Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable()
{
@Override
public void run()
{
try (Connection connection = getConnection();
CallableStatement callableStatement = connection.prepareCall("{call check_daily(?, ?, ?, ?, ?)}"))
{
callableStatement.setInt(1, accountId);
callableStatement.setInt(2, coins);
callableStatement.setInt(3, gems);
callableStatement.registerOutParameter(4, java.sql.Types.BOOLEAN);
callableStatement.registerOutParameter(5, java.sql.Types.TIMESTAMP);
callableStatement.executeUpdate();
final boolean pass = callableStatement.getBoolean(4);
final Timestamp timeStamp = callableStatement.getTimestamp(5);
Bukkit.getScheduler().runTask(plug, new Runnable()
{
@Override
public void run()
{
if (pass)
{
_manager.Get(player).setDailyTime(new Timestamp(BonusManager.getSqlTime()));
result.run(true);
}
else
{
Recharge.Instance.use(player, "AttemptDailyBonus", 1000 * 10, false, false);
_manager.Get(player).setDailyTime(timeStamp);
result.run(false);
}
}
});
}
catch (Exception e)
{
Recharge.Instance.use(player, "AttemptDailyBonus", 1000 * 30, false, false);
e.printStackTrace();
result.run(false);
}
}
});
}
@Deprecated
public void giveTickets(final Player player, final Callback<Boolean> result)
{
final int accountId = _manager.getClientManager().Get(player).getAccountId();
Bukkit.getScheduler().runTaskAsynchronously(_manager.getPlugin(), new Runnable()
{
@Override
public void run()
{
final int newTickets = jooq().update(Tables.bonus).set(Tables.bonus.tickets, Tables.bonus.tickets.sub(-1)).
where(Tables.bonus.accountId.eq(accountId)).returning(Tables.bonus.tickets).fetchOne().getTickets();
Bukkit.getScheduler().runTask(_manager.getPlugin(), new Runnable()
{
@Override
public void run()
{
}
});
}
});
}
public void attemptRankBonus(final Player player, final Callback<Boolean> result)
{
if (!Recharge.Instance.usable(player, "AttemptRankBonus")) {
result.run(false);
return;
}
final int accountId = _manager.getClientManager().Get(player).getAccountId();
final int coins = _manager.getRankBonusAmount(player).getCoins();
if (coins == 0/* && gems == 0 */) {
result.run(false);
return;
}
final JavaPlugin plug = _manager.getPlugin();
Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable() {
@Override
public void run()
{
try (Connection connection = getConnection();
CallableStatement callableStatement = connection.prepareCall("{call check_rank(?, ?, ?, ?, ?)}")) {
callableStatement.setInt(1, accountId);
callableStatement.setInt(2, coins);
callableStatement.setInt(3, 0);
callableStatement.registerOutParameter(4, java.sql.Types.BOOLEAN);
callableStatement.registerOutParameter(5, java.sql.Types.DATE);
callableStatement.executeUpdate();
final boolean pass = callableStatement.getBoolean(4);
final Date date = callableStatement.getDate(5);
Bukkit.getScheduler().runTask(plug, new Runnable() {
@Override
public void run()
{
_manager.Get(player).setRankTime(date);
if (pass)
{
result.run(true);
}
else
{
Recharge.Instance.use(player, "AttemptRankBonus", 1000 * 10, false, false);
result.run(false);
}
}
});
} catch (Exception e) {
Recharge.Instance.use(player, "AttemptRankBonus", 1000 * 30, false, false);
e.printStackTrace();
result.run(false);
}
}
});
}
public void attemptVoteBonus(final int accountId, final Callback<Pair<Boolean, Date>> result)
{
final int coins = 0;
final int gems = 0;
final JavaPlugin plug = _manager.getPlugin();
Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable() {
@Override
public void run()
{
try (Connection connection = getConnection();
CallableStatement callableStatement = connection.prepareCall("{call check_vote(?, ?, ?, ?, ?)}")) {
callableStatement.setInt(1, accountId);
callableStatement.setInt(2, coins);
callableStatement.setInt(3, gems);
callableStatement.registerOutParameter(4, Types.BOOLEAN);
callableStatement.registerOutParameter(5, Types.DATE);
callableStatement.executeUpdate();
final boolean pass = callableStatement.getBoolean(4);
final Date date = callableStatement.getDate(5);
Bukkit.getScheduler().runTask(plug, new Runnable() {
@Override
public void run()
{
// _manager.Get(player).setVoteTime(date);
result.run(Pair.create(pass, date));
}
});
} catch (Exception e) {
e.printStackTrace();
result.run(null);
}
}
});
}
public void getTimeOffset(final Callback<Long> callback)
{
final long startTime = System.currentTimeMillis();
final Plugin plugin = _manager.getPlugin();
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run()
{
executeQuery("SELECT CURRENT_TIMESTAMP", new ResultSetCallable() {
@Override
public void processResultSet(ResultSet resultSet) throws SQLException
{
resultSet.next();
long theirTimeUnadjusted = resultSet.getTimestamp(1).getTime();
long ourCurrentTime = System.currentTimeMillis();
long latencyOffset = (ourCurrentTime - startTime) / 2;
long theirTime = theirTimeUnadjusted - latencyOffset;
final long offSet = theirTime - ourCurrentTime;
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run()
{
callback.run(offSet);
}
});
}
});
}
});
}
public void getClientData(final int accountId, final Callback<BonusClientData> callback)
{
String query = "SELECT * FROM bonus WHERE accountId = '" + accountId + "';";
executeQuery(query, new ResultSetCallable()
{
@Override
public void processResultSet(ResultSet resultSet) throws SQLException
{
BonusClientData clientData = loadData(accountId, resultSet);
callback.run(clientData);
}
});
}
public void saveStreak(int accountId, BonusClientData clientData)
{
jooq().update(Tables.bonus).set(Tables.bonus.dailyStreak, clientData.getDailyStreak())
.set(Tables.bonus.maxDailyStreak, clientData.getMaxDailyStreak())
.set(Tables.bonus.voteStreak, clientData.getVoteStreak())
.set(Tables.bonus.maxVoteStreak, clientData.getMaxVoteStreak())
.where(Tables.bonus.accountId.eq(accountId)).execute();
}
@Override
protected void initialize()
{
executeUpdate(CREATE_BONUS_TABLE);
}
@Override
protected void update()
{
}
}

View File

@ -0,0 +1,50 @@
package mineplex.core.bonuses;
import java.util.UUID;
public class GiveDonorData
{
private String _playerName;
private int _accountId;
private UUID _uuid;
private int _giveAmount;
private int _attempts;
public GiveDonorData(String playerName, int accountId, UUID uuid, int giveAmount)
{
_playerName = playerName;
_accountId = accountId;
_uuid = uuid;
_giveAmount = giveAmount;
}
public String getPlayerName()
{
return _playerName;
}
public int getAccountId()
{
return _accountId;
}
public UUID getUuid()
{
return _uuid;
}
public int getGiveAmount()
{
return _giveAmount;
}
public int getAttempts()
{
return _attempts;
}
public void incrementAttempts()
{
_attempts++;
}
}

View File

@ -0,0 +1,23 @@
package mineplex.core.bonuses;
public class StreakRecord
{
private String _playerName;
private int _streak;
public StreakRecord(String playerName, int streak)
{
_playerName = playerName;
_streak = streak;
}
public String getPlayerName()
{
return _playerName;
}
public int getStreak()
{
return _streak;
}
}

View File

@ -0,0 +1,290 @@
package mineplex.core.bonuses.animations;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import mineplex.core.common.util.UtilAction;
import mineplex.core.common.util.UtilFirework;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilParticle.ViewDist;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.reward.Reward;
import mineplex.core.reward.RewardData;
import mineplex.core.reward.RewardRarity;
import mineplex.core.treasure.animation.Animation;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class AnimationCarl extends Animation
{
private boolean _isDone;
private Block _creeper;
private Object _type;
private Player _player;
private HashSet<Item> _items = new HashSet<Item>();
public AnimationCarl(Entity creeper)
{
_creeper = creeper.getLocation().getBlock();
}
@Override
protected void tick()
{
if(_type instanceof String)
{
if(((String) _type).contentEquals("DAILY") || ((String) _type).contentEquals("POLL"))
{
for (int i = 50; i < 60; i++)
{
Item gem = _creeper.getWorld().dropItem(_creeper.getLocation().add(0.5, 1.5, 0.5), ItemStackFactory.Instance.CreateStack(Material.EMERALD, (byte) 0, 1, " " + i));
Item coin = _creeper.getWorld().dropItem(_creeper.getLocation().add(0.5, 1.5, 0.5), ItemStackFactory.Instance.CreateStack(Material.DOUBLE_PLANT, (byte) 0, 1, " " + i));
_items.add(gem);
_items.add(coin);
Vector vel = new Vector(Math.sin(i * 9/5d), 0, Math.cos(i * 9/5d));
UtilAction.velocity(gem, vel, Math.abs(Math.sin(i * 12/3000d)), false, 0, 0.2 + Math.abs(Math.cos(i * 12/3000d))*0.6, 1, false);
UtilAction.velocity(coin, vel, Math.abs(Math.sin(UtilMath.r(i) * 30/3000d)), false, 0, 0.2 + Math.abs(Math.cos(UtilMath.r(i) * 30/3000d))*0.6, 1, false);
}
}
if(((String) _type).contentEquals("RANK"))
{
for (int i = 50; i < 60; i++)
{
Item coin = _creeper.getWorld().dropItem(_creeper.getLocation().add(0.5, 1.5, 0.5), ItemStackFactory.Instance.CreateStack(Material.DOUBLE_PLANT, (byte) 0, 1, " " + i));
_items.add(coin);
Vector vel = new Vector(Math.sin(UtilMath.r(i) * 7/5d), 0, Math.cos(UtilMath.r(i) * 7/5d));
UtilAction.velocity(coin, vel, Math.abs(Math.sin(UtilMath.r(i) * 7/3000d)), false, 0, 0.2 + Math.abs(Math.cos(UtilMath.r(i) * 7/3000d))*0.6, 1, false);
}
}
if(!((String) _type).contentEquals("DAILY")&& !((String) _type).contentEquals("RANK")&& !((String) _type).contentEquals("POLL"))
{
Item paper = _creeper.getWorld().dropItem(_creeper.getLocation().add(0.5, 1.5, 0.5), ItemStackFactory.Instance.CreateStack(Material.PAPER, (byte) 0, 1, " " + 64));
_items.add(paper);
Vector vel = new Vector(Math.sin(64 * 8/5d), 0, Math.cos(64 * 8/5d));
UtilAction.velocity(paper, vel, Math.abs(Math.sin(64 * 9/3000d)), false, 0, 0.2 + Math.abs(Math.cos(64 + 9/3000d))*0.6, 1, false);
for (int i = 50; i < 60; i++)
{
Item gem = _creeper.getWorld().dropItem(_creeper.getLocation().add(0.5, 1.5, 0.5), ItemStackFactory.Instance.CreateStack(Material.EMERALD, (byte) 0, 1, " " + i));
_items.add(gem);
Vector velo = new Vector(Math.sin(i * 8/5d), 0, Math.cos(i * 8/5d));
UtilAction.velocity(gem, velo, Math.abs(Math.sin(i * 8/3000d)), false, 0, 0.2 + Math.abs(Math.cos(i + 8/3000d))*0.6, 1, false);
}
}
finish();
}
if(_type instanceof Reward)
{
if(getTicks() == 0)
{
RewardData rewardData = ((Reward)_type).getFakeRewardData(_player);
ItemStack itemStack = rewardData.getDisplayItem();
Item item = _creeper.getWorld().dropItem(_creeper.getLocation().add(0.5, 1.7, 0.5), itemStack);
_items.add(item);
Vector vel = new Vector(_player.getLocation().getX() - _creeper.getLocation().getX(), 0, _player.getLocation().getZ() - _creeper.getLocation().getZ());
UtilAction.velocity(item, vel, 0.1, false, 0, 0.2 + 1*0.4, 1, false);
}
if(((Reward)_type).getRarity() == RewardRarity.RARE)
{
RareAnimation();
}
else if(((Reward)_type).getRarity() == RewardRarity.LEGENDARY)
{
LegendAnimation();
}
else if(((Reward)_type).getRarity() == RewardRarity.MYTHICAL)
{
MythicalAnimation();
}
else
{
finish();
}
}
}
@Override
protected void onFinish() {
_isDone = true;
setTicks(0);
}
public boolean isDone()
{
return _isDone;
}
public void setDone(boolean b)
{
_isDone = b;
}
public void setType(Object type)
{
_type = type;
}
public void setPlayer(Player player)
{
_player = player;
}
public void LegendAnimation()
{
if (getTicks() < 1)
{
UtilFirework.playFirework(_creeper.getLocation().add(0.5, 0.5, 0.5), Type.BALL_LARGE, Color.LIME, true, true);
}
if (getTicks() == 1)
{
_creeper.getLocation().getWorld().playSound(_creeper.getLocation().add(0.5, 0.5, 0.5), Sound.ENDERDRAGON_DEATH, 10F, 2.0F);
}
else if (getTicks() < 35)
{
double radius = 2 - (getTicks() / 10D * 2);
int particleAmount = 20 - (getTicks() * 2);
Location _centerLocation = _creeper.getLocation().add(0.5, 0.1, 0.5);
for (int i = 0; i < particleAmount; i++)
{
double xDiff = Math.sin(i/(double)particleAmount * 2 * Math.PI) * radius;
double zDiff = Math.cos(i/(double)particleAmount * 2 * Math.PI) * radius;
for(double e = 0.1 ; e < 3 ; e += 0.6)
{
Location location = _centerLocation.clone().add(xDiff, e, zDiff);
UtilParticle.PlayParticle(UtilParticle.ParticleType.HAPPY_VILLAGER, location, 0, 0, 0, 0, 1, ViewDist.NORMAL, UtilServer.getPlayers());
}
}
}
else
{
finish();
}
}
public void MythicalAnimation()
{
if (getTicks() < 30)
{
UtilFirework.playFirework(_creeper.getLocation().add(0.5, 0.5, 0.5), Type.BALL_LARGE, Color.RED, true, true);
}
if (getTicks() == 1)
{
_creeper.getLocation().getWorld().playSound(_creeper.getLocation().add(0.5, 0.5, 0.5), Sound.PORTAL_TRAVEL, 10F, 2.0F);
_creeper.getLocation().getWorld().playSound(_creeper.getLocation().add(0.5, 0.5, 0.5), Sound.ZOMBIE_UNFECT, 10F, 0.1F);
}
else if (getTicks() < 40)
{
UtilFirework.launchFirework(_creeper.getLocation().add(0.5, 0.5, 0.5), Type.BALL_LARGE, Color.RED, true, true,
new Vector((Math.random()-0.5)*0.05, 0.1, (Math.random()-0.5)*0.05), 1);
//Particle Spiral Up
double radius = getTicks() / 20D;
int particleAmount = getTicks() / 2;
for (int i = 0; i < particleAmount; i++)
{
double xDiff = Math.sin(i/(double)particleAmount * 2 * Math.PI) * radius;
double zDiff = Math.cos(i/(double)particleAmount * 2 * Math.PI) * radius;
Location location = _creeper.getLocation().add(0.5, 0, 0.5).clone().add(xDiff, -1.3, zDiff);
UtilParticle.PlayParticle(UtilParticle.ParticleType.WITCH_MAGIC, location, 0, 0, 0, 0, 1,
ViewDist.NORMAL, UtilServer.getPlayers());
}
Location _centerLocation = _creeper.getLocation().add(0.5, 0.1, 0.5);
for (int i = 0; i < particleAmount; i++)
{
double xDiff = Math.sin(i/(double)particleAmount * 2 * Math.PI) * radius;
double zDiff = Math.cos(i/(double)particleAmount * 2 * Math.PI) * radius;
for(double e = 0.1 ; e < 3 ; e += 0.5)
{
Location location = _centerLocation.clone().add(xDiff, e, zDiff);
UtilParticle.PlayParticle(UtilParticle.ParticleType.WITCH_MAGIC, location, 0, 0, 0, 0, 1, ViewDist.NORMAL, UtilServer.getPlayers());
}
}
}
else
{
finish();
}
}
public void RareAnimation()
{
if (getTicks() == 1)
{
for(int i = 0; i < 3; i++)
{
UtilFirework.playFirework(_creeper.getLocation().add(0.5, i, 0.5), Type.BALL, Color.FUCHSIA, false, false);
}
_creeper.getWorld().playSound(_creeper.getLocation(), Sound.WITHER_SPAWN, 10F, 1.2F);
}
else if (getTicks() >= 60)
{
finish();
}
else if (getTicks() < 35)
{
double radius = 2 - (getTicks() / 10D * 2);
int particleAmount = 20 - (getTicks() * 2);
Location _centerLocation = _creeper.getLocation().add(0.5, 0.1, 0.5);
for (int i = 0; i < particleAmount; i++)
{
double xDiff = Math.sin(i/(double)particleAmount * 2 * Math.PI) * radius;
double zDiff = Math.cos(i/(double)particleAmount * 2 * Math.PI) * radius;
for(double e = 0.1 ; e < 3 ; e += 0.6)
{
Location location = _centerLocation.clone().add(xDiff, e, zDiff);
UtilParticle.PlayParticle(UtilParticle.ParticleType.WITCH_MAGIC, location, 0, 0, 0, 0, 1, ViewDist.NORMAL, UtilServer.getPlayers());
}
}
}
}
public void itemClean()
{
Iterator<Item> itemIterator = _items.iterator();
while (itemIterator.hasNext())
{
Item item = itemIterator.next();
if (item.isOnGround() || !item.isValid() || item.getTicksLived() > 60)
{
item.remove();
itemIterator.remove();
}
}
}
}

View File

@ -0,0 +1,34 @@
package mineplex.core.bonuses.commands;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.reward.RewardType;
import mineplex.core.bonuses.BonusManager;
public class AnimationCommand extends CommandBase<BonusManager>{
private BonusManager _plugin;
public AnimationCommand(BonusManager plugin)
{
super(plugin, Rank.DEVELOPER, "animation");
_plugin = plugin;
}
@Override
public void Execute(Player caller, String[] args)
{
caller = Bukkit.getPlayer(args[0]);
_plugin.addPendingExplosion(caller, _plugin.getRewardManager().nextReward(caller, null, false, RewardType.SpinnerFiller, true));
if (args.length >= 2)
{
_plugin.addPendingExplosion(caller, args[1]);
}
}
}

View File

@ -0,0 +1,23 @@
package mineplex.core.bonuses.commands;
import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.bonuses.gui.BonusGui;
public class GuiCommand extends CommandBase<BonusManager>{
public GuiCommand(BonusManager plugin)
{
super(plugin, Rank.DEVELOPER, "bonus");
}
@Override
public void Execute(Player caller, String[] args)
{
new BonusGui(Plugin.getPlugin(), caller, Plugin, Plugin.getRewardManager()).openInventory();
}
}

View File

@ -0,0 +1,68 @@
package mineplex.core.bonuses.commands;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.bonuses.BonusManager;
import org.bukkit.entity.Player;
public class TicketCommand extends CommandBase<BonusManager>
{
public TicketCommand(BonusManager plugin)
{
super(plugin, Rank.ADMIN, "ticket");
}
@Override
public void Execute(final Player caller, String[] args)
{
if (args.length < 2)
{
UtilPlayer.message(caller, F.main("Carl", "Missing Args: " + F.elem("/ticket <player> <amount>")));
return;
}
final String targetName = args[0];
final String ticketString = args[1];
Player target = UtilPlayer.searchExact(targetName);
rewardTickets(caller, target, target.getName(), ticketString);
}
private void rewardTickets(final Player caller, final Player target, final String targetName, String ticketString)
{
try
{
final int tickets = Integer.parseInt(ticketString);
int accountId = Plugin.getClientManager().getAccountId(target);
Plugin.getRepository().attemptAddTickets(accountId, Plugin.Get(target), tickets, new Callback<Boolean>()
{
@Override
public void run(Boolean data)
{
if (data)
{
UtilPlayer.message(caller, F.main("Carl", "You gave " + F.elem(tickets + " Carl Tickets") + " to " + F.name(targetName) + "."));
if (target != null && !target.equals(caller))
{
UtilPlayer.message(target, F.main("Carl", F.name(caller.getName()) + " gave you " + F.elem(tickets + " Carl Tickets") + "."));
}
}
else
{
UtilPlayer.message(caller, F.main("Carl", "Failed to give tickets. Try again later!"));
}
}
});
}
catch (Exception e)
{
UtilPlayer.message(caller, F.main("Carl", "Invalid Ticket Amount"));
}
}
}

View File

@ -0,0 +1,54 @@
package mineplex.core.bonuses.event;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when a player attempts to purchase a spin through carl
*/
public class CarlSpinnerEvent extends Event implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
private Player _player;
private boolean _cancelled;
public CarlSpinnerEvent(Player player)
{
_player = player;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public Player getPlayer()
{
return _player;
}
public void setPlayer(Player player)
{
_player = player;
}
@Override
public boolean isCancelled()
{
return _cancelled;
}
@Override
public void setCancelled(boolean b)
{
_cancelled = b;
}
}

View File

@ -0,0 +1,42 @@
package mineplex.core.bonuses.gui;
import mineplex.core.gui.SimpleGui;
import mineplex.core.reward.RewardManager;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.bonuses.gui.buttons.CarlSpinButton;
import mineplex.core.bonuses.gui.buttons.DailyBonusButton;
import mineplex.core.bonuses.gui.buttons.PollButton;
import mineplex.core.bonuses.gui.buttons.RankBonusButton;
import mineplex.core.bonuses.gui.buttons.VoteButton;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class BonusGui extends SimpleGui
{
private BonusManager manager;
public BonusGui(Plugin plugin, Player player, BonusManager manager, RewardManager rewardManager)
{
super(plugin, player, player.getName() + "'s Bonuses", 5 * 9);
this.manager = manager;
setItem(10, new VoteButton(plugin, player, this, manager));
setItem(12, new RankBonusButton(getPlugin(), player, this, manager));
setItem(14, new DailyBonusButton(getPlugin(), player, this, manager));
setItem(16, new PollButton(getPlugin(), player, manager.getPollManager(), manager.getClientManager(), this, manager));
setItem(31, new CarlSpinButton(getPlugin(), player, manager, rewardManager));
}
@Override
protected void finalize() throws Throwable
{
super.finalize();
}
}

View File

@ -0,0 +1,280 @@
package mineplex.core.bonuses.gui;
import java.util.ArrayList;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.gui.DisplayItem;
import mineplex.core.gui.SimpleGui;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.reward.Reward;
import mineplex.core.reward.RewardData;
import mineplex.core.reward.RewardManager;
import mineplex.core.reward.RewardRarity;
import mineplex.core.reward.RewardType;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.bonuses.gui.buttons.RewardButton;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class SpinGui extends SimpleGui
{
private static final int HOPPER_SLOT = 4;
private static final int CARL_SLOT = 22;
private static final int[] LINE_NUMS = { /*-27, -18,*/ -9, 9/*, 18*/ };
private int _tickCount;
private RewardData _rewardData;
private Reward _reward;
private BonusManager _manager;
private int _currentRewardIndex;
private int _ticksThisSwap;
private int _ticksPerSwap;
private int _swapCount;
private Reward[] _rewards;
private boolean _stopped;
private boolean _rewarded;
private ArrayList<Integer> _ticks;
private int _frame;
private float _pitch;
private int _stopSpinnerAt;
public SpinGui(Plugin plugin, Player player, RewardManager rewardManager, BonusManager manager)
{
super(plugin, player, "Carl's Spinner", 27);
_manager = manager;
ShopItem carlItem = new ShopItem(Material.SKULL_ITEM, (byte) 4, "Carl's Spinner", new String[] {ChatColor.RESET + "Good Luck!" }, 1, false, false);
setItem(HOPPER_SLOT, new DisplayItem(new ItemStack(Material.HOPPER)));
//setItem(CARL_SLOT, new DisplayItem(carlItem));
_ticks = new ArrayList<>();
_frame = 0;
_pitch = 1;
_ticksPerSwap = 1;
for (int i=0 ; i<40 ; i++)
_ticks.add(1);
for (int i=0 ; i<20 ; i++)
_ticks.add(2);
for (int i=0 ; i<10 ; i++)
_ticks.add(4);
for (int i=0 ; i<4 ; i++)
_ticks.add(6);
for (int i=0 ; i<3 ; i++)
_ticks.add(8);
if (Math.random() > 0.5)
{
_ticks.add(12);
}
_stopSpinnerAt = _ticks.size();
//Create Rewards
_rewards = new Reward[_stopSpinnerAt+10]; //Adding 10, so theres items to the right still.
for (int i = 0; i < _stopSpinnerAt+10 ; i++)
{
if (i != _stopSpinnerAt + 4)
{
_rewards[i] = rewardManager.nextReward(player, null, false, RewardType.SpinnerFiller, true);
}
else
{
_rewards[i] = rewardManager.nextReward(player, null, false, RewardType.SpinnerReal, true);
_reward = _rewards[i];
}
}
_rewardData = _reward.giveReward("Carls Spinner", getPlayer());
}
private void tick()
{
if(_stopped)
return;
_ticksThisSwap++;
// Swap
if (_ticksThisSwap >= _ticksPerSwap)
{
_ticksThisSwap = 0;
_swapCount++;
if(_pitch == 1)
_pitch = (float) 1.5;
else if(_pitch == 1.5)
_pitch = 2;
else if(_pitch == 2)
_pitch = 1;
getPlayer().playSound(getPlayer().getEyeLocation(), Sound.NOTE_PLING, 1, _pitch);
_currentRewardIndex++;
updateGui();
// Slow
_ticksPerSwap = _ticks.get(_currentRewardIndex - 1);
if(_currentRewardIndex == _stopSpinnerAt)
_stopped = true;
}
_tickCount++;
}
public void updateGui()
{
for (int i = 0; i < 9; i++)
{
int index = _currentRewardIndex + i;
int slot = 9 + i;
RewardData data = _rewards[index].getFakeRewardData(getPlayer());
setItem(slot, new RewardButton(data));
// Glass Panes
for (int j = 0; j < LINE_NUMS.length; j++)
{
int paneSlot = slot + LINE_NUMS[j];
if (paneSlot == HOPPER_SLOT)
continue;
setItem(paneSlot, new DisplayItem(data.getRarity().getItemStack()));
}
}
}
@EventHandler
public void update(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
tick();
checkIfDone();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void close(InventoryCloseEvent event)
{
if(_rewarded)
return;
if(event.getPlayer() != getPlayer())
return;
_manager.addPendingExplosion(getPlayer(), _reward);
if (_reward.getRarity() == RewardRarity.RARE)
{
Bukkit.broadcastMessage(F.main("Treasure", F.name(event.getPlayer().getName()) + " won " + C.cPurple + "Rare " + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
else if (_reward.getRarity() == RewardRarity.LEGENDARY)
{
Bukkit.broadcastMessage(F.main("Treasure", F.name(event.getPlayer().getName()) + " won " + C.cGreen + "Legendary " + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
else if (_reward.getRarity() == RewardRarity.MYTHICAL)
{
Bukkit.broadcastMessage(F.main("Treasure", F.name(event.getPlayer().getName()) + " won " + C.cRed + "Mythical " + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
else
{
UtilPlayer.message(getPlayer(), F.main("Carl's Spinner", "You won " + _rewardData.getRarity().getColor() + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
}
@EventHandler
public void Glass(UpdateEvent event)
{
if (event.getType() != UpdateType.FAST)
return;
if(!_stopped)
return;
if(!_rewarded)
return;
if(_frame == 0)
{
setItem(CARL_SLOT, new DisplayItem(_rewardData.getRarity().getItemStack()));
setItem(HOPPER_SLOT, new DisplayItem(_rewardData.getRarity().getItemStack()));
_frame++;
}
else if(_frame < 5)
{
setItem(HOPPER_SLOT + _frame, new DisplayItem(_rewardData.getRarity().getItemStack()));
setItem(HOPPER_SLOT - _frame, new DisplayItem(_rewardData.getRarity().getItemStack()));
setItem(CARL_SLOT + _frame, new DisplayItem(_rewardData.getRarity().getItemStack()));
setItem(CARL_SLOT - _frame, new DisplayItem(_rewardData.getRarity().getItemStack()));
setItem(13 + _frame, new DisplayItem(_rewardData.getRarity().getItemStack()));
setItem(13 - _frame, new DisplayItem(_rewardData.getRarity().getItemStack()));
_frame++;
}
if(_frame == 6)
{
}
}
public void checkIfDone()
{
if(!_stopped)
return;
if(_rewarded)
return;
_manager.addPendingExplosion(getPlayer(), _reward);
if (_reward.getRarity() == RewardRarity.RARE)
{
Bukkit.broadcastMessage(F.main("Treasure", F.name(getPlayer().getName()) + " won " + C.cPurple + "Rare " + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
else if (_reward.getRarity() == RewardRarity.LEGENDARY)
{
Bukkit.broadcastMessage(F.main("Treasure", F.name(getPlayer().getName()) + " won " + C.cGreen + "Legendary " + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
else if (_reward.getRarity() == RewardRarity.MYTHICAL)
{
Bukkit.broadcastMessage(F.main("Treasure", F.name(getPlayer().getName()) + " won " + C.cRed + "Mythical " + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
else
{
UtilPlayer.message(getPlayer(), F.main("Carl's Spinner", "You won " + _rewardData.getRarity().getColor() + _rewardData.getFriendlyName() + C.cGray + " from Carl's Spinner."));
}
ItemStack item = getInventory().getItem(13);
getInventory().setItem(13, ItemStackFactory.Instance.CreateStack(item.getType(), (byte) 0, 1, _rewardData.getFriendlyName()));
_rewarded = true;
}
}

View File

@ -0,0 +1,85 @@
package mineplex.core.bonuses.gui.buttons;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import mineplex.core.common.util.C;
import mineplex.core.gui.GuiItem;
import mineplex.core.reward.RewardManager;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.bonuses.BonusClientData;
import mineplex.core.bonuses.BonusManager;
public class CarlSpinButton implements GuiItem
{
private Plugin _plugin;
private Player _player;
private BonusManager _bonusManager;
private RewardManager _rewardManager;
public CarlSpinButton(Plugin plugin, Player player, BonusManager bonusManager, RewardManager rewardManager)
{
_plugin = plugin;
_player = player;
_bonusManager = bonusManager;
_rewardManager = rewardManager;
}
@Override
public void setup()
{
}
@Override
public void close()
{
}
@Override
public void click(ClickType clickType)
{
BonusClientData client = _bonusManager.Get(_player);
int tickets = client.getTickets();
if (tickets > 0)
{
_bonusManager.attemptCarlSpin(_player);
}
// new SpinGui(_plugin, _player, _rewardManager).openInventory();
}
@Override
public ItemStack getObject()
{
BonusClientData client = _bonusManager.Get(_player);
int tickets = client.getTickets();
String name = (tickets > 0 ? C.cGreen : C.cRed) + C.Bold + "Carl's Spinner";
ArrayList<String> lore = new ArrayList<String>();
Material material = Material.SKULL_ITEM;
byte data = (byte) 4;
lore.add(" ");
if (tickets > 0)
{
lore.add(ChatColor.RESET + "Click to Spin");
}
else
{
lore.add(ChatColor.RESET + "You need a Carl Spin Ticket to Spin");
}
lore.add(" ");
lore.add(ChatColor.YELLOW + "Your Tickets: " + C.cWhite + tickets);
return new ShopItem(material, data, name, lore.toArray(new String[0]), 1, false, false);
}
}

View File

@ -0,0 +1,211 @@
package mineplex.core.bonuses.gui.buttons;
import java.util.ArrayList;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilTime;
import mineplex.core.common.util.UtilTime.TimeUnit;
import mineplex.core.gui.GuiItem;
import mineplex.core.gui.ItemRefresher;
import mineplex.core.gui.pages.LoadingWindow;
import mineplex.core.gui.pages.TimedMessageWindow;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.bonuses.BonusAmount;
import mineplex.core.bonuses.BonusClientData;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.bonuses.StreakRecord;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class DailyBonusButton implements GuiItem, Listener
{
private ItemStack _item;
private Player _player;
private Plugin _plugin;
private ItemRefresher _gui;
private BonusManager _bonusManager;
public DailyBonusButton(Plugin plugin, Player player, ItemRefresher gui, BonusManager bonusManager)
{
this._bonusManager = bonusManager;
this._player = player;
this._plugin = plugin;
this._gui = gui;
}
@Override
public void setup()
{
Bukkit.getPluginManager().registerEvents(this, getPlugin());
setItem();
}
@Override
public void close()
{
HandlerList.unregisterAll(this);
}
@Override
public void click(ClickType clickType)
{
if (isAvailable()) {
_item = ItemStackFactory.Instance.CreateStack(Material.LAPIS_BLOCK, (byte)0, 1, ChatColor.BLUE + "Processing...");
refreshItem();
new LoadingWindow(getPlugin(), getPlayer(), 6*9);
_bonusManager.attemptDailyBonus(getPlayer(), _bonusManager.getDailyBonusAmount(_player), new Callback<Boolean>() {
@Override
public void run(Boolean t)
{
if (t) {
setItem();
if (getPlayer().getOpenInventory() != null) {
new TimedMessageWindow(getPlugin(), getPlayer(), ItemStackFactory.Instance.CreateStack(Material.STAINED_GLASS_PANE, DyeColor.LIME.getData(), 1, ChatColor.GREEN + "Bonus collected!"), "Bonus collected!", 6*9, 20*3, getGui()).openInventory();
} else {
UtilPlayer.message(getPlayer(), F.main("Bonus", "Bonus collected!"));
}
_bonusManager.addPendingExplosion(getPlayer(), "DAILY");
getPlayer().playSound(getPlayer().getLocation(), Sound.NOTE_PLING, 1, 1.6f);
} else {
if (getPlayer().getOpenInventory() != null) {
new TimedMessageWindow(getPlugin(), getPlayer(), ItemStackFactory.Instance.CreateStack(Material.STAINED_GLASS_PANE, DyeColor.RED.getData(), 1, ChatColor.RED + "Failed to collect bonus!"), "Failed to collect bonus!", 6*9, 20*3, getGui()).openInventory();
} else {
UtilPlayer.message(getPlayer(), F.main("Bonus", "Failed to collect bonus!"));
}
getPlayer().playSound(getPlayer().getLocation(), Sound.ENDERDRAGON_GROWL, 1, 10);
}
getPlayer().closeInventory();
}
});
} else
getPlayer().playSound(getPlayer().getLocation(), Sound.ITEM_BREAK, 1, 10);
return;
}
@EventHandler
public void onUpdate(UpdateEvent event)
{
if (!event.getType().equals(UpdateType.SEC))
return;
// refreshItem(); // Todo Unnecessary?
}
private void setItem()
{
ArrayList<String> lore = new ArrayList<String>();
Material material;
String itemName;
byte data = 0;
if (isAvailable())
{
material = Material.CHEST;
itemName = C.cGreen + C.Bold + "Daily Reward";
lore.add(" ");
lore.add(ChatColor.RESET + "Click to Claim!");
}
else
{
material = Material.REDSTONE_BLOCK;
itemName = C.cRed + C.Bold + "Daily Reward";
lore.add(" ");
lore.add(ChatColor.RESET + "Next reward in " + UtilTime.convertString(timeLeft(), 0, TimeUnit.FIT) + "!");
}
lore.add(" ");
BonusClientData client = _bonusManager.Get(_player);
BonusAmount bonusAmount = _bonusManager.getDailyBonusAmount(_player);
bonusAmount.addLore(lore);
lore.add(" ");
lore.add(C.cYellow + "Current Streak: " + C.cWhite + client.getDailyStreak());
lore.add(C.cYellow + "Streak Bonus: " + C.cWhite + _bonusManager.getDailyMultiplier(_player) + "%");
lore.add(" ");
lore.add(C.cYellow + "Highest Streak: " + C.cWhite + client.getMaxDailyStreak());
if (client.getDailyTime() != null)
{
long lastBonus = _bonusManager.getLocalTime(client.getDailyTime().getTime());
long timeLeft = _bonusManager.getStreakTimeRemaining(lastBonus, BonusManager.DAILY_STREAK_RESET_TIME);
if (timeLeft > 0)
{
lore.add(C.cYellow + "Streak Reset: " + C.cWhite + UtilTime.convertString(timeLeft, 1, TimeUnit.FIT));
}
}
StreakRecord streakRecord = _bonusManager.getDailyStreak();
if (streakRecord != null)
{
lore.add(" ");
lore.add(C.cYellow + "Record: " + C.cWhite + streakRecord.getPlayerName());
lore.add(C.cYellow + "Streak: " + C.cWhite + streakRecord.getStreak());
}
_item = new ShopItem(material, itemName, lore.toArray(new String[0]), 1, false, false);
}
@Override
public ItemStack getObject()
{
return _item;
}
public void refreshItem()
{
getGui().refreshItem(this);
}
public long timeLeft()
{
long timeLeft = _bonusManager.nextDailyBonus(getPlayer()) - System.currentTimeMillis();
return timeLeft;
}
public boolean isAvailable()
{
return (timeLeft() <= 0);
}
public Plugin getPlugin()
{
return _plugin;
}
public Player getPlayer()
{
return _player;
}
public ItemRefresher getGui()
{
return _gui;
}
}

View File

@ -0,0 +1,219 @@
package mineplex.core.bonuses.gui.buttons;
import java.util.ArrayList;
import java.util.HashMap;
import mineplex.core.account.CoreClientManager;
import mineplex.core.bonuses.BonusAmount;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilText;
import mineplex.core.gui.GuiInventory;
import mineplex.core.gui.GuiItem;
import mineplex.core.gui.SimpleGui;
import mineplex.core.gui.SimpleGuiItem;
import mineplex.core.gui.botton.BackBotton;
import mineplex.core.gui.pages.TimedMessageWindow;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.poll.Poll;
import mineplex.core.poll.PollManager;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class PollButton extends SimpleGui implements GuiItem {
protected boolean _create;
private PollManager _pollManager;
private BonusManager _bonusManager;
private CoreClientManager _clientManager;
private GuiInventory _master;
private HashMap<Integer, GuiItem> hard = new HashMap<Integer, GuiItem>();
private Poll _poll;
public PollButton(Plugin plugin, Player player, PollManager pollManager, CoreClientManager clientManager, GuiInventory master, BonusManager bonusManager)
{
super(plugin, player, "Poll:", 6 * 9);
this._create = true;
this._master = master;
this._clientManager = clientManager;
this._pollManager = pollManager;
hard.put(0, new BackBotton(master));
_bonusManager = bonusManager;
}
@Override
public void setup()
{
if (_create)
{
this._poll = _pollManager.getNextPoll(_pollManager.Get(getPlayer()), _clientManager.Get(getPlayer()).GetRank());
if (_poll != null)
{
setItem(13, getQuestionItem(_poll.getQuestion()));
int[] slots = even(9, _poll.getAnswers().length);
for (int i = 0; i < slots.length; i++)
{
AnswerItem item = new AnswerItem(_poll, i);
setItem(9 * 3 + slots[i], item);
}
}
}
}
@Override
public ItemStack getObject()
{
ArrayList<String> lore = new ArrayList<>();
if (_poll == null)
{
lore.add("");
lore.add(C.cWhite + "You've voted on all of the polls!");
return ItemStackFactory.Instance.CreateStack(Material.REDSTONE_BLOCK, (byte) 0, 1, ChatColor.RED + C.Bold + "Vote on Poll", lore);
}
else
{
lore.add("");
lore.add(C.cWhite + _poll.getQuestion());
lore.add("");
int i = 1;
for(String str : _poll.getAnswers())
{
lore.add(C.cAqua + "" + i + ".) " + C.cWhite + str);
i++;
}
lore.add("");
BonusAmount amount = new BonusAmount();
amount.setCoins(_poll.getCoinReward());
amount.setGems(_poll.getCoinReward());
amount.addLore(lore);
// lore.add(C.cYellow + "Reward:" + C.cWhite + " 500 Gems");
lore.add("");
lore.add(C.cGreen + "Click to go to the vote page!");
return ItemStackFactory.Instance.CreateStack(Material.BOOK_AND_QUILL, (byte) 0, 1, C.cGreen + C.Bold + "Vote on Poll", lore);
}
}
@Override
public void click(ClickType clickType)
{
if (_poll == null)
{
getPlayer().playSound(getPlayer().getLocation(), Sound.ITEM_BREAK, 1, 1.6f);
}
else
{
getPlayer().playSound(getPlayer().getLocation(), Sound.NOTE_PLING, 1, 1.6f);
openInventory();
}
}
public GuiItem getQuestionItem(String question)
{
ArrayList<String> lore = new ArrayList<>();
lore.add("");
for (String string : wrap(question))
lore.add(C.cWhite + string);
lore.add("");
int i = 1;
for(String str : _poll.getAnswers())
{
lore.add(C.cAqua + "" + i + ".) " + C.cWhite + str);
i++;
}
lore.add("");
BonusAmount amount = new BonusAmount();
amount.setCoins(_poll.getCoinReward());
amount.setGems(_poll.getCoinReward());
amount.addLore(lore);
return new SimpleGuiItem(ItemStackFactory.Instance.CreateStack(Material.BOOK_AND_QUILL, (byte) 0, 1, ChatColor.GREEN + C.cGreen + C.Bold + "Vote on Poll",
lore));
}
public static String[] wrap(String text)
{
return UtilText.wrap(text, 40);
}
public static int[] even(int size, int amount)
{
int[] list = new int[amount];
float interval = (size / amount);
float offset = -(interval / 2);
for (int i = 1; i <= amount; i++)
{
list[i - 1] = (int) (Math.ceil(i * interval) + offset);
}
return list;
}
public Poll getPoll()
{
return _poll;
}
public GuiInventory getMaster()
{
return _master;
}
private class AnswerItem implements GuiItem
{
private int num;
private AnswerItem(Poll poll, int num)
{
this.num = num;
}
@Override
public ItemStack getObject()
{
ArrayList<String> lore = new ArrayList<>();
lore.add("");
lore.add(C.cWhite + getPoll().getAnswers()[num]);
return ItemStackFactory.Instance.CreateStack(Material.EMERALD, (byte) 0, 1, ChatColor.GREEN + "Option " + (num + 1), lore);
}
@Override
public void click(ClickType clickType)
{
_create = true;
_pollManager.answerPoll(getPlayer(), _poll, num + 1);
getPlayer().playSound(getPlayer().getLocation(), Sound.NOTE_PLING, 1, 1.6f);
new TimedMessageWindow(getPlugin(), getPlayer(), ItemStackFactory.Instance.CreateStack(Material.EMERALD_BLOCK, (byte) 0, 1, ChatColor.GREEN + "Your anwser:", wrap(getPoll().getAnswers()[num])), ChatColor.GREEN + "Moo", 6 * 9, 50, getMaster()).openInventory();
_bonusManager.addPendingExplosion(getPlayer(), "POLL");
getPlayer().closeInventory();
}
@Override
public void setup() {}
@Override
public void close() {}
}
@Override
public void close() {}
}

View File

@ -0,0 +1,242 @@
package mineplex.core.bonuses.gui.buttons;
import java.util.ArrayList;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilTime;
import mineplex.core.common.util.UtilTime.TimeUnit;
import mineplex.core.gui.GuiItem;
import mineplex.core.gui.ItemRefresher;
import mineplex.core.gui.pages.LoadingWindow;
import mineplex.core.gui.pages.TimedMessageWindow;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.bonuses.BonusAmount;
import mineplex.core.bonuses.BonusManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class RankBonusButton implements GuiItem, Listener {
private boolean hasRank;
private ItemStack _item;
private Player _player;
private Plugin _plugin;
private ItemRefresher _gui;
private BonusManager _bonusManager;
public RankBonusButton(Plugin plugin, Player player, ItemRefresher gui, BonusManager bonusManager)
{
this._bonusManager = bonusManager;
this._player = player;
this._plugin = plugin;
this._gui = gui;
}
@Override
public void setup()
{
if (_bonusManager.getRankBonusAmount(getPlayer()).isGreaterThanZero())
{
this.hasRank = true;
Bukkit.getPluginManager().registerEvents(this, getPlugin());
}
else
{
this.hasRank = false;
}
setItem();
}
@Override
public void close()
{
HandlerList.unregisterAll(this);
}
@Override
public void click(ClickType clickType)
{
if (isAvailable() && _bonusManager.isPastAugust()) {
_item = ItemStackFactory.Instance.CreateStack(Material.LAPIS_BLOCK, (byte)0, 1, ChatColor.BLUE + "Processing...");
refreshItem();
new LoadingWindow(getPlugin(), getPlayer(), 6*9);
_bonusManager.attemptRankBonus(getPlayer(), new Callback<Boolean>()
{
@Override
public void run(Boolean t)
{
setItem();
if (t)
{
if (getPlayer().getOpenInventory() != null)
{
new TimedMessageWindow(getPlugin(), getPlayer(), ItemStackFactory.Instance.CreateStack(Material.STAINED_GLASS_PANE, DyeColor.LIME.getData(), 1, ChatColor.GREEN + "Bonus collected!"), "Bonus collected!", 6 * 9, 20 * 3, getGui()).openInventory();
}
else
{
UtilPlayer.message(getPlayer(), F.main("Bonus", "Bonus collected!"));
}
_bonusManager.addPendingExplosion(getPlayer(), "RANK");
getPlayer().playSound(getPlayer().getLocation(), Sound.NOTE_PLING, 1, 1.6f);
}
else
{
if (getPlayer().getOpenInventory() != null)
{
new TimedMessageWindow(getPlugin(), getPlayer(), ItemStackFactory.Instance.CreateStack(Material.STAINED_GLASS_PANE, DyeColor.RED.getData(), 1, ChatColor.RED + "Failed to collect bonus!"), "Failed to collect bonus!", 6 * 9, 20 * 3, getGui()).openInventory();
}
else
{
UtilPlayer.message(getPlayer(), F.main("Bonus", "Failed to collect bonus!"));
}
getPlayer().playSound(getPlayer().getLocation(), Sound.ENDERDRAGON_GROWL, 1, 10);
}
getPlayer().closeInventory();
}
});
} else
getPlayer().playSound(getPlayer().getLocation(), Sound.ITEM_BREAK, 1, 10);
return;
}
@EventHandler
public void onUpdate(UpdateEvent event)
{
if (!event.getType().equals(UpdateType.SEC))
return;
// refreshItem(); // Todo Unnecessary?
}
@Override
public ItemStack getObject()
{
return _item;
}
private void setItem()
{
ArrayList<String> lore = new ArrayList<String>();
Material material;
String itemName;
byte data = 0;
if (_bonusManager.isPastAugust())
{
if (!hasRank)
{
material = Material.REDSTONE_BLOCK;
itemName = C.cRed + ChatColor.BOLD + "Rank Monthly Bonus";
lore.add(" ");
lore.add(ChatColor.WHITE + "Players with a Rank get a Monthly Bonus!");
lore.add(ChatColor.WHITE + "");
lore.add(ChatColor.AQUA + "Ultra receives 7500 Coins Monthly");
lore.add(ChatColor.LIGHT_PURPLE + "Hero receives 15000 Coins Monthly");
lore.add(ChatColor.GREEN + "Legend receives 30000 Coins Monthly");
lore.add(ChatColor.WHITE + "");
lore.add(ChatColor.WHITE + "Purchase a Rank at;");
lore.add(ChatColor.WHITE + "www.mineplex.com/shop");
}
else
{
if (isAvailable())
{
material = Material.ENDER_CHEST;
itemName = C.cGreen + C.Bold + "Rank Monthly Bonus";
lore.add(" ");
lore.add(ChatColor.RESET + "Click to Claim!");
}
else
{
material = Material.REDSTONE_BLOCK;
itemName = C.cRed + C.Bold + "Rank Monthly Bonus";
lore.add(" ");
lore.add(ChatColor.RESET + "Next reward in " + UtilTime.convertString(timeLeft(), 0, TimeUnit.FIT) + "!");
}
lore.add(" ");
lore.add(C.cYellow + "Rank: " + C.cWhite + _bonusManager.getClientManager().Get(_player).GetRank().Name);
BonusAmount bonusAmount = _bonusManager.getRankBonusAmount(_player);
bonusAmount.addLore(lore);
}
}
else
{
itemName = C.cRed + ChatColor.BOLD + "Rank Monthly Bonus";
material = Material.REDSTONE_BLOCK;
lore.add(" ");
lore.add(ChatColor.RESET + "You can claim your Monthly Bonus");
lore.add(ChatColor.RESET + "here, starting from September!");
}
_item = new ShopItem(material, itemName, lore.toArray(new String[0]), 1, false, false);
}
public void refreshItem()
{
_gui.refreshItem(this);
}
public long timeLeft()
{
return _bonusManager.nextRankBonus(getPlayer()) - System.currentTimeMillis();
}
public boolean isAvailable()
{
if (!hasRank)
{
UtilPlayer.message(getPlayer(), "----------------------------------------");
UtilPlayer.message(getPlayer(), "");
UtilPlayer.message(getPlayer(), "Purchase a Rank at the Mineplex Shop:");
UtilPlayer.message(getPlayer(), C.cGreen + "www.mineplex.com/shop");
UtilPlayer.message(getPlayer(), "");
UtilPlayer.message(getPlayer(), "----------------------------------------");
getPlayer().closeInventory();
return false;
}
return (timeLeft() <= 0);
}
public Plugin getPlugin()
{
return _plugin;
}
public Player getPlayer()
{
return _player;
}
public ItemRefresher getGui()
{
return _gui;
}
}

View File

@ -0,0 +1,46 @@
package mineplex.core.bonuses.gui.buttons;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import mineplex.core.gui.GuiItem;
import mineplex.core.reward.RewardData;
public class RewardButton implements GuiItem
{
private RewardData _data;
public RewardButton(RewardData data)
{
_data = data;
}
@Override
public void setup()
{
}
@Override
public void close()
{
}
@Override
public void click(ClickType clickType)
{
// Do nothing
}
@Override
public ItemStack getObject()
{
ItemStack stack = _data.getDisplayItem();
ItemMeta meta = stack.getItemMeta();
meta.setDisplayName(_data.getFriendlyName());
stack.setItemMeta(meta);
return stack;
}
}

View File

@ -0,0 +1,186 @@
package mineplex.core.bonuses.gui.buttons;
import java.util.ArrayList;
import mineplex.core.common.jsonchat.ClickEvent;
import mineplex.core.common.jsonchat.JsonMessage;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilTime;
import mineplex.core.common.util.UtilTime.TimeUnit;
import mineplex.core.gui.GuiItem;
import mineplex.core.gui.ItemRefresher;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.bonuses.BonusAmount;
import mineplex.core.bonuses.BonusClientData;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.bonuses.StreakRecord;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class VoteButton implements GuiItem, Listener {
private ItemStack _item;
private String _url;
private Player _player;
private Plugin _plugin;
private ItemRefresher _gui;
private BonusManager _bonusManager;
public VoteButton(Plugin plugin, Player player, ItemRefresher gui, BonusManager bonusManager)
{
this._bonusManager = bonusManager;
this._player = player;
this._plugin = plugin;
this._gui = gui;
}
@Override
public void setup()
{
//TODO get url from db
_url = _bonusManager.getVoteLink();
setItem();
Bukkit.getPluginManager().registerEvents(this, getPlugin());
}
@Override
public void close()
{
HandlerList.unregisterAll(this);
}
@Override
public void click(ClickType clickType)
{
if (isAvailable())
{
getPlayer().closeInventory();
getPlayer().playSound(getPlayer().getLocation(), Sound.NOTE_PLING, 1, 1.6f);
UtilPlayer.message(getPlayer(), "----------------------------------------------------");
UtilPlayer.message(getPlayer(), "");
new JsonMessage("Click to Open in Web Browser").click(ClickEvent.OPEN_URL, _url).sendToPlayer(getPlayer());
new JsonMessage(C.cGreen + _url).click(ClickEvent.OPEN_URL, _url).sendToPlayer(getPlayer());
UtilPlayer.message(getPlayer(), "");
UtilPlayer.message(getPlayer(), "Please be patient, votes may take a few minutes to register.");
UtilPlayer.message(getPlayer(), "");
UtilPlayer.message(getPlayer(), "----------------------------------------------------");
getPlayer().closeInventory();
}
else
{
getPlayer().playSound(getPlayer().getLocation(), Sound.ITEM_BREAK, 1, 10);
}
}
@Override
public ItemStack getObject()
{
return _item;
}
private void setItem()
{
ArrayList<String> lore = new ArrayList<String>();
Material material;
String itemName;
byte data = 0;
if (isAvailable())
{
material = Material.JUKEBOX;
itemName = C.cGreen + C.Bold + "Vote for Mineplex";
lore.add(" ");
lore.add(ChatColor.RESET + "Click to Vote!");
}
else
{
material = Material.REDSTONE_BLOCK;
itemName = C.cRed + C.Bold + "Vote for Mineplex";
lore.add(" ");
lore.add(ChatColor.RESET + "Next vote in " + UtilTime.convertString(timeLeft(), 0, TimeUnit.FIT) + "!");
}
lore.add(" ");
BonusClientData client = _bonusManager.Get(_player);
BonusAmount bonusAmount = _bonusManager.getVoteBonusAmount(_player);
bonusAmount.addLore(lore);
lore.add(" ");
lore.add(C.cYellow + "Current Streak: " + C.cWhite + client.getVoteStreak());
lore.add(C.cYellow + "Streak Bonus: " + C.cWhite + "+" + _bonusManager.getVoteMultiplyer(client.getVoteStreak()) + "%");
if (client.getVoteTime() != null)
{
long lastBonus = _bonusManager.getLocalTime(client.getVoteTime().getTime());
long timeLeft = _bonusManager.getStreakTimeRemaining(lastBonus, BonusManager.VOTE_STREAK_RESET_TIME);
if (timeLeft > 0)
{
lore.add(C.cYellow + "Streak Reset: " + C.cWhite + UtilTime.convertString(timeLeft, 1, TimeUnit.FIT));
}
}
lore.add(" ");
lore.add(C.cYellow + "Highest Streak: " + C.cWhite + client.getMaxVoteStreak());
StreakRecord streakRecord = _bonusManager.getVoteStreak();
if (streakRecord != null)
{
lore.add(" ");
lore.add(C.cYellow + "Record: " + C.cWhite + streakRecord.getPlayerName());
lore.add(C.cYellow + "Streak: " + C.cWhite + streakRecord.getStreak());
}
_item = new ShopItem(material, itemName, lore.toArray(new String[0]), 1, false, false);
}
public long timeLeft()
{
return _bonusManager.nextVoteTime(getPlayer()) - System.currentTimeMillis();
}
public boolean isAvailable()
{
if (_url == null)
return false;
return (timeLeft() <= 0);
}
public Plugin getPlugin()
{
return _plugin;
}
public Player getPlayer()
{
return _player;
}
public ItemRefresher getGui()
{
return _gui;
}
}

View File

@ -0,0 +1,31 @@
package mineplex.core.bonuses.redis;
import org.bukkit.entity.Player;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.common.util.UtilPlayer;
import mineplex.serverdata.commands.CommandCallback;
import mineplex.serverdata.commands.ServerCommand;
public class VoteHandler implements CommandCallback
{
private BonusManager _bonusManager;
public VoteHandler(BonusManager bonusManager)
{
_bonusManager = bonusManager;
}
@Override
public void run(ServerCommand command)
{
VotifierCommand v = ((VotifierCommand) command);
Player player = UtilPlayer.searchExact(v.getPlayerName());
if (player != null)
{
_bonusManager.handleVote(player, v.getGemsReceived());
}
}
}

View File

@ -0,0 +1,28 @@
package mineplex.core.bonuses.redis;
import mineplex.serverdata.commands.ServerCommand;
public class VotifierCommand extends ServerCommand
{
private String _playerName;
private int _gemsReceived;
public VotifierCommand(String playerName, int gemsReceived, String... targetServer)
{
super(targetServer);
_playerName = playerName;
_gemsReceived = gemsReceived;
}
public String getPlayerName()
{
return _playerName;
}
public int getGemsReceived()
{
return _gemsReceived;
}
}

View File

@ -0,0 +1,164 @@
package mineplex.core.botspam;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank;
import mineplex.core.message.PrivateMessageEvent;
import mineplex.core.punish.Category;
import mineplex.core.punish.Punish;
import mineplex.core.botspam.command.BotSpamCommand;
import mineplex.core.botspam.repository.BotSpamRepository;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class BotSpamManager extends MiniPlugin
{
private Punish _punish;
private CoreClientManager _clientManager;
private BotSpamRepository _repository;
private volatile ArrayList<SpamText> _spam = new ArrayList<SpamText>();
public BotSpamManager(JavaPlugin plugin, CoreClientManager clientManager, Punish punish)
{
super("SpamBot Manager", plugin);
_punish = punish;
_clientManager = clientManager;
_repository = new BotSpamRepository(plugin);
_spam = _repository.getSpamText();
}
@EventHandler
public void onPrivateMessage(PrivateMessageEvent event)
{
Player recipient = event.getRecipient();
// Ignore messages sent to staff members
if (_clientManager.hasRank(recipient, Rank.HELPER))
return;
for (SpamText spamText : _spam)
{
if (spamText.isEnabled() && spamText.isSpam(event.getMessage()))
{
punishBot(event.getSender(), spamText);
event.setCancelled(true);
return;
}
}
}
public void punishBot(Player player, final SpamText botText)
{
_punish.AddPunishment(player.getName(), Category.Other, "Bot Spam #" + botText.getId(), "Chiss", 1, true, -1, true);
// Update bot text count
runAsync(new Runnable()
{
@Override
public void run()
{
_repository.addPunishment(botText);
}
});
}
public void addSpamText(final String caller, final String text, final Runnable callback)
{
runAsync(new Runnable()
{
@Override
public void run()
{
_repository.addSpamText(caller, text);
_spam = _repository.getSpamText();
if (callback != null)
runSync(callback);
}
});
}
public void enableSpamText(final String caller, final SpamText spamText, final Runnable callback)
{
runAsync(new Runnable()
{
@Override
public void run()
{
_repository.enableSpamText(caller, spamText);
runSync(new Runnable()
{
@Override
public void run()
{
spamText.setEnabled(true);
spamText.setEnabledBy(caller);
if (callback != null)
callback.run();
}
});
}
});
}
public void disableSpamText(final String caller, final SpamText spamText, final Runnable callback)
{
runAsync(new Runnable()
{
@Override
public void run()
{
_repository.disableSpamText(caller, spamText);
runSync(new Runnable()
{
@Override
public void run()
{
spamText.setEnabled(false);
spamText.setDisabledBy(caller);
if (callback != null)
callback.run();
}
});
}
});
}
public List<SpamText> getSpamTexts()
{
return _spam;
}
@EventHandler
public void updateText(UpdateEvent event)
{
if (event.getType() == UpdateType.MIN_01)
{
runAsync(new Runnable()
{
@Override
public void run()
{
_spam = _repository.getSpamText();
}
});
}
}
@Override
public void addCommands()
{
addCommand(new BotSpamCommand(this));
}
}

View File

@ -0,0 +1,78 @@
package mineplex.core.botspam;
public class SpamText
{
private int _id;
private String _text;
private int _punishments;
private boolean _enabled;
private String _createdBy;
private String _disabledBy;
private String _enabledBy;
public SpamText(int id, String text, int punishments, boolean enabled, String createdBy, String enabledBy, String disabledBy)
{
_id = id;
_text = text;
_punishments = punishments;
_enabled = enabled;
_createdBy = createdBy;
_enabledBy = enabledBy;
_disabledBy = disabledBy;
}
public boolean isSpam(String message)
{
return message.toLowerCase().contains(_text.toLowerCase());
}
public int getId()
{
return _id;
}
public String getText()
{
return _text;
}
public int getPunishments()
{
return _punishments;
}
public boolean isEnabled()
{
return _enabled;
}
public void setEnabled(boolean enabled)
{
_enabled = enabled;
}
public String getCreatedBy()
{
return _createdBy;
}
public String getEnabledBy()
{
return _enabledBy;
}
public String getDisabledBy()
{
return _disabledBy;
}
public void setEnabledBy(String enabledBy)
{
_enabledBy = enabledBy;
}
public void setDisabledBy(String disabledBy)
{
_disabledBy = disabledBy;
}
}

View File

@ -0,0 +1,64 @@
package mineplex.core.botspam.command;
import org.bukkit.entity.Player;
import mineplex.core.botspam.SpamText;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.botspam.BotSpamManager;
public class BotSpamAddCommand extends CommandBase<BotSpamManager>
{
public BotSpamAddCommand(BotSpamManager plugin)
{
super(plugin, Rank.DEVELOPER, "add");
}
@Override
public void Execute(final Player caller, String[] args)
{
if (args != null && args.length >= 1)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++)
{
if (i > 0) sb.append(" ");
sb.append(args[i]);
}
final String text = sb.toString();
if (text.length() < 8)
{
UtilPlayer.message(caller, F.main("BotSpam", "Spam text must be at least 8 characters"));
return;
}
for (SpamText spamText : Plugin.getSpamTexts())
{
if (text.equalsIgnoreCase(spamText.getText()))
{
UtilPlayer.message(caller, F.main("BotSpam", "That Spam Text already exists. Type " + F.elem("/botspam list") + " to view"));
return;
}
}
Plugin.addSpamText(caller.getName(), text, new Runnable()
{
@Override
public void run()
{
if (caller.isOnline())
UtilPlayer.message(caller, F.main("BotSpam", "Added Spam Text: " + F.elem(text)));
}
});
}
else
{
UtilPlayer.message(caller, F.main("BotSpam", "/botspam add <text>"));
}
}
}

View File

@ -0,0 +1,31 @@
package mineplex.core.botspam.command;
import org.bukkit.entity.Player;
import mineplex.core.command.MultiCommandBase;
import mineplex.core.common.Rank;
import mineplex.core.botspam.BotSpamManager;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
public class BotSpamCommand extends MultiCommandBase<BotSpamManager>
{
public BotSpamCommand(BotSpamManager plugin)
{
super(plugin, Rank.DEVELOPER, "botban", "botspam");
AddCommand(new BotSpamAddCommand(Plugin));
AddCommand(new BotSpamEnableCommand(Plugin));
AddCommand(new BotSpamDisableCommand(Plugin));
AddCommand(new BotSpamListCommand(Plugin));
}
@Override
protected void Help(Player caller, String[] args)
{
UtilPlayer.message(caller, F.main("BotSpam", "/botspam list"));
UtilPlayer.message(caller, F.main("BotSpam", "/botspam add <text>"));
UtilPlayer.message(caller, F.main("BotSpam", "/botspam enable <text id>"));
UtilPlayer.message(caller, F.main("BotSpam", "/botspam disable <text id>"));
}
}

View File

@ -0,0 +1,71 @@
package mineplex.core.botspam.command;
import org.bukkit.entity.Player;
import mineplex.core.botspam.SpamText;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.botspam.BotSpamManager;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
public class BotSpamDisableCommand extends CommandBase<BotSpamManager>
{
public BotSpamDisableCommand(BotSpamManager plugin)
{
super(plugin, Rank.DEVELOPER, "disable");
}
@Override
public void Execute(final Player caller, String[] args)
{
if (args != null && args.length == 1)
{
final int spamId;
try
{
spamId = Integer.parseInt(args[0]);
}
catch (Exception e)
{
UtilPlayer.message(caller, F.main("BotSpam", "/botspam disable <text id>"));
return;
}
SpamText text = null;
for (SpamText spamText : Plugin.getSpamTexts())
{
if (spamText.getId() == spamId)
text = spamText;
}
if (text == null)
{
UtilPlayer.message(caller, F.main("BotSpam", "Could not find a spam text with the id " + F.elem("" + spamId)));
return;
}
if (!text.isEnabled())
{
UtilPlayer.message(caller, F.main("BotSpam", "That spam text is already disabled"));
return;
}
final SpamText finalText = text;
Plugin.disableSpamText(caller.getName(), text, new Runnable()
{
@Override
public void run()
{
UtilPlayer.message(caller, F.main("BotSpam", "Disabled Spam Text " + F.elem(finalText.getText())));
}
});
}
else
{
UtilPlayer.message(caller, F.main("BotSpam", "/botspam disable <text id>"));
}
}
}

View File

@ -0,0 +1,71 @@
package mineplex.core.botspam.command;
import org.bukkit.entity.Player;
import mineplex.core.botspam.SpamText;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.botspam.BotSpamManager;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
public class BotSpamEnableCommand extends CommandBase<BotSpamManager>
{
public BotSpamEnableCommand(BotSpamManager plugin)
{
super(plugin, Rank.DEVELOPER, "enable");
}
@Override
public void Execute(final Player caller, String[] args)
{
if (args != null && args.length == 1)
{
final int spamId;
try
{
spamId = Integer.parseInt(args[0]);
}
catch (Exception e)
{
UtilPlayer.message(caller, F.main("BotSpam", "/botspam enable <text id>"));
return;
}
SpamText text = null;
for (SpamText spamText : Plugin.getSpamTexts())
{
if (spamText.getId() == spamId)
text = spamText;
}
if (text == null)
{
UtilPlayer.message(caller, F.main("BotSpam", "Could not find a spam text with the id " + F.elem("" + spamId)));
return;
}
if (text.isEnabled())
{
UtilPlayer.message(caller, F.main("BotSpam", "That spam text is already enabled"));
return;
}
final SpamText finalText = text;
Plugin.enableSpamText(caller.getName(), text, new Runnable()
{
@Override
public void run()
{
UtilPlayer.message(caller, F.main("BotSpam", "Enabled Spam Text " + F.elem(finalText.getText())));
}
});
}
else
{
UtilPlayer.message(caller, F.main("BotSpam", "/botspam enable <text id>"));
}
}
}

View File

@ -0,0 +1,46 @@
package mineplex.core.botspam.command;
import org.bukkit.entity.Player;
import mineplex.core.botspam.SpamText;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.botspam.BotSpamManager;
import mineplex.core.common.jsonchat.ClickEvent;
import mineplex.core.common.jsonchat.HoverEvent;
import mineplex.core.common.jsonchat.JsonMessage;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
public class BotSpamListCommand extends CommandBase<BotSpamManager>
{
public BotSpamListCommand(BotSpamManager plugin)
{
super(plugin, Rank.DEVELOPER, "list");
}
@Override
public void Execute(Player caller, String[] args)
{
UtilPlayer.message(caller, F.main("BotSpam", "Listing Spam Texts. Hover for more details"));
UtilPlayer.message(caller, ""); // Blank Line!
for (SpamText spamText : Plugin.getSpamTexts())
{
String modifyMessage = spamText.isEnabled() ? C.cRed + "Click To Disable" : C.cGreen + "Click To Enable";
String hoverMessage = C.cYellow + "Spam Id: " + C.cWhite + spamText.getId() + "\\n" + C.cYellow + "Ban Count: " + C.cWhite + spamText.getPunishments() + "\\n" + C.cYellow + "Enabled: " + C.cWhite + spamText.isEnabled();
hoverMessage += "\\n\\n" + C.cYellow + "Created By: " + C.cWhite + spamText.getCreatedBy();
if (spamText.getEnabledBy() != null)
hoverMessage += "\\n" + C.cYellow + "Enabled By: " + C.cWhite + spamText.getEnabledBy();
if (spamText.getDisabledBy() != null)
hoverMessage += "\\n" + C.cYellow + "Disabled By: " + C.cWhite + spamText.getDisabledBy();
hoverMessage += "\\n\\n" + modifyMessage;
JsonMessage message = new JsonMessage((spamText.isEnabled() ? "" : C.cRed) + spamText.getText());
message.hover(HoverEvent.SHOW_TEXT, hoverMessage);
message.click(ClickEvent.RUN_COMMAND, "/botspam " + (spamText.isEnabled() ? "disable" : "enable") + " " + spamText.getId());
message.send(JsonMessage.MessageType.SYSTEM_MESSAGE, caller);
}
}
}

View File

@ -0,0 +1,88 @@
package mineplex.core.botspam.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.botspam.SpamText;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnInt;
import mineplex.core.database.column.ColumnVarChar;
public class BotSpamRepository extends RepositoryBase
{
private static final String GET_SPAM_TEXT = "SELECT * FROM botSpam";
private static final String ADD_SPAM_TEXT = "INSERT INTO botSpam (text, createdBy, enabledBy) VALUES (?, ?, ?)";
private static final String DELETE_SPAM_TEXT = "DELETE FROM botSpam WHERE id = ?";
private static final String ENABLE_SPAM_TEXT = "UPDATE botSpam SET enabled = 1, enabledBy = ? WHERE id = ?";
private static final String DISABLE_SPAM_TEXT = "UPDATE botSpam SET enabled = 0 AND disabledBy = ? WHERE id = ?";
private static final String ADD_PUNISHMENT = "UPDATE botSpam SET punishments = punishments + 1 WHERE id = ?";
public BotSpamRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
}
public ArrayList<SpamText> getSpamText()
{
final ArrayList<SpamText> list = new ArrayList<SpamText>();
executeQuery(GET_SPAM_TEXT, new ResultSetCallable()
{
@Override
public void processResultSet(ResultSet resultSet) throws SQLException
{
while (resultSet.next())
{
int id = resultSet.getInt(1);
String text = resultSet.getString(2);
int punishments = resultSet.getInt(3);
boolean enabled = resultSet.getBoolean(4);
String createdBy = resultSet.getString(5);
String enabledBy = resultSet.getString(6);
String disabledBy = resultSet.getString(7);
list.add(new SpamText(id, text, punishments, enabled, createdBy, enabledBy, disabledBy));
}
}
});
return list;
}
public void addPunishment(SpamText text)
{
executeUpdate(ADD_PUNISHMENT, new ColumnInt("id", text.getId()));
}
public void disableSpamText(String caller, SpamText text)
{
executeUpdate(DISABLE_SPAM_TEXT, new ColumnVarChar("disabledBy", 100, caller), new ColumnInt("id", text.getId()));
}
public void enableSpamText(String caller, SpamText text)
{
executeUpdate(ENABLE_SPAM_TEXT, new ColumnVarChar("enabledBy", 100, caller), new ColumnInt("id", text.getId()));
}
public void addSpamText(String caller, String spamText)
{
executeInsert(ADD_SPAM_TEXT, null, new ColumnVarChar("text", 200, spamText), new ColumnVarChar("createdBy", 100, caller), new ColumnVarChar("enabledBy", 100, caller));
}
@Override
protected void initialize()
{
}
@Override
protected void update()
{
}
}

View File

@ -176,7 +176,7 @@ public class Chat extends MiniPlugin
if (_silenced == 0)
return false;
if (_clientManager.Get(player).GetRank().Has(player, Rank.MODERATOR, false))
if (_clientManager.Get(player).GetRank().has(player, Rank.MODERATOR, false))
return false;
if (_silenced == -1)
@ -210,7 +210,7 @@ public class Chat extends MiniPlugin
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event)
{
if (_clientManager.Get(event.getPlayer()).GetRank().Has(Rank.ADMIN)) return;
if (_clientManager.Get(event.getPlayer()).GetRank().has(Rank.ADMIN)) return;
// Prevent silenced players from using signs
if (SilenceCheck(event.getPlayer()))
@ -317,13 +317,13 @@ public class Chat extends MiniPlugin
UtilPlayer.message(sender, C.cYellow + "Buy a Rank at " + C.cGreen + "www.mineplex.com/shop" + C.cYellow + " to remove this limit!");
event.setCancelled(true);
}
else if (!_clientManager.Get(sender).GetRank().Has(Rank.MODERATOR) &&
else if (!_clientManager.Get(sender).GetRank().has(Rank.MODERATOR) &&
!Recharge.Instance.use(sender, "Chat Message", 400, false, false))
{
UtilPlayer.message(sender, F.main("Chat", "You are sending messages too fast."));
event.setCancelled(true);
}
else if (!_clientManager.Get(sender).GetRank().Has(Rank.HELPER) &&
else if (!_clientManager.Get(sender).GetRank().has(Rank.HELPER) &&
msgContainsHack(event.getMessage()))
{
UtilPlayer.message(sender, F.main("Chat",
@ -337,12 +337,12 @@ public class Chat extends MiniPlugin
MessageData lastMessage = _playerLastMessage.get(sender.getUniqueId());
long chatSlowTime = 1000L * _chatSlow;
long timeDiff = System.currentTimeMillis() - lastMessage.getTimeSent();
if (timeDiff < chatSlowTime && !_clientManager.Get(sender).GetRank().Has(Rank.HELPER))
if (timeDiff < chatSlowTime && !_clientManager.Get(sender).GetRank().has(Rank.HELPER))
{
UtilPlayer.message(sender, F.main("Chat", "Chat slow enabled. Please wait " + F.time(UtilTime.convertString(chatSlowTime - timeDiff, 1, UtilTime.TimeUnit.FIT))));
event.setCancelled(true);
}
else if (!_clientManager.Get(sender).GetRank().Has(Rank.MODERATOR) &&
else if (!_clientManager.Get(sender).GetRank().has(Rank.MODERATOR) &&
UtilText.isStringSimilar(event.getMessage(), lastMessage.getMessage(), 0.8f))
{
UtilPlayer.message(sender, F.main("Chat", "This message is too similar to your previous message."));

View File

@ -18,7 +18,7 @@ public class ChatSlowCommand extends CommandBase<Chat>
@Override
public void Execute(Player caller, String[] args)
{
if (args != null && args.length == 1)
if (args.length == 1)
{
try
{

View File

@ -48,7 +48,7 @@ public class CommandCenter implements Listener
public void OnPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
String commandName = event.getMessage().substring(1);
String[] args = null;
String[] args = new String[] {};
if (commandName.contains(" "))
{
@ -62,7 +62,7 @@ public class CommandCenter implements Listener
{
event.setCancelled(true);
if (ClientManager.Get(event.getPlayer()).GetRank().Has(event.getPlayer(), command.GetRequiredRank(), command.GetSpecificRanks(), true))
if (ClientManager.Get(event.getPlayer()).GetRank().has(event.getPlayer(), command.GetRequiredRank(), command.GetSpecificRanks(), true))
{
if (!Recharge.Instance.use(event.getPlayer(), "Command", 500, false, false))
{
@ -76,19 +76,6 @@ public class CommandCenter implements Listener
}
}
@EventHandler
public void onTabComplete(TabCompleteEvent event)
{
ICommand command = Commands.get(event.getCommand().toLowerCase());
if (command != null)
{
List<String> suggestions = command.onTabComplete(event.getSender(), event.getCommand(), event.getArgs());
if (suggestions != null)
event.setSuggestions(suggestions);
}
}
public void AddCommand(ICommand command)
{

View File

@ -40,7 +40,7 @@ public abstract class MultiCommandBase<PluginType extends MiniPlugin> extends Co
public void Execute(Player caller, String[] args)
{
String commandName = null;
String[] newArgs = null;
String[] newArgs = new String[] {};
if (args != null && args.length > 0)
{
@ -59,7 +59,7 @@ public abstract class MultiCommandBase<PluginType extends MiniPlugin> extends Co
ICommand command = Commands.get(commandName);
if (command != null && CommandCenter.ClientManager.Get(caller).GetRank().Has(caller, command.GetRequiredRank(), command.GetSpecificRanks(), true))
if (command != null && CommandCenter.ClientManager.Get(caller).GetRank().has(caller, command.GetRequiredRank(), command.GetSpecificRanks(), true))
{
command.SetAliasUsed(commandName);

View File

@ -19,6 +19,9 @@ import mineplex.core.common.util.UtilServer;
import mineplex.core.cosmetic.ui.CosmeticShop;
import mineplex.core.donation.DonationManager;
import mineplex.core.gadget.GadgetManager;
import mineplex.core.gadget.gadgets.OutfitTeam;
import mineplex.core.gadget.types.Gadget;
import mineplex.core.gadget.types.GadgetType;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.mount.MountManager;
@ -191,4 +194,15 @@ public class CosmeticManager extends MiniPlugin
{
return _treasureManager;
}
public void disableTeamArmor()
{
for (Gadget gadget : getGadgetManager().getGadgets(GadgetType.Costume))
{
if (gadget instanceof OutfitTeam)
{
((OutfitTeam)gadget).setEnabled(false);
}
}
}
}

View File

@ -6,6 +6,7 @@ import org.bukkit.entity.Creature;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.CurrencyType;
@ -20,6 +21,7 @@ import mineplex.core.cosmetic.ui.button.OpenMusic;
import mineplex.core.cosmetic.ui.button.OpenParticles;
import mineplex.core.cosmetic.ui.button.OpenPets;
import mineplex.core.donation.DonationManager;
import mineplex.core.donation.Donor;
import mineplex.core.gadget.types.Gadget;
import mineplex.core.gadget.types.GadgetType;
import mineplex.core.mount.Mount;
@ -41,6 +43,13 @@ public class Menu extends ShopPageBase<CosmeticManager, CosmeticShop>
@Override
protected void buildPage()
{
Donor donor = getDonationManager().Get(getPlayer());
// addItem(2, new ShopItem(CurrencyType.Gems.GetDisplayMaterial(), donor.GetGems() + " Gems", new String[] {
// " "
// }, 1, false));
addItem(4, new ShopItem(175, getDonationManager().Get(getPlayer().getName()).getCoins() + " Coins", new String[]
{
" ",
@ -54,9 +63,13 @@ public class Menu extends ShopPageBase<CosmeticManager, CosmeticShop>
ChatColor.RESET + "Receives 15000 Coins per Month",
" ",
ChatColor.RESET + C.cGreen + "Legend Rank",
ChatColor.RESET + "Recieves 30000 Coins per Month"
ChatColor.RESET + "Receives 30000 Coins per Month"
}, 1, false));
// addItem(6, new ShopItem(Material.GOLD_INGOT, donor.getGold() + " Gold", new String[] {
// " "
// }, 1, false));
addButton(18, new ShopItem(Material.NETHER_STAR, "Particle Effects", 1, false), new OpenParticles(this));
addButton(20, new ShopItem(Material.BOW, "Gadgets", 1, false), new OpenGadgets(this));
addButton(22, new ShopItem(Material.LEATHER, "Morphs", 1, false), new OpenMorphs(this));

View File

@ -37,7 +37,7 @@ public class MobCommand extends MultiCommandBase<Creature>
@Override
protected void Help(Player caller, String[] args)
{
if (args == null)
if (args == null || args.length == 0)
{
HashMap<EntityType, Integer> entMap = new HashMap<EntityType, Integer>();

View File

@ -13,6 +13,9 @@ import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.column.Column;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
@ -62,6 +65,11 @@ public abstract class RepositoryBase implements Listener
return _dataSource;
}
protected DSLContext jooq()
{
return DSL.using(DBPool.ACCOUNT, SQLDialect.MYSQL);
}
/**
* Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool!
* @see Connection#close()

View File

@ -442,7 +442,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
return new PacketPlayOutMapChunk(_bedChunk, true, 0, UtilPlayer.is1_8(player) ? 48 : 0);
}
private Packet[] getBedPackets(Location recieving, DisguisePlayer playerDisguise)
private Packet[] getBedPackets(Location recieving, DisguisePlayer playerDisguise, boolean is18)
{
try
{
@ -458,7 +458,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport(playerDisguise.GetEntity());
teleportPacket.c += (int) (0.35D * 32);
teleportPacket.c += (int) ((is18 ? 0.07D : 0.25D) * 32);
return new Packet[]
{
@ -502,7 +502,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
&& ((DisguisePlayer) entry.getKey()).getSleepingDirection() != null)
{
packets.addAll(Arrays.asList(getBedPackets(newLoc, (DisguisePlayer) entry.getKey())));
packets.addAll(Arrays.asList(getBedPackets(newLoc, (DisguisePlayer) entry.getKey(), UtilPlayer.is1_8(player))));
}
}
}
@ -853,7 +853,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
if (pDisguise.getSleepingDirection() != null)
{
for (Packet packet : getBedPackets(player.getLocation(), pDisguise))
for (Packet packet : getBedPackets(player.getLocation(), pDisguise, UtilPlayer.is1_8(player)))
{
handlePacket(packet, packetVerifier);
}

View File

@ -30,9 +30,9 @@ public abstract class DisguiseInsentient extends DisguiseLiving
{
if (rank != null)
{
if (rank.Has(Rank.ULTRA))
if (rank.has(Rank.ULTRA))
{
name = rank.GetTag(true, true) + " " + ChatColor.RESET + name;
name = rank.getTag(true, true) + " " + ChatColor.RESET + name;
}
}

View File

@ -24,6 +24,7 @@ import mineplex.core.donation.repository.token.DonorTokenWrapper;
import mineplex.core.server.util.TransactionResponse;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.playerCache.PlayerCache;
public class DonationManager extends MiniDbClientPlugin<Donor>
{
@ -279,7 +280,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
{
public void run()
{
RewardCoins(null, caller, player.getName(), ClientManager.getCachedClientAccountId(player.getUniqueId()), total, false);
RewardCoins(null, caller, player.getName(), PlayerCache.getInstance().getPlayer(player.getUniqueId()).getAccountId(), total, false);
}
});
}

View File

@ -24,7 +24,7 @@ public class GemCommand extends CommandBase<DonationManager>
{
if (args.length < 2)
{
UtilPlayer.message(caller, F.main("gem", "Missing Args: " + F.elem("/gem <player> <amount>")));
UtilPlayer.message(caller, F.main("Gem", "Missing Args: " + F.elem("/gem <player> <amount>")));
return;
}
@ -59,7 +59,7 @@ public class GemCommand extends CommandBase<DonationManager>
}
catch (Exception e)
{
UtilPlayer.message(caller, F.main("gem", "Invalid gems Amount"));
UtilPlayer.message(caller, F.main("Gem", "Invalid gems Amount"));
}
}
@ -71,16 +71,16 @@ public class GemCommand extends CommandBase<DonationManager>
{
if (completed)
{
UtilPlayer.message(caller, F.main("gem", "You gave " + F.elem(gems + " gems") + " to " + F.name(targetName) + "."));
UtilPlayer.message(caller, F.main("Gem", "You gave " + F.elem(gems + " gems") + " to " + F.name(targetName) + "."));
if (target != null)
{
UtilPlayer.message(target, F.main("gem", F.name(caller.getName()) + " gave you " + F.elem(gems + " gems") + "."));
UtilPlayer.message(target, F.main("Gem", F.name(caller.getName()) + " gave you " + F.elem(gems + " gems") + "."));
}
}
else
{
UtilPlayer.message(caller, F.main("gem", "There was an error giving " + F.elem(gems + " gems") + " to " + F.name(targetName) + "."));
UtilPlayer.message(caller, F.main("Gem", "There was an error giving " + F.elem(gems + " gems") + " to " + F.name(targetName) + "."));
}
}
}, caller.getName(), targetName, uuid, gems);

View File

@ -23,6 +23,7 @@ public class GoldCommand extends CommandBase<DonationManager>
if (args == null || args.length == 0)
{
UtilPlayer.message(caller, F.main("Gold", "Your Gold: " + F.elem("" + Plugin.Get(caller).getGold())));
return;
}
else if (args.length < 2)
{

View File

@ -251,7 +251,7 @@ public class FriendManager extends MiniDbClientPlugin<FriendData>
public void showFriends(Player caller)
{
boolean isStaff = ClientManager.Get(caller).GetRank().Has(Rank.HELPER);
boolean isStaff = ClientManager.Get(caller).GetRank().has(Rank.HELPER);
boolean gotAFriend = false;
List<FriendStatus> friendStatuses = Get(caller).getFriends();
Collections.sort(friendStatuses, _friendSorter);

View File

@ -159,7 +159,7 @@ public class FriendRepository extends RepositoryBase
Set<String> friendNames = new HashSet<String>();
for(FriendStatus status : friendData.getFriends())
{
friendNames.add(status.Name);
friendNames.add(status.Name.toLowerCase());
}
// Load PlayerStatus' for friends
@ -188,7 +188,7 @@ public class FriendRepository extends RepositoryBase
*/
public String fetchPlayerServer(String playerName)
{
PlayerStatus status = _repository.getElement(playerName);
PlayerStatus status = _repository.getElement(playerName.toLowerCase());
return (status == null) ? null : status.getServer();
}

View File

@ -92,7 +92,7 @@ public class GadgetManager extends MiniPlugin
addGadget(new ItemTNT(this));
addGadget(new ItemMelonLauncher(this));
addGadget(new ItemFleshHook(this));
//addGadget(new ItemPaintballGun(this));
addGadget(new ItemPaintballGun(this));
addGadget(new ItemBatGun(this));
addGadget(new ItemCoinBomb(this));
addGadget(new ItemPaintbrush(this));
@ -166,11 +166,11 @@ public class GadgetManager extends MiniPlugin
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
if (_clientManager.Get(event.getPlayer()).GetRank().Has(Rank.MODERATOR))
if (_clientManager.Get(event.getPlayer()).GetRank().has(Rank.MODERATOR))
{
for (GadgetType gadgetType : _gadgets.keySet())
{
if (gadgetType == GadgetType.Particle && _clientManager.Get(event.getPlayer()).GetRank().Has(Rank.ADMIN))
if (gadgetType == GadgetType.Particle && _clientManager.Get(event.getPlayer()).GetRank().has(Rank.ADMIN))
{
for (Gadget gadget : _gadgets.get(gadgetType))
{
@ -455,12 +455,16 @@ public class GadgetManager extends MiniPlugin
@EventHandler
public void chissMeow(PlayerToggleSneakEvent event)
{
if (event.getPlayer().getName().equals("Chiss"))
{
if (!event.getPlayer().isSneaking())
{
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.CAT_MEOW, 1f, 1f);
}
}
if (event.getPlayer().isSneaking())
return;
if (event.getPlayer().getName().equalsIgnoreCase("Chiss"))
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.CAT_MEOW, 1f, 1f);
if (event.getPlayer().getName().equalsIgnoreCase("defek7"))
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.WOLF_BARK, 1f, 1f);
if (event.getPlayer().getName().equalsIgnoreCase("sterling_"))
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.PIG_IDLE, 1f, 1f);
}
}

View File

@ -18,9 +18,15 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.util.Vector;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilBlock;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilParticle.ParticleType;
import mineplex.core.common.util.UtilParticle.ViewDist;
import mineplex.core.common.util.UtilServer;
import mineplex.core.gadget.GadgetManager;
import mineplex.core.gadget.event.GadgetBlockEvent;
import mineplex.core.gadget.types.ItemGadget;
@ -34,12 +40,13 @@ public class ItemPaintballGun extends ItemGadget
public ItemPaintballGun(GadgetManager manager)
{
super(manager, "Paintball Gun", new String[]
{
{
C.cWhite + "PEW PEW PEW PEW!",
},
-1,
Material.GOLD_BARDING, (byte)0,
200, new Ammo("Paintball Gun", "100 Paintballs", Material.GOLD_BARDING, (byte)0, new String[] { C.cWhite + "100 Paintballs for you to shoot!" }, 500, 100));
}, -1, Material.GOLD_BARDING, (byte) 0, 200, new Ammo("Paintball Gun", "100 Paintballs", Material.GOLD_BARDING,
(byte) 0, new String[]
{
C.cWhite + "100 Paintballs for you to shoot!"
}, 500, 100));
}
@Override
@ -49,7 +56,7 @@ public class ItemPaintballGun extends ItemGadget
proj.setVelocity(proj.getVelocity().multiply(2));
_balls.add(proj);
//Sound
// Sound
player.getWorld().playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 1.5f, 1.2f);
}
@ -59,47 +66,26 @@ public class ItemPaintballGun extends ItemGadget
if (!_balls.remove(event.getEntity()))
return;
Location loc = event.getEntity().getLocation().add(event.getEntity().getVelocity());
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 49);
Location loc = event.getEntity().getLocation();
byte color = 2;
double r = Math.random();
if (r > 0.8) color = 4;
else if (r > 0.6) color = 5;
else if (r > 0.4) color = 9;
else if (r > 0.2) color = 14;
Vector vec = event.getEntity().getVelocity().normalize().multiply(0.05);
for (Block block : UtilBlock.getInRadius(loc, 3d).keySet())
if (vec.length() > 0)
{
if (block.getType() == Material.PORTAL)
return;
int i = 0;
if (block.getType() == Material.CACTUS)
return;
while (UtilBlock.airFoliage(loc.getBlock()))
{
loc.add(vec);
if (block.getType() == Material.SUGAR_CANE_BLOCK)
return;
if (i++ > 50)
break;
}
}
List<Block> blocks = new ArrayList<Block>();
blocks.addAll(UtilBlock.getInRadius(loc, 1.5d).keySet());
loc.getWorld().playSound(loc, Sound.DIG_STONE, 1.3F, 1.3F);
GadgetBlockEvent gadgetEvent = new GadgetBlockEvent(this, blocks);
Bukkit.getServer().getPluginManager().callEvent(gadgetEvent);
if (gadgetEvent.isCancelled())
return;
for (Block block : gadgetEvent.getBlocks())
{
if (!UtilBlock.solid(block))
continue;
if (block.getType() == Material.CARPET)
Manager.getBlockRestore().Add(block, 171, color, 4000);
else
Manager.getBlockRestore().Add(block, 35, color, 4000);
}
UtilParticle.PlayParticle(ParticleType.RED_DUST, loc, 0.2F, 0.2F, 0.2F, 1, 70, ViewDist.LONG, UtilServer.getPlayers());
}
@EventHandler

View File

@ -23,6 +23,7 @@ import mineplex.core.common.util.UtilEvent;
import mineplex.core.common.util.UtilGear;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilEvent.ActionType;
import mineplex.core.gadget.GadgetManager;
import mineplex.core.gadget.types.ItemGadget;
@ -35,6 +36,8 @@ public class ItemPaintbrush extends ItemGadget
private NautHashMap<String, Byte> _brushColor = new NautHashMap<String, Byte>();
private NautHashMap<String, Location> _brushPrevious = new NautHashMap<String, Location>();
private NautHashMap<String, Location> _playerLocation = new NautHashMap<String, Location>();
public ItemPaintbrush(GadgetManager manager)
{
super(manager, "Paintbrush", new String[]
@ -83,6 +86,7 @@ public class ItemPaintbrush extends ItemGadget
ApplyItem(player, true);
_brushColor.put(player.getName(), (byte)15);
_playerLocation.put(player.getName(), player.getLocation());
}
@ -91,6 +95,7 @@ public class ItemPaintbrush extends ItemGadget
{
_brushColor.remove(player.getName());
_brushPrevious.remove(player.getName());
_playerLocation.remove(player.getName());
RemoveItem(player);
}
@ -115,6 +120,27 @@ public class ItemPaintbrush extends ItemGadget
player.playSound(player.getLocation(), Sound.ORB_PICKUP, 2f, 1f);
}
@EventHandler
public void disableDistance(UpdateEvent event)
{
if (event.getType() != UpdateType.SEC)
return;
for (Player player : UtilServer.getPlayers())
{
if (!GetActive().contains(player))
continue;
Location loc = _playerLocation.get(player.getName());
if (loc == null || UtilMath.offset(player.getLocation(), loc) > 12)
{
Disable(player);
}
}
}
@EventHandler
public void paint(UpdateEvent event)
{

View File

@ -82,7 +82,7 @@ public class MorphBlaze extends MorphGadget
@EventHandler
public void HeroOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().Has(Rank.HERO))
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.HERO))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}

View File

@ -170,7 +170,7 @@ public class MorphCreeper extends MorphGadget
@EventHandler
public void HeroOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().Has(Rank.HERO))
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.HERO))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}

View File

@ -83,7 +83,7 @@ public class MorphPig extends MorphGadget
@EventHandler
public void HeroOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().Has(Rank.ULTRA))
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.ULTRA))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}

View File

@ -27,6 +27,8 @@ import mineplex.core.recharge.Recharge;
public class OutfitTeam extends OutfitGadget
{
private boolean _enabled = true;
private HashMap<String, Color> _colorSetting = new HashMap<String, Color>();
public OutfitTeam(GadgetManager manager, String name,
@ -100,6 +102,9 @@ public class OutfitTeam extends OutfitGadget
@EventHandler(priority=EventPriority.LOWEST)
public void setColor(PlayerCommandPreprocessEvent event)
{
if (!_enabled)
return;
Player player = event.getPlayer();
if (!event.getMessage().toLowerCase().startsWith("/team"))
@ -235,4 +240,9 @@ public class OutfitTeam extends OutfitGadget
{
return _colorSetting.get(player.getName());
}
public void setEnabled(boolean var)
{
_enabled = var;
}
}

View File

@ -46,7 +46,7 @@ public class ParticleLegend extends ParticleGadget
@EventHandler
public void legendOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().Has(Rank.LEGEND))
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.LEGEND))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}

View File

@ -11,6 +11,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.common.structs.ItemContainer;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilInv;
import mineplex.core.common.util.UtilItem;
@ -65,7 +66,7 @@ public class Give extends MiniPlugin
public void give(Player player, String target, String itemNames, String amount, String enchants)
{
//Item
LinkedList<Entry<Material, Byte>> itemList = new LinkedList<Entry<Material, Byte>>();
LinkedList<ItemContainer> itemList = new LinkedList<ItemContainer>();
itemList = UtilItem.matchItem(player, itemNames, true);
if (itemList.isEmpty())
return;
@ -128,11 +129,15 @@ public class Give extends MiniPlugin
if (givenList.length() > 0)
givenList = givenList.substring(0, givenList.length()-1);
for (Entry<Material, Byte> curItem : itemList)
for (ItemContainer curItem : itemList)
{
for (Player cur : giveList)
{
ItemStack stack = ItemStackFactory.Instance.CreateStack(curItem.getKey(), curItem.getValue(), count);
ItemStack stack;
if (curItem.Name == null)
stack = ItemStackFactory.Instance.CreateStack(curItem.Type, curItem.Data, count);
else
stack = ItemStackFactory.Instance.CreateStack(curItem.Type, curItem.Data, count, curItem.Name);
//Enchants
stack.addUnsafeEnchantments(enchs);
@ -142,18 +147,18 @@ public class Give extends MiniPlugin
{
//Inform
if (!cur.equals(player))
UtilPlayer.message(cur, F.main("Give", "You received " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.getKey(), curItem.getValue(), false)) + " from " + F.elem(player.getName()) + "."));
UtilPlayer.message(cur, F.main("Give", "You received " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.Type, curItem.Data, false)) + " from " + F.elem(player.getName()) + "."));
}
}
if (target.equalsIgnoreCase("all"))
UtilPlayer.message(player, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.getKey(), curItem.getValue(), false)) + " to " + F.elem("ALL")) + ".");
UtilPlayer.message(player, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.Type, curItem.Data, false)) + " to " + F.elem("ALL")) + ".");
else if (giveList.size() > 1)
UtilPlayer.message(player, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.getKey(), curItem.getValue(), false)) + " to " + F.elem(givenList) + "."));
UtilPlayer.message(player, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.Type, curItem.Data, false)) + " to " + F.elem(givenList) + "."));
else
UtilPlayer.message(player, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.getKey(), curItem.getValue(), false)) + " to " + F.elem(giveList.getFirst().getName()) + "."));
UtilPlayer.message(player, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem.Type, curItem.Data, false)) + " to " + F.elem(giveList.getFirst().getName()) + "."));
}
}
}

View File

@ -0,0 +1,8 @@
package mineplex.core.gui;
import org.bukkit.event.inventory.ClickType;
public interface ClickExecutor
{
public void click(ClickType clickType);
}

View File

@ -0,0 +1,5 @@
package mineplex.core.gui;
public interface Container<T> {
public T getObject();
}

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