Merge remote-tracking branch 'origin/master'

This commit is contained in:
Shaun Bennett 2014-11-11 01:32:55 -06:00
commit 23ab9756dc
156 changed files with 5292 additions and 1637 deletions

3
.gitignore vendored
View File

@ -26,3 +26,6 @@ Servers
Debug
*.gitignore
/Maps/GRASER UHC
/MutualNDA (1)-signed.pdf
/MutualNDA - signed-signed.pdf
/MutualNDA - signed.pdf

View File

@ -4,6 +4,7 @@ import mineplex.bungee.lobbyBalancer.LobbyBalancer;
import mineplex.bungee.motd.MotdManager;
import mineplex.bungee.playerCount.PlayerCount;
import mineplex.bungee.playerStats.PlayerStats;
import mineplex.bungee.playerTracker.PlayerTracker;
import mineplex.bungee.status.InternetStatus;
import net.md_5.bungee.api.plugin.Plugin;
@ -18,5 +19,6 @@ public class Mineplexer extends Plugin
new FileUpdater(this);
new PlayerStats(this);
new InternetStatus(this);
new PlayerTracker(this);
}
}

View File

@ -25,9 +25,7 @@ public class LobbyBalancer implements Listener, Runnable
private List<MinecraftServer> _sortedLobbies = new ArrayList<MinecraftServer>();
private static Object _serverLock = new Object();
private int _bestServerIndex = 0;
private int _playersSentToBestServer = 0;
private int _maxPlayersToSendToBestServer = 1;
private int _lobbyIndex = 0;
public LobbyBalancer(Plugin plugin)
{
@ -39,7 +37,7 @@ public class LobbyBalancer implements Listener, Runnable
loadLobbyServers();
_plugin.getProxy().getPluginManager().registerListener(_plugin, this);
_plugin.getProxy().getScheduler().schedule(_plugin, this, 200L, 200L, TimeUnit.MILLISECONDS);
_plugin.getProxy().getScheduler().schedule(_plugin, this, 150L, 150L, TimeUnit.MILLISECONDS);
}
@EventHandler
@ -47,45 +45,16 @@ public class LobbyBalancer implements Listener, Runnable
{
if (!event.getTarget().getName().equalsIgnoreCase("Lobby"))
return;
int bungeeBufferNumber = 20;
synchronized (_serverLock)
{
if (_playersSentToBestServer >= _maxPlayersToSendToBestServer)
{
_playersSentToBestServer = 0;
while (_bestServerIndex < _sortedLobbies.size())
{
_maxPlayersToSendToBestServer = (_sortedLobbies.get(_bestServerIndex).getMaxPlayerCount() - _sortedLobbies.get(_bestServerIndex).getPlayerCount()) / bungeeBufferNumber;
if (_maxPlayersToSendToBestServer > 0)
break;
_bestServerIndex++;
}
if (_maxPlayersToSendToBestServer == 0)
{
_bestServerIndex = 0;
_maxPlayersToSendToBestServer = 1;
// Since we had to enter our dangerzone, decrease buffer so we try to hit another server
bungeeBufferNumber -= 2;
if (bungeeBufferNumber <= 0)
bungeeBufferNumber = 0;
}
}
if (_lobbyIndex >= _sortedLobbies.size() || _sortedLobbies.get(_lobbyIndex).getPlayerCount() >= _sortedLobbies.get(_lobbyIndex).getMaxPlayerCount())
_lobbyIndex = 0;
if (_bestServerIndex < _sortedLobbies.size())
{
event.setTarget(_plugin.getProxy().getServerInfo(_sortedLobbies.get(_bestServerIndex).getName()));
System.out.println("Sending " + event.getPlayer().getName() + " to " + _sortedLobbies.get(_bestServerIndex).getName() + "(" + _sortedLobbies.get(_bestServerIndex).getPublicAddress() + ")");
}
_playersSentToBestServer++;
event.setTarget(_plugin.getProxy().getServerInfo(_sortedLobbies.get(_lobbyIndex).getName()));
_sortedLobbies.get(_lobbyIndex).incrementPlayerCount(1);
System.out.println("Sending " + event.getPlayer().getName() + " to " + _sortedLobbies.get(_lobbyIndex).getName() + "(" + _sortedLobbies.get(_lobbyIndex).getPublicAddress() + ")");
_lobbyIndex++;
}
}
@ -122,16 +91,12 @@ public class LobbyBalancer implements Listener, Runnable
Collections.sort(_sortedLobbies, new LobbySorter());
_playersSentToBestServer = 0;
_bestServerIndex = 0;
if (_sortedLobbies.size() > 0)
_maxPlayersToSendToBestServer = (_sortedLobbies.get(_bestServerIndex).getMaxPlayerCount() - _sortedLobbies.get(_bestServerIndex).getPlayerCount());
long timeSpentInLock = System.currentTimeMillis() - startTime;
if (timeSpentInLock > 50)
System.out.println("[==] TIMING [==] Locked loading servers for " + timeSpentInLock + "ms");
_lobbyIndex = 0;
}
}
}

View File

@ -45,6 +45,6 @@ public class PlayerCount implements Listener, Runnable
{
net.md_5.bungee.api.ServerPing serverPing = event.getResponse();
event.setResponse(new net.md_5.bungee.api.ServerPing(serverPing.getVersion(), new Players(_totalMaxPlayers, _totalPlayers, null), serverPing.getDescription(), serverPing.getFaviconObject()));
event.setResponse(new net.md_5.bungee.api.ServerPing(serverPing.getVersion(), new Players(_totalPlayers + 1, _totalPlayers, null), serverPing.getDescription(), serverPing.getFaviconObject()));
}
}

View File

@ -0,0 +1,49 @@
package mineplex.bungee.playerTracker;
import java.io.File;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.ServerSwitchEvent;
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
{
private Plugin _plugin;
private PlayerTrackerRepository _repository = null;
public PlayerTracker(Plugin plugin)
{
_plugin = plugin;
_plugin.getProxy().getPluginManager().registerListener(_plugin, this);
_repository = new PlayerTrackerRepository();
_repository.initialize(!new File("eu.dat").exists());
}
@EventHandler
public void playerConnect(final ServerSwitchEvent event)
{
_plugin.getProxy().getScheduler().runAsync(_plugin, new Runnable()
{
public void run()
{
_repository.updatePlayerServer(event.getPlayer().getName(), event.getPlayer().getServer().getInfo().getName());
}
});
}
@EventHandler
public void playerDisconnect(final PlayerDisconnectEvent event)
{
_plugin.getProxy().getScheduler().runAsync(_plugin, new Runnable()
{
public void run()
{
_repository.deleteServerTransfers(event.getPlayer().getName());
}
});
}
}

View File

@ -1,4 +1,4 @@
package mineplex.core.playerTracker;
package mineplex.bungee.playerTracker;
import java.sql.Connection;
import java.sql.DriverManager;
@ -6,29 +6,37 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import mineplex.core.database.DBPool;
public class PlayerTrackerRepository
{
private String _serverName = "";
private static Object _connectionLock = new Object();
private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private boolean _us = true;
private static String CREATE_PLAYERMAP_TABLE = "CREATE TABLE IF NOT EXISTS playerMap (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(256), serverName VARCHAR(256), us BOOLEAN NOT NULL DEFAULT 1, PRIMARY KEY (id), UNIQUE INDEX playerIndex (playerName));";
private static String RETRIEVE_PLAYERMAP = "SELECT playerName, serverName FROM playerMap WHERE playerName = ? AND us = ?;";
private static String INSERT_PLAYERMAP = "INSERT INTO playerMap (playerName, serverName, us) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE serverName = VALUES(serverName), us = VALUES(us);";
private static String DELETE_PLAYERMAP = "DELETE FROM playerMap WHERE playerName = ? AND serverName = ? AND us = ?;";
private static String DELETE_PLAYERMAP = "DELETE FROM playerMap WHERE playerName = ? AND us = ?;";
public void initialize(String serverName, boolean us)
private Connection _connection = null;
public void initialize(boolean us)
{
_serverName = serverName;
_us = us;
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.ACCOUNT.getConnection())
try
{
Class.forName("com.mysql.jdbc.Driver");
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = connection.prepareStatement(CREATE_PLAYERMAP_TABLE);
preparedStatement = _connection.prepareStatement(CREATE_PLAYERMAP_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
@ -57,17 +65,25 @@ public class PlayerTrackerRepository
PreparedStatement preparedStatement = null;
String server = "N/A";
try (Connection connection = DBPool.ACCOUNT.getConnection())
try
{
preparedStatement = connection.prepareStatement(RETRIEVE_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setBoolean(2, _us);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
synchronized (_connectionLock)
{
server = resultSet.getString(1);
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(RETRIEVE_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setBoolean(2, _us);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
server = resultSet.getString(1);
}
}
}
catch (Exception exception)
@ -108,14 +124,21 @@ public class PlayerTrackerRepository
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.ACCOUNT.getConnection())
try
{
preparedStatement = connection.prepareStatement(DELETE_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setString(2, _serverName);
preparedStatement.setBoolean(3, _us);
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement.executeUpdate();
preparedStatement = _connection.prepareStatement(DELETE_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setBoolean(2, _us);
preparedStatement.executeUpdate();
}
}
catch (Exception exception)
{
@ -137,18 +160,26 @@ public class PlayerTrackerRepository
}
}
public void updatePlayerServer(String playerName)
public void updatePlayerServer(String playerName, String serverName)
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.ACCOUNT.getConnection())
try
{
preparedStatement = connection.prepareStatement(INSERT_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setString(2, _serverName);
preparedStatement.setBoolean(3, _us);
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement.executeUpdate();
preparedStatement = _connection.prepareStatement(INSERT_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setString(2, serverName);
preparedStatement.setBoolean(3, _us);
preparedStatement.executeUpdate();
}
}
catch (Exception exception)
{

View File

@ -45,11 +45,17 @@ public class BungeeRotator
{
if (usServers.size() < maxRecordCount && server.US)
{
if (usServers.size() >= 2 && server.Players > 900)
continue;
System.out.println("SELECTED " + server.Address + " " + (server.US ? "us" : "eu") + " " + server.Players + "/" + server.MaxPlayers);
usServers.add(server.Address);
}
else if (euServers.size() < maxRecordCount && !server.US)
{
if (euServers.size() >= 2 && server.Players > 900)
continue;
System.out.println("SELECTED " + server.Address + " " + (server.US ? "us" : "eu") + " " + server.Players + "/" + server.MaxPlayers);
euServers.add(server.Address);
}

View File

@ -22,6 +22,11 @@ public class UtilAlg
return sortedSet;
}
public static Location getMidpoint(Location a, Location b)
{
return a.add(b.subtract(a).multiply(0.5));
}
public static Vector getTrajectory(Entity from, Entity to)
{
return getTrajectory(from.getLocation().toVector(), to.getLocation().toVector());
@ -179,4 +184,6 @@ public class UtilAlg
{
return cross(vec, getRight(vec));
}
}

View File

@ -199,6 +199,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler
exception.printStackTrace();
}
}
/*
else if (packet instanceof PacketPlayOutAttachEntity)
{
PacketPlayOutAttachEntity attachPacket = (PacketPlayOutAttachEntity)packet;
@ -227,7 +228,8 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler
_entityMap.get(owner).remove(attachPacket.c);
}
else
*/
*/
/*
//System.out.println(owner.getName() + " id=" + owner.getEntityId() + " recieving AttachPacket b=" + attachPacket.b + " c=" + attachPacket.c);
if (attachPacket.c == -1 && _entityMap.get(owner).containsKey(attachPacket.b))
{
@ -332,6 +334,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler
_entityMap.get(owner).put(attachPacket.b, armorPacket.a);
}
}
*/
}
}

View File

@ -20,9 +20,9 @@ public class RankBenefitsGiver9000Repository extends RepositoryBase
private static String INSERT_BENEFIT = "INSERT INTO rankBenefits (uuid, benefit) VALUES (?, ?);";
private static String RETRIEVE_BENEFITS = "SELECT benefit FROM rankBenefits WHERE uuid = ?;";
public RankBenefitsGiver9000Repository(Plugin plugin)
public RankBenefitsGiver9000Repository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override

View File

@ -5,14 +5,13 @@ import java.util.List;
import java.util.UUID;
import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.account.repository.token.LoginToken;
import mineplex.core.account.repository.token.RankUpdateToken;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.UUIDFetcher;
import mineplex.core.database.DBPool;
import mineplex.core.database.DatabaseRunnable;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.column.ColumnBoolean;
@ -33,9 +32,9 @@ public class AccountRepository extends RepositoryBase
private String _webAddress;
public AccountRepository(Plugin plugin, String webAddress)
public AccountRepository(JavaPlugin plugin, String webAddress)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
_webAddress = webAddress;
}

View File

@ -1,7 +1,15 @@
package mineplex.core.achievement;
import mineplex.core.common.util.C;
public enum Achievement
{
GLOBAL_MINEPLEX_LEVEL("Mineplex Level", 20000,
new String[]{"Global.ExpEarned"},
new String[]{"Level up by doing well in games!"},
getExperienceLevels(),
AchievementCategory.GLOBAL),
GLOBAL_GEM_HUNTER("Gem Hunter", 10000,
new String[]{"Global.GemsEarned"},
new String[]{"+1 for every Gem earned in any game."},
@ -172,7 +180,7 @@ public enum Achievement
DRAW_MY_THING_PURE_LUCK("Pure Luck", 800,
new String[]{"Draw My Thing.PureLuck"},
new String[]{"Guess a word in the first 5 seconds"},
new String[]{"Guess a word in the first 8 seconds"},
new int[]{1},
AchievementCategory.DRAW_MY_THING),
@ -492,14 +500,14 @@ public enum Achievement
SNEAK_ASSASSINS_INCOMPETENCE("Incompetence", 600,
new String[]{"Sneaky Assassins.Incompetence"},
new String[]{"Kill 500 NPCs."},
new int[]{500},
new String[]{"Kill 200 NPCs."},
new int[]{200},
AchievementCategory.SNEAKY_ASSASSINS),
SNEAK_ASSASSINS_I_SEE_YOU("I See You", 800,
new String[]{"Sneaky Assassins.ISeeYou"},
new String[]{"Reveal 250 players."},
new int[]{250},
new String[]{"Reveal 50 players."},
new int[]{50},
AchievementCategory.SNEAKY_ASSASSINS),
//Micro Battle
@ -582,6 +590,62 @@ public enum Achievement
_category = category;
}
private static int[] getExperienceLevels()
{
int[] levels = new int[100];
int expReq = 0;
for (int i=0 ; i<20 ; i++)
{
expReq += 2000;
levels[i] = expReq;
}
for (int i=20 ; i<40 ; i++)
{
expReq += 3000;
levels[i] = expReq;
}
for (int i=40 ; i<60 ; i++)
{
expReq += 4000;
levels[i] = expReq;
}
for (int i=60 ; i<80 ; i++)
{
expReq += 5000;
levels[i] = expReq;
}
for (int i=80 ; i<levels.length ; i++)
{
expReq += 6000;
levels[i] = expReq;
}
return levels;
}
public static String getExperienceString(int level)
{
if (level < 20)
return C.cGray + level;
if (level < 40)
return C.cBlue + level;
if (level < 60)
return C.cDGreen + level;
if (level < 80)
return C.cGold + level;
return C.cRed + level;
}
public String getName()
{
return _name;

View File

@ -12,6 +12,7 @@ import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.command.StatsCommand;
import mineplex.core.achievement.ui.AchievementShop;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilGear;
@ -190,4 +191,19 @@ public class AchievementManager extends MiniPlugin
return true;
}
public String getMineplexLevel(Player sender, Rank rank)
{
int level = get(sender, Achievement.GLOBAL_MINEPLEX_LEVEL).getLevel();
if (rank.Has(Rank.OWNER))
level = Math.max(level, 50 + get(sender, Achievement.GLOBAL_GEM_HUNTER).getLevel());
else if (rank.Has(Rank.ADMIN))
level = Math.max(level, 30 + get(sender, Achievement.GLOBAL_GEM_HUNTER).getLevel());
else if (rank.Has(Rank.MODERATOR))
level = Math.max(level, 5);
return Achievement.getExperienceString(level) + " " + ChatColor.RESET;
}
}

View File

@ -24,11 +24,13 @@ import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.antihack.types.Fly;
import mineplex.core.antihack.types.Idle;
import mineplex.core.antihack.types.Reach;
import mineplex.core.antihack.types.Speed;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilTime;
@ -45,7 +47,7 @@ public class AntiHack extends MiniPlugin
public static AntiHack Instance;
private boolean _enabled = true;
private boolean _strict = true;
private boolean _strict = false;
private boolean _kick = true;
public Punish Punish;
@ -75,8 +77,9 @@ public class AntiHack extends MiniPlugin
//Other Times
public int FlightTriggerCancel = 2000;
public ArrayList<Detector> _detectors;
public ArrayList<Detector> _movementDetectors;
public ArrayList<Detector> _combatDetectors;
private AntiHackRepository _repository;
protected AntiHack(JavaPlugin plugin, Punish punish, Portal portal, PreferencesManager preferences, CoreClientManager clientManager)
@ -91,11 +94,14 @@ public class AntiHack extends MiniPlugin
_repository = new AntiHackRepository(plugin.getConfig().getString("serverstatus.name"));
_repository.initialize();
_detectors = new ArrayList<Detector>();
_movementDetectors = new ArrayList<Detector>();
_combatDetectors = new ArrayList<Detector>();
_detectors.add(new Fly(this));
_detectors.add(new Idle(this));
_detectors.add(new Speed(this));
_movementDetectors.add(new Fly(this));
_movementDetectors.add(new Idle(this));
_movementDetectors.add(new Speed(this));
_combatDetectors.add(new Reach(this));
}
public static void Initialize(JavaPlugin plugin, Punish punish, Portal portal, PreferencesManager preferences, CoreClientManager clientManager)
@ -179,7 +185,7 @@ public class AntiHack extends MiniPlugin
public void setIgnore(Player player, long time)
{
//Wipe Detection
for (Detector detector : _detectors)
for (Detector detector : _movementDetectors)
detector.Reset(player);
synchronized (_antiHackLock)
@ -195,11 +201,28 @@ public class AntiHack extends MiniPlugin
public boolean isValid(Player player, boolean groundValid)
{
//Near Other Player
for (Player other : UtilServer.getPlayers())
{
if (player.equals(other))
continue;
if (other.getGameMode() != GameMode.SURVIVAL)
continue;
if (other.getVehicle() != null)
continue;
if (UtilMath.offset(player, other) < 2)
return true;
}
if (player.isFlying() || player.isInsideVehicle() || player.getGameMode() != GameMode.SURVIVAL)
{
return true;
}
//On Ground
if (groundValid)
{
if (UtilEnt.onBlock(player) || player.getLocation().getBlock().getType() != Material.AIR)
@ -403,7 +426,10 @@ public class AntiHack extends MiniPlugin
_offense.remove(player);
for (Detector detector : _detectors)
for (Detector detector : _movementDetectors)
detector.Reset(player);
for (Detector detector : _combatDetectors)
detector.Reset(player);
}
}
@ -432,7 +458,10 @@ public class AntiHack extends MiniPlugin
_offense.remove(player);
for (Detector detector : _detectors)
for (Detector detector : _movementDetectors)
detector.Reset(player);
for (Detector detector : _combatDetectors)
detector.Reset(player);
}
}
@ -459,6 +488,11 @@ public class AntiHack extends MiniPlugin
System.out.println("MAC Strict: " + strict);
}
public boolean isStrict()
{
return _strict;
}
public void setKick(boolean kick)
{
_kick = kick;

View File

@ -0,0 +1,124 @@
package mineplex.core.antihack.types;
import java.util.ArrayList;
import java.util.HashMap;
import mineplex.core.MiniPlugin;
import mineplex.core.antihack.AntiHack;
import mineplex.core.antihack.Detector;
import mineplex.core.common.util.UtilEvent;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilServer;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerMoveEvent;
public class Reach extends MiniPlugin implements Detector
{
private AntiHack Host;
private HashMap<Player, ArrayList<Location>> _history = new HashMap<Player, ArrayList<Location>>();
public Reach (AntiHack host)
{
super("Speed Detector", host.GetPlugin());
Host = host;
}
@EventHandler(priority = EventPriority.LOWEST)
public void recordMove(UpdateEvent event)
{
if (!Host.IsEnabled())
return;
if (event.getType() != UpdateType.TICK)
return;
for (Player player : UtilServer.getPlayers())
{
if (player.getGameMode() != GameMode.SURVIVAL)
continue;
if (!_history.containsKey(player))
_history.put(player, new ArrayList<Location>());
_history.get(player).add(0, player.getLocation());
while (_history.get(player).size() > 40)
{
_history.get(player).remove(_history.get(player).size()-1);
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void reachDetect(EntityDamageEvent event)
{
if (event.getCause() != DamageCause.ENTITY_ATTACK)
return;
if (!(event.getEntity() instanceof Player))
return;
LivingEntity damagerEntity = UtilEvent.GetDamagerEntity(event, false);
if (!(damagerEntity instanceof Player))
return;
Player damager = (Player)damagerEntity;
Player damagee = (Player)event.getEntity();
if (!isInRange(damager.getLocation(), damagee.getLocation()))
{
ArrayList<Location> damageeHistory = _history.get(damagee);
if (damageeHistory != null)
{
for (Location historyLoc : damageeHistory)
{
if (isInRange(damager.getLocation(), historyLoc))
{
return;
}
}
}
//Host.addSuspicion(damager, "Reach");
}
}
private boolean isInRange(Location a, Location b)
{
//2d Range
double distFlat = UtilMath.offset2d(a, b); //Limit is 3.40
if (distFlat > 3.4)
{
return true;
}
//3d Range
double dist = UtilMath.offset(a, b); //Limit is 6 (highest i saw was 5.67)
if (dist > 6.0)
{
return true;
}
return false;
}
@Override
public void Reset(Player player)
{
_history.remove(player);
}
}

View File

@ -0,0 +1,25 @@
package mineplex.core.data;
import org.bukkit.block.Block;
import org.bukkit.Material;
public class BlockData
{
public Block Block;
public Material Material;
public byte Data;
public long Time;
public BlockData(Block block)
{
Block = block;
Material = block.getType();
Data = block.getData();
Time = System.currentTimeMillis();
}
public void restore()
{
Block.setTypeIdAndData(Material.getId(), Data, true);
}
}

View File

@ -5,7 +5,7 @@ import java.sql.Connection;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBPool
public final class DBPool
{
public static final DataSource ACCOUNT = openDataSource("jdbc:mysql://db.mineplex.com/Account", "root", "tAbechAk3wR7tuTh");
public static final DataSource QUEUE = openDataSource("jdbc:mysql://db.mineplex.com/Queue", "root", "tAbechAk3wR7tuTh");
@ -30,4 +30,9 @@ public class DBPool
return source;
}
private DBPool()
{
}
}

View File

@ -1,73 +1,99 @@
package mineplex.core.database;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.column.Column;
import mineplex.core.logger.Logger;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class RepositoryBase implements Listener
{
protected static Object _connectionLock = new Object();
private Connection _connection = null;
private static Object _queueLock = new Object();
private NautHashMap<DatabaseRunnable, String> _failedQueue = new NautHashMap<DatabaseRunnable, String>();
private final Plugin _plugin;
private final DataSource _dataSource;
public RepositoryBase(Plugin plugin, DataSource dataSource)
private String _connectionString;
private String _userName;
private String _password;
protected JavaPlugin Plugin;
public RepositoryBase(JavaPlugin plugin, String connectionString, String username, String password)
{
_plugin = plugin;
_dataSource = dataSource;
Plugin = plugin;
_connectionString = connectionString;
_userName = username;
_password = password;
Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable()
{
public void run()
{
initialize();
update();
synchronized (_connectionLock)
{
initialize();
update();
}
}
});
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
protected abstract void initialize();
protected abstract void update();
protected Connection getConnection() throws SQLException
protected Connection getConnection()
{
return getDataSource().getConnection();
try
{
if (_connection == null || !_connection.isValid(1))
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
catch (SQLException e)
{
e.printStackTrace();
}
return _connection;
}
protected int executeUpdate(String query, Column<?>... columns)
protected int executeUpdate(String query, Column<?>...columns)
{
PreparedStatement preparedStatement = null;
int affectedRows = 0;
try (Connection connection = getConnection())
try
{
preparedStatement = connection.prepareStatement(query);
for (int i = 0; i < columns.length; i++)
if (_connection == null || !_connection.isValid(1))
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(query);
for (int i=0; i < columns.length; i++)
{
columns[i].setValue(preparedStatement, i + 1);
columns[i].setValue(preparedStatement, i+1);
}
affectedRows = preparedStatement.executeUpdate();
}
catch (Exception exception)
@ -81,30 +107,30 @@ public abstract class RepositoryBase implements Listener
try
{
preparedStatement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return affectedRows;
}
protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column<?>... columns)
protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column<?>...columns)
{
ResultSet resultSet = null;
try
{
for (int i = 0; i < columns.length; i++)
for (int i=0; i < columns.length; i++)
{
columns[i].setValue(statement, i + 1);
columns[i].setValue(statement, i+1);
}
resultSet = statement.executeQuery();
callable.processResultSet(resultSet);
}
catch (Exception exception)
@ -112,13 +138,13 @@ public abstract class RepositoryBase implements Listener
exception.printStackTrace();
}
finally
{
{
if (resultSet != null)
{
try
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
@ -126,15 +152,18 @@ public abstract class RepositoryBase implements Listener
}
}
}
protected void executeQuery(String query, ResultSetCallable callable, Column<?>... columns)
protected void executeQuery(String query, ResultSetCallable callable, Column<?>...columns)
{
PreparedStatement preparedStatement = null;
try (Connection connection = getConnection())
try
{
preparedStatement = connection.prepareStatement(query);
if (_connection == null || !_connection.isValid(1))
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(query);
executeQuery(preparedStatement, callable, columns);
}
catch (Exception exception)
@ -148,7 +177,7 @@ public abstract class RepositoryBase implements Listener
try
{
preparedStatement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
@ -156,112 +185,102 @@ public abstract class RepositoryBase implements Listener
}
}
}
protected int executeUpdate(PreparedStatement preparedStatement, Column<?>... columns)
protected int executeUpdate(PreparedStatement preparedStatement, Column<?>...columns)
{
int affectedRows = 0;
try
{
for (int i = 0; i < columns.length; i++)
for (int i=0; i < columns.length; i++)
{
columns[i].setValue(preparedStatement, i + 1);
columns[i].setValue(preparedStatement, i+1);
}
affectedRows = preparedStatement.executeUpdate();
}
catch (Exception exception)
{
exception.printStackTrace();
}
return affectedRows;
}
protected void handleDatabaseCall(final DatabaseRunnable databaseRunnable, final String errorMessage)
{
Thread asyncThread = new Thread(new Runnable()
{
public void run()
{
try
{
databaseRunnable.run();
}
catch (Exception exception)
{
Logger.Instance.log(errorMessage + exception.getMessage());
databaseRunnable.incrementFailCount();
synchronized (_queueLock)
{
_failedQueue.put(databaseRunnable, errorMessage);
}
}
}
});
Thread asyncThread = new Thread(new Runnable()
{
public void run()
{
try
{
databaseRunnable.run();
}
catch (Exception exception)
{
Logger.Instance.log(errorMessage + exception.getMessage());
databaseRunnable.incrementFailCount();
synchronized (_queueLock)
{
_failedQueue.put(databaseRunnable, errorMessage);
}
}
}
});
asyncThread.start();
}
@EventHandler
public void processDatabaseQueue(UpdateEvent event)
{
if (event.getType() != UpdateType.MIN_01)
return;
processFailedQueue();
}
private void processFailedQueue()
{
synchronized (_queueLock)
{
for (Iterator<DatabaseRunnable> runnablesIterator = _failedQueue.keySet().iterator(); runnablesIterator.hasNext(); )
for (Iterator<DatabaseRunnable> runnablesIterator = _failedQueue.keySet().iterator(); runnablesIterator.hasNext();)
{
final DatabaseRunnable databaseRunnable = runnablesIterator.next();
Thread asyncThread = new Thread(new Runnable()
{
public void run()
{
try
{
databaseRunnable.run();
}
catch (Exception exception)
{
Logger.Instance.log(_failedQueue.get(databaseRunnable) + exception.getMessage());
if (databaseRunnable.getFailedCounts() < 4)
{
synchronized (_queueLock)
{
_failedQueue.put(databaseRunnable, _failedQueue.get(databaseRunnable));
}
}
else
{
Logger.Instance.log("Abandoning database call : " + _failedQueue.get(databaseRunnable));
}
}
}
});
runnablesIterator.remove();
Thread asyncThread = new Thread(new Runnable()
{
public void run()
{
try
{
databaseRunnable.run();
}
catch (Exception exception)
{
Logger.Instance.log(_failedQueue.get(databaseRunnable) + exception.getMessage());
if (databaseRunnable.getFailedCounts() < 4)
{
synchronized (_queueLock)
{
_failedQueue.put(databaseRunnable, _failedQueue.get(databaseRunnable));
}
}
else
{
Logger.Instance.log("Abandoning database call : " + _failedQueue.get(databaseRunnable));
}
}
}
});
runnablesIterator.remove();
asyncThread.start();
}
}
}
public Plugin getPlugin()
{
return _plugin;
}
public DataSource getDataSource()
{
return _dataSource;
}
}

View File

@ -28,6 +28,7 @@ public class DonationManager extends MiniPlugin
private Object _donorLock = new Object();
private NautHashMap<Player, NautHashMap<String, Integer>> _gemQueue = new NautHashMap<Player, NautHashMap<String, Integer>>();
private NautHashMap<Player, NautHashMap<String, Integer>> _coinQueue = new NautHashMap<Player, NautHashMap<String, Integer>>();
public DonationManager(JavaPlugin plugin, String webAddress)
{
@ -247,4 +248,56 @@ public class DonationManager extends MiniPlugin
}
}, caller, name, uuid.toString(), amount);
}
public void RewardCoinsLater(final String caller, final Player player, final int amount)
{
if (!_coinQueue.containsKey(player))
_coinQueue.put(player, new NautHashMap<String, Integer>());
int totalAmount = amount;
if (_coinQueue.get(player).containsKey(caller))
totalAmount += _coinQueue.get(player).get(caller);
_coinQueue.get(player).put(caller, totalAmount);
//Do Temp Change
Donor donor = Get(player.getName());
if (donor != null)
donor.addCoins(amount);
}
@EventHandler
public void UpdateCoinQueue(UpdateEvent event)
{
if (event.getType() != UpdateType.SLOWER)
return;
for (Player player : _coinQueue.keySet())
{
String caller = null;
int total = 0;
for (String curCaller : _coinQueue.get(player).keySet())
{
caller = curCaller;
total += _coinQueue.get(player).get(curCaller);
}
if (caller == null)
continue;
//Actually Add Gems
RewardCoins(null, caller, player.getName(), player.getUniqueId(), total, false);
System.out.println("Queue Added [" + player + "] with Coins [" + total + "] for [" + caller + "]");
//Clean
_coinQueue.get(player).clear();
}
//Clean
_coinQueue.clear();
}
}

View File

@ -2,12 +2,10 @@ package mineplex.core.donation.repository;
import java.util.UUID;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.UUIDFetcher;
import mineplex.core.database.DBPool;
import mineplex.core.database.DatabaseRunnable;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.column.ColumnInt;
@ -30,9 +28,9 @@ public class DonationRepository extends RepositoryBase
private String _webAddress;
public DonationRepository(Plugin plugin, String webAddress)
public DonationRepository(JavaPlugin plugin, String webAddress)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
_webAddress = webAddress;
}

View File

@ -22,11 +22,27 @@ public class EloManager extends MiniPlugin
{
super("Elo Rating", plugin);
_repository = new EloRepository();
setupConfigValues(plugin);
_repository = new EloRepository(plugin.getConfig().getString("elo.connectionurl"));
_ratingSystem = new EloRatingSystem(new KFactor(0, 1200, 25), new KFactor(1201, 1600, 20), new KFactor(1601, 2000, 15), new KFactor(2001, 2500, 10));
_playerElos = new NautHashMap<String, NautHashMap<String, Integer>>();
}
private void setupConfigValues(JavaPlugin plugin)
{
try
{
plugin.getConfig().addDefault("elo.connectionurl", "jdbc:mysql://sqlstats.mineplex.com:3306/Mineplex?autoReconnect=true&failOverReadOnly=false&maxReconnects=10");
plugin.getConfig().set("elo.connectionurl", plugin.getConfig().getString("elo.connectionurl"));
plugin.saveConfig();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@EventHandler
public void retrievePlayersElos(final RetrieveClientInformationEvent event)
{

View File

@ -7,18 +7,24 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import mineplex.core.common.util.C;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.DBPool;
public class EloRepository
{
private String _connectionString;
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private static String CREATE_ELO_TABLE = "CREATE TABLE IF NOT EXISTS eloRating (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(256), gameType VARCHAR(256), elo INT, PRIMARY KEY (id), UNIQUE INDEX uuid_gameType_index (uuid, gameType));";
private static String INSERT_ELO = "INSERT INTO eloRating (uuid, gameType, elo) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE elo=VALUES(elo);";
private static String RETRIEVE_ELO = "SELECT gameType, elo FROM eloRating WHERE uuid = ?;";
public EloRepository()
private Connection _connection = null;
public EloRepository(String connectionUrl)
{
_connectionString = connectionUrl;
initialize();
}
@ -26,10 +32,12 @@ public class EloRepository
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = connection.prepareStatement(CREATE_ELO_TABLE);
preparedStatement = _connection.prepareStatement(CREATE_ELO_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
@ -58,9 +66,14 @@ public class EloRepository
int affectedRows = 0;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
preparedStatement = connection.prepareStatement(INSERT_ELO);
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(INSERT_ELO);
preparedStatement.setString(1, uuid);
preparedStatement.setString(2, gameType);
@ -105,9 +118,14 @@ public class EloRepository
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
preparedStatement = connection.prepareStatement(RETRIEVE_ELO);
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(RETRIEVE_ELO);
preparedStatement.setString(1, uuid.toString());
resultSet = preparedStatement.executeQuery();

View File

@ -12,7 +12,9 @@ import org.bukkit.event.EventHandler;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniClientPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.account.event.RetrieveClientInformationEvent;
import mineplex.core.common.Rank;
import mineplex.core.common.jsonchat.ChildJsonMessage;
import mineplex.core.common.jsonchat.JsonMessage;
import mineplex.core.common.util.C;
@ -33,13 +35,15 @@ public class FriendManager extends MiniClientPlugin<FriendData>
{
private static FriendSorter _friendSorter = new FriendSorter();
private CoreClientManager _clientManager;
private PreferencesManager _preferenceManager;
private FriendRepository _repository;
public FriendManager(JavaPlugin plugin, PreferencesManager preferences)
public FriendManager(JavaPlugin plugin, CoreClientManager clientManager, PreferencesManager preferences)
{
super("Friends", plugin);
_clientManager = clientManager;
_preferenceManager = preferences;
_repository = new FriendRepository(plugin);
}
@ -258,6 +262,7 @@ public class FriendManager extends MiniClientPlugin<FriendData>
public void showFriends(Player caller)
{
boolean isStaff = _clientManager.Get(caller).GetRank().Has(Rank.HELPER);
boolean gotAFriend = false;
List<FriendStatus> friendStatuses = Get(caller).Friends;
Collections.sort(friendStatuses, _friendSorter);
@ -286,13 +291,31 @@ public class FriendManager extends MiniClientPlugin<FriendData>
//Online Friend
if (friend.Online)
{
message.add("Teleport").color("green").bold().click("run_command", "/server " + friend.ServerName).hover("show_text", "Teleport to " + friend.Name + "'s server.");
if (friend.ServerName.contains("STAFF") || friend.ServerName.contains("CUST"))
{
if (isStaff && friend.ServerName.contains("STAFF"))
message.add("Teleport").color("green").bold().click("run_command", "/server " + friend.ServerName).hover("show_text", "Teleport to " + friend.Name + "'s server.");
else
message.add("No Teleport").color("yellow").bold();
}
else
message.add("Teleport").color("green").bold().click("run_command", "/server " + friend.ServerName).hover("show_text", "Teleport to " + friend.Name + "'s server.");
message.add(" - ").color("white");
message.add("Delete").color("red").bold().click("run_command", "/unfriend " + friend.Name).hover("show_text", "Remove " + friend.Name + " from your friends list.");
message.add(" - ").color("white");
message.add(friend.Name).color(friend.Online ? "green" : "gray");
message.add(" - ").color("white");
message.add(friend.ServerName).color("dark_green");
if (friend.ServerName.contains("STAFF") || friend.ServerName.contains("CUST"))
{
if (isStaff && friend.ServerName.contains("STAFF"))
message.add(friend.ServerName).color("dark_green");
else
message.add("Private Staff Server").color("dark_green");
}
else
message.add(friend.ServerName).color("dark_green");
onlineLines.add(message);
}

View File

@ -5,11 +5,9 @@ import java.sql.SQLException;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnVarChar;
@ -28,9 +26,9 @@ public class FriendRepository extends RepositoryBase
// Not mutual, need to drop accountFriend to recreate with constraint.
// On add record need to check for a reverse uuidsource/uuidtarget and set mutual
public FriendRepository(Plugin plugin)
public FriendRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override

View File

@ -125,6 +125,8 @@ public class GadgetManager extends MiniPlugin
addGadget(new ParticleRain(this));
addGadget(new ParticleHelix(this));
addGadget(new ParticleGreen(this));
addGadget(new ParticleHeart(this));
addGadget(new ParticleFairy(this));
// Music
addGadget(new MusicGadget(this, "13 Disc", new String[] {""}, -2, 2256, 178000));

View File

@ -110,7 +110,7 @@ public class ItemCoinBomb extends ItemGadget
event.setCancelled(true);
event.getItem().remove();
Manager.getDonationManager().RewardCoins(null, this.GetName() + " Pickup", event.getPlayer().getName(), event.getPlayer().getUniqueId(), 4);
Manager.getDonationManager().RewardCoinsLater(GetName() + " Pickup", event.getPlayer(), 4);
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.ORB_PICKUP, 1f, 2f);

View File

@ -189,7 +189,7 @@ public class ItemGemBomb extends ItemGadget
event.setCancelled(true);
event.getItem().remove();
Manager.getDonationManager().RewardGems(null, this.GetName() + " Pickup", event.getPlayer().getName(), event.getPlayer().getUniqueId(), 4);
Manager.getDonationManager().RewardGemsLater(GetName() + " Pickup", event.getPlayer(), 4);
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.ORB_PICKUP, 1f, 2f);
}

View File

@ -16,6 +16,7 @@ import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import mineplex.core.common.CurrencyType;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilAction;
@ -70,7 +71,7 @@ public class MorphVillager extends MorphGadget implements IThrown
}
@EventHandler
public void Audio(PlayerInteractEvent event)
public void skill(PlayerInteractEvent event)
{
Player player = event.getPlayer();
@ -80,6 +81,12 @@ public class MorphVillager extends MorphGadget implements IThrown
if (!UtilEvent.isAction(event, ActionType.L))
return;
if (Manager.getDonationManager().Get(player.getName()).GetBalance(CurrencyType.Gems) < 20)
{
UtilPlayer.message(player, F.main("Gadget", "You do not have enough Gems."));
return;
}
if (!Recharge.Instance.use(player, GetName(), 800, false, false))
return;
@ -143,7 +150,7 @@ public class MorphVillager extends MorphGadget implements IThrown
event.setCancelled(true);
event.getItem().remove();
Manager.getDonationManager().RewardGems(null, this.GetName() + " Pickup", event.getPlayer().getName(), event.getPlayer().getUniqueId(), 16);
Manager.getDonationManager().RewardGemsLater(GetName() + " Pickup", event.getPlayer(), 16);
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.ORB_PICKUP, 1f, 2f);
}

View File

@ -0,0 +1,73 @@
package mineplex.core.gadget.gadgets;
import java.util.HashMap;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerQuitEvent;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.gadget.types.ParticleGadget;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.gadget.GadgetManager;
public class ParticleFairy extends ParticleGadget
{
private HashMap<Player, ParticleFairyData> _fairy = new HashMap<Player, ParticleFairyData>();
public ParticleFairy(GadgetManager manager)
{
super(manager, "Flame Fairy", new String[]
{
C.cWhite + "HEY! LISTEN!",
C.cWhite + "HEY! LISTEN!",
C.cWhite + "HEY! LISTEN!",
},
-2,
Material.BLAZE_POWDER, (byte)0);
}
@EventHandler
public void playParticle(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
//Launch
for (Player player : GetActive())
{
if (!shouldDisplay(player))
continue;
//Create
if (!_fairy.containsKey(player))
_fairy.put(player, new ParticleFairyData(player));
_fairy.get(player).Update();
}
}
@Override
public void DisableCustom(Player player)
{
if (_active.remove(player))
UtilPlayer.message(player, F.main("Gadget", "You unsummoned " + F.elem(GetName()) + "."));
clean(player);
}
@EventHandler
public void quit(PlayerQuitEvent event)
{
clean(event.getPlayer());
}
private void clean(Player player)
{
_fairy.remove(player);
}
}

View File

@ -0,0 +1,87 @@
package mineplex.core.gadget.gadgets;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilParticle.ParticleType;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public class ParticleFairyData
{
public Player Player;
public Location Fairy;
public Vector Direction;
public Location Target;
public double Speed;
public long IdleTime;
public ParticleFairyData(Player player)
{
Player = player;
Direction = new Vector(1,0,0);
Fairy = player.getEyeLocation();
Target = getNewTarget();
Speed = 0.2;
IdleTime = 0;
}
public void Update()
{
//Update Target
if (UtilMath.offset(Player.getEyeLocation(), Target) > 3 || UtilMath.offset(Fairy, Target) < 1)
Target = getNewTarget();
//Pause?
if (Math.random() > 0.98)
IdleTime = System.currentTimeMillis() + (long)(Math.random() * 3000);
//Speed
if (UtilMath.offset(Player.getEyeLocation(), Fairy) < 3)
{
if (IdleTime > System.currentTimeMillis())
{
Speed = Math.max(0, Speed - 0.005);
}
else
{
Speed = Math.min(0.15, Speed + 0.005);
}
}
else
{
IdleTime = 0;
Speed = Math.min(0.15 + UtilMath.offset(Player.getEyeLocation(), Fairy) * 0.05, Speed + 0.02);
}
//Modify Direction
Direction.add(UtilAlg.getTrajectory(Fairy, Target).multiply(0.15));
if (Direction.length() < 1)
Speed = Speed * Direction.length();
UtilAlg.Normalize(Direction);
//Move
if (UtilMath.offset(Fairy, Target) > 0.1)
Fairy.add(Direction.clone().multiply(Speed));
//Particle
UtilParticle.PlayParticle(ParticleType.FLAME, Fairy, 0, 0, 0, 0, 1);
UtilParticle.PlayParticle(ParticleType.LAVA, Fairy, 0, 0, 0, 0, 1);
//Sound
Fairy.getWorld().playSound(Fairy, Sound.CAT_PURREOW, 0.1f, 3f);
}
private Location getNewTarget()
{
return Player.getEyeLocation().add(Math.random() * 6 - 3, Math.random() * 1.5, Math.random() * 6 - 3);
}
}

View File

@ -2,6 +2,7 @@ package mineplex.core.gadget.gadgets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.GameMode;
import org.bukkit.Location;
@ -91,7 +92,7 @@ public class ParticleFoot extends ParticleGadget
UtilParticle.PlayParticle(ParticleType.FOOTSTEP, loc, 0f, 0f, 0f, 0, 1);
UtilParticle.PlayParticle(ParticleType.LARGE_SMOKE, loc.add(0, 0.1, 0), 0f, 0f, 0f, 0, 1);
UtilParticle.PlayParticle(ParticleType.LARGE_SMOKE, loc.clone().add(0, 0.1, 0), 0f, 0f, 0f, 0, 1);
}
}
@ -100,14 +101,13 @@ public class ParticleFoot extends ParticleGadget
if (_steps.isEmpty())
return;
Iterator<Location> stepIterator = _steps.keySet().iterator();
Iterator<Entry<Location, Long>> stepIterator = _steps.entrySet().iterator();
while (stepIterator.hasNext())
{
Location step = stepIterator.next();
long time = _steps.get(step);
if (UtilTime.elapsed(time, 10000))
Entry<Location, Long> entry = stepIterator.next();
if (UtilTime.elapsed(entry.getValue(), 10000))
stepIterator.remove();
}
}

View File

@ -40,17 +40,31 @@ public class ParticleGreen extends ParticleGadget
if (!shouldDisplay(player))
continue;
if (Manager.isMoving(player))
{
UtilParticle.PlayParticle(ParticleType.HAPPY_VILLAGER, player.getLocation().add(0, 1f, 0), 0f, 0f, 0f, 0, 1);
}
else
{
float x = (float) (Math.sin(player.getTicksLived()/5d) * 1f);
float z = (float) (Math.cos(player.getTicksLived()/5d) * 1f);
UtilParticle.PlayParticle(ParticleType.HAPPY_VILLAGER, player.getLocation().add(x, 1, z), 0f, 0f, 0f, 0, 1);
}
float x = (float) (Math.sin(player.getTicksLived()/7d) * 1f);
float z = (float) (Math.cos(player.getTicksLived()/7d) * 1f);
float y = (float) (Math.cos(player.getTicksLived()/17d) * 1f + 1f);
UtilParticle.PlayParticle(ParticleType.HAPPY_VILLAGER, player.getLocation().add(x, y, z), 0f, 0f, 0f, 0, 1);
// if (Manager.isMoving(player))
// {
// UtilParticle.PlayParticle(ParticleType.HAPPY_VILLAGER, player.getLocation().add(0, 1f, 0), 0f, 0f, 0f, 0, 1);
// }
// else
// {
// float scale = Math.abs((float) (Math.sin(player.getTicksLived()/30d) * 2f)) + 1;
// // float vertical = (float) (Math.cos(player.getTicksLived()/50d) * 1f);
//
// int dir = player.isSneaking() ? 1 : -1;
//
// for (double i=0 ; i<Math.PI * 2 ; i += 0.2)
// {
// double x = Math.sin(i + (dir * player.getTicksLived()/50d)) * (i%(Math.PI/2d));
// double z = Math.cos(i + (dir * player.getTicksLived()/50d)) * (i%(Math.PI/2d));
//
// UtilParticle.PlayParticle(ParticleType.HAPPY_VILLAGER, player.getLocation().add(x, 1, z), 0f, 0f, 0f, 0, 1);
// }
// }
}
}
}

View File

@ -0,0 +1,129 @@
package mineplex.core.gadget.gadgets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerQuitEvent;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilParticle.ParticleType;
import mineplex.core.gadget.types.ParticleGadget;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.gadget.GadgetManager;
public class ParticleHeart extends ParticleGadget {
private HashMap<Player, HashMap<Player, Location>> _target = new HashMap<Player, HashMap<Player, Location>>();
public ParticleHeart(GadgetManager manager)
{
super(manager, "I Heart You", new String[]
{
C.cWhite + "With these particles, you can",
C.cWhite + "show off how much you heart",
C.cWhite + "everyone on Mineplex!",
},
-2,
Material.APPLE, (byte)0);
}
@EventHandler
public void playParticle(UpdateEvent event)
{
if (event.getType() != UpdateType.FASTEST)
return;
//Launch
for (Player player : GetActive())
{
if (!shouldDisplay(player))
continue;
if (!_target.containsKey(player))
_target.put(player, new HashMap<Player, Location>());
if (Recharge.Instance.use(player, GetName(), 500, false, false))
{
for (Player other : UtilServer.getPlayers())
{
if (other.equals(player))
continue;
if (other.getGameMode() != GameMode.SURVIVAL)
continue;
if (_target.get(player).containsKey(other))
continue;
if (UtilMath.offset(player, other) > 6)
continue;
_target.get(player).put(other, player.getLocation().add(0, 1, 0));
break;
}
}
if (Manager.isMoving(player))
UtilParticle.PlayParticle(ParticleType.HEART, player.getLocation().add(0, 1, 0), 0f, 0f, 0f, 0, 1);
else
UtilParticle.PlayParticle(ParticleType.HEART, player.getLocation().add(0, 1, 0), 0.5f, 0.5f, 0.5f, 0, 1);
}
//Particle
for (HashMap<Player, Location> heart : _target.values())
{
Iterator<Entry<Player, Location>> heartIterator = heart.entrySet().iterator();
while (heartIterator.hasNext())
{
Entry<Player, Location> entry = heartIterator.next();
entry.getValue().add(UtilAlg.getTrajectory(entry.getValue(), entry.getKey().getEyeLocation()).multiply(0.6));
UtilParticle.PlayParticle(ParticleType.HEART, entry.getValue(), 0, 0, 0, 0, 1);
if (UtilMath.offset(entry.getValue(), entry.getKey().getEyeLocation()) < 0.6)
heartIterator.remove();
}
}
}
@Override
public void DisableCustom(Player player)
{
if (_active.remove(player))
UtilPlayer.message(player, F.main("Gadget", "You unsummoned " + F.elem(GetName()) + "."));
clean(player);
}
@EventHandler
public void quit(PlayerQuitEvent event)
{
clean(event.getPlayer());
}
private void clean(Player player)
{
_target.remove(player);
for (HashMap<Player, Location> map : _target.values())
map.remove(player);
}
}

View File

@ -5,10 +5,8 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnInt;
@ -31,9 +29,9 @@ public class InventoryRepository extends RepositoryBase
private static String INSERT_CLIENT_INVENTORY = "INSERT INTO accountInventory (accountId, itemId, count) SELECT accounts.id, ?, ? FROM accounts WHERE accounts.uuid = ? ON DUPLICATE KEY UPDATE count=count + VALUES(count);";
private static String RETRIEVE_CLIENT_INVENTORY = "SELECT items.name, ic.name as category, count FROM accountInventory AS ai INNER JOIN items ON items.id = ai.itemId INNER JOIN itemCategories AS ic ON ic.id = items.categoryId INNER JOIN accounts ON accounts.id = ai.accountId WHERE accounts.uuid = ?;";
public InventoryRepository(Plugin plugin)
public InventoryRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override

View File

@ -21,7 +21,9 @@ public class Logger
public Logger(JavaPlugin plugin)
{
_repository = new LoggerRepository(plugin.getConfig().getString("serverstatus.name"));
setupConfigValues(plugin);
_repository = new LoggerRepository(plugin.getConfig().getString("log.connectionurl"), plugin.getConfig().getString("serverstatus.name"));
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
@ -34,6 +36,20 @@ public class Logger
});
}
private void setupConfigValues(JavaPlugin plugin)
{
try
{
plugin.getConfig().addDefault("log.connectionurl", "jdbc:mysql://sqlstats.mineplex.com:3306/Mineplex?autoReconnect=true&failOverReadOnly=false&maxReconnects=10");
plugin.getConfig().set("log.connectionurl", plugin.getConfig().getString("log.connectionurl"));
plugin.saveConfig();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void log(final String message)
{
System.out.println(message);

View File

@ -5,17 +5,23 @@ import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import mineplex.core.database.DBPool;
public class LoggerRepository
{
private static Object _connectionLock = new Object();
private String _connectionString;
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private static String CREATE_LOG_TABLE = "CREATE TABLE IF NOT EXISTS errorLog (id INT NOT NULL AUTO_INCREMENT, server VARCHAR(256), message VARCHAR(256), date LONG, PRIMARY KEY (id));";
private static String INSERT_LOG = "INSERT INTO errorLog (server, message, date) VALUES (?, ?, now());";
private Connection _connection = null;
private String _serverName;
public LoggerRepository(String serverName)
public LoggerRepository(String connectionUrl, String serverName)
{
_connectionString = connectionUrl;
_serverName = serverName;
initialize();
@ -25,10 +31,12 @@ public class LoggerRepository
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = connection.prepareStatement(CREATE_LOG_TABLE);
preparedStatement = _connection.prepareStatement(CREATE_LOG_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
@ -55,18 +63,26 @@ public class LoggerRepository
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
preparedStatement = connection.prepareStatement(INSERT_LOG);
for (String msg : message)
synchronized (_connectionLock)
{
preparedStatement.setString(1, _serverName);
preparedStatement.setString(2, msg.substring(0, Math.min(257, msg.length())));
preparedStatement.addBatch();
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(INSERT_LOG);
for (String msg : message)
{
preparedStatement.setString(1, _serverName);
preparedStatement.setString(2, msg.substring(0, Math.min(257, msg.length())));
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
}
preparedStatement.executeBatch();
}
catch (Exception exception)
{

View File

@ -1,46 +0,0 @@
package mineplex.core.playerTracker;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.account.event.ClientUnloadEvent;
public class PlayerTracker extends MiniPlugin
{
private PlayerTrackerRepository _repository = null;
public PlayerTracker(JavaPlugin plugin, String serverName, boolean us)
{
super("Player Tracker", plugin);
_repository = new PlayerTrackerRepository();
_repository.initialize(serverName, us);
}
@EventHandler
public void trackPlayer(final PlayerJoinEvent event)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
_repository.updatePlayerServer(event.getPlayer().getName());
}
});
}
@EventHandler
public void untrackPlayer(final ClientUnloadEvent event)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
_repository.deleteServerTransfers(event.GetName());
}
});
}
}

View File

@ -19,6 +19,8 @@ import mineplex.core.portal.Commands.*;
import mineplex.serverdata.Region;
import mineplex.serverdata.ServerCommandManager;
import mineplex.serverdata.ServerManager;
import mineplex.serverdata.transfers.ServerTransfer;
import mineplex.serverdata.transfers.TransferCommand;
public class Portal extends MiniPlugin
{

View File

@ -0,0 +1,29 @@
package mineplex.core.portal;
import mineplex.serverdata.CommandCallback;
import mineplex.serverdata.ServerCommand;
import mineplex.serverdata.transfers.ServerTransfer;
import mineplex.serverdata.transfers.TransferCommand;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class TransferHandler implements CommandCallback
{
public void run(ServerCommand command)
{
if (command instanceof TransferCommand)
{
TransferCommand transferCommand = (TransferCommand) command;
ServerTransfer transfer = transferCommand.getTransfer();
Player player = Bukkit.getPlayer(transfer.getPlayerName());
if (player != null && player.isOnline())
{
Portal.getInstance().SendPlayerToServer(player, transfer.getServerName());
}
}
}
}

View File

@ -36,13 +36,28 @@ public class PreferencesManager extends MiniClientPlugin<UserPreferences>
{
super("Preferences", plugin);
_repository = new PreferencesRepository(plugin);
setupConfigValues();
_repository = new PreferencesRepository(plugin, plugin.getConfig().getString("preferences.connectionurl"));
_shop = new PreferencesShop(this, clientManager, donationManager);
AddCommand(new PreferencesCommand(this));
}
private void setupConfigValues()
{
try
{
GetPlugin().getConfig().addDefault("preferences.connectionurl", "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10");
GetPlugin().getConfig().set("preferences.connectionurl", GetPlugin().getConfig().getString("preferences.connectionurl"));
GetPlugin().saveConfig();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected UserPreferences AddPlayer(String player)
{

View File

@ -1,17 +1,14 @@
package mineplex.core.preferences;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnVarChar;
@ -23,9 +20,9 @@ public class PreferencesRepository extends RepositoryBase
private static String RETRIEVE_ACCOUNT_PREFERENCES = "SELECT games, visibility, showChat, friendChat, privateMessaging, partyRequests, invisibility, forcefield, showMacReports, ignoreVelocity, pendingFriendRequests FROM accountPreferences WHERE uuid = ?;";
private static String UPDATE_ACCOUNT_PREFERENCES = "UPDATE accountPreferences SET games = ?, visibility = ?, showChat = ?, friendChat = ?, privateMessaging = ?, partyRequests = ?, invisibility = ?, forcefield = ?, showMacReports = ?, ignoreVelocity = ?, pendingFriendRequests = ? WHERE uuid=?;";
public PreferencesRepository(Plugin plugin)
public PreferencesRepository(JavaPlugin plugin, String connectionString)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, connectionString, "root", "tAbechAk3wR7tuTh");
}
@Override
@ -43,9 +40,9 @@ public class PreferencesRepository extends RepositoryBase
{
PreparedStatement preparedStatement = null;
try (Connection connection = getConnection())
try
{
preparedStatement = connection.prepareStatement(UPDATE_ACCOUNT_PREFERENCES);
preparedStatement = getConnection().prepareStatement(UPDATE_ACCOUNT_PREFERENCES);
for (Entry<String, UserPreferences> entry : preferences.entrySet())
{

View File

@ -13,20 +13,22 @@ import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilTime;
import mineplex.core.common.util.UtilTime.TimeUnit;
import mineplex.core.punish.Command.*;
import mineplex.core.punish.Command.PunishCommand;
import mineplex.core.punish.Tokens.PunishClientToken;
import mineplex.core.punish.Tokens.PunishmentToken;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.craftbukkit.libs.com.google.gson.Gson;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.plugin.java.JavaPlugin;
public class Punish extends MiniPlugin
@ -78,13 +80,16 @@ public class Punish extends MiniPlugin
if (client.IsBanned())
{
Punishment punishment = client.GetPunishment(PunishmentSentence.Ban);
String time = F.time(UtilTime.convertString(punishment.GetRemaining(), 0, TimeUnit.FIT));
String time = UtilTime.convertString(punishment.GetRemaining(), 0, TimeUnit.FIT);
if (punishment.GetHours() == -1)
time = C.cRed + "Permanent";
time = "Permanent";
String reason = C.consoleHead + F.main(GetName(), punishment.GetAdmin() + " banned you because of '" + F.elem(punishment.GetReason()) + "' for " + time);
String reason = C.cRed + C.Bold + "You are banned for " + time +
"\n" + C.cWhite + punishment.GetReason() +
"\n" + C.cDGreen + "Unfairly banned? Appeal at " + C.cGreen + "www.mineplex.com/appeals"
;
event.disallow(Result.KICK_BANNED, reason);
}
}
@ -154,7 +159,7 @@ public class Punish extends MiniPlugin
}
else if (banResult == PunishmentResponse.Punished)
{
final String durationString = F.time(UtilTime.convertString(finalDuration < 0 ? -1 : (long)(finalDuration * 3600000), 1, TimeUnit.FIT));
final String durationString = UtilTime.convertString(finalDuration < 0 ? -1 : (long)(finalDuration * 3600000), 1, TimeUnit.FIT);
if (sentence == PunishmentSentence.Ban)
{
@ -165,12 +170,18 @@ public class Punish extends MiniPlugin
{
public void run()
{
UtilPlayer.kick(UtilPlayer.searchOnline(null, playerName, false), GetName(), caller == null ? "Mineplex Anti-Cheat" : caller.getName() + " banned you because of " + F.elem(reason) + " for " +
durationString + ".");
String kickReason = C.cRed + C.Bold + "You were banned for " + durationString + " by " + (caller == null ? "Mineplex Anti-Cheat" : caller.getName()) +
"\n" + C.cWhite + reason +
"\n" + C.cDGreen + "Unfairly banned? Appeal at " + C.cGreen + "www.mineplex.com/appeals"
;
Player target = UtilPlayer.searchOnline(null, playerName, false);
if (target != null)
target.kickPlayer(kickReason);
}
});
UtilServer.broadcast(F.main(GetName(), F.elem(caller == null ? "Mineplex Anti-Cheat" : caller.getName()) + " banned " + F.elem(playerName) + " because of " + F.elem(reason) + " for " + durationString + "."));
informOfPunish(playerName, F.main(GetName(), caller == null ? "Mineplex Anti-Cheat" : caller.getName() + " banned " + playerName + " for " + durationString + "."));
}
else
{
@ -178,8 +189,19 @@ public class Punish extends MiniPlugin
System.out.println(F.main(GetName(), F.elem(caller == null ? "Mineplex Anti-Cheat" : caller.getName()) + " muted " + F.elem(playerName) + " because of " + F.elem(reason) + " for " +
durationString + "."));
UtilServer.broadcast(F.main(GetName(), F.elem(caller == null ? "Mineplex Anti-Cheat" : caller.getName()) + " muted " + F.elem(playerName) + " because of " + F.elem(reason) + " for " +
durationString + "."));
//Warning
if (finalDuration == 0)
informOfPunish(playerName, F.main(GetName(), caller == null ? "Mineplex Anti-Cheat" : caller.getName() + " issued a friendly warning to " + playerName + "."));
else
informOfPunish(playerName, F.main(GetName(), caller == null ? "Mineplex Anti-Cheat" : caller.getName() + " muted " + playerName + " for " + durationString + "."));
//Inform
Player target = UtilPlayer.searchExact(playerName);
if (target != null)
{
UtilPlayer.message(target, F.main("Punish", F.elem(C.cGray + C.Bold + "Reason: ") + reason));
target.playSound(target.getLocation(), Sound.CAT_MEOW, 1f, 1f);
}
_repository.LoadPunishClient(playerName, new Callback<PunishClientToken>()
{
@ -191,9 +213,22 @@ public class Punish extends MiniPlugin
}
}
}
}, playerName, category.toString(), sentence, reason, duration, caller == null ? "Mineplex Anti-Cheat" : caller.getName(), severity);
}
private void informOfPunish(String punishee, String msg)
{
for (Player player : UtilServer.getPlayers())
{
if (_clientManager.Get(player).GetRank().Has(Rank.HELPER) || player.getName().equals(punishee))
{
player.sendMessage(msg);
}
}
}
public void LoadClient(PunishClientToken token)
{
PunishClient client = new PunishClient();
@ -230,4 +265,29 @@ public class Punish extends MiniPlugin
{
return _clientManager;
}
public int factorial(int n)
{
if (n == 0)
return 1;
return n * (factorial(n-1));
}
@EventHandler
public void tabComplete(PlayerChatTabCompleteEvent event)
{
if (!_clientManager.Get(event.getPlayer()).GetRank().Has(Rank.HELPER))
return;
if (!event.getChatMessage().equals(event.getLastToken()))
return;
Player player = UtilPlayer.searchOnline(event.getPlayer(), event.getLastToken(), true);
if (player != null)
{
event.getTabCompletions().clear();
event.getTabCompletions().add("/p " + player.getName() + " ");
}
}
}

View File

@ -3,10 +3,13 @@ package mineplex.core.punish.UI;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import mineplex.core.antihack.AntiHack;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap;
@ -70,32 +73,28 @@ public class PunishPage extends CraftInventoryCustom implements Listener
PunishClient client = _plugin.GetClient(_target);
int chatOffenseCount = 0;
int exploitingCount = 0;
int hackingCount = 0;
HashMap<Category, HashMap<Integer, Integer>> offenseMap = new HashMap<Category, HashMap<Integer, Integer>>();
for (Category category : Category.values())
{
//Initialise Offences
offenseMap.put(category, new HashMap<Integer, Integer>());
offenseMap.get(category).put(1, 0);
offenseMap.get(category).put(2, 0);
offenseMap.get(category).put(3, 0);
}
List<Entry<Category, Punishment>> punishments = new ArrayList<Entry<Category, Punishment>>();
for (Category category : client.GetPunishments().keySet())
{
{
for (Punishment punishment : client.GetPunishments().get(category))
{
punishments.add(new AbstractMap.SimpleEntry<Category, Punishment>(category, punishment));
}
switch (category)
{
case ChatOffense:
chatOffenseCount = client.GetPunishments().get(category).size();
break;
case Exploiting:
exploitingCount = client.GetPunishments().get(category).size();
break;
case Hacking:
hackingCount = client.GetPunishments().get(category).size();
break;
default:
break;
//Count by Severity
if (!punishment.GetRemoved() && punishment.GetSeverity() > 0 && punishment.GetSeverity() < 4)
offenseMap.get(category).put(punishment.GetSeverity(), 1 + offenseMap.get(category).get(punishment.GetSeverity()));
}
}
@ -103,9 +102,9 @@ public class PunishPage extends CraftInventoryCustom implements Listener
String examplePrefixEx = ChatColor.RESET + "" + ChatColor.WHITE;
String examplePrefixNote = ChatColor.RESET + "" + ChatColor.DARK_GREEN;
_chatOffenseButton = new ShopItem(Material.BOOK_AND_QUILL, (byte)0, "Chat Offense", new String[] { ChatColor.RESET + "Past offenses : " + ChatColor.YELLOW + chatOffenseCount, examplePrefix + "Verbal Abuse, Spam, Harassment, Trolling, etc" }, 1, false, true);
_exploitingButton = new ShopItem(Material.HOPPER, (byte)0, "General Offense", new String[] { ChatColor.RESET + "Past offenses : " + ChatColor.YELLOW + exploitingCount, examplePrefix + "Commmand/Map/Class/Skill exploits, etc" }, 1, false, true);
_hackingButton = new ShopItem(Material.IRON_SWORD, (byte)0, "Client Mod", new String[] { ChatColor.RESET + "Past offenses : " + ChatColor.YELLOW + hackingCount, examplePrefix + "X-ray, Forcefield, Speed, Fly, Inventory Hacks, etc" }, 1, false, true);
_chatOffenseButton = new ShopItem(Material.BOOK_AND_QUILL, (byte)0, "Chat Offense", new String[] { examplePrefix + "Verbal Abuse, Spam, Harassment, Trolling, etc" }, 1, false, true);
_exploitingButton = new ShopItem(Material.HOPPER, (byte)0, "General Offense", new String[] { examplePrefix + "Command/Map/Class/Skill exploits, etc" }, 1, false, true);
_hackingButton = new ShopItem(Material.IRON_SWORD, (byte)0, "Client Mod", new String[] { examplePrefix + "X-ray, Forcefield, Speed, Fly, Inventory Hacks, etc" }, 1, false, true);
_warningButton = new ShopItem(Material.PAPER, (byte)0, "Warning", new String[] { }, 1, false, true);
_permMuteButton = new ShopItem(Material.EMERALD_BLOCK, (byte)0, "Permanent Mute", new String[] { }, 1, false, true);
_permBanButton = new ShopItem(Material.REDSTONE_BLOCK, (byte)0, "Permanent Ban", new String[] { }, 1, false, true);
@ -114,133 +113,175 @@ public class PunishPage extends CraftInventoryCustom implements Listener
getInventory().setItem(12, _exploitingButton.getHandle());
getInventory().setItem(14, _hackingButton.getHandle());
//Mute
//XXX Mute
{
AddButton(19, new ShopItem(Material.INK_SACK, (byte)2, "Severity 1", new String[] {
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + "2 Hours",
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.ChatOffense).get(1),
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + getDurationString(Category.ChatOffense, 1, offenseMap),
" ",
examplePrefix + "Spamming same thing in chat (3-5 times)",
examplePrefix + "Light Spam",
examplePrefixEx + " Sending the same message 2-5 times",
" ",
examplePrefix + "Light Advertising;",
examplePrefixEx + " 'anyone want to play on minecade?'",
" ",
examplePrefix + "Light Abuse/Harassment",
examplePrefixEx + " 'you suck a this game'",
" ",
examplePrefix + "Hackusations",
examplePrefixEx + " 'you're such a hacker!'",
" ",
examplePrefix + "Trolling",
" ",
examplePrefix + "Constantly just talking crap",
" ",
examplePrefix + "Pestering staff in admin chat",
" ",
examplePrefix + "Accusing a player of hacks in chat",
" ",
examplePrefixNote + "Use Severity 2 if many Severity 1 past offences",
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 1, false, 2));
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 1, false, getDuration(Category.ChatOffense, 1, offenseMap)));
if (_plugin.GetClients().Get(_player).GetRank().Has(Rank.MODERATOR))
{
AddButton(28, new ShopItem(Material.INK_SACK, (byte)11, "Severity 2", new String[] {
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + "24 Hours",
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.ChatOffense).get(2),
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + getDurationString(Category.ChatOffense, 2, offenseMap),
" ",
examplePrefix + "Spamming same thing in chat (6-14 times)",
examplePrefix + "Medium Spam",
examplePrefixEx + " Sending the same message 6-20 times",
" ",
examplePrefix + "Medium Advertising;",
examplePrefixEx + " 'check out my server! crap.server.net'",
examplePrefixEx + " 'join crap.server.net' - posted once",
" ",
examplePrefix + "Rudeness, arguing or abuse between players;",
examplePrefixEx + " 'go fucking cry, you baby'.",
examplePrefix + "Medium Abuse/Harassment",
examplePrefixEx + " 'piss off you stupid newb'",
examplePrefixEx + " 'SHIT ADMINS ARE SHIT!!!'",
examplePrefixEx + " 'youre terrible, learn to play'",
examplePrefixEx + " 'you're terrible, learn to play'",
" ",
examplePrefixNote + "Use Severity 3 if many Severity 2 past offences",
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 2, false, 24));
examplePrefix + "Avoiding Chat Filter",
examplePrefixEx + " 'F|_|<K YOU'",
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 2, false, getDuration(Category.ChatOffense, 2, offenseMap)));
AddButton(37, new ShopItem(Material.INK_SACK, (byte)1, "Severity 3", new String[] {
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + "Permanent",
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.ChatOffense).get(3),
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + getDurationString(Category.ChatOffense, 3, offenseMap),
" ",
examplePrefix + "Spamming same thing in chat (15+ times)",
examplePrefix + "Severe Spam",
examplePrefixEx + " Sending the same message 20+ times",
examplePrefixEx + " Only really used for a spam bot",
" ",
examplePrefix + "Strong Advertising;",
examplePrefixEx + " 'JOIN MINECADE!! MINEPLEX SUCKS'",
" ",
examplePrefix + "Severe chat abuse towards players/staff",
examplePrefix + "Severe Abuse/Harassment",
examplePrefixEx + " 'go fucking die in a fire you fucking sack of shit'",
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 3, false, -1));
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 3, false, getDuration(Category.ChatOffense, 3, offenseMap)));
}
}
//General
//XXX General
{
AddButton(21, new ShopItem(Material.INK_SACK, (byte)2, "Severity 1", new String[] {
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + "2 Hours",
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Exploiting).get(1),
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Exploiting, 1, offenseMap),
" ",
examplePrefix + "Some Examples;",
examplePrefixEx + " Trolling (Gameplay Only)",
examplePrefixEx + " ",
examplePrefix + "Team Killing",
examplePrefixEx + " Intentionally killing your team mates",
" ",
examplePrefixNote + "Use Severity 2 if many Severity 1 past offences",
}, 1, false, true), new PunishButton(this, Category.Exploiting, 1, true, 2));
examplePrefix + "Trolling (Gameplay)",
examplePrefixEx + " Using abilities to trap players in spawn",
" ",
examplePrefix + "Map/Bug Exploiting",
examplePrefixEx + " Abusing an exploit to gain an advantage",
}, 1, false, true), new PunishButton(this, Category.Exploiting, 1, true, getDuration(Category.Exploiting, 1, offenseMap)));
if (_plugin.GetClients().Get(_player).GetRank().Has(Rank.MODERATOR))
{
AddButton(30, new ShopItem(Material.INK_SACK, (byte)11, "Severity 2", new String[] {
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + "24",
" ",
examplePrefix + "Examples;",
examplePrefixEx + " Team killing with water in Bridges",
examplePrefixEx + " Wither Skeleton block glitching in SSM to hide",
" ",
examplePrefixNote + "Use Severity 3 if many Severity 2 past offences",
}, 1, false, true), new PunishButton(this, Category.Exploiting, 2, true, 24));
AddButton(39, new ShopItem(Material.INK_SACK, (byte)1, "Severity 3", new String[] {
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + "Permanent",
" ",
examplePrefix + "Examples;",
examplePrefixEx + " Repeatedly crashing server with glitch",
" ",
}, 1, false, true), new PunishButton(this, Category.Exploiting, 3, true, -1));
}
// if (_plugin.GetClients().Get(_player).GetRank().Has(Rank.MODERATOR))
// {
//
// AddButton(30, new ShopItem(Material.INK_SACK, (byte)11, "Severity 2", new String[] {
// ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Exploiting).get(2),
// ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Exploiting, 2, offenseMap),
// " ",
// examplePrefix + "Empty",
// examplePrefixEx + " Currently no reason to use this :)",
// }, 1, false, true), new PunishButton(this, Category.Exploiting, 2, true, getDuration(Category.Exploiting, 2, offenseMap)));
//
// AddButton(39, new ShopItem(Material.INK_SACK, (byte)1, "Severity 3", new String[] {
// ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Exploiting).get(3),
// ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Exploiting, 3, offenseMap),
// " ",
// examplePrefix + "Server Lag/Crash",
// examplePrefixEx + " Abusing a bug to lag or crash a server",
// " ",
// }, 1, false, true), new PunishButton(this, Category.Exploiting, 3, true, getDuration(Category.Exploiting, 3, offenseMap)));
// }
}
//Hacks
//XXX Hacks
{
AddButton(23, new ShopItem(Material.INK_SACK, (byte)2, "Severity 1", new String[] {
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + "12 Hours",
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Hacking).get(1),
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Hacking, 1, offenseMap),
" ",
examplePrefix + "Damage Indicators, Better Sprint, Minimaps",
" ",
examplePrefixNote + "Use this for 1st Offence"
}, 1, false, true), new PunishButton(this, Category.Hacking, 1, true, 12));
examplePrefix + "Examples;",
examplePrefixEx + " Damage Indicators",
examplePrefixEx + " Better Sprint",
examplePrefixEx + " Player Radar",
}, 1, false, true), new PunishButton(this, Category.Hacking, 1, true, getDuration(Category.Hacking, 1, offenseMap)));
if (_plugin.GetClients().Get(_player).GetRank().Has(Rank.MODERATOR))
{
AddButton(32, new ShopItem(Material.INK_SACK, (byte)11, "Severity 2", new String[] {
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + "1 Week",
" ",
examplePrefix + "Examples;",
examplePrefixEx + " Damage Indicators",
examplePrefixEx + " Better Sprint",
examplePrefixEx + " Player Radar",
" ",
examplePrefixNote + "Use this for 2nd Offence",
" ",
examplePrefixNote + "Use Severity 3 for 3rd Offence",
}, 1, false, true), new PunishButton(this, Category.Hacking, 2, true, 168));
//Sev 2
String[] sev2 = new String[]
{
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Hacking).get(2),
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Hacking, 2, offenseMap),
" ",
examplePrefix + "Hacks;",
examplePrefixEx + " Fly Hack",
examplePrefixEx + " Forcefield",
examplePrefixEx + " Speed Hack",
examplePrefixEx + " Reach Hack",
" ",
C.cAqua + "Use this for punishing",
C.cAqua + "Fly Hacks on this server!",
};
AddButton(41, new ShopItem(Material.INK_SACK, (byte)1, "Severity 3", new String[] {
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + "Permanent",
" ",
examplePrefix + "Examples;",
examplePrefixEx + " Fly Hack",
examplePrefixEx + " Speed Hack",
examplePrefixEx + " Forcefield",
" ",
examplePrefixNote + "Must be 100% sure they were hacking!"
}, 1, false, true), new PunishButton(this, Category.Hacking, 3, true, -1));
String[] sev2Strict = new String[]
{
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Hacking).get(2),
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Hacking, 2, offenseMap),
" ",
examplePrefix + "Hacks;",
examplePrefixEx + " Forcefield",
examplePrefixEx + " Speed Hack",
examplePrefixEx + " Reach Hack",
" ",
C.cRed + "Do not use this for punishing",
C.cRed + "Fly Hacks on this server!"
};
AddButton(32, new ShopItem(Material.INK_SACK, (byte)11, "Severity 2",
(AntiHack.Instance.isStrict() ? sev2Strict : sev2)
, 1, false, true), new PunishButton(this, Category.Hacking, 2, true, getDuration(Category.Hacking, 2, offenseMap)));
//Sev 3
String[] sev3 = new String[]
{
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Hacking).get(3),
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Hacking, 3, offenseMap),
" ",
C.cRed + "Do not use this for punishing",
C.cRed + "Fly Hacks on this server!"
};
String[] sev3Strict = new String[]
{
ChatColor.RESET + "Past Offences: " + ChatColor.YELLOW + offenseMap.get(Category.Hacking).get(3),
ChatColor.RESET + "Ban Duration: " + ChatColor.YELLOW + getDurationString(Category.Hacking, 3, offenseMap),
" ",
C.cAqua + "Use this for punishing",
C.cAqua + "Fly Hacks on this server!",
};
AddButton(41, new ShopItem(Material.INK_SACK, (byte)1, "Severity 3",
(AntiHack.Instance.isStrict() ? sev3Strict : sev3)
, 1, false, true), new PunishButton(this, Category.Hacking, 3, true, getDuration(Category.Hacking, 3, offenseMap)));
}
}
//Other
//XXX Other
AddButton(25, new ShopItem(Material.PAPER, (byte)0, "Warning", new String[] {
" ",
examplePrefix + "Example Warning Input;",
@ -250,7 +291,7 @@ public class PunishPage extends CraftInventoryCustom implements Listener
examplePrefixEx + " Trolling - was trying to make bob angry in chat",
}, 1, false, true), new PunishButton(this, Category.Warning, 1, false, 0));
if (_plugin.GetClients().Get(_player).GetRank().Has(Rank.MODERATOR))
{
AddButton(34, new ShopItem(Material.REDSTONE_BLOCK, (byte)0, "Permanent Ban", new String[] {
@ -259,11 +300,15 @@ public class PunishPage extends CraftInventoryCustom implements Listener
examplePrefixNote + "Must supply detailed reason for Ban."
}, 1, false, true), new PunishButton(this, Category.Other, 1, true, -1));
AddButton(43, new ShopItem(Material.EMERALD_BLOCK, (byte)0, "Permanent Mute", new String[] {
AddButton(43, new ShopItem(Material.BOOK_AND_QUILL, (byte)0, "Permanent Mute", new String[] {
ChatColor.RESET + "Mute Duration: " + ChatColor.YELLOW + "Permanent",
" ",
examplePrefix + "Severe Advertising;",
examplePrefixEx + " 'JOIN MINECADE! MINEPLEX SUCKS!",
examplePrefixEx + " 'join crap.server.net! FREE ADMIN!",
" ",
examplePrefixNote + "Must supply detailed reason for Mute."
}, 1, false, true), new PunishButton(this, Category.Other, 1, false, -1));
}, 1, false, true), new PunishButton(this, Category.ChatOffense, 4, false, -1));
}
Collections.sort(punishments, new PunishmentSorter());
@ -306,72 +351,65 @@ public class PunishPage extends CraftInventoryCustom implements Listener
Punishment punishment = punishmentEntry.getValue();
//Reason Lines for LORE
ArrayList<String> reasonLines = new ArrayList<String>();
String reason = punishment.GetReason();
while (reason.length() > 0)
{
int index = Math.min(reason.length(), 24);
while (index < reason.length() && reason.charAt(index) != ' ')
index++;
reasonLines.add(reason.substring(0, index));
reason = reason.substring(index, reason.length());
}
//LORE
ArrayList<String> output = new ArrayList<String>();
output.add(C.cYellow + "Punishment Type: " + ChatColor.RESET + punishment.GetCategory().toString());
if (punishmentEntry.getKey() == Category.ChatOffense ||
punishmentEntry.getKey() == Category.Exploiting ||
punishmentEntry.getKey() == Category.Hacking)
punishmentEntry.getKey() == Category.Exploiting ||
punishmentEntry.getKey() == Category.Hacking)
{
if (punishment.GetRemoved())
{
button.SetLore(new String[]
{
ChatColor.RESET + "Punishment Type: " + ChatColor.YELLOW + punishment.GetCategory().toString(),
ChatColor.RESET + "Severity: " + ChatColor.YELLOW + punishment.GetSeverity(),
" ",
ChatColor.RESET + "Reason: " + ChatColor.YELLOW + punishment.GetReason(),
" ",
ChatColor.RESET + "Admin: " + ChatColor.YELLOW + punishment.GetAdmin(),
ChatColor.RESET + "Date: " + ChatColor.YELLOW + UtilTime.when(punishment.GetTime()),
" ",
ChatColor.RESET + "Removed by: " + (punishment.GetRemoved() ? ChatColor.GREEN + punishment.GetRemoveAdmin() : ChatColor.RED + "Not Removed"),
ChatColor.RESET + "Remove Reason: " + (punishment.GetRemoved() ? ChatColor.GREEN + punishment.GetRemoveReason() : ChatColor.RED + "Not Removed"),
});
}
else
{
button.SetLore(new String[]
{
ChatColor.RESET + "Punishment Type: " + ChatColor.YELLOW + punishment.GetCategory().toString(),
ChatColor.RESET + "Severity: " + ChatColor.YELLOW + punishment.GetSeverity(),
" ",
ChatColor.RESET + "Reason: " + ChatColor.YELLOW + punishment.GetReason(),
" ",
ChatColor.RESET + "Admin: " + ChatColor.YELLOW + punishment.GetAdmin(),
ChatColor.RESET + "Date: " + ChatColor.YELLOW + UtilTime.when(punishment.GetTime()),
});
}
output.add(C.cYellow + "Severity: " + ChatColor.RESET + punishment.GetSeverity());
}
else
output.add(" ");
for (int i=0 ; i<reasonLines.size() ; i++)
{
if (punishment.GetRemoved())
{
button.SetLore(new String[]
{
ChatColor.RESET + "Punishment Type: " + ChatColor.YELLOW + punishment.GetCategory().toString(),
" ",
ChatColor.RESET + "Reason: " + ChatColor.YELLOW + punishment.GetReason(),
" ",
ChatColor.RESET + "Admin: " + ChatColor.YELLOW + punishment.GetAdmin(),
ChatColor.RESET + "Date: " + ChatColor.YELLOW + UtilTime.when(punishment.GetTime()),
" ",
ChatColor.RESET + "Removed by: " + (punishment.GetRemoved() ? ChatColor.GREEN + punishment.GetRemoveAdmin() : ChatColor.RED + "Not Removed"),
ChatColor.RESET + "Remove Reason: " + (punishment.GetRemoved() ? ChatColor.GREEN + punishment.GetRemoveReason() : ChatColor.RED + "Not Removed"),
});
}
if (i == 0)
output.add(C.cYellow + "Reason: " + ChatColor.RESET + reasonLines.get(i));
else
{
button.SetLore(new String[]
{
ChatColor.RESET + "Punishment Type: " + ChatColor.YELLOW + punishment.GetCategory().toString(),
" ",
ChatColor.RESET + "Reason: " + ChatColor.YELLOW + punishment.GetReason(),
" ",
ChatColor.RESET + "Admin: " + ChatColor.YELLOW + punishment.GetAdmin(),
ChatColor.RESET + "Date: " + ChatColor.YELLOW + UtilTime.when(punishment.GetTime()),
});
}
output.add(C.cYellow + " " + ChatColor.RESET + reasonLines.get(i));
}
output.add(" ");
output.add(C.cYellow + "Staff: " + ChatColor.RESET + punishment.GetAdmin());
output.add(" ");
output.add(C.cYellow + "Date: " + ChatColor.RESET + UtilTime.when(punishment.GetTime()));
if (punishment.GetRemoved())
{
output.add(" ");
output.add(C.cYellow + "Removed by: " + (punishment.GetRemoved() ? ChatColor.RESET + punishment.GetRemoveAdmin() : ChatColor.RED + "Not Removed"));
output.add(C.cYellow + "Remove Reason: " + (punishment.GetRemoved() ? ChatColor.RESET + punishment.GetRemoveReason() : ChatColor.RED + "Not Removed"));
}
String[] loreString = new String[output.size()];
for (int i=0 ; i<output.size() ; i++)
{
loreString[i] = output.get(i);
}
button.SetLore(loreString);
if ((punishment.GetHours() == -1 || punishment.GetRemaining() > 0) && !punishment.GetRemoved() && punishment.GetActive())
{
@ -456,4 +494,101 @@ public class PunishPage extends CraftInventoryCustom implements Listener
}
});
}
public String getDurationString(Category category, int severity, HashMap<Category, HashMap<Integer, Integer>> pastOffences)
{
int hours = getDuration(category, severity, pastOffences);
if (hours == -1)
return "Permanent";
return UtilTime.MakeStr((long)hours * 3600000L);
}
public int getDuration(Category category, int severity, HashMap<Category, HashMap<Integer, Integer>> pastOffences)
{
if (category == Category.ChatOffense)
{
int hours = 0;
if (severity >= 1)
{
hours += calculateTime(2, 2, 48, pastOffences.get(category).get(1), severity != 1);
}
if (severity >= 2)
{
hours += calculateTime(24, 24, 168, pastOffences.get(category).get(2), severity != 2);
}
if (severity >= 3)
{
hours += calculateTime(720, 720, 720, pastOffences.get(category).get(3), severity != 3);
}
return hours;
}
if (category == Category.Exploiting)
{
int hours = 0;
if (severity >= 1)
{
hours += calculateTime(4, 4, 96, pastOffences.get(category).get(1), severity != 1);
}
if (severity >= 2)
{
hours += calculateTime(48, 48, 336, pastOffences.get(category).get(2), severity != 2);
}
if (severity >= 3)
{
return -1;
}
return hours;
}
if (category == Category.Hacking)
{
int hours = 0;
if (severity >= 1)
{
hours += calculateTime(24, 24, 168, pastOffences.get(category).get(1), severity != 1);
}
if (severity >= 2)
{
//Permanent!
if (pastOffences.get(category).get(2) > 0)
return -1;
hours = 720;
}
if (severity >= 3)
{
return -1;
}
return hours;
}
return 0;
}
private int calculateTime(int baseAmount, int addAmount, int pastLimit, int offenses, boolean zeroBase)
{
int amount = 0;
if (zeroBase)
baseAmount = 0;
// At what point does Bonus > pastLimit
int breakLimitCount = 0;
while (baseAmount + addAmount * breakLimitCount * breakLimitCount < pastLimit)
breakLimitCount++;
amount += Math.min(baseAmount + addAmount * offenses * offenses, pastLimit);
amount += Math.max(0, (offenses - breakLimitCount) * pastLimit);
return amount;
}
}

View File

@ -12,6 +12,7 @@ import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.updater.UpdateType;
import mineplex.core.account.event.ClientUnloadEvent;
import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilPlayer;
@ -91,17 +92,6 @@ public class Recharge extends MiniPlugin
}
}
}
/*
public boolean use(Player player, String ability, long recharge, boolean inform)
{
return use(player, ability, ability, recharge, inform, false);
}
public boolean use(Player player, String ability, String abilityFull, long recharge, boolean inform)
{
return use(player, ability, ability, recharge, inform, false);
}
*/
public boolean use(Player player, String ability, long recharge, boolean inform, boolean attachItem)
{
@ -150,7 +140,12 @@ public class Recharge extends MiniPlugin
public void useForce(Player player, String ability, long recharge)
{
UseRecharge(player, ability, recharge, false, false);
useForce(player, ability, recharge, false);
}
public void useForce(Player player, String ability, long recharge, boolean attachItem)
{
UseRecharge(player, ability, recharge, attachItem, false);
}
public boolean usable(Player player, String ability)
@ -183,10 +178,8 @@ public class Recharge extends MiniPlugin
RechargeEvent rechargeEvent = new RechargeEvent(player, ability, recharge);
UtilServer.getServer().getPluginManager().callEvent(rechargeEvent);
if (attachItem || attachDurability)
Get(player).put(ability, new RechargeData(this, player, ability, player.getItemInHand(), rechargeEvent.GetRecharge(), attachItem, attachDurability));
else
Get(player).put(ability, new RechargeData(System.currentTimeMillis()+rechargeEvent.GetRecharge()));
Get(player).put(ability, new RechargeData(this, player, ability, player.getItemInHand(),
rechargeEvent.GetRecharge(), attachItem, attachDurability));
}
public void recharge(Player player, String ability)
@ -195,13 +188,41 @@ public class Recharge extends MiniPlugin
}
@EventHandler
public void clearPlayer(PlayerQuitEvent event)
public void clearPlayer(ClientUnloadEvent event)
{
_recharge.remove(event.getPlayer().getName());
_recharge.remove(event.GetName());
}
public void setDisplayForce(Player player, String ability, boolean displayForce)
{
if (!_recharge.containsKey(player.getName()))
return;
if (!_recharge.get(player.getName()).containsKey(ability))
return;
_recharge.get(player.getName()).get(ability).DisplayForce = displayForce;
}
public void Reset(Player player)
{
_recharge.put(player.getName(), new NautHashMap<String, RechargeData>());
}
public void debug(Player player, String ability)
{
if (!_recharge.containsKey(player.getName()))
{
player.sendMessage("No Recharge Map.");
return;
}
if (!_recharge.get(player.getName()).containsKey(ability))
{
player.sendMessage("Ability Not Found.");
return;
}
_recharge.get(player.getName()).get(ability).debug(player);
}
}

View File

@ -2,6 +2,7 @@ package mineplex.core.recharge;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilGear;
import mineplex.core.common.util.UtilInv;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
@ -28,14 +29,10 @@ public class RechargeData
public ItemStack Item;
public boolean DisplayForce = false;
public boolean AttachItem;
public boolean AttachDurability;
public RechargeData(long time)
{
Time = time;
}
public RechargeData(Recharge host, Player player, String name, ItemStack stack, long rechargeTime, boolean attachitem, boolean attachDurability)
{
Host = host;
@ -52,16 +49,16 @@ public class RechargeData
public boolean Update()
{
if (Item != null && Name != null && Player != null)
if ((DisplayForce || Item != null) && Name != null && Player != null)
{
//Holding Recharge Item
double percent = (double)(System.currentTimeMillis() - Time)/(double)Recharge;
if (AttachItem)
if (DisplayForce || AttachItem)
{
try
{
if (Player.getItemInHand().getType() == Item.getType())
if (DisplayForce || (Item != null && UtilGear.isMat(Player.getItemInHand(), Item.getType())))
{
if (!UtilTime.elapsed(Time, Recharge))
{
@ -84,27 +81,10 @@ public class RechargeData
}
}
if (AttachDurability)
if (AttachDurability && Item != null)
{
Item.setDurability((short) (Item.getType().getMaxDurability() - (Item.getType().getMaxDurability() * percent)));
}
/*
ItemMeta itemMeta = Item.getItemMeta();
if (System.currentTimeMillis() < Time)
itemMeta.setDisplayName(C.cRed + C.Bold + Name + ChatColor.RESET + " - " + C.cYellow + C.Bold + UtilTime.MakeStr(Time - System.currentTimeMillis()));
else
itemMeta.setDisplayName(C.cGreen + C.Bold + Name);
Item.setItemMeta(itemMeta);
if (System.currentTimeMillis() < Time)
Item.removeEnchantment(Enchantment.DURABILITY);
else
Item.addEnchantment(Enchantment.DURABILITY, 1);
*/
}
@ -115,4 +95,12 @@ public class RechargeData
{
return Recharge - (System.currentTimeMillis() - Time);
}
public void debug(Player player)
{
player.sendMessage("Recharge: " + Recharge);
player.sendMessage("Time: " + Time);
player.sendMessage("Elapsed: " + (System.currentTimeMillis() - Time));
player.sendMessage("Remaining: " + GetRemaining());
}
}

View File

@ -0,0 +1,44 @@
package mineplex.core.report;
import java.util.HashSet;
import java.util.Set;
import mineplex.serverdata.Data;
public class Report implements Data
{
private int _reportId;
public int getReportId() { return _reportId; }
private String _serverName;
public String getServerName() { return _serverName; }
private String _playerName;
public String getPlayerName() { return _playerName; }
// Set of account ids of players who contributed to reporting this player
private Set<String> _reporters;
public Set<String> getReporters() { return _reporters; }
public void addReporter(String reporter) { _reporters.add(reporter); }
/**
* Class constructor
* @param reportId
* @param playerName
* @param serverName
*/
public Report(int reportId, String playerName, String serverName)
{
_reportId = reportId;
_playerName = playerName;
_serverName = serverName;
_reporters = new HashSet<String>();
}
@Override
public String getDataId()
{
return String.valueOf(_reportId);
}
}

View File

@ -0,0 +1,318 @@
package mineplex.core.report;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandCenter;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.portal.Portal;
import mineplex.core.report.command.ReportNotification;
import mineplex.serverdata.DataRepository;
import mineplex.serverdata.RedisDataRepository;
import mineplex.serverdata.Region;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
/**
* ReportManager hooks into a synchronized network-wide report system
* with methods for updating/fetching/closing reports in real time.
* @author Ty
*
*/
public class ReportManager {
private static ReportManager instance;
// Holds active/open reports in a synchronized database.
private DataRepository<Report> reportRepository;
private DataRepository<ReportProfile> reportProfiles;
// Stores/logs closed tickets, and various reporter/staff actions.
private ReportRepository reportSqlRepository;
// A mapping of PlayerName(String) to the ReportId(Integer) for all active reports on this server.
private Map<String, Integer> activeReports;
/**
* Private constructor to prevent non-singleton instances.
*/
private ReportManager()
{
this.reportRepository = new RedisDataRepository<Report>(Region.ALL, Report.class, "reports");
this.reportProfiles = new RedisDataRepository<ReportProfile>(Region.ALL, ReportProfile.class, "reportprofiles");
this.activeReports = new HashMap<String, Integer>();
// TODO: Get JavaPlugin instance and locate ConnectionString from config?
this.reportSqlRepository = new ReportRepository(ReportPlugin.getPlugin(), "CONNECTION STRING HERE");
reportSqlRepository.initialize();
}
public void retrieveReportResult(int reportId, Player reportCloser, String reason)
{
// Prompt the report closer with a menu of options to determine the result
// of the report. When confirmation is received, THEN close report.
}
public void closeReport(int reportId, Player reportCloser, String reason)
{
retrieveReportResult(reportId, reportCloser, reason);
}
public void closeReport(int reportId, Player reportCloser, String reason,
ReportResult result)
{
if (isActiveReport(reportId))
{
Report report = getReport(reportId);
reportRepository.removeElement(String.valueOf(reportId)); // Remove report from redis database
removeActiveReport(reportId);
int closerId = getPlayerAccount(reportCloser).GetAccountId();
String playerName = getReport(reportId).getPlayerName();
int playerId = getPlayerAccount(playerName).GetAccountId();
String server = null; // TODO: Get current server name
reportSqlRepository.logReport(reportId, playerId, server, closerId, result, reason);
// Update the reputation/profiles of all reporters on this closing report.
for (String reporterName : report.getReporters())
{
CoreClient reporterAccount = getPlayerAccount(reporterName);
ReportProfile reportProfile = getReportProfile(String.valueOf(reporterAccount.GetAccountId()));
reportProfile.onReportClose(result);
reportProfiles.addElement(reportProfile);
}
if (reportCloser != null)
{
// Notify staff that the report was closed.
sendReportNotification(String.format("[Report %d] %s closed this report. (%s).", reportId,
reportCloser.getName(), result.toDisplayMessage()));
}
}
}
public void handleReport(int reportId, Player reportHandler)
{
if (reportRepository.elementExists(String.valueOf(reportId)))
{
Report report = getReport(reportId);
Portal.transferPlayer(reportHandler.getName(), report.getServerName());
String handlerName = reportHandler.getName();
sendReportNotification(String.format("[Report %d] %s is handling this report.", reportId, handlerName));
// TODO: Send display message to handler when they arrive on the server
// with info about the case/report.
int handlerId = getPlayerAccount(reportHandler).GetAccountId();
reportSqlRepository.logReportHandling(reportId, handlerId); // Log handling into sql database
}
}
public void reportPlayer(Player reporter, Player reportedPlayer, String reason)
{
int reporterId = getPlayerAccount(reporter).GetAccountId();
ReportProfile reportProfile = getReportProfile(String.valueOf(reporterId));
if (reportProfile.canReport())
{
Report report = null;
if (hasActiveReport(reportedPlayer))
{
int reportId = getActiveReport(reportedPlayer.getName());
report = getReport(reportId);
report.addReporter(reporter.getName());
}
else
{
String serverName = null; // TODO: Fetch name of current server
int reportId = generateReportId();
report = new Report(reportId, reportedPlayer.getName(), serverName);
report.addReporter(reporter.getName());
activeReports.put(reportedPlayer.getName().toLowerCase(), report.getReportId());
reportRepository.addElement(report);
}
if (report != null)
{
// [Report 42] [MrTwiggy +7] [Cheater102 - 5 - Speed hacking]
String message = String.format("[Report %d] [%s %d] [%s - %d - %s]", report.getReportId(),
reporter.getName(), reportProfile.getReputation(),
reportedPlayer.getName(), report.getReporters().size(), reason);
sendReportNotification(message);
reportSqlRepository.logReportSending(report.getReportId(), reporterId, reason);
}
}
}
public void onPlayerQuit(Player player)
{
if (hasActiveReport(player))
{
int reportId = getActiveReport(player.getName());
this.closeReport(reportId, null, "Player Quit", ReportResult.UNDETERMINED);
// TODO: Handle 'null' report closer in closeReport metohd for NPEs.
sendReportNotification(String.format("[Report %d] %s has left the game.", reportId, player.getName()));
}
}
public ReportProfile getReportProfile(String playerName)
{
ReportProfile profile = reportProfiles.getElement(playerName);
if (profile == null)
{
profile = new ReportProfile(playerName, getAccountId(playerName));
saveReportProfile(profile);
}
return profile;
}
private void saveReportProfile(ReportProfile profile)
{
reportProfiles.addElement(profile);
}
/**
* @return a uniquely generated report id.
*/
public int generateReportId()
{
JedisPool pool = ((RedisDataRepository<Report>) reportRepository).getJedisPool();
Jedis jedis = pool.getResource();
long uniqueReportId = -1;
try
{
uniqueReportId = jedis.incr("reports.unique-id");
}
catch (JedisConnectionException exception)
{
exception.printStackTrace();
pool.returnBrokenResource(jedis);
jedis = null;
}
finally
{
if (jedis != null)
{
pool.returnResource(jedis);
}
}
return (int) uniqueReportId;
}
public Report getReport(int reportId)
{
return reportRepository.getElement(String.valueOf(reportId));
}
private CoreClient getPlayerAccount(Player player)
{
return getPlayerAccount(player.getName());
}
private CoreClient getPlayerAccount(String playerName)
{
return CommandCenter.Instance.GetClientManager().Get(playerName);
}
private int getAccountId(String playerName)
{
return getPlayerAccount(playerName).GetAccountId();
}
/**
* @param player - the player whose report notification settings are to be checked
* @return true, if the player should receive report notifications, false otherwise.
*/
public boolean hasReportNotifications(Player player)
{
// If player is not staff, return false.
// If player is staff but has report notifications pref disabled, return false;
// Else return true.
return false;
}
/**
* Send a network-wide {@link ReportNotification} to all online staff.
* @param message - the report notification message to send.
*/
public void sendReportNotification(String message)
{
ReportNotification reportNotification = new ReportNotification(message);
reportNotification.publish();
}
/**
* @param playerName - the name of the player whose active report id is being fetched
* @return the report id for the active report corresponding with playerName, if one
* currently exists, -1 otherwise.
*/
public int getActiveReport(String playerName)
{
if (activeReports.containsKey(playerName.toLowerCase()))
{
return activeReports.get(playerName.toLowerCase());
}
return -1;
}
public boolean hasActiveReport(Player player)
{
return getActiveReport(player.getName()) != -1;
}
public boolean isActiveReport(int reportId)
{
for (Entry<String, Integer> activeReport : activeReports.entrySet())
{
if (activeReport.getValue() == reportId)
{
return true;
}
}
return false;
}
public boolean removeActiveReport(int reportId)
{
for (Entry<String, Integer> activeReport : activeReports.entrySet())
{
if (activeReport.getValue() == reportId)
{
activeReports.remove(activeReport.getKey());
return true;
}
}
return false;
}
/**
* @return the singleton instance of {@link ReportManager}.
*/
public static ReportManager getInstance()
{
if (instance == null)
{
instance = new ReportManager();
}
return instance;
}
}

View File

@ -0,0 +1,32 @@
package mineplex.core.report;
import mineplex.core.MiniPlugin;
import mineplex.core.report.command.ReportCloseCommand;
import mineplex.core.report.command.ReportCommand;
import mineplex.core.report.command.ReportDebugCommand;
import mineplex.core.report.command.ReportHandleCommand;
import org.bukkit.plugin.java.JavaPlugin;
public class ReportPlugin extends MiniPlugin
{
private static JavaPlugin instance;
public static JavaPlugin getPlugin() { return instance; }
public ReportPlugin(JavaPlugin plugin, String serverName)
{
super("ReportPlugin", plugin);
instance = plugin;
}
@Override
public void AddCommands()
{
AddCommand(new ReportCommand(this));
AddCommand(new ReportHandleCommand(this));
AddCommand(new ReportCloseCommand(this));
AddCommand(new ReportDebugCommand(this));
}
}

View File

@ -0,0 +1,61 @@
package mineplex.core.report;
import mineplex.serverdata.Data;
public class ReportProfile implements Data
{
private String _playerName;
private int _playerId;
private int _totalReports;
private int _successfulReports;
private int _reputation;
public int getReputation() { return _reputation; }
private boolean _banned;
public ReportProfile(String playerName, int playerId)
{
_playerName = playerName;
_playerId = playerId;
_totalReports = 0;
_successfulReports = 0;
_reputation = 0;
_banned = false;
}
@Override
public String getDataId()
{
return String.valueOf(_playerId);
}
public boolean canReport()
{
return !_banned;
}
/**
* Called when a report made by this player is closed.
* @param result - the result of the closed report.
*/
public void onReportClose(ReportResult result)
{
_totalReports++;
if (result == ReportResult.MUTED || result == ReportResult.BANNED)
{
_successfulReports++;
_reputation++;
}
else if (result == ReportResult.ABUSE)
{
_reputation = -1;
_banned = true;
}
}
}

View File

@ -0,0 +1,78 @@
package mineplex.core.report;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.Map.Entry;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnInt;
import mineplex.core.database.column.ColumnVarChar;
import mineplex.core.preferences.UserPreferences;
import org.bukkit.plugin.java.JavaPlugin;
public class ReportRepository extends RepositoryBase
{
/*
* *ReportTicket
id, date, accountId reported player, server, accountId of staff who closed, result, reason
ReportSenders
id, date, reportId, accountId of Reporter, Reason for report
ReportHandlers
id, date, reportId, accountId of Staff
This will be used to determine if staff are handling
*/
private static String CREATE_TICKET_TABLE = "CREATE TABLE IF NOT EXISTS reportTickets (reportId INT NOT NULL, date LONG, eventDate LONG, playerId INT NOT NULL, server VARCHAR(50), closerId INT NOT NULL, result VARCHAR(25), reason VARCHAR(100), PRIMARY KEY (reportId), INDEX playerIdIndex (playerId), INDEX closerIdIndex (closerId));";
private static String CREATE_HANDLER_TABLE = "CREATE TABLE IF NOT EXISTS reportHandlers (id INT NOT NULL AUTO_INCREMENT, reportId INT NOT NULL, eventDate LONG, handlerId INT NOT NULL, PRIMARY KEY (id), INDEX handlerIdIndex (handlerId) );";
private static String CREATE_REPORTERS_TABLE = "CREATE TABLE IF NOT EXISTS reportSenders (id INT NOT NULL AUTO_INCREMENT, reportId INT NOT NULL, eventDate LONG, reporterId INT NOT NULL, reason VARCHAR(100), PRIMARY KEY (id), INDEX reporterIdIndex (reporterId));";
private static String INSERT_TICKET = "INSERT INTO reportTickets (reportId, eventDate, playerId, server, closerId, result, reason) VALUES (?, now(), ?, ?, ?, ?, ?);";
private static String INSERT_HANDLER = "INSERT INTO reportHandlers (eventDate, reportId, handlerId) VALUES(now(), ?, ?);";
private static String INSERT_SENDER = "INSERT INTO reportSenders (eventDate, reportId, reporterId, reason) VALUES(now(), ?, ?, ?);";
public ReportRepository(JavaPlugin plugin, String connectionString)
{
super(plugin, connectionString, "root", "tAbechAk3wR7tuTh"); // TODO: Config file for host/pass?
}
@Override
protected void initialize()
{
executeUpdate(CREATE_TICKET_TABLE);
executeUpdate(CREATE_HANDLER_TABLE);
executeUpdate(CREATE_REPORTERS_TABLE);
}
@Override
protected void update()
{
}
public void logReportHandling(int reportId, int handlerId)
{
executeUpdate(INSERT_HANDLER, new ColumnInt("reportId", reportId), new ColumnInt("handlerId", handlerId));
}
public void logReportSending(int reportId, int reporterId, String reason)
{
executeUpdate(INSERT_SENDER, new ColumnInt("reportId", reportId), new ColumnInt("reporterId", reporterId),
new ColumnVarChar("reason", 100, reason));
}
public void logReport(int reportId, int playerId, String server, int closerId, ReportResult result, String reason)
{
executeUpdate(INSERT_TICKET, new ColumnInt("reportId", reportId), new ColumnInt("playerId", playerId),
new ColumnVarChar("server", 50, server), new ColumnInt("closerId", closerId),
new ColumnVarChar("result", 25, result.toString()), new ColumnVarChar("reason", 100, reason));
}
}

View File

@ -0,0 +1,25 @@
package mineplex.core.report;
import org.bukkit.ChatColor;
public enum ReportResult
{
UNDETERMINED(ChatColor.WHITE, "Could not determine"),
MUTED(ChatColor.YELLOW, "Muted"),
BANNED(ChatColor.RED, "Banned"),
ABUSE(ChatColor.DARK_RED, "Abuse of report system");
private ChatColor color;
private String displayMessage;
private ReportResult(ChatColor color, String displayMessage)
{
this.color = color;
this.displayMessage = displayMessage;
}
public String toDisplayMessage()
{
return color + displayMessage;
}
}

View File

@ -0,0 +1,39 @@
package mineplex.core.report.command;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
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.portal.Portal;
import mineplex.core.report.ReportManager;
import mineplex.core.report.ReportPlugin;
import org.bukkit.entity.Player;
public class ReportCloseCommand extends CommandBase<ReportPlugin>
{
public ReportCloseCommand(ReportPlugin plugin)
{
super(plugin, Rank.ADMIN, "reportclose", "rc");
}
@Override
public void Execute(final Player player, final String[] args)
{
if(args == null || args.length < 2)
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cRed + "Your arguments are inappropriate for this command!"));
return;
}
else
{
int reportId = Integer.parseInt(args[0]);
String reason = F.combine(args, 1, null, false);
ReportManager.getInstance().closeReport(reportId, player, reason);
}
}
}

View File

@ -0,0 +1,48 @@
package mineplex.core.report.command;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
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.portal.Portal;
import mineplex.core.report.ReportManager;
import mineplex.core.report.ReportPlugin;
import org.bukkit.entity.Player;
public class ReportCommand extends CommandBase<ReportPlugin>
{
public ReportCommand(ReportPlugin plugin)
{
super(plugin, Rank.ALL, "report");
}
@Override
public void Execute(final Player player, final String[] args)
{
if(args == null || args.length < 2)
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cRed + "Your arguments are inappropriate for this command!"));
return;
}
else
{
String playerName = args[0];
Player reportedPlayer = UtilPlayer.searchOnline(player, playerName, false);
String reason = F.combine(args, 1, null, false);
if (reportedPlayer != null)
{
ReportManager.getInstance().reportPlayer(player, reportedPlayer, reason);
}
else
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cRed + "Unable to find player '"
+ playerName + "'!"));
}
}
}
}

View File

@ -0,0 +1,38 @@
package mineplex.core.report.command;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
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.portal.Portal;
import mineplex.core.report.ReportManager;
import mineplex.core.report.ReportPlugin;
import org.bukkit.entity.Player;
public class ReportHandleCommand extends CommandBase<ReportPlugin>
{
public ReportHandleCommand(ReportPlugin plugin)
{
super(plugin, Rank.ADMIN, "reporthandle", "rh");
}
@Override
public void Execute(final Player player, final String[] args)
{
if(args == null || args.length < 1)
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cRed + "Your arguments are inappropriate for this command!"));
return;
}
else
{
int reportId = Integer.parseInt(args[0]);
ReportManager.getInstance().handleReport(reportId, player);
}
}
}

View File

@ -0,0 +1,31 @@
package mineplex.core.report.command;
import org.bukkit.entity.Player;
import mineplex.core.common.util.UtilServer;
import mineplex.core.report.ReportManager;
import mineplex.serverdata.ServerCommand;
public class ReportNotification extends ServerCommand
{
// TODO: Encode in JSON-interactive chat message
private String notification;
public ReportNotification(String notification)
{
super(); // Send to all servers
}
public void run()
{
// Message all players that can receive report notifications.
for (Player player : UtilServer.getPlayers())
{
if (ReportManager.getInstance().hasReportNotifications(player))
{
player.sendMessage(notification);
}
}
}
}

View File

@ -269,6 +269,10 @@ public class RewardManager
new ItemStack(Material.REDSTONE), rarity, 10));
addReward(new UnknownPackageReward(this, donationManager, "Emerald Twirl Particles", "Green Ring",
new ItemStack(Material.EMERALD), rarity, 8));
addReward(new UnknownPackageReward(this, donationManager, "Flame Fairy Particles", "Flame Fairy",
new ItemStack(Material.APPLE), rarity, 4));
addReward(new UnknownPackageReward(this, donationManager, "Heart Particles", "I Heart You",
new ItemStack(Material.BLAZE_POWDER), rarity, 2));
}
public void addReward(Reward reward)

View File

@ -1,13 +1,8 @@
package mineplex.core.reward;
import java.sql.Connection;
import java.sql.SQLException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.database.Tables;
import org.jooq.DSLContext;
@ -18,9 +13,9 @@ import org.jooq.impl.DSL;
*/
public class RewardRepository extends RepositoryBase
{
public RewardRepository(Plugin plugin)
public RewardRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override
@ -37,26 +32,21 @@ public class RewardRepository extends RepositoryBase
public void logReward(Player player, String type, String rarity, String reward)
{
try
{
try (Connection connection = getConnection())
{
DSLContext context = DSL.using(connection);
DSLContext context;
context.insertInto(Tables.rewardLog)
.set(Tables.rewardLog.accountId, DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.uuid.eq(player.getUniqueId().toString())))
.set(Tables.rewardLog.date, DSL.currentTimestamp())
.set(Tables.rewardLog.type, type)
.set(Tables.rewardLog.rarity, rarity)
.set(Tables.rewardLog.reward, reward)
.execute();
}
}
catch (SQLException e)
synchronized (this)
{
e.printStackTrace();
context = DSL.using(getConnection());
}
context.insertInto(Tables.rewardLog)
.set(Tables.rewardLog.accountId, DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.uuid.eq(player.getUniqueId().toString())))
.set(Tables.rewardLog.date, DSL.currentTimestamp())
.set(Tables.rewardLog.type, type)
.set(Tables.rewardLog.rarity, rarity)
.set(Tables.rewardLog.reward, reward)
.execute();
}
}

View File

@ -0,0 +1,58 @@
package mineplex.core.serverConfig;
import java.lang.reflect.Field;
import net.minecraft.server.v1_7_R4.PlayerList;
import org.bukkit.craftbukkit.v1_7_R4.CraftServer;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.serverdata.Region;
import mineplex.serverdata.ServerGroup;
import mineplex.serverdata.ServerManager;
public class ServerConfiguration extends MiniPlugin
{
private Field _playerListMaxPlayers;
private ServerGroup _serverGroup;
public ServerConfiguration(JavaPlugin plugin)
{
super("Server Configuration", plugin);
Region region = plugin.getConfig().getBoolean("serverstatus.us") ? Region.US : Region.EU;
for (ServerGroup serverGroup : ServerManager.getServerRepository(region).getServerGroups(false))
{
if (serverGroup.getName().equalsIgnoreCase(plugin.getConfig().getString("serverstatus.group")))
{
_serverGroup = serverGroup;
break;
}
}
if (_serverGroup == null)
return;
try
{
_playerListMaxPlayers = PlayerList.class.getDeclaredField("maxPlayers");
_playerListMaxPlayers.setAccessible(true);
_playerListMaxPlayers.setInt(((CraftServer)_plugin.getServer()).getHandle(), _serverGroup.getMaxPlayers());
}
catch (Exception e)
{
e.printStackTrace();
}
_plugin.getServer().setWhitelist(_serverGroup.getWhitelist());
((CraftServer)_plugin.getServer()).getServer().setPvP(_serverGroup.getPvp());
((CraftServer)_plugin.getServer()).getServer().setTexturePack(_serverGroup.getResourcePack());
}
public ServerGroup getServerGroup()
{
return _serverGroup;
}
}

View File

@ -6,25 +6,35 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import mineplex.core.common.util.C;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.DBPool;
public class SimpleStatsRepository
{
private static Object _connectionLock = new Object();
private String _connectionString = "jdbc:mysql://sqlstats.mineplex.com:3306/Mineplex?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh"; //try to obfuscate this in the future!
private static String CREATE_STATS_TABLE = "CREATE TABLE IF NOT EXISTS simpleStats (id INT NOT NULL AUTO_INCREMENT, statName VARCHAR(64), statValue VARCHAR(64), PRIMARY KEY (id));";
private static String RETRIEVE_STATS_RECORDS = "SELECT simpleStats.statName, simpleStats.statValue FROM simpleStats;";
private static String STORE_STATS_RECORD = "INSERT INTO simpleStats (statName,statValue) VALUES(?,?);";
private static String RETRIEVE_STAT_RECORD = "SELECT simpleStats.statName, simpleStats.statValue FROM simpleStats WHERE statName = '?';";
private Connection _connection = null;
public void initialize()
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
Class.forName("com.mysql.jdbc.Driver");
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = connection.prepareStatement(CREATE_STATS_TABLE);
preparedStatement = _connection.prepareStatement(CREATE_STATS_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
@ -53,15 +63,23 @@ public class SimpleStatsRepository
PreparedStatement preparedStatement = null;
NautHashMap<String, String> statRecords = new NautHashMap<String, String>();
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
preparedStatement = connection.prepareStatement(RETRIEVE_STATS_RECORDS);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
synchronized (_connectionLock)
{
statRecords.put(resultSet.getString(1), resultSet.getString(2));
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(RETRIEVE_STATS_RECORDS);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
statRecords.put(resultSet.getString(1), resultSet.getString(2));
}
}
}
catch (Exception exception)
@ -102,13 +120,21 @@ public class SimpleStatsRepository
{
PreparedStatement preparedStatement = null;
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
preparedStatement = connection.prepareStatement(STORE_STATS_RECORD);
preparedStatement.setString(1, statName);
preparedStatement.setString(2, statValue);
preparedStatement.executeUpdate();
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(STORE_STATS_RECORD);
preparedStatement.setString(1, statName);
preparedStatement.setString(2, statValue);
preparedStatement.executeUpdate();
}
}
catch (Exception exception)
{
@ -136,16 +162,24 @@ public class SimpleStatsRepository
PreparedStatement preparedStatement = null;
NautHashMap<String, String> statRecords = new NautHashMap<String, String>();
try (Connection connection = DBPool.STATS_MINEPLEX.getConnection())
try
{
preparedStatement = connection.prepareStatement(RETRIEVE_STAT_RECORD);
preparedStatement.setString(1, statName);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
synchronized (_connectionLock)
{
statRecords.put(resultSet.getString(1), resultSet.getString(2));
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(RETRIEVE_STAT_RECORD);
preparedStatement.setString(1, statName);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
statRecords.put(resultSet.getString(1), resultSet.getString(2));
}
}
}
catch (Exception exception)

View File

@ -11,6 +11,7 @@ import mineplex.core.MiniClientPlugin;
import mineplex.core.account.event.RetrieveClientInformationEvent;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilServer;
import mineplex.core.stats.command.GiveStatCommand;
import mineplex.core.stats.command.TimeCommand;
import mineplex.core.stats.event.StatChangeEvent;
@ -182,5 +183,6 @@ public class StatsManager extends MiniClientPlugin<PlayerStats>
public void AddCommands()
{
AddCommand(new TimeCommand(this));
AddCommand(new GiveStatCommand(this));
}
}

View File

@ -1,6 +1,5 @@
package mineplex.core.stats;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -8,11 +7,9 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnVarChar;
@ -39,9 +36,9 @@ public class StatsRepository extends RepositoryBase
private static String RETRIEVE_STATS = "SELECT id, name FROM stats;";
private static String INSERT_STAT = "INSERT INTO stats (name) VALUES (?);";
public StatsRepository(Plugin plugin)
public StatsRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override
@ -88,9 +85,9 @@ public class StatsRepository extends RepositoryBase
{
System.out.println("saving stats.");
try (Connection connection = getConnection())
try
{
DSLContext context = DSL.using(connection);
DSLContext context = DSL.using(getConnection());
List<Update> updates = new ArrayList<>();
List<Insert> inserts = new ArrayList<>();
@ -137,33 +134,36 @@ public class StatsRepository extends RepositoryBase
}
}
public PlayerStats loadOfflinePlayerStats(String playerName) throws SQLException
public PlayerStats loadOfflinePlayerStats(String playerName)
{
try (Connection connection = getConnection())
PlayerStats playerStats = null;
DSLContext context;
synchronized (this)
{
PlayerStats playerStats = null;
DSLContext context = DSL.using(connection);
Result<Record2<String, Integer>> result = context.select(Tables.stats.name, Tables.accountStats.value).from(Tables.accountStats)
.join(Tables.stats)
.on(Tables.stats.id.eq(Tables.accountStats.statId))
.where(Tables.accountStats.accountId.eq(DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.name.eq(playerName)))
).fetch();
if (result.isNotEmpty())
{
playerStats = new PlayerStats();
for (Record2<String, Integer> record : result)
{
playerStats.addStat(record.value1(), record.value2());
}
}
return playerStats;
context = DSL.using(getConnection());
}
Result<Record2<String, Integer>> result = context.select(Tables.stats.name, Tables.accountStats.value).from(Tables.accountStats)
.join(Tables.stats)
.on(Tables.stats.id.eq(Tables.accountStats.statId))
.where(Tables.accountStats.accountId.eq(DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.name.eq(playerName)))
).fetch();
if (result.isNotEmpty())
{
playerStats = new PlayerStats();
for (Record2<String, Integer> record : result)
{
playerStats.addStat(record.value1(), record.value2());
}
}
return playerStats;
}
public PlayerStats loadClientInformation(String uuid)

View File

@ -0,0 +1,42 @@
package mineplex.core.stats.command;
import org.bukkit.entity.Player;
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.stats.StatsManager;
public class GiveStatCommand extends CommandBase<StatsManager>
{
public GiveStatCommand(StatsManager plugin)
{
super(plugin, Rank.OWNER, "givestat");
}
@Override
public void Execute(final Player caller, final String[] args)
{
if (args.length < 3)
{
UtilPlayer.message(caller, F.main("Stats", "/givestat <Target> <Name> <Amount>"));
return;
}
try
{
Player player = UtilPlayer.searchOnline(caller, args[0], true);
if (player == null)
return;
Plugin.incrementStat(player, args[1], Integer.parseInt(args[2]));
UtilPlayer.message(caller, F.main("Stats", "Applied " + F.elem(Integer.parseInt(args[2]) + " " + args[1]) + " to " + F.elem(player.getName()) + "."));
}
catch (Exception e)
{
UtilPlayer.message(caller, F.main("Stats", "/givestat <Name> <Amount>"));
}
}
}

View File

@ -15,6 +15,7 @@ import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.serverdata.MinecraftServer;
import mineplex.serverdata.Region;
import mineplex.serverdata.ServerCommandManager;
import mineplex.serverdata.ServerManager;
import mineplex.serverdata.ServerRepository;
import mineplex.serverdata.Utility;
@ -47,6 +48,9 @@ public class ServerStatusManager extends MiniPlugin
setupConfigValues();
_name = plugin.getConfig().getString("serverstatus.name");
ServerCommandManager.getInstance().initializeServer(_name);
_us = plugin.getConfig().getBoolean("serverstatus.us");
Region region = _us ? Region.US : Region.EU;
@ -104,7 +108,7 @@ public class ServerStatusManager extends MiniPlugin
@EventHandler
public void saveServerStatus(UpdateEvent event)
{
if (event.getType() != UpdateType.SEC)
if (event.getType() != UpdateType.FASTER)
return;
if (!_enabled)

View File

@ -1,9 +1,7 @@
package mineplex.enjinTranslator;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.column.ColumnInt;
import mineplex.core.database.column.ColumnVarChar;
@ -12,9 +10,9 @@ public class TempRepository extends RepositoryBase
{
private static String INSERT_CLIENT_INVENTORY = "INSERT INTO accountInventory (accountId, itemId, count) SELECT accounts.id, 5, ? FROM accounts WHERE accounts.name = ? ON DUPLICATE KEY UPDATE count=count + VALUES(count);";
public TempRepository(Plugin plugin)
public TempRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
public void addGemBooster(String name, int amount)

View File

@ -4,7 +4,6 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.CustomTagFix;
import mineplex.core.Replay;
import mineplex.core.account.CoreClientManager;
import mineplex.core.antihack.AntiHack;
import mineplex.core.antistack.AntiStack;
@ -26,12 +25,12 @@ import mineplex.core.movement.Movement;
import mineplex.core.npc.NpcManager;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.pet.PetManager;
import mineplex.core.playerTracker.PlayerTracker;
import mineplex.core.portal.Portal;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.projectile.ProjectileManager;
import mineplex.core.punish.Punish;
import mineplex.core.recharge.Recharge;
import mineplex.core.serverConfig.ServerConfiguration;
import mineplex.core.spawn.Spawn;
import mineplex.core.status.ServerStatusManager;
import mineplex.core.task.TaskManager;
@ -61,7 +60,7 @@ public class Hub extends JavaPlugin implements IRelation
@Override
public void onEnable()
{
{
getConfig().addDefault(WEB_CONFIG, "http://accounts.mineplex.com/");
getConfig().set(WEB_CONFIG, getConfig().getString(WEB_CONFIG));
saveConfig();
@ -80,6 +79,8 @@ public class Hub extends JavaPlugin implements IRelation
Punish punish = new Punish(this, webServerAddress, clientManager);
DonationManager donationManager = new DonationManager(this, webServerAddress);
new ServerConfiguration(this);
//Other Modules
PreferencesManager preferenceManager = new PreferencesManager(this, clientManager, donationManager);
@ -100,7 +101,6 @@ public class Hub extends JavaPlugin implements IRelation
PacketHandler packetHandler = new PacketHandler(this);
DisguiseManager disguiseManager = new DisguiseManager(this, packetHandler);
HubManager hubManager = new HubManager(this, new BlockRestore(this), clientManager, donationManager, new ConditionManager(this), disguiseManager, new TaskManager(this, webServerAddress), portal, partyManager, preferenceManager, petManager, pollManager);
new PlayerTracker(this, serverStatusManager.getCurrentServerName(), serverStatusManager.getUs());
QueueManager queueManager = new QueueManager(this, clientManager, donationManager, new EloManager(this), partyManager);
@ -134,7 +134,7 @@ public class Hub extends JavaPlugin implements IRelation
new ClassCombatShop(shopManager, clientManager, donationManager, "Knight", classManager.GetClass("Knight"));
new ClassCombatShop(shopManager, clientManager, donationManager, "Assassin", classManager.GetClass("Assassin"));
new FriendManager(this, preferenceManager);
new FriendManager(this, clientManager, preferenceManager);
//Updates
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Updater(this), 1, 1);

View File

@ -1,5 +1,6 @@
package mineplex.hub;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.Bukkit;
@ -43,6 +44,7 @@ import mineplex.core.RankBenefitsGiver9000;
import mineplex.core.account.CoreClient;
import mineplex.core.account.CoreClientManager;
import mineplex.core.account.event.RetrieveClientInformationEvent;
import mineplex.core.achievement.Achievement;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.blockrestore.BlockRestore;
import mineplex.core.common.Rank;
@ -102,7 +104,7 @@ import mineplex.minecraft.game.core.damage.CustomDamageEvent;
public class HubManager extends MiniClientPlugin<HubClient>
{
// Snowman!
public HubType Type = HubType.Halloween;
public HubType Type = HubType.Normal;
private BlockRestore _blockRestore;
private CoreClientManager _clientManager;
@ -137,6 +139,8 @@ public class HubManager extends MiniClientPlugin<HubClient>
private boolean _shuttingDown;
private HashMap<String, Long> _portalTime = new HashMap<String, Long>();
private HashMap<String, ArrayList<String>> _creativeAdmin = new HashMap<String, ArrayList<String>>();
//Admin
private boolean _gadgetsEnabled = true;
@ -610,6 +614,9 @@ public class HubManager extends MiniClientPlugin<HubClient>
boolean ownsUltra = _donationManager.Get(player.getName()).OwnsUltraPackage();
//Level Prefix
String levelStr = _achievementManager.getMineplexLevel(player, rank);
//Rank Prefix
String rankStr = "";
if (rank != Rank.ALL)
@ -627,7 +634,7 @@ public class HubManager extends MiniClientPlugin<HubClient>
event.getRecipients().clear();
event.setMessage(event.getMessage().substring(1, event.getMessage().length()));
event.setFormat(C.cDPurple + C.Bold + "Party " + C.cWhite + C.Bold + "%1$s " + C.cPurple + "%2$s");
event.setFormat(levelStr + C.cDPurple + C.Bold + "Party " + C.cWhite + C.Bold + "%1$s " + C.cPurple + "%2$s");
for (String name : party.GetPlayers())
{
@ -656,7 +663,7 @@ public class HubManager extends MiniClientPlugin<HubClient>
}
event.setMessage(event.getMessage());
event.setFormat(rankStr + C.cYellow + "%1$s " + C.cWhite + "%2$s");
event.setFormat(levelStr + rankStr + C.cYellow + "%1$s " + C.cWhite + "%2$s");
}
}
}
@ -996,4 +1003,39 @@ public class HubManager extends MiniClientPlugin<HubClient>
if (!_gadgetsEnabled)
event.setCancelled(true);
}
public void addGameMode(Player caller, Player target)
{
if (!_creativeAdmin.containsKey(caller.getName()))
_creativeAdmin.put(caller.getName(), new ArrayList<String>());
if (target.getGameMode() == GameMode.CREATIVE)
{
_creativeAdmin.get(caller.getName()).add(target.getName());
}
else
{
_creativeAdmin.get(caller.getName()).remove(target.getName());
}
}
@EventHandler
public void clearGameMode(PlayerQuitEvent event)
{
ArrayList<String> creative = _creativeAdmin.remove(event.getPlayer().getName());
if (creative == null)
return;
for (String name : creative)
{
Player player = UtilPlayer.searchExact(name);
if (player == null)
continue;
player.setGameMode(GameMode.SURVIVAL);
UtilPlayer.message(player, F.main("Game Mode", event.getPlayer().getName() + " left the game. Creative Mode: " + F.tf(false)));
}
}
}

View File

@ -5,6 +5,8 @@ import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.hub.HubManager;
public class GameModeCommand extends CommandBase<HubManager>
@ -17,9 +19,27 @@ public class GameModeCommand extends CommandBase<HubManager>
@Override
public void Execute(Player caller, String[] args)
{
if (caller.getGameMode() == GameMode.SURVIVAL)
caller.setGameMode(GameMode.CREATIVE);
Player target = caller;
if (args != null && args.length >= 1)
{
target = UtilPlayer.searchOnline(caller, args[0], true);
if (target == null)
return;
}
if (target.getGameMode() == GameMode.SURVIVAL)
target.setGameMode(GameMode.CREATIVE);
else
caller.setGameMode(GameMode.SURVIVAL);
target.setGameMode(GameMode.SURVIVAL);
if (!target.equals(caller))
{
Plugin.addGameMode(caller, target);
UtilPlayer.message(target, F.main("Game Mode", caller.getName() + " toggled your Creative Mode: " + F.tf(target.getGameMode() == GameMode.CREATIVE)));
}
UtilPlayer.message(caller, F.main("Game Mode", target.getName() + " Creative Mode: " + F.tf(target.getGameMode() == GameMode.CREATIVE)));
}
}

View File

@ -8,7 +8,6 @@ import java.util.UUID;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnInt;
@ -29,7 +28,7 @@ public class PollRepository extends RepositoryBase
public PollRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override

View File

@ -231,7 +231,7 @@ public class MapParser extends JavaPlugin implements Listener
}
}
//@EventHandler
@EventHandler
public void DisableCreatures(EntitySpawnEvent event)
{
if (event.getEntityType() == EntityType.DROPPED_ITEM || event.getEntity() instanceof LivingEntity)

View File

@ -1,6 +1,8 @@
package mineplex.minecraft.game.classcombat.Skill.Knight;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import org.bukkit.entity.Player;
@ -21,7 +23,7 @@ import mineplex.minecraft.game.classcombat.Skill.SkillFactory;
public class Fortitude extends Skill
{
private WeakHashMap<Player, Double> _preHealth = new WeakHashMap<Player, Double>();
private WeakHashMap<Player, Integer> _health = new WeakHashMap<Player, Integer>();
private WeakHashMap<Player, Double> _health = new WeakHashMap<Player, Double>();
private WeakHashMap<Player, Long> _last = new WeakHashMap<Player, Long>();
public Fortitude(SkillFactory skills, String name, ClassType classType, SkillType skillType, int cost, int levels)
@ -34,7 +36,7 @@ public class Fortitude extends Skill
"up to #0#1 of the health you lost.",
"",
"You restore health at a rate of",
"1 health per #3.5#-0.5 seconds.",
"1 health per #3#-0.5 seconds.",
"",
"This does not stack, and is reset if",
"you are hit again."
@ -74,7 +76,7 @@ public class Fortitude extends Skill
double diff = _preHealth.remove(damagee) - damagee.getHealth();
_health.put(damagee, Math.min(level,(int)(diff + 0.5)));
_health.put(damagee, Math.min(level, diff));
_last.put(damagee, System.currentTimeMillis());
}
@ -84,33 +86,35 @@ public class Fortitude extends Skill
if (event.getType() != UpdateType.FASTER)
return;
HashSet<Player> remove = new HashSet<Player>();
for (Player cur : _health.keySet())
Iterator<Entry<Player, Double>> healthIterator = _health.entrySet().iterator();
while (healthIterator.hasNext())
{
int level = getLevel(cur);
if (level == 0) continue;
if (UtilTime.elapsed(_last.get(cur), 3500 - (500 * level)))
{
_health.put(cur, _health.get(cur) - 1);
_last.put(cur, System.currentTimeMillis());
if (_health.get(cur) <= 0)
remove.add(cur);
//Heal
UtilPlayer.health(cur, 1);
//Effect
UtilParticle.PlayParticle(ParticleType.HEART, cur.getEyeLocation(), 0, 0.2f, 0, 0, 1);
}
}
for (Player cur : remove)
{
_health.remove(cur);
_last.remove(cur);
Entry<Player, Double> entry = healthIterator.next();
int level = getLevel(entry.getKey());
if (level == 0)
continue;
if (!UtilTime.elapsed(_last.get(entry.getKey()), 3000 - (500 * level)))
continue;
//Work out healing
double toHeal = Math.min(entry.getValue(), 1);
entry.setValue(entry.getValue() - toHeal);
//Heal
UtilPlayer.health(entry.getKey(), toHeal);
//Effect
UtilParticle.PlayParticle(ParticleType.HEART, entry.getKey().getEyeLocation(), 0, 0.2f, 0, 0, 1);
//Finished
if (entry.getValue() <= 0)
healthIterator.remove();
//Last Tick
_last.put(entry.getKey(), System.currentTimeMillis());
}
}

View File

@ -3,6 +3,7 @@ package mineplex.minecraft.game.classcombat.Skill.Mage;
import java.util.HashMap;
import java.util.HashSet;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
@ -10,6 +11,7 @@ import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerDropItemEvent;
import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType;
@ -18,6 +20,7 @@ import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.updater.UpdateType;
import mineplex.core.common.util.UtilBlock;
import mineplex.core.common.util.UtilGear;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
@ -127,7 +130,6 @@ public class ArcticArmor extends Skill
Remove(cur);
continue;
}
//Check Allowed
SkillTriggerEvent trigger = new SkillTriggerEvent(cur, GetName(), GetClassType());
@ -176,6 +178,44 @@ public class ArcticArmor extends Skill
Factory.Condition().Factory().Protection(GetName(), other, cur, 1.9, 1, false, true, true);
}
}
@EventHandler
public void Damage(UpdateEvent event)
{
if (event.getType() != UpdateType.FAST)
return;
for (Player cur : UtilServer.getPlayers())
{
if (cur.getGameMode() != GameMode.SURVIVAL)
continue;
if (cur.getEyeLocation().getBlock().getType() == Material.ICE)
{
Player damager = null;
double closest = 0;
for (Player player : _active)
{
if (player.equals(cur))
continue;
double dist = UtilMath.offset(player, cur);
if (dist < 5 && (damager == null || dist < closest))
{
damager = player;
closest = dist;
}
}
//Damage Event
Factory.Damage().NewDamageEvent(cur, damager, null,
DamageCause.CUSTOM, 2, false, true, false,
damager == null ? null : damager.getName(), "Arctic Ice");
}
}
}
@EventHandler
public void Slow(UpdateEvent event)

View File

@ -70,7 +70,7 @@ public class Fissure extends SkillActive
@Override
public void Skill(Player player, int level)
{
FissureData data = new FissureData(this, player, level, player.getLocation().getDirection(), player.getLocation().add(0, -0.5, 0));
FissureData data = new FissureData(this, player, level, player.getLocation().getDirection(), player.getLocation().add(0, -0.4, 0));
_active.add(data);
//Inform

View File

@ -48,7 +48,7 @@ public class Agility extends SkillActive
"Speed I for #3#1 seconds. You take",
"#45#5 % less damage and take no knockback.",
"",
"Agility ends if you interact."
"Agility ends if you Left-Click."
});
}

View File

@ -61,7 +61,7 @@ public class WolfsPounce extends SkillChargeSword
public void DoSkillCustom(Player player, float charge)
{
//Action
UtilAction.velocity(player, 0.4 + (1.2*charge), 0.2, 0.2 + (0.6*charge), true);
UtilAction.velocity(player, 0.4 + (1.4*charge), 0.2, 0.2 + (0.7*charge), true);
_live.put(player, System.currentTimeMillis());
//Inform

View File

@ -435,7 +435,7 @@ public class SkillFactory extends MiniPlugin implements ISkillFactory
AddSkill(new Agility(this, "Agility", ClassType.Ranger, SkillType.Axe,
1, 4,
0, 0,
20000, 2000, true,
14000, 1000, true,
new Material[] {Material.IRON_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE},
new Action[] {Action.RIGHT_CLICK_AIR, Action.RIGHT_CLICK_BLOCK}));

View File

@ -1,5 +1,8 @@
package mineplex.minecraft.game.classcombat.shop.page;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@ -15,6 +18,7 @@ import mineplex.minecraft.game.classcombat.shop.button.EditAndSaveCustomBuildBut
import mineplex.minecraft.game.classcombat.shop.button.SelectCustomBuildButton;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.donation.DonationManager;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.shop.page.ShopPageBase;
@ -85,7 +89,35 @@ public class CustomBuildPage extends ShopPageBase<ClassShopManager, ClassCombatS
if (customBuild != null)
{
AddButton(slot, new ShopItem(Material.INK_SACK, itemData, "Apply " + customBuild.Name, lockedText, 1, locked, true), new SelectCustomBuildButton(this, customBuild));
String[] skills = new String[7];
skills[0] = C.cYellow + " ";
skills[1] = C.cYellow + "Sword: " + ChatColor.RESET +
((customBuild.SwordSkillLevel != null && customBuild.SwordSkillLevel > 0) ?
(customBuild.SwordSkill + " " + customBuild.SwordSkillLevel) : "None");
skills[2] = C.cYellow + "Axe: " + ChatColor.RESET +
((customBuild.AxeSkillLevel != null && customBuild.AxeSkillLevel > 0) ?
(customBuild.AxeSkill + " " + customBuild.AxeSkillLevel) : "None");
skills[3] = C.cYellow + "Bow: " + ChatColor.RESET +
((customBuild.BowSkillLevel != null && customBuild.BowSkillLevel > 0) ?
(customBuild.BowSkill + " " + customBuild.BowSkillLevel) : "None");
skills[4] = C.cYellow + "Passive A: " + ChatColor.RESET +
((customBuild.ClassPassiveASkillLevel != null && customBuild.ClassPassiveASkillLevel > 0) ?
(customBuild.ClassPassiveASkill + " " + customBuild.ClassPassiveASkillLevel) : "None");
skills[5] = C.cYellow + "Passive B: " + ChatColor.RESET +
((customBuild.ClassPassiveBSkillLevel != null && customBuild.ClassPassiveBSkillLevel > 0) ?
(customBuild.ClassPassiveBSkill + " " + customBuild.ClassPassiveBSkillLevel) : "None");
skills[6] = C.cYellow + "Passive C: " + ChatColor.RESET +
((customBuild.GlobalPassiveSkillLevel != null && customBuild.GlobalPassiveSkillLevel > 0) ?
(customBuild.GlobalPassiveSkill + " " + customBuild.GlobalPassiveSkillLevel) : "None");
AddButton(slot, new ShopItem(Material.INK_SACK, itemData, "Apply " + customBuild.Name, skills, 1, locked, true), new SelectCustomBuildButton(this, customBuild));
}
else
{

View File

@ -8,6 +8,5 @@
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpcore-4.2.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.ServerData"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/jedis-2.4.2.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -9,14 +9,14 @@ import java.util.Set;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import mineplex.core.portal.Portal;
import mineplex.core.portal.ServerTransfer;
import mineplex.serverdata.DataRepository;
import mineplex.serverdata.MinecraftServer;
import mineplex.serverdata.RedisDataRepository;
import mineplex.serverdata.Region;
import mineplex.serverdata.ServerManager;
import mineplex.serverdata.ServerRepository;
import mineplex.serverdata.transfers.ServerTransfer;
import mineplex.serverdata.transfers.TransferCommand;
public class QueueRepository
{
@ -130,7 +130,10 @@ public class QueueRepository
{
for (String playerName : queueParty.getPlayers())
{
Portal.transferPlayer(playerName, emptyServer.getName());
// Execute a transfer command
ServerTransfer serverTransfer = new ServerTransfer(playerName, emptyServer.getName());
TransferCommand transferCommand = new TransferCommand(serverTransfer);
transferCommand.publish();
}
}
}

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AFTER_CLEAN_TARGETS" value="ServerData,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AUTO_TARGETS" value="ServerData,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_MANUAL_TARGETS" value="ServerData,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AFTER_CLEAN_TARGETS" value="Hub,Arcade,StaffServer,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AUTO_TARGETS" value="Arcade,Hub,StaffServer,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_MANUAL_TARGETS" value="Arcade,Hub,StaffServer,"/>
<booleanAttribute key="org.eclipse.ant.ui.ATTR_TARGETS_UPDATED" value="true"/>
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${resource}"/>
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${project}"/>
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>

View File

@ -0,0 +1,7 @@
package mineplex.serverdata;
public interface CommandCallback
{
public void run(ServerCommand command);
}

View File

@ -0,0 +1,17 @@
package mineplex.serverdata;
public class CommandType
{
private Class<? extends ServerCommand> _commandClazz;
public Class<? extends ServerCommand> getCommandType() { return _commandClazz; }
private CommandCallback _commandCallback;
public CommandCallback getCallback() { return _commandCallback; }
public CommandType(Class<? extends ServerCommand> commandClazz, CommandCallback commandCallback)
{
_commandClazz = commandClazz;
_commandCallback = commandCallback;
}
}

View File

@ -27,9 +27,9 @@ public class RedisDataRepository<T extends Data> implements DataRepository<T>
// The geographical region of the servers stored by this ServerRepository
private Region _region;
private Class<T> elementType;
private Class<T> _elementType;
private String elementLabel;
private String _elementLabel;
/**
* Class constructor
@ -40,10 +40,10 @@ public class RedisDataRepository<T extends Data> implements DataRepository<T>
public RedisDataRepository(String host, int port, Region region,
Class<T> elementType, String elementLabel)
{
this._jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
this._region = region;
this.elementType = elementType;
this.elementLabel = elementLabel;
_jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
_region = region;
_elementType = elementType;
_elementLabel = elementLabel;
}
public RedisDataRepository(Region region, Class<T> elementType, String elementLabel)
@ -54,7 +54,7 @@ public class RedisDataRepository<T extends Data> implements DataRepository<T>
public String getElementSetKey()
{
return concatenate("data", elementLabel, _region.toString());
return concatenate("data", _elementLabel, _region.toString());
}
public String generateKey(T element)
@ -315,7 +315,7 @@ public class RedisDataRepository<T extends Data> implements DataRepository<T>
protected T deserialize(String serializedData)
{
return Utility.deserialize(serializedData, elementType);
return Utility.deserialize(serializedData, _elementType);
}
protected String serialize(T element)

View File

@ -241,7 +241,6 @@ public class RedisServerRepository implements ServerRepository
servers.add(server);
}
}
}
catch (JedisConnectionException exception)
{
@ -261,21 +260,31 @@ public class RedisServerRepository implements ServerRepository
}
@Override
public Collection<ServerGroup> getServerGroups()
public Collection<ServerGroup> getServerGroups(boolean fetch)
{
Collection<ServerGroup> servers = new HashSet<ServerGroup>();
Jedis jedis = _jedisPool.getResource();
try
{
String key = "servergroups";
Set<String> names = jedis.smembers(key);
for (String groupName : names)
Set<Response<Map<String, String>>> serverDatas = new HashSet<Response<Map<String, String>>>();
Pipeline pipeline = jedis.pipelined();
for (String serverName : names)
{
String dataKey = concatenate(key, groupName);
Map<String, String> data = jedis.hgetAll(dataKey);
servers.add(new ServerGroup(data, _region));
String dataKey = concatenate(key, serverName);
serverDatas.add(pipeline.hgetAll(dataKey));
}
pipeline.sync();
for (Response<Map<String, String>> response : serverDatas)
{
Map<String, String> data = response.get();
servers.add(new ServerGroup(data, _region, fetch));
}
}
catch (JedisConnectionException exception)

View File

@ -4,7 +4,7 @@ public abstract class ServerCommand
{
// The names of servers targetted to receive this ServerCommand.
private String[] targetServers;
private String[] _targetServers;
/**
* Class constructor
@ -12,13 +12,16 @@ public abstract class ServerCommand
*/
public ServerCommand(String... targetServers)
{
this.targetServers = targetServers;
_targetServers = targetServers;
}
/**
* Run the command on it's destination target server.
*/
public abstract void run();
public void run()
{
// Not yet implemented in base
}
/**
* @param serverName - the name of the server to be checked for whether they are a target
@ -27,10 +30,10 @@ public abstract class ServerCommand
*/
public boolean isTargetServer(String serverName)
{
if (targetServers == null || targetServers.length == 0) // Targets all online servers
if (_targetServers == null || _targetServers.length == 0) // Targets all online servers
return true;
for (String targetServer : targetServers)
for (String targetServer : _targetServers)
{
if (targetServer.equalsIgnoreCase(serverName))
{

View File

@ -3,6 +3,7 @@ package mineplex.serverdata;
import java.util.HashMap;
import java.util.Map;
import mineplex.serverdata.transfers.TransferCommand;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@ -11,23 +12,30 @@ public class ServerCommandManager
{
// The singleton instance of ServerCommandManager
private static ServerCommandManager instance;
private static ServerCommandManager _instance;
public final String SERVER_COMMANDS_CHANNEL = "commands.server";
private JedisPool _jedisPool;
private Map<String, Class<? extends ServerCommand>> _commandTypes;
private Map<String, CommandType> _commandTypes;
private String _localServerName;
public void initializeServer(String serverName) { _localServerName = serverName; }
public boolean isServerInitialized() { return _localServerName != null; }
/**
* Private class constructor to prevent non-singleton instances.
*/
private ServerCommandManager()
{
this._jedisPool = new JedisPool(new JedisPoolConfig(), ServerManager.DEFAULT_REDIS_HOST,
_jedisPool = new JedisPool(new JedisPoolConfig(), ServerManager.DEFAULT_REDIS_HOST,
ServerManager.DEFAULT_REDIS_PORT);
this._commandTypes = new HashMap<String, Class<? extends ServerCommand>>();
_commandTypes = new HashMap<String, CommandType>();
initialize();
// Register default command types
registerCommandType(TransferCommand.class);
}
/**
@ -92,14 +100,27 @@ public class ServerCommandManager
*/
public void handleCommand(String commandType, String serializedCommand)
{
if (!isServerInitialized())
{
// TODO: Log un-initialized server receiving command?
return;
}
if (_commandTypes.containsKey(commandType))
{
ServerCommand serverCommand = Utility.deserialize(serializedCommand, _commandTypes.get(commandType));
Class<? extends ServerCommand> commandClazz = _commandTypes.get(commandType).getCommandType();
ServerCommand serverCommand = Utility.deserialize(serializedCommand, commandClazz);
//if (serverCommand.isTargetServer("THIS SERVER NAME HERE")) // TODO: Find server name ref
//{
if (serverCommand.isTargetServer(_localServerName))
{
// TODO: Run synchronously?
serverCommand.run(); // Run the server command
CommandCallback callback = _commandTypes.get(commandType).getCallback();
serverCommand.run(); // Run server command without callback
if (callback != null)
{
callback.run(serverCommand); // Run callback
}
//}
}
}
@ -108,12 +129,22 @@ public class ServerCommandManager
* Register a new type of {@link ServerCommand}.
* @param commandType - the {@link ServerCommand} type to register.
*/
public void registerCommandType(String commandName, Class<? extends ServerCommand> commandType)
public void registerCommandType(Class<? extends ServerCommand> commandType, CommandCallback callback)
{
if (!_commandTypes.containsKey(commandName))
String commandName = commandType.toString();
if (_commandTypes.containsKey(commandName))
{
_commandTypes.put(commandName, commandType);
// Log overwriting of command type?
}
CommandType cmdType = new CommandType(commandType, callback);
_commandTypes.put(commandName, cmdType);
}
public void registerCommandType(Class<? extends ServerCommand> commandType)
{
registerCommandType(commandType, null);
}
/**
@ -121,11 +152,11 @@ public class ServerCommandManager
*/
public static ServerCommandManager getInstance()
{
if (instance == null)
if (_instance == null)
{
instance = new ServerCommandManager();
_instance = new ServerCommandManager();
}
return instance;
return _instance;
}
}

View File

@ -68,6 +68,9 @@ public class ServerGroup
private boolean _tournament;
public boolean getTournament() { return _tournament; }
private boolean _tournamentPoints;
public boolean getTournamentPoints() { return _tournamentPoints; }
private boolean _teamRejoin;
public boolean getTeamRejoin() { return _teamRejoin; }
@ -116,6 +119,14 @@ public class ServerGroup
private boolean _addNoCheat;
public boolean getAddNoCheat() { return _addNoCheat; }
private boolean _whitelist;
public boolean getWhitelist() { return _whitelist; }
private boolean _staffOnly;
public boolean getStaffOnly() { return _staffOnly; }
private String _resourcePack = "";
public String getResourcePack() { return _resourcePack; }
// The set of active MinecraftServers that belong to this server group
private Set<MinecraftServer> _servers;
public Set<MinecraftServer> getServers() { return _servers; }
@ -126,7 +137,7 @@ public class ServerGroup
* the internal state of this ServerGroup.
* @param region - the region from which to fetch active {@link MinecraftServer}s.
*/
public ServerGroup(Map<String, String> data, Region region)
public ServerGroup(Map<String, String> data, Region region, boolean fetch)
{
_name = data.get("name");
_prefix = data.get("prefix");
@ -144,6 +155,7 @@ public class ServerGroup
_maxPlayers = Integer.valueOf(data.get("maxPlayers"));
_pvp = Boolean.valueOf(data.get("pvp"));
_tournament = Boolean.valueOf(data.get("tournament"));
_tournamentPoints = Boolean.valueOf(data.get("tournamentPoints"));
_generateFreeVersions = Boolean.valueOf(data.get("generateFreeVersions"));
_games = data.get("games");
_serverType = data.get("serverType");
@ -160,8 +172,12 @@ public class ServerGroup
_hotbarInventory = Boolean.valueOf(data.get("hotbarInventory"));
_hotbarHubClock = Boolean.valueOf(data.get("hotbarHubClock"));
_playerKickIdle = Boolean.valueOf(data.get("playerKickIdle"));
_staffOnly = Boolean.valueOf(data.get("staffOnly"));
_whitelist = Boolean.valueOf(data.get("whitelist"));
_resourcePack = data.containsKey("resourcePack") ? data.get("resourcePack") : "";
fetchServers(region);
if (fetch)
fetchServers(region);
}
/**

View File

@ -61,7 +61,7 @@ public interface ServerRepository
* @return a newly instanced snapshot {@link Collection} of all the
* currently active {@link ServerGroup}s in the repository.
*/
public Collection<ServerGroup> getServerGroups();
public Collection<ServerGroup> getServerGroups(boolean fetch);
public Collection<MinecraftServer> getDeadServers();

View File

@ -1,15 +1,15 @@
package mineplex.core.portal;
package mineplex.serverdata.transfers;
public class ServerTransfer
{
// The name of the player who is being transferred.
private String playerName;
public String getPlayerName() { return playerName; }
private String _playerName;
public String getPlayerName() { return _playerName; }
// The name of the destination server in this ServerTransfer.
private String serverName;
public String getServerName() { return serverName; }
private String _serverName;
public String getServerName() { return _serverName; }
/**
* Class constructor
@ -18,7 +18,7 @@ public class ServerTransfer
*/
public ServerTransfer(String playerName, String serverName)
{
this.playerName = playerName;
this.serverName = serverName;
_playerName = playerName;
_serverName = serverName;
}
}

View File

@ -1,7 +1,4 @@
package mineplex.core.portal;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
package mineplex.serverdata.transfers;
import mineplex.serverdata.ServerCommand;
@ -15,7 +12,8 @@ public class TransferCommand extends ServerCommand
{
// The ServerTransfer to be sent to another server for enactment
private ServerTransfer transfer;
private ServerTransfer _transfer;
public ServerTransfer getTransfer() { return _transfer; }
/**
* Class constructor
@ -23,17 +21,12 @@ public class TransferCommand extends ServerCommand
*/
public TransferCommand(ServerTransfer transfer)
{
this.transfer = transfer;
_transfer = transfer;
}
@Override
public void run()
{
Player player = Bukkit.getPlayer(transfer.getPlayerName());
if (player != null && player.isOnline())
{
Portal.getInstance().SendPlayerToServer(player, transfer.getServerName());
}
// Utilitizes a callback functionality to seperate dependencies
}
}

View File

@ -39,6 +39,8 @@ public class ServerMonitor
private static SimpleDateFormat _dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
private static Logger _logger = Logger.getLogger("ServerMonitor");
private static int _totalPlayers = 0;
public static void main (String args[])
{
Region region = !new File("eu.dat").exists() ? Region.US : Region.EU;
@ -74,7 +76,8 @@ public class ServerMonitor
while (true)
{
Collection<ServerGroup> serverGroups = _repository.getServerGroups();
_totalPlayers = 0;
Collection<ServerGroup> serverGroups = _repository.getServerGroups(true);
Collection<MinecraftServer> serverStatuses = _repository.getServerStatuses();
for (MinecraftServer deadServer : _repository.getDeadServers())
@ -88,7 +91,10 @@ public class ServerMonitor
for (ServerGroup serverGroup : serverGroups)
{
serverGroupMap.put(serverGroup.getName(), serverGroup);
_totalPlayers += serverGroup.getPlayerCount();
}
System.out.println("Total Players : " + _totalPlayers);
for (MinecraftServer minecraftServer : serverStatuses)
{
@ -277,16 +283,26 @@ public class ServerMonitor
serversToAdd = 0;
}
}
else if (serverGroup.getName().equalsIgnoreCase("UltraHardcore"))
{
int maxUHC = Math.max(1, _totalPlayers / 6000);
if (serversToAdd > 0)
serversToAdd = maxUHC - joinableServers;
if (joinableServers > maxUHC)
serversToKill = maxUHC - joinableServers;
}
while (serversToAdd > 0)
{
serverNum = serverGroup.generateUniqueId(serverNum + 1);
Collections.sort(dedicatedServers, new DedicatedServerSorter());
DedicatedServer bestServer = getBestDedicatedServer(dedicatedServers, serverGroup);
if (bestServer == null)
{
System.out.println("No best dynamic server available for group " + serverGroup.getName());
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!! NO DEDICATED SERVER AVAILABLE FOR GROUP " + serverGroup.getName() + " !!!!!!!!!!!!!!!!!!!!!!!!!!!!");
break;
}
@ -398,8 +414,7 @@ public class ServerMonitor
if (serverData.getAvailableRam() > serverGroup.getRequiredRam()
&& serverData.getAvailableCpu() > serverGroup.getRequiredCpu())
{
if (bestServer == null
|| serverData.getServerCount(serverGroup) < bestServer.getServerCount(serverGroup))
if (bestServer == null || serverData.getServerCount(serverGroup) < bestServer.getServerCount(serverGroup))
{
bestServer = serverData;
}
@ -416,20 +431,20 @@ public class ServerMonitor
private static void startServer(final DedicatedServer serverSpace, final ServerGroup serverGroup, final int serverNum, final boolean free)
{
String cmd = "/home/mineplex/easyRemoteStartServer.sh";
String cmd = "/home/mineplex/easyRemoteStartServerCustom.sh";
final String groupPrefix = serverGroup.getPrefix();
final String serverName = serverSpace.getName();
final String serverAddress = serverSpace.getPublicAddress();
ProcessRunner pr = new ProcessRunner(new String[] {"/bin/sh", cmd, serverAddress, serverSpace.getPrivateAddress(), (serverGroup.getPortSection() + serverNum) + "", serverGroup.getRequiredRam() + "", serverGroup.getWorldZip(), serverGroup.getPlugin(), serverGroup.getConfigPath(), serverGroup.getName(), serverGroup.getPrefix() + "-" + serverNum, serverGroup.getMinPlayers() + "", serverGroup.getMaxPlayers() + "", serverGroup.getPvp() + "", serverGroup.getTournament() + "", free + "", serverSpace.isUsRegion() ? "true" : "false", serverGroup.getArcadeGroup() + "", serverGroup.getGames(), serverGroup.getServerType(), serverGroup.getAddNoCheat() + "", serverGroup.getTeamAutoJoin() + "", serverGroup.getTeamForceBalance() + "", serverGroup.getTeamRejoin() + "", serverGroup.getGameAutoStart() + "", serverGroup.getGameTimeout() + "", serverGroup.getHotbarHubClock() + "", serverGroup.getHotbarInventory() + "", serverGroup.getPlayerKickIdle() + "", serverGroup.getRewardGems() + "", serverGroup.getRewardItems() + "", serverGroup.getRewardAchievements() + "", serverGroup.getRewardStats() + ""});
ProcessRunner pr = new ProcessRunner(new String[] {"/bin/sh", cmd, serverAddress, serverSpace.getPrivateAddress(), (serverGroup.getPortSection() + serverNum) + "", serverGroup.getRequiredRam() + "", serverGroup.getWorldZip(), serverGroup.getPlugin(), serverGroup.getConfigPath(), serverGroup.getName(), serverGroup.getPrefix() + "-" + serverNum, serverSpace.isUsRegion() ? "true" : "false", serverGroup.getAddNoCheat() + "" });
pr.start(new GenericRunnable<Boolean>()
{
public void run(Boolean error)
{
if (error)
log("[" + serverName + ":" + serverAddress + "] Errored " + serverName + "(" + groupPrefix+ "-" + serverNum + (free ? "-FREE" : "") + ")");
log("[" + serverName + ":" + serverAddress + " Free Resources; CPU " + serverSpace.getAvailableCpu() + " RAM " + serverSpace.getAvailableRam() + "MB] Errored " + serverName + "(" + groupPrefix+ "-" + serverNum + (free ? "-FREE" : "") + ")");
else
log("[" + serverName + ":" + serverAddress + "] Added " + serverName + "(" + groupPrefix+ "-" + serverNum + (free ? "-FREE" : "") + ")");
log("[" + serverName + ":" + serverAddress + " Free Resources; CPU " + serverSpace.getAvailableCpu() + " RAM " + serverSpace.getAvailableRam() + "MB] Added " + serverName + "(" + groupPrefix+ "-" + serverNum + (free ? "-FREE" : "") + ")");
}
});

View File

@ -9,7 +9,6 @@ import mineplex.core.inventory.InventoryManager;
import mineplex.core.memory.MemoryFix;
import mineplex.core.monitor.LagMeter;
import mineplex.core.npc.NpcManager;
import mineplex.core.playerTracker.PlayerTracker;
import mineplex.core.portal.Portal;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.recharge.Recharge;

View File

@ -111,7 +111,7 @@ public class CustomerSupport extends MiniPlugin
for (CoinTransactionToken transaction : donor.getCoinTransactions())
{
if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward") || transaction.Source.contains("purchase"))
if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Halloween Pumpkin") || transaction.Source.equalsIgnoreCase("Treasure Chest") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward") || transaction.Source.contains("purchase"))
{
coinTransactionTotal += transaction.Amount;

View File

@ -1,12 +1,6 @@
package nautilus.game.arcade;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
@ -37,12 +31,12 @@ import mineplex.core.mount.MountManager;
import mineplex.core.npc.NpcManager;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.pet.PetManager;
import mineplex.core.playerTracker.PlayerTracker;
import mineplex.core.portal.Portal;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.projectile.ProjectileManager;
import mineplex.core.punish.Punish;
import mineplex.core.recharge.Recharge;
import mineplex.core.serverConfig.ServerConfiguration;
import mineplex.core.spawn.Spawn;
import mineplex.core.status.ServerStatusManager;
import mineplex.core.teleport.Teleport;
@ -62,6 +56,8 @@ public class Arcade extends JavaPlugin
private DamageManager _damageManager;
private ArcadeManager _gameManager;
private ServerConfiguration _serverConfiguration;
@Override
public void onEnable()
@ -88,6 +84,8 @@ public class Arcade extends JavaPlugin
_donationManager = new DonationManager(this, webServerAddress);
_serverConfiguration = new ServerConfiguration(this);
PreferencesManager preferenceManager = new PreferencesManager(this, _clientManager, _donationManager);
new MessageManager(this, _clientManager, preferenceManager);
@ -122,12 +120,11 @@ public class Arcade extends JavaPlugin
//Arcade Manager
_gameManager = new ArcadeManager(this, serverStatusManager, ReadServerConfig(), _clientManager, _donationManager, _damageManager, disguiseManager, creature, teleport, new Blood(this), antistack, portal, preferenceManager, inventoryManager, packetHandler, cosmeticManager, projectileManager, petManager, webServerAddress);
new PlayerTracker(this, serverStatusManager.getCurrentServerName(), serverStatusManager.getUs());
new MemoryFix(this);
new CustomTagFix(this, packetHandler);
new FriendManager(this, preferenceManager);
new FriendManager(this, _clientManager, preferenceManager);
//Updates
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Updater(this), 1, 1);
@ -135,7 +132,6 @@ public class Arcade extends JavaPlugin
MinecraftServer.getServer().getPropertyManager().setProperty("debug", true);
}
@Override
public void onDisable()
{
@ -151,124 +147,47 @@ public class Arcade extends JavaPlugin
{
GameServerConfig config = new GameServerConfig();
//Load Track Data
String line = null;
try
{
File file = new File("ArcadeSettings.config");
if (!file.exists())
WriteServerConfig(GetDefaultConfig());
FileInputStream fstream = new FileInputStream("ArcadeSettings.config");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null)
config.ServerType = _serverConfiguration.getServerGroup().getServerType();
config.MinPlayers = _serverConfiguration.getServerGroup().getMinPlayers();
config.MaxPlayers = _serverConfiguration.getServerGroup().getMaxPlayers();
config.Tournament = _serverConfiguration.getServerGroup().getTournament();
config.TournamentPoints = _serverConfiguration.getServerGroup().getTournamentPoints();
config.TeamRejoin = _serverConfiguration.getServerGroup().getTeamRejoin();
config.TeamAutoJoin = _serverConfiguration.getServerGroup().getTeamAutoJoin();
config.TeamForceBalance = _serverConfiguration.getServerGroup().getTeamForceBalance();
config.GameAutoStart = _serverConfiguration.getServerGroup().getGameAutoStart();
config.GameTimeout = _serverConfiguration.getServerGroup().getGameTimeout();
config.RewardGems = _serverConfiguration.getServerGroup().getRewardGems();
config.RewardItems = _serverConfiguration.getServerGroup().getRewardItems();
config.RewardStats = _serverConfiguration.getServerGroup().getRewardStats();
config.RewardAchievements = _serverConfiguration.getServerGroup().getRewardAchievements();
config.HotbarInventory = _serverConfiguration.getServerGroup().getHotbarInventory();
config.HotbarHubClock = _serverConfiguration.getServerGroup().getHotbarHubClock();
config.PlayerKickIdle = _serverConfiguration.getServerGroup().getPlayerKickIdle();
for (String gameName : _serverConfiguration.getServerGroup().getGames().split(","))
{
String[] tokens = line.split("=");
if (tokens.length < 2)
continue;
if (tokens[0].equals("SERVER_TYPE"))
try
{
config.ServerType = tokens[1];
GameType type = GameType.valueOf(gameName);
config.GameList.add(type);
}
else if (tokens[0].equals("PLAYERS_MIN"))
catch (Exception e)
{
config.MinPlayers = Integer.parseInt(tokens[1]);
}
else if (tokens[0].equals("PLAYERS_MAX"))
{
config.MaxPlayers = Integer.parseInt(tokens[1]);
}
else if (tokens[0].equals("TOURNAMENT"))
{
config.Tournament = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("TOURNAMENT_POINTS"))
{
config.TournamentPoints = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("TEAM_REJOIN"))
{
config.TeamRejoin = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("TEAM_AUTO_JOIN"))
{
config.TeamAutoJoin = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("TEAM_FORCE_BALANCE"))
{
config.TeamForceBalance = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("GAME_AUTO_START"))
{
config.GameAutoStart = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("GAME_TIMEOUT"))
{
config.GameTimeout = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("REWARD_GEMS"))
{
config.RewardGems = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("REWARD_ITEMS"))
{
config.RewardItems = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("REWARD_STATS"))
{
config.RewardStats = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("REWARD_ACHIEVEMENTS"))
{
config.RewardAchievements = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("HOTBAR_INVENTORY"))
{
config.HotbarInventory = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("HOTBAR_HUB_CLOCK"))
{
config.HotbarHubClock = Boolean.parseBoolean(tokens[1]);
}
else if (tokens[0].equals("PLAYER_KICK_IDLE"))
{
config.PlayerKickIdle = Boolean.parseBoolean(tokens[1]);
}
//Games
else
{
try
{
GameType type = GameType.valueOf(tokens[0]);
boolean enabled = Boolean.valueOf(tokens[1]);
if (enabled)
config.GameList.add(type);
}
catch (Exception e)
{
}
}
}
in.close();
}
catch (Exception e)
catch (Exception ex)
{
System.out.println("Error reading ServerConfiguration values : " + ex.getMessage());
}
if (!config.IsValid())
config = GetDefaultConfig();
WriteServerConfig(config);
return config;
}
@ -284,53 +203,6 @@ public class Arcade extends JavaPlugin
return config;
}
public void WriteServerConfig(GameServerConfig config)
{
try
{
FileWriter fstream = new FileWriter("ArcadeSettings.config");
BufferedWriter out = new BufferedWriter(fstream);
out.write("SERVER_TYPE=" + config.ServerType + "\n");
out.write("PLAYERS_MIN=" + config.MinPlayers + "\n");
out.write("PLAYERS_MAX=" + config.MaxPlayers + "\n");
out.write("\nTOURNAMENT=" + config.Tournament + "\n");
out.write("\nTOURNAMENT_POINTS=" + config.TournamentPoints + "\n");
out.write("\nTEAM_REJOIN=" + config.TeamRejoin + "\n");
out.write("TEAM_AUTO_JOIN=" + config.TeamAutoJoin + "\n");
out.write("TEAM_FORCE_BALANCE=" + config.TeamForceBalance + "\n");
out.write("\nGAME_AUTO_START=" + config.GameAutoStart + "\n");
out.write("GAME_TIMEOUT=" + config.GameTimeout + "\n");
out.write("\nREWARD_GEMS=" + config.RewardGems + "\n");
out.write("REWARD_ITEMS=" + config.RewardItems + "\n");
out.write("REWARD_STATS=" + config.RewardStats + "\n");
out.write("REWARD_ACHIEVEMENTS=" + config.RewardAchievements + "\n");
out.write("\nHOTBAR_INVENTORY=" + config.HotbarInventory + "\n");
out.write("HOTBAR_HUB_CLOCK=" + config.HotbarHubClock + "\n");
out.write("\nPLAYER_KICK_IDLE=" + config.PlayerKickIdle + "\n");
out.write("\n\nGames List;\n");
for (GameType type : GameType.values())
{
out.write(type.toString() + "=" + config.GameList.contains(type) + "\n");
}
out.close();
}
catch (Exception e)
{
}
}
private void DeleteFolders()
{
File curDir = new File(".");

View File

@ -99,6 +99,7 @@ import nautilus.game.arcade.managers.GameChatManager;
import nautilus.game.arcade.managers.GameCreationManager;
import nautilus.game.arcade.managers.GameFlagManager;
import nautilus.game.arcade.managers.GameGemManager;
import nautilus.game.arcade.managers.GameHostManager;
import nautilus.game.arcade.managers.GameLobbyManager;
import nautilus.game.arcade.managers.GameLootManager;
import nautilus.game.arcade.managers.GameManager;
@ -140,9 +141,11 @@ public class ArcadeManager extends MiniPlugin implements IRelation
private GamePlayerManager _gamePlayerManager;
private GameTournamentManager _gameTournamentManager;
private GameWorldManager _gameWorldManager;
private GameHostManager _gameHostManager;
private ServerStatusManager _serverStatusManager;
private InventoryManager _inventoryManager;
private CosmeticManager _cosmeticManager;
private final IdleManager _idleManager;
private AchievementManager _achievementManager;
private StatsManager _statsManager;
@ -253,6 +256,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
_gameGemManager = new GameGemManager(this);
_gameManager = new GameManager(this);
_gameLobbyManager = new GameLobbyManager(this, packetHandler);
_gameHostManager = new GameHostManager(this);
new GameFlagManager(this);
_gamePlayerManager = new GamePlayerManager(this);
new GameAchievementManager(this);
@ -261,8 +265,8 @@ public class ArcadeManager extends MiniPlugin implements IRelation
new GameLootManager(this, petManager);
_gameWorldManager = new GameWorldManager(this);
new MiscManager(this);
new IdleManager(this);
new HalloweenManager(this);
_idleManager = new IdleManager(this);
//new HalloweenManager(this);
_arcadeRepository = new ArcadeRepository(plugin);
// Game Addons
@ -394,6 +398,11 @@ public class ArcadeManager extends MiniPlugin implements IRelation
return _gameCreationManager;
}
public GameHostManager GetGameHostManager()
{
return _gameHostManager;
}
public GameFactory GetGameFactory()
{
return _gameFactory;
@ -499,6 +508,13 @@ public class ArcadeManager extends MiniPlugin implements IRelation
@EventHandler
public void MessageMOTD(ServerListPingEvent event)
{
//Mineplex Private Servers
// if (_gameHostManager.isHostExpired())
// {
// event.setMotd(ChatColor.RED + "Finished");
// return;
// }
String extrainformation = "|" + _serverConfig.ServerType + "|" + (_game == null ? "Unknown" : _game.GetName())
+ "|" + ((_game == null || _game.WorldData == null) ? "Unknown" : _game.WorldData.MapName);
@ -942,6 +958,11 @@ public class ArcadeManager extends MiniPlugin implements IRelation
{
return _serverConfig.MaxPlayers;
}
public String GetHost()
{
return _serverConfig.HostName;
}
@EventHandler
public void ObserverQuit(GameStateChangeEvent event)
@ -998,14 +1019,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
@Override
public void run()
{
try
{
getArcadeRepository().saveBasicStats(game.GetType(), IsTournamentServer(), (int) (System.currentTimeMillis() - game.getGameLiveTime()), data);
}
catch (SQLException e)
{
e.printStackTrace();
}
getArcadeRepository().saveBasicStats(game.GetType(), IsTournamentServer(), (int) (System.currentTimeMillis() - game.getGameLiveTime()), data);
}
});
}
@ -1029,14 +1043,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
@Override
public void run()
{
try
{
getArcadeRepository().saveLeaderboardStats(0, type.ordinal(), data);
}
catch (SQLException e)
{
e.printStackTrace();
}
getArcadeRepository().saveLeaderboardStats(0, type.ordinal(), data);
}
});
}
@ -1065,4 +1072,9 @@ public class ArcadeManager extends MiniPlugin implements IRelation
{
_youtube.remove(event.getPlayer());
}
public IdleManager getIdleManager()
{
return _idleManager;
}
}

View File

@ -1,16 +1,12 @@
package nautilus.game.arcade;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.database.DBPool;
import mineplex.core.database.RepositoryBase;
import mineplex.database.Tables;
import mineplex.database.tables.records.GamesRecord;
@ -22,9 +18,9 @@ public class ArcadeRepository extends RepositoryBase
{
private final String serverName;
public ArcadeRepository(Plugin plugin)
public ArcadeRepository(JavaPlugin plugin)
{
super(plugin, DBPool.ACCOUNT);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
serverName = plugin.getConfig().getString("serverstatus.name");
}
@ -41,67 +37,71 @@ public class ArcadeRepository extends RepositoryBase
}
public void saveBasicStats(GameType type, boolean tournament, int duration, Map<UUID, Boolean> players) throws SQLException
public void saveBasicStats(GameType type, boolean tournament, int duration, Map<UUID, Boolean> players)
{
try (Connection connection = getConnection())
DSLContext context;
synchronized (this)
{
DSLContext context = DSL.using(connection);
GamesRecord record = context.newRecord(Tables.games);
record.setDuration(duration);
record.setTournament(tournament);
record.setType(type.name());
record.setServer(serverName);
record.store();
List<Query> queryList = new ArrayList<>(players.size());
for (Map.Entry<UUID, Boolean> entry : players.entrySet())
{
Query query = context
.insertInto(Tables.gamePlayers)
.set(Tables.gamePlayers.gameId, record.getId())
.set(Tables.gamePlayers.accountId, DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.uuid.eq(entry.getKey().toString())))
.set(Tables.gamePlayers.winner, entry.getValue());
queryList.add(query);
}
context.batch(queryList).execute();
context = DSL.using(getConnection());
}
GamesRecord record = context.newRecord(Tables.games);
record.setDuration(duration);
record.setTournament(tournament);
record.setType(type.name());
record.setServer(serverName);
record.store();
List<Query> queryList = new ArrayList<>(players.size());
for (Map.Entry<UUID, Boolean> entry : players.entrySet())
{
Query query = context
.insertInto(Tables.gamePlayers)
.set(Tables.gamePlayers.gameId, record.getId())
.set(Tables.gamePlayers.accountId, DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.uuid.eq(entry.getKey().toString())))
.set(Tables.gamePlayers.winner, entry.getValue());
queryList.add(query);
}
context.batch(queryList).execute();
}
public void saveLeaderboardStats(int tournamentId, int gameId, Map<UUID, Boolean> players) throws SQLException
public void saveLeaderboardStats(int tournamentId, int gameId, Map<UUID, Boolean> players)
{
try (Connection connection = getConnection())
DSLContext context;
synchronized (this)
{
DSLContext context = DSL.using(connection);
List<Query> queryList = new ArrayList<>(players.size());
for (Map.Entry<UUID, Boolean> entry : players.entrySet())
{
int winIncrement = entry.getValue() ? 1 : 0;
Query query = context
.insertInto(Tables.tournamentLeaderboard)
.set(Tables.tournamentLeaderboard.tournamentId, tournamentId)
.set(Tables.tournamentLeaderboard.gameId, gameId)
.set(Tables.tournamentLeaderboard.accountId, DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.uuid.eq(entry.getKey().toString())))
.set(Tables.tournamentLeaderboard.wins, winIncrement)
.set(Tables.tournamentLeaderboard.total, 1)
.onDuplicateKeyUpdate()
.set(Tables.tournamentLeaderboard.wins, Tables.tournamentLeaderboard.wins.plus(winIncrement))
.set(Tables.tournamentLeaderboard.total, Tables.tournamentLeaderboard.total.plus(1));
queryList.add(query);
}
context.batch(queryList).execute();
context = DSL.using(getConnection());
}
List<Query> queryList = new ArrayList<>(players.size());
for (Map.Entry<UUID, Boolean> entry : players.entrySet())
{
int winIncrement = entry.getValue() ? 1 : 0;
Query query = context
.insertInto(Tables.tournamentLeaderboard)
.set(Tables.tournamentLeaderboard.tournamentId, tournamentId)
.set(Tables.tournamentLeaderboard.gameId, gameId)
.set(Tables.tournamentLeaderboard.accountId, DSL.select(Tables.accounts.id)
.from(Tables.accounts)
.where(Tables.accounts.uuid.eq(entry.getKey().toString())))
.set(Tables.tournamentLeaderboard.wins, winIncrement)
.set(Tables.tournamentLeaderboard.total, 1)
.onDuplicateKeyUpdate()
.set(Tables.tournamentLeaderboard.wins, Tables.tournamentLeaderboard.wins.plus(winIncrement))
.set(Tables.tournamentLeaderboard.total, Tables.tournamentLeaderboard.total.plus(1));
queryList.add(query);
}
context.batch(queryList).execute();
}
}

View File

@ -215,6 +215,8 @@ public abstract class Game implements Listener
public boolean TeamArmorHotbar = false;
public boolean GiveClock = true;
public boolean AllowParticles = true;
public double GemMultiplier = 1;
public boolean GemHunterEnabled = true;
@ -284,6 +286,7 @@ public abstract class Game implements Listener
new KillsStatTracker(this),
new DeathsStatTracker(this),
new AssistsStatTracker(this),
new ExperienceStatTracker(this),
new WinStatTracker(this),
new LoseStatTracker(this),
new DamageDealtStatTracker(this),
@ -1246,4 +1249,9 @@ public abstract class Game implements Listener
_statTrackers.clear();
}
public ArcadeManager getArcadeManager()
{
return Manager;
}
}

View File

@ -12,6 +12,8 @@ public class GameServerConfig
public ArrayList<GameType> GameList = new ArrayList<GameType>();
//Flags
public String HostName = "";
public boolean Tournament = false;
public boolean TournamentPoints = false;

View File

@ -13,6 +13,7 @@ import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Chicken;
import org.bukkit.entity.Cow;
import org.bukkit.entity.Entity;
@ -28,11 +29,13 @@ import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
@ -42,6 +45,7 @@ import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilBlock;
import mineplex.core.common.util.UtilEvent;
import mineplex.core.common.util.UtilGear;
import mineplex.core.common.util.UtilWorld;
import mineplex.core.common.util.UtilEvent.ActionType;
import mineplex.core.common.util.UtilMath;
@ -1567,6 +1571,42 @@ public class Bridge extends TeamGame implements OreObsfucation
{
if (!_bridgesDown)
{
if (!event.getToBlock().getRelative(BlockFace.UP).equals(event.getBlock()))
{
event.setCancelled(true);
}
}
}
// @EventHandler
// public void liquidBlockDeny(BlockBreakEvent event)
// {
// if (_bridgesDown)
// return;
//
// if (!IsAlive(event.getPlayer()))
// return;
//
// if (event.getBlock().getRelative(BlockFace.UP).isLiquid() || event.getBlock().getRelative(BlockFace.UP).getRelative(BlockFace.UP).isLiquid())
// {
// UtilPlayer.message(event.getPlayer(), F.main("Game",
// "Cannot tunnel under liquids."));
//
// event.setCancelled(true);
// }
// }
@EventHandler
public void boatDeny(PlayerInteractEvent event)
{
if (!UtilEvent.isAction(event, ActionType.R))
return;
if (UtilGear.isMat(event.getPlayer().getItemInHand(), Material.BOAT))
{
UtilPlayer.message(event.getPlayer(), F.main("Game",
"You cannot place boats."));
event.setCancelled(true);
}
}

View File

@ -3,6 +3,7 @@ package nautilus.game.arcade.game.games.champions;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.minecraft.game.core.combat.DeathMessageType;
import mineplex.minecraft.game.core.damage.CustomDamageEvent;
import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.GameType;
import nautilus.game.arcade.game.GameTeam;
@ -20,7 +21,9 @@ import nautilus.game.arcade.stats.TheLongestShotStatTracker;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.inventory.InventoryType;
public class ChampionsDominate extends Domination
{
@ -52,6 +55,7 @@ public class ChampionsDominate extends Domination
};
Manager.GetDamage().UseSimpleWeaponDamage = false;
Manager.getCosmeticManager().setHideParticles(true);
this.StrictAntiHack = true;
@ -59,6 +63,8 @@ public class ChampionsDominate extends Domination
EloRanking = false;
EloStart = 1000;
this.DisableKillCommand = false;
registerStatTrackers(
new KillReasonStatTracker(this, "Backstab", "Assassination"),
@ -94,4 +100,24 @@ public class ChampionsDominate extends Domination
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void InventoryDamageCancel(CustomDamageEvent event)
{
if (event.IsCancelled())
return;
Player player = event.GetDamageePlayer();
if (player == null)
return;
if (!IsAlive(player))
return;
if (player.getOpenInventory() == null || player.getOpenInventory().getTopInventory() == null)
return;
if (player.getOpenInventory().getTopInventory().getType() == InventoryType.CHEST)
player.closeInventory();
}
}

View File

@ -2,11 +2,14 @@ package nautilus.game.arcade.game.games.champions;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.inventory.InventoryType;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.minecraft.game.core.combat.DeathMessageType;
import mineplex.minecraft.game.core.damage.CustomDamageEvent;
import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.GameType;
import nautilus.game.arcade.game.GameTeam;
@ -53,11 +56,14 @@ public class ChampionsTDM extends TeamDeathmatch
};
this.Manager.GetDamage().UseSimpleWeaponDamage = false;
Manager.getCosmeticManager().setHideParticles(true);
this.StrictAntiHack = true;
InventoryOpenChest = true;
this.DisableKillCommand = false;
registerStatTrackers(
new WinWithoutLosingTeammateStatTracker(this, "FlawlessVictory"),
new KillAllOpposingStatTracker(this),
@ -94,4 +100,24 @@ public class ChampionsTDM extends TeamDeathmatch
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void InventoryDamageCancel(CustomDamageEvent event)
{
if (event.IsCancelled())
return;
Player player = event.GetDamageePlayer();
if (player == null)
return;
if (!IsAlive(player))
return;
if (player.getOpenInventory() == null || player.getOpenInventory().getTopInventory() == null)
return;
if (player.getOpenInventory().getTopInventory().getType() == InventoryType.CHEST)
player.closeInventory();
}
}

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