Merge branch 'develop' into feature/dinnerbone-morph

This commit is contained in:
LCastr0 2016-12-25 15:34:00 -02:00
commit 140da98922
39 changed files with 583 additions and 656 deletions

View File

@ -60,7 +60,7 @@ public class PlayerTracker implements Listener
{ {
public void run() public void run()
{ {
PlayerStatus snapshot = new PlayerStatus(event.getPlayer().getName(), event.getServer().getInfo().getName()); PlayerStatus snapshot = new PlayerStatus(event.getPlayer().getUniqueId(), event.getPlayer().getName(), event.getServer().getInfo().getName());
_repository.addElement(snapshot, DEFAULT_STATUS_TIMEOUT); _repository.addElement(snapshot, DEFAULT_STATUS_TIMEOUT);
} }
}); });
@ -73,7 +73,7 @@ public class PlayerTracker implements Listener
{ {
public void run() public void run()
{ {
_repository.removeElement(event.getPlayer().getName().toLowerCase()); _repository.removeElement(event.getPlayer().getUniqueId().toString());
} }
}); });
} }
@ -82,7 +82,7 @@ public class PlayerTracker implements Listener
public void playerConnect(final PostLoginEvent event) public void playerConnect(final PostLoginEvent event)
{ {
_ignoreKick.add(event.getPlayer().getUniqueId()); _ignoreKick.add(event.getPlayer().getUniqueId());
PlayerJoinCommand command = new PlayerJoinCommand(event.getPlayer().getUniqueId()); PlayerJoinCommand command = new PlayerJoinCommand(event.getPlayer().getUniqueId(), event.getPlayer().getName());
command.publish(); command.publish();
} }

View File

@ -1,9 +1,11 @@
package mineplex.core.antihack; package mineplex.core.antihack;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -27,6 +29,7 @@ import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerToggleFlightEvent; import org.bukkit.event.player.PlayerToggleFlightEvent;
import org.bukkit.plugin.ServicePriority; import org.bukkit.plugin.ServicePriority;
@ -138,7 +141,9 @@ public class AntiHack extends MiniPlugin
private final Set<String> _detailedMessages = new HashSet<>(); private final Set<String> _detailedMessages = new HashSet<>();
private Set<Player> _pendingBan = new HashSet<>(); private Set<Player> _pendingBan = Collections.synchronizedSet(new HashSet<>());
private Set<UUID> _banned = Collections.synchronizedSet(new HashSet<>());
// These are the GWEN checks to ignore when handling PlayerViolationEvent // These are the GWEN checks to ignore when handling PlayerViolationEvent
private HashSet<Class<? extends Check>> _ignoredChecks = new HashSet<>(); private HashSet<Class<? extends Check>> _ignoredChecks = new HashSet<>();
@ -186,11 +191,18 @@ public class AntiHack extends MiniPlugin
new BanwaveAnimationSpin().run(player, after); new BanwaveAnimationSpin().run(player, after);
} }
@EventHandler
public void onQuit(PlayerQuitEvent event)
{
UUID uuid = event.getPlayer().getUniqueId();
runSync(() -> _banned.remove(uuid));
}
public void doBan(Player player, Class<? extends Check> cause) public void doBan(Player player, Class<? extends Check> cause)
{ {
runSync(() -> runSync(() ->
{ {
if (_pendingBan.add(player)) if (_pendingBan.add(player) && !_banned.contains(player.getUniqueId()))
{ {
CoreClient coreClient = _clientManager.Get(player); CoreClient coreClient = _clientManager.Get(player);
@ -202,8 +214,6 @@ public class AntiHack extends MiniPlugin
String id = generateId(); String id = generateId();
String finalMessage = "[GWEN] " + id; String finalMessage = "[GWEN] " + id;
_logger.saveMetadata(player, id, () -> _logger.saveMetadata(player, id, () ->
{
_logger.resetViolations(player, () ->
{ {
runAsync(() -> runAsync(() ->
{ {
@ -212,13 +222,16 @@ public class AntiHack extends MiniPlugin
}); });
_punish.AddPunishment(coreClient.getName(), Category.Hacking, finalMessage, AntiHack.NAME, 3, true, -1, true, after); _punish.AddPunishment(coreClient.getName(), Category.Hacking, finalMessage, AntiHack.NAME, 3, true, -1, true, after);
});
}, custom); }, custom);
}; };
if (coreClient.GetRank().has(Rank.TWITCH)) if (coreClient.GetRank().has(Rank.TWITCH))
{ {
doPunish.accept(result -> _pendingBan.remove(player)); doPunish.accept(result ->
{
_pendingBan.remove(player);
_banned.add(player.getUniqueId());
});
} }
else else
{ {
@ -228,6 +241,7 @@ public class AntiHack extends MiniPlugin
if (result == PunishmentResponse.Punished) if (result == PunishmentResponse.Punished)
{ {
announceBan(player); announceBan(player);
_banned.add(player.getUniqueId());
} }
_pendingBan.remove(player); _pendingBan.remove(player);
}) })

View File

@ -2,164 +2,24 @@ package mineplex.core.antihack.logging;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;
import org.bukkit.plugin.java.JavaPlugin;
import com.mineplex.anticheat.checks.Check;
import com.mineplex.anticheat.checks.CheckManager;
import mineplex.core.antihack.ViolationLevels;
import mineplex.core.database.MinecraftRepository; import mineplex.core.database.MinecraftRepository;
import mineplex.serverdata.database.DBPool; import mineplex.serverdata.database.DBPool;
import gnu.trove.map.TIntObjectMap;
public class AnticheatDatabase extends MinecraftRepository public class AnticheatDatabase extends MinecraftRepository
{ {
/* /*
CREATE TABLE IF NOT EXISTS anticheat_vl_logs (accountId INT, checkId INT, maxViolations INT, totalAlerts INT, sinceLastBan INT, PRIMARY KEY(accountId, checkId));
CREATE TABLE IF NOT EXISTS anticheat_ban_metadata (id INT NOT NULL AUTO_INCREMENT, accountId INT, banId CHAR(10) NOT NULL, data MEDIUMTEXT NOT NULL, PRIMARY KEY(id)); CREATE TABLE IF NOT EXISTS anticheat_ban_metadata (id INT NOT NULL AUTO_INCREMENT, accountId INT, banId CHAR(10) NOT NULL, data MEDIUMTEXT NOT NULL, PRIMARY KEY(id));
*/ */
private static final String INSERT_INTO_METADATA = "INSERT INTO anticheat_ban_metadata (accountId, banId, data) VALUES (?, ?, ?);"; private static final String INSERT_INTO_METADATA = "INSERT INTO anticheat_ban_metadata (accountId, banId, data) VALUES (?, ?, ?);";
private static final String UPDATE_VIOLATIONS = "INSERT INTO anticheat_vl_logs (accountId, checkId, " public AnticheatDatabase()
+ "maxViolations, sinceLastBan, totalAlerts) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY"
+ " UPDATE maxViolations = VALUES(maxViolations), totalAlerts = VALUES(totalAlerts), sinceLastBan = VALUES(sinceLastBan);";
private static final String CLEAR_LAST_BAN_VIOLATIONS = "UPDATE anticheat_vl_logs SET sinceLastBan = 0 WHERE accountId = ?;";
private static final String GET_VLS = "SELECT checkId, maxViolations, sinceLastBan, totalAlerts FROM anticheat_vl_logs";
private static final String GET_VLS_BY_ACCOUNT_ID = GET_VLS + " WHERE accountId = ?";
private static final String GET_VLS_FOR_CHECK = GET_VLS + " WHERE checkId = ? AND accountId = ?";
public AnticheatDatabase(JavaPlugin plugin)
{ {
super(DBPool.getAccount()); super(DBPool.getAccount());
} }
/**
* Submit a set of user violation changes batch style.
*
* @param uploadQueue the {@link TIntObjectMap} describing the changes.
*/
public void saveViolationLevels(Map<Integer, ViolationLevels> uploadQueue)
{
try (Connection connection = getConnection())
{
PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_VIOLATIONS);
uploadQueue.forEach((accountId, vls) ->
{
CheckManager.AVAILABLE_CHECKS.values().forEach(check ->
{
int checkId = CheckManager.getCheckId(check),
maxVls = vls.getMaxViolationsForCheck(check),
maxVlsSinceLastBan = vls.getLastBanViolationsForCheck(check),
totalAlerts = vls.getTotalAlertsForCheck(check);
// if neither value has been set don't store anything
if (maxVls < 0 && totalAlerts < 0 && maxVlsSinceLastBan < 0)
{
return;
}
maxVls = Math.max(maxVls, 0);
maxVlsSinceLastBan = Math.max(maxVlsSinceLastBan, 0);
totalAlerts = Math.max(totalAlerts, 0);
try
{
preparedStatement.setInt(1, accountId);
preparedStatement.setInt(2, checkId);
preparedStatement.setInt(3, maxVls);
preparedStatement.setInt(4, maxVlsSinceLastBan);
preparedStatement.setInt(5, totalAlerts);
preparedStatement.addBatch();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
});
preparedStatement.executeBatch();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
/**
* Attempts to retrieve violation levels for the given account id.
*
* @param accountId The account id;
* @return an {@link Optional} describing the user's violation levels, or an empty one if none
* are found.
* @throws SQLException On failing to connect to the database.
*/
public Optional<ViolationLevels> getViolationLevels(int accountId)
{
ViolationLevels levels = new ViolationLevels();
try (Connection connection = getConnection())
{
PreparedStatement statement = connection.prepareStatement(GET_VLS_BY_ACCOUNT_ID);
statement.setInt(1, accountId);
ResultSet result = statement.executeQuery();
while (result.next())
{
int checkId = result.getInt("checkId");
Class<? extends Check> checkType = CheckManager.getCheckById(checkId);
if (checkType == null)
{
System.err.println("Whoops. Unintended refactor?");
continue;
}
levels.updateMaxViolations(checkType, result.getInt("maxViolations"));
levels.updateMaxViolationsSinceLastBan(checkType, result.getInt("sinceLastBan"));
levels.setTotalAlerts(checkType, result.getInt("totalAlerts"));
}
}
catch (SQLException ex)
{
ex.printStackTrace();
}
return Optional.of(levels);
}
public void clearLastBan(int accountId, Runnable after)
{
try (Connection connection = getConnection())
{
PreparedStatement statement = connection.prepareStatement(CLEAR_LAST_BAN_VIOLATIONS);
statement.setInt(1, accountId);
statement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
if (after != null)
after.run();
}
}
public void saveMetadata(int accountId, String id, String base64, Runnable after) public void saveMetadata(int accountId, String id, String base64, Runnable after)
{ {
try (Connection connection = getConnection()) try (Connection connection = getConnection())
@ -181,16 +41,4 @@ public class AnticheatDatabase extends MinecraftRepository
after.run(); after.run();
} }
} }
@Override
protected void initialize()
{
}
@Override
protected void update()
{
}
} }

View File

@ -11,7 +11,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.tukaani.xz.LZMA2Options; import org.tukaani.xz.LZMA2Options;
import org.tukaani.xz.XZ; import org.tukaani.xz.XZ;
@ -43,12 +42,8 @@ public class AntihackLogger extends MiniPlugin
{ {
public static final Gson GSON = new Gson(); public static final Gson GSON = new Gson();
private static final int PUSH_QUEUE_TIME_IN_SECONDS = 60;
private final CoreClientManager _clientManager = require(CoreClientManager.class); private final CoreClientManager _clientManager = require(CoreClientManager.class);
private final Map<Integer, ViolationLevels> _violationLevels = new ConcurrentHashMap<>();
private final Map<String, AnticheatMetadata> _metadata = new HashMap<>(); private final Map<String, AnticheatMetadata> _metadata = new HashMap<>();
private final AnticheatDatabase _db; private final AnticheatDatabase _db;
@ -57,9 +52,7 @@ public class AntihackLogger extends MiniPlugin
{ {
super("AnticheatPlugin"); super("AnticheatPlugin");
_db = new AnticheatDatabase(getPlugin()); _db = new AnticheatDatabase();
runSyncTimer(this::pushQueuedViolationChanges, 20, 20 * PUSH_QUEUE_TIME_IN_SECONDS);
registerMetadata(new ServerInfoMetadata()); registerMetadata(new ServerInfoMetadata());
registerMetadata(new ViolationInfoMetadata()); registerMetadata(new ViolationInfoMetadata());
@ -67,12 +60,6 @@ public class AntihackLogger extends MiniPlugin
registerMetadata(new PlayerInfoMetadata()); registerMetadata(new PlayerInfoMetadata());
} }
@Override
public void disable()
{
pushQueuedViolationChanges();
}
@EventHandler @EventHandler
public void addCommands() public void addCommands()
{ {
@ -102,53 +89,9 @@ public class AntihackLogger extends MiniPlugin
} }
} }
private void pushQueuedViolationChanges()
{
Map<Integer, ViolationLevels> clone = new HashMap<>(_violationLevels);
runAsync(() -> _db.saveViolationLevels(clone));
}
@EventHandler
public void onCheckFail(PlayerViolationEvent event)
{
ViolationLevels playerVls = _violationLevels.get(_clientManager.getAccountId(event.getPlayer()));
Class<? extends Check> check = event.getCheckClass();
playerVls.updateMaxViolations(check, event.getViolations());
playerVls.updateMaxViolationsSinceLastBan(check, event.getViolations());
playerVls.incrementAlerts(check);
}
@EventHandler
public void onLoad(PlayerLoginEvent event)
{
runAsync(() ->
{
int accountId = _clientManager.getAccountId(event.getPlayer());
_db.getViolationLevels(accountId)
.ifPresent(vls ->
{
_violationLevels.put(accountId, vls);
});
});
}
@EventHandler @EventHandler
public void onQuit(PlayerQuitEvent event) public void onQuit(PlayerQuitEvent event)
{ {
Player player = event.getPlayer();
int accountId =_clientManager.getAccountId(event.getPlayer());
ViolationLevels levels = _violationLevels.get(accountId);
if (levels != null)
{
Map<Integer, ViolationLevels> clone = new HashMap<>();
clone.put(accountId, levels);
runAsync(() -> _db.saveViolationLevels(clone));
}
_metadata.values().forEach(metadata -> metadata.remove(event.getPlayer().getUniqueId())); _metadata.values().forEach(metadata -> metadata.remove(event.getPlayer().getUniqueId()));
} }
@ -206,9 +149,4 @@ public class AntihackLogger extends MiniPlugin
throw new IllegalArgumentException("Attempting to register: " + metadata.getId()); throw new IllegalArgumentException("Attempting to register: " + metadata.getId());
} }
} }
public void resetViolations(Player player, Runnable after)
{
_db.clearLastBan(_clientManager.getAccountId(player), after);
}
} }

View File

@ -1,13 +1,12 @@
package mineplex.core.communities; package mineplex.core.communities;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilPlayer;
import mineplex.core.game.GameDisplay; import mineplex.core.game.GameDisplay;
@ -16,8 +15,8 @@ public class Community
private final int _id; private final int _id;
private String _name; private String _name;
private String _description; private String _description;
private Map<UUID, CommunityMemberInfo> _members = new HashMap<>(); private Map<UUID, CommunityMemberInfo> _members = new ConcurrentHashMap<>();
private Map<UUID, CommunityJoinRequestInfo> _joinRequests = new HashMap<>(); private Map<UUID, CommunityJoinRequestInfo> _joinRequests = new ConcurrentHashMap<>();
private ChatColor[] _chatFormat; private ChatColor[] _chatFormat;
private long _chatDelay; private long _chatDelay;
private GameDisplay _favoriteGame; private GameDisplay _favoriteGame;

View File

@ -36,6 +36,10 @@ public class CommunityJoinRequestInfo
public void update(String name) public void update(String name)
{ {
if (name == null)
{
return;
}
Name = name; Name = name;
buildIcon(); buildIcon();
} }

View File

@ -2,11 +2,12 @@ package mineplex.core.communities;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -19,11 +20,10 @@ import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.collect.Lists;
import mineplex.core.Managers; import mineplex.core.Managers;
import mineplex.core.MiniDbClientPlugin; import mineplex.core.MiniDbClientPlugin;
import mineplex.core.account.CoreClientManager; import mineplex.core.account.CoreClientManager;
import mineplex.core.account.ILoginProcessor;
import mineplex.core.common.jsonchat.ClickEvent; import mineplex.core.common.jsonchat.ClickEvent;
import mineplex.core.common.jsonchat.JsonMessage; import mineplex.core.common.jsonchat.JsonMessage;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
@ -76,13 +76,16 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
private final Map<Integer, Community> _loadedCommunities; private final Map<Integer, Community> _loadedCommunities;
public final List<Integer> BrowserIds = new LinkedList<>(); public final List<Integer> BrowserIds = new LinkedList<>();
private final List<UUID> _creating = new ArrayList<>();
public final DataRepository<PlayerStatus> StatusRepository; public final DataRepository<PlayerStatus> StatusRepository;
private ServerRepository _serverRepo; private ServerRepository _serverRepo;
private boolean _us; private boolean _us;
private boolean _cycling = false; private volatile boolean _cycling = false;
private volatile boolean _updateJoinRequests = false;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public CommunityManager(JavaPlugin plugin, CoreClientManager clientManager) public CommunityManager(JavaPlugin plugin, CoreClientManager clientManager)
@ -101,6 +104,34 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
_loadedCommunities = new ConcurrentHashMap<>(); _loadedCommunities = new ConcurrentHashMap<>();
clientManager.addStoredProcedureLoginProcessor(new ILoginProcessor()
{
@Override
public String getName()
{
return "community-invite-loader";
}
@Override
public void processLoginResultSet(String playerName, UUID uuid, int accountId, ResultSet resultSet) throws SQLException
{
while (resultSet.next())
{
String region = resultSet.getString("region");
if ((_us && region.equalsIgnoreCase("US")) || (!_us && region.equalsIgnoreCase("EU")))
{
CommunityManager.this.Get(uuid).Invites.add(resultSet.getInt("communityId"));
}
}
}
@Override
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT ci.communityId, c.region FROM communityInvites AS ci INNER JOIN communities AS c ON c.id=ci.communityId WHERE accountId=" + accountId + ";";
}
});
Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, () -> Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, () ->
{ {
if (_cycling) if (_cycling)
@ -110,8 +141,13 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
LinkedList<Community> communities = new LinkedList<>(); LinkedList<Community> communities = new LinkedList<>();
_loadedCommunities.values().forEach(community -> communities.add(community)); _loadedCommunities.values().forEach(community -> communities.add(community));
_repo.updateMembersAndJoinRequests(communities); _repo.updateMembers(communities);
}, 0L, 20 * 5); if (_updateJoinRequests)
{
_repo.updateJoinRequests(communities);
}
_updateJoinRequests = !_updateJoinRequests;
}, 0L, 20 * 7);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () ->
{ {
@ -136,6 +172,13 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
ServerCommandManager.getInstance().registerCommandType(CommunityUpdateSetting.class, new CommunityUpdateSettingHandler(this)); ServerCommandManager.getInstance().registerCommandType(CommunityUpdateSetting.class, new CommunityUpdateSettingHandler(this));
} }
public boolean ownsCommunity(UUID uuid)
{
return _loadedCommunities.values().stream()
.flatMap(community -> community.getMembers().entrySet().stream())
.anyMatch(entry -> entry.getKey().equals(uuid) && entry.getValue().Role == CommunityRole.LEADER);
}
private void cycleBrowser() private void cycleBrowser()
{ {
if (_cycling) if (_cycling)
@ -145,15 +188,10 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
_cycling = true; _cycling = true;
runAsync(() -> runAsync(() ->
{ {
final List<Integer> resultant = Lists.newArrayList();
final List<Integer> ids = new LinkedList<>(); final List<Integer> ids = new LinkedList<>();
_loadedCommunities.values().stream().filter(c -> c.getMembers().size() >= 5 && c.getPrivacySetting() != PrivacySetting.PRIVATE).forEach(c -> resultant.add(c.getId())); _loadedCommunities.values().stream().filter(c -> c.getMembers().size() >= 5 && c.getPrivacySetting() != PrivacySetting.PRIVATE).forEach(c -> ids.add(c.getId()));
Random random = new Random(); Collections.shuffle(ids);
while (!resultant.isEmpty())
{
ids.add(resultant.remove(random.nextInt(resultant.size())));
}
runSync(() -> runSync(() ->
{ {
@ -192,7 +230,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
} }
setting.parseValueInto(newValue, community); setting.parseValueInto(newValue, community);
//community.message(F.main(getName(), F.name(sender) + " has changed settings in " + F.name(community.getName()) + "!")); //community.message(F.main(getName(), F.name(sender) + " has changed settings in " + F.name(community.getName()) + "!"));
UtilServer.CallEvent(new CommunitySettingUpdateEvent(community)); runSync(() -> UtilServer.CallEvent(new CommunitySettingUpdateEvent(community)));
} }
public void handleCommunityNameUpdate(Integer id, String sender, String name) public void handleCommunityNameUpdate(Integer id, String sender, String name)
@ -205,7 +243,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
String oldName = community.getName(); String oldName = community.getName();
community.setName(name); community.setName(name);
community.message(F.main(getName(), F.name(sender) + " has changed the name of " + F.name(oldName) + " to " + F.name(community.getName()) + "!")); community.message(F.main(getName(), F.name(sender) + " has changed the name of " + F.name(oldName) + " to " + F.name(community.getName()) + "!"));
UtilServer.CallEvent(new CommunityNameUpdateEvent(community)); runSync(() -> UtilServer.CallEvent(new CommunityNameUpdateEvent(community)));
} }
public void handleCommunityMembershipRoleUpdate(Integer id, String sender, UUID uuid, CommunityRole role) public void handleCommunityMembershipRoleUpdate(Integer id, String sender, UUID uuid, CommunityRole role)
@ -216,7 +254,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
return; return;
} }
CommunityMemberInfo member = community.getMembers().get(uuid); CommunityMemberInfo member = community.getMembers().get(uuid);
member.Role = role; member.updateRole(role);
if (Bukkit.getPlayer(uuid) != null) if (Bukkit.getPlayer(uuid) != null)
{ {
if (role.ordinal() > CommunityRole.COLEADER.ordinal()) if (role.ordinal() > CommunityRole.COLEADER.ordinal())
@ -227,7 +265,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
} }
String name = member.Name; String name = member.Name;
community.message(F.main(getName(), F.name(sender) + " has changed " + F.name(name + "'s") + " role to " + F.elem(role.getDisplay()) + " in " + F.name(community.getName()) + "!"), CommunityRole.COLEADER); community.message(F.main(getName(), F.name(sender) + " has changed " + F.name(name + "'s") + " role to " + F.elem(role.getDisplay()) + " in " + F.name(community.getName()) + "!"), CommunityRole.COLEADER);
UtilServer.CallEvent(new CommunityMembershipUpdateEvent(community)); runSync(() -> UtilServer.CallEvent(new CommunityMembershipUpdateEvent(community)));
} }
public void handleCommunityMembershipUpdate(Integer id, String sender, String playerName, UUID playerUUID, Integer accountId, boolean kick, boolean leave) public void handleCommunityMembershipUpdate(Integer id, String sender, String playerName, UUID playerUUID, Integer accountId, boolean kick, boolean leave)
@ -262,17 +300,20 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
if (Bukkit.getPlayer(playerUUID) != null) if (Bukkit.getPlayer(playerUUID) != null)
{ {
Get(Bukkit.getPlayer(playerUUID)).joinCommunity(community); Get(Bukkit.getPlayer(playerUUID)).joinCommunity(community);
Get(Bukkit.getPlayer(playerUUID)).Invites.remove(community.getId()); runSync(() -> Get(Bukkit.getPlayer(playerUUID)).Invites.remove(community.getId()));
} }
community.message(F.main(getName(), F.name(playerName) + " has joined " + F.name(community.getName()) + "!")); community.message(F.main(getName(), F.name(playerName) + " has joined " + F.name(community.getName()) + "!"));
} }
runSync(() ->
{
UtilServer.CallEvent(new CommunityMembershipUpdateEvent(community)); UtilServer.CallEvent(new CommunityMembershipUpdateEvent(community));
if (Bukkit.getPlayer(playerUUID) != null) if (Bukkit.getPlayer(playerUUID) != null)
{ {
UtilServer.CallEvent(new CommunityMemberDataUpdateEvent(Bukkit.getPlayer(playerUUID))); UtilServer.CallEvent(new CommunityMemberDataUpdateEvent(Bukkit.getPlayer(playerUUID)));
} }
});
} }
public void handleCommunityInvite(Integer id, String sender, String targetName, UUID targetUUID) public void handleCommunityInvite(Integer id, String sender, String targetName, UUID targetUUID)
@ -282,6 +323,8 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
{ {
return; return;
} }
runSync(() ->
{
if (Bukkit.getPlayer(targetUUID) != null) if (Bukkit.getPlayer(targetUUID) != null)
{ {
if (!Get(Bukkit.getPlayer(targetUUID)).Invites.contains(community.getId())) if (!Get(Bukkit.getPlayer(targetUUID)).Invites.contains(community.getId()))
@ -295,6 +338,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
UtilServer.CallEvent(new CommunityMemberDataUpdateEvent(Bukkit.getPlayer(targetUUID))); UtilServer.CallEvent(new CommunityMemberDataUpdateEvent(Bukkit.getPlayer(targetUUID)));
} }
} }
});
community.message(F.main(getName(), F.name(sender) + " has invited " + F.name(targetName) + " to " + F.name(community.getName()) + "!"), CommunityRole.COLEADER); community.message(F.main(getName(), F.name(sender) + " has invited " + F.name(targetName) + " to " + F.name(community.getName()) + "!"), CommunityRole.COLEADER);
} }
@ -305,6 +349,8 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
{ {
return; return;
} }
runSync(() ->
{
if (Bukkit.getPlayer(targetUUID) != null) if (Bukkit.getPlayer(targetUUID) != null)
{ {
Get(Bukkit.getPlayer(targetUUID)).Invites.remove(community.getId()); Get(Bukkit.getPlayer(targetUUID)).Invites.remove(community.getId());
@ -314,6 +360,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
} }
UtilServer.CallEvent(new CommunityMemberDataUpdateEvent(Bukkit.getPlayer(targetUUID))); UtilServer.CallEvent(new CommunityMemberDataUpdateEvent(Bukkit.getPlayer(targetUUID)));
} }
});
if (announce) if (announce)
{ {
community.message(F.main(getName(), F.name(targetName) + "'s invitation to join " + F.name(community.getName()) + " has been revoked by " + F.name(sender) + "!"), CommunityRole.COLEADER); community.message(F.main(getName(), F.name(targetName) + "'s invitation to join " + F.name(community.getName()) + " has been revoked by " + F.name(sender) + "!"), CommunityRole.COLEADER);
@ -334,7 +381,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
community.getJoinRequests().put(playerUUID, new CommunityJoinRequestInfo(playerName, playerUUID, accountId)); community.getJoinRequests().put(playerUUID, new CommunityJoinRequestInfo(playerName, playerUUID, accountId));
community.message(F.main(getName(), F.name(playerName) + " has requested to join " + F.name(community.getName()) + "!"), CommunityRole.COLEADER); community.message(F.main(getName(), F.name(playerName) + " has requested to join " + F.name(community.getName()) + "!"), CommunityRole.COLEADER);
UtilServer.CallEvent(new CommunityJoinRequestsUpdateEvent(community)); runSync(() -> UtilServer.CallEvent(new CommunityJoinRequestsUpdateEvent(community)));
} }
public void handleCommunityCloseJoinRequest(Integer id, String sender, String playerName, UUID playerUUID, Integer accountId, boolean announce) public void handleCommunityCloseJoinRequest(Integer id, String sender, String playerName, UUID playerUUID, Integer accountId, boolean announce)
@ -354,14 +401,15 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
community.message(F.main(getName(), F.name(playerName) + "'s request to join " + F.name(community.getName()) + " has been denied by " + F.name(sender) + "!"), CommunityRole.COLEADER); community.message(F.main(getName(), F.name(playerName) + "'s request to join " + F.name(community.getName()) + " has been denied by " + F.name(sender) + "!"), CommunityRole.COLEADER);
} }
UtilServer.CallEvent(new CommunityJoinRequestsUpdateEvent(community)); runSync(() -> UtilServer.CallEvent(new CommunityJoinRequestsUpdateEvent(community)));
} }
public void handleCommunityCreation(Integer id, UUID leaderUUID) public void handleCommunityCreation(Integer id, String name, Integer leaderId, UUID leaderUUID, String leaderName)
{ {
runAsync(() -> runAsync(() ->
{ {
_repo.loadCommunity(id, _loadedCommunities); _loadedCommunities.put(id, new Community(id, name));
_loadedCommunities.get(id).getMembers().put(leaderUUID, new CommunityMemberInfo(leaderName, leaderUUID, leaderId, CommunityRole.LEADER, System.currentTimeMillis()));
runSync(() -> runSync(() ->
{ {
Community community = _loadedCommunities.get(id); Community community = _loadedCommunities.get(id);
@ -384,7 +432,10 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
} }
community.message(F.main(getName(), F.name(senderName) + " has disbanded community " + F.name(community.getName()) + "!")); community.message(F.main(getName(), F.name(senderName) + " has disbanded community " + F.name(community.getName()) + "!"));
UtilServer.CallEvent(new CommunityDisbandEvent(community)); UtilServer.CallEvent(new CommunityDisbandEvent(community));
runSync(() ->
{
UtilServer.GetPlayers().stream().filter(player -> Get(player).Invites.contains(community.getId())).forEach(player -> Get(player).Invites.remove(community.getId())); UtilServer.GetPlayers().stream().filter(player -> Get(player).Invites.contains(community.getId())).forEach(player -> Get(player).Invites.remove(community.getId()));
});
community.getMembers().keySet().stream().filter(uuid -> Bukkit.getPlayer(uuid) != null).forEach(uuid -> Get(Bukkit.getPlayer(uuid)).leaveCommunity(community)); community.getMembers().keySet().stream().filter(uuid -> Bukkit.getPlayer(uuid) != null).forEach(uuid -> Get(Bukkit.getPlayer(uuid)).leaveCommunity(community));
_loadedCommunities.remove(community.getId()); _loadedCommunities.remove(community.getId());
runSync(() -> runSync(() ->
@ -455,7 +506,7 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
} }
else else
{ {
UtilPlayer.message(sender, F.main(getName(), "Either " + F.name(target) + " does not exist or you have already invited them to " + F.name(community.getName()) + "!")); UtilPlayer.message(sender, F.main(getName(), F.name(target) + " does not exist!"));
} }
}); });
} }
@ -586,19 +637,34 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
new CommunityUpdateMemberRole(community.getId(), sender.getName(), info.UUID.toString(), role.toString()).publish(); new CommunityUpdateMemberRole(community.getId(), sender.getName(), info.UUID.toString(), role.toString()).publish();
} }
public void handleCreate(Player sender, int accountId, String name) public void handleCreate(Player sender, String senderName, int accountId, String name)
{ {
if (_creating.contains(sender.getUniqueId()))
{
UtilPlayer.message(sender, F.main(getName(), "You are already creating a Community!"));
return;
}
_creating.add(sender.getUniqueId());
runAsync(() -> runAsync(() ->
{ {
_repo.createCommunity(name, accountId, id -> _repo.createCommunity(name, accountId, id ->
{ {
if (id == -1) if (id == -1)
{ {
sender.sendMessage(F.main(getName(), "Failed to create community " + F.elem(name))); UtilPlayer.message(sender, F.main(getName(), "Failed to create community " + F.elem(name)));
runSync(() -> _creating.remove(sender.getUniqueId()));
} }
else else
{ {
new CommunityCreate(sender.getUniqueId().toString(), id).publish(); if (ownsCommunity(sender.getUniqueId()))
{
UtilPlayer.message(sender, F.main(getName(), "You already own a community!"));
_repo.deleteCommunity(id);
runSync(() -> _creating.remove(sender.getUniqueId()));
return;
}
new CommunityCreate(sender.getUniqueId().toString(), senderName, accountId, id, name).publish();
runSync(() -> _creating.remove(sender.getUniqueId()));
} }
}); });
}); });
@ -651,19 +717,11 @@ public class CommunityManager extends MiniDbClientPlugin<CommunityMemberData>
@EventHandler @EventHandler
public void loadInvites(PlayerJoinEvent event) public void loadInvites(PlayerJoinEvent event)
{ {
final int accountId = Managers.get(CoreClientManager.class).getAccountId(event.getPlayer());
final CommunityMemberData data = Get(event.getPlayer()); final CommunityMemberData data = Get(event.getPlayer());
runAsync(() ->
{
_repo.loadInvites(accountId, data.Invites);
runSync(() ->
{
if (data.Invites.size() > 0 && Managers.get(PreferencesManager.class).get(event.getPlayer()).isActive(Preference.COMMUNITY_INVITES)) if (data.Invites.size() > 0 && Managers.get(PreferencesManager.class).get(event.getPlayer()).isActive(Preference.COMMUNITY_INVITES))
{ {
UtilPlayer.message(event.getPlayer(), F.main(getName(), "You have been invited to join " + F.elem(data.Invites.size()) + " communities!")); UtilPlayer.message(event.getPlayer(), F.main(getName(), "You have been invited to join " + F.elem(data.Invites.size()) + " communities!"));
} }
});
});
} }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)

View File

@ -1,15 +1,15 @@
package mineplex.core.communities; package mineplex.core.communities;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import mineplex.core.Managers; import mineplex.core.Managers;
public class CommunityMemberData public class CommunityMemberData
{ {
private final Map<Integer, CommunityRole> _communities = new HashMap<>(); private final Map<Integer, CommunityRole> _communities = new ConcurrentHashMap<>();
public final List<Integer> Invites = new ArrayList<>(); public final List<Integer> Invites = new ArrayList<>();

View File

@ -15,20 +15,19 @@ public class CommunityMemberInfo
public final UUID UUID; public final UUID UUID;
public final int AccountId; public final int AccountId;
public CommunityRole Role; public CommunityRole Role;
public boolean OwnsCommunity = false;
public boolean ReadingChat = true; public boolean ReadingChat = true;
private ItemStack _memberIcon, _outsiderIcon; private ItemStack _memberIcon, _outsiderIcon;
private long _sinceLastLogin; private long _lastLogin;
private boolean _online = false; private boolean _online = false;
private String _currentServer = ""; private String _currentServer = "";
public CommunityMemberInfo(String name, UUID uuid, int accountId, CommunityRole role, long timeSinceLastLogin) public CommunityMemberInfo(String name, UUID uuid, int accountId, CommunityRole role, long lastLogin)
{ {
Name = name; Name = name;
UUID = uuid; UUID = uuid;
AccountId = accountId; AccountId = accountId;
Role = role; Role = role;
_sinceLastLogin = timeSinceLastLogin; _lastLogin = lastLogin;
buildIcons(); buildIcons();
} }
@ -44,7 +43,7 @@ public class CommunityMemberInfo
} }
else else
{ {
builder.addLore(C.cYellow + "Last Seen " + C.cWhite + UtilTime.MakeStr(_sinceLastLogin) + " Ago"); builder.addLore(C.cYellow + "Last Seen " + C.cWhite + UtilTime.MakeStr(System.currentTimeMillis() - _lastLogin) + " Ago");
} }
if (_online) if (_online)
{ {
@ -54,11 +53,32 @@ public class CommunityMemberInfo
_memberIcon = builder.build(); _memberIcon = builder.build();
} }
public void update(String name, CommunityRole role, long timeSinceLastLogin, boolean online, String currentServer) public void setOffline()
{ {
_online = false;
_currentServer = "";
buildIcons();
}
public void updateName(String name)
{
if (name == null)
{
return;
}
Name = name; Name = name;
buildIcons();
}
public void updateRole(CommunityRole role)
{
Role = role; Role = role;
_sinceLastLogin = timeSinceLastLogin; buildIcons();
}
public void update(long lastLogin, boolean online, String currentServer)
{
_lastLogin = lastLogin;
_online = online; _online = online;
_currentServer = currentServer; _currentServer = currentServer;

View File

@ -20,12 +20,6 @@ public class CommunityChatCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 1) if (args.length < 1)
{ {
UtilPlayer.message(caller, F.help("/com chat <community>", "Selects which community you chat to", Rank.ALL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com chat <community>", "Selects which community you chat to", Rank.ALL, ChatColor.AQUA));

View File

@ -33,12 +33,6 @@ public class CommunityCommand extends MultiCommandBase<CommunityManager>
@Override @Override
protected void Help(Player caller, String[] args) protected void Help(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length > 0) if (args.length > 0)
{ {
if (args[0].equalsIgnoreCase("help")) if (args[0].equalsIgnoreCase("help"))

View File

@ -25,12 +25,6 @@ public class CommunityCreateCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 1) if (args.length < 1)
{ {
UtilPlayer.message(caller, F.help("/com create <name>", "Creates a new community", Rank.ETERNAL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com create <name>", "Creates a new community", Rank.ETERNAL, ChatColor.AQUA));
@ -57,16 +51,17 @@ public class CommunityCreateCommand extends CommandBase<CommunityManager>
UtilPlayer.message(caller, F.main(Plugin.getName(), "That name is not allowed!")); UtilPlayer.message(caller, F.main(Plugin.getName(), "That name is not allowed!"));
return; return;
} }
final int accountId = Managers.get(CoreClientManager.class).getAccountId(caller);
final String senderName = Managers.get(CoreClientManager.class).Get(caller).getName();
Plugin.runAsync(() -> Plugin.runAsync(() ->
{ {
int accountId = Managers.get(CoreClientManager.class).getAccountId(caller);
if (Managers.get(Chat.class).getFilteredMessage(caller, args[0]).contains("*")) if (Managers.get(Chat.class).getFilteredMessage(caller, args[0]).contains("*"))
{ {
UtilPlayer.message(caller, F.main(Plugin.getName(), "That name is not allowed!")); UtilPlayer.message(caller, F.main(Plugin.getName(), "That name is not allowed!"));
} }
else else
{ {
Plugin.handleCreate(caller, accountId, args[0]); Plugin.runSync(() -> Plugin.handleCreate(caller, senderName, accountId, args[0]));
} }
}); });
} }

View File

@ -26,12 +26,6 @@ public class CommunityDescriptionCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 2) if (args.length < 2)
{ {
UtilPlayer.message(caller, F.help("/com description <community> <description>", "Sets the description of a community you manage", Rank.ALL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com description <community> <description>", "Sets the description of a community you manage", Rank.ALL, ChatColor.AQUA));

View File

@ -24,12 +24,6 @@ public class CommunityDisbandCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 1) if (args.length < 1)
{ {
UtilPlayer.message(caller, F.help("/com disband <community>", "Disbands a community you own", Rank.ETERNAL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com disband <community>", "Disbands a community you own", Rank.ETERNAL, ChatColor.AQUA));

View File

@ -24,12 +24,6 @@ public class CommunityInviteCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 2) if (args.length < 2)
{ {
UtilPlayer.message(caller, F.help("/com invite <player> <community>", "Invites a player to a community you manage", Rank.ALL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com invite <player> <community>", "Invites a player to a community you manage", Rank.ALL, ChatColor.AQUA));

View File

@ -21,12 +21,6 @@ public class CommunityJoinCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 1) if (args.length < 1)
{ {
UtilPlayer.message(caller, F.help("/com join <community>", "Joins a community that is open or you have been invited to", Rank.ALL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com join <community>", "Joins a community that is open or you have been invited to", Rank.ALL, ChatColor.AQUA));

View File

@ -25,12 +25,6 @@ public class CommunityMCSCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 1) if (args.length < 1)
{ {
UtilPlayer.message(caller, F.help("/com mcs <community>", "Opens the Mineplex Community Server of a community you manage", Rank.ALL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com mcs <community>", "Opens the Mineplex Community Server of a community you manage", Rank.ALL, ChatColor.AQUA));

View File

@ -27,12 +27,6 @@ public class CommunityRenameCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 2) if (args.length < 2)
{ {
UtilPlayer.message(caller, F.help("/com rename <community> <name>", "Changes the name of a community you own", Rank.ETERNAL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com rename <community> <name>", "Changes the name of a community you own", Rank.ETERNAL, ChatColor.AQUA));

View File

@ -24,12 +24,6 @@ public class CommunityUnInviteCommand extends CommandBase<CommunityManager>
@Override @Override
public void Execute(Player caller, String[] args) public void Execute(Player caller, String[] args)
{ {
if (true)
{
caller.sendMessage(F.main("Communities", "Coming soon!"));
return;
}
if (args.length < 2) if (args.length < 2)
{ {
UtilPlayer.message(caller, F.help("/com uninvite <player> <community>", "Revokes a player's invitation to a community you manage", Rank.ALL, ChatColor.AQUA)); UtilPlayer.message(caller, F.help("/com uninvite <player> <community>", "Revokes a player's invitation to a community you manage", Rank.ALL, ChatColor.AQUA));

View File

@ -54,7 +54,7 @@ public class CommunityMemberButton extends CommunitiesGUIButton
} }
if (_info.Role == CommunityRole.COLEADER && type == ClickType.SHIFT_LEFT) if (_info.Role == CommunityRole.COLEADER && type == ClickType.SHIFT_LEFT)
{ {
if (_info.OwnsCommunity) if (getCommunityManager().ownsCommunity(_info.UUID))
{ {
UtilPlayer.message(_viewer, F.main(getCommunityManager().getName(), F.name(_info.Name) + " can only own one community at a time!")); UtilPlayer.message(_viewer, F.main(getCommunityManager().getName(), F.name(_info.Name) + " can only own one community at a time!"));
return; return;

View File

@ -10,11 +10,13 @@ import org.bukkit.event.EventHandler;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
import mineplex.core.communities.Community; import mineplex.core.communities.Community;
import mineplex.core.communities.CommunityDisbandEvent; import mineplex.core.communities.CommunityDisbandEvent;
import mineplex.core.communities.CommunityJoinRequestsUpdateEvent;
import mineplex.core.communities.CommunityMemberDataUpdateEvent; import mineplex.core.communities.CommunityMemberDataUpdateEvent;
import mineplex.core.communities.CommunityMemberInfo; import mineplex.core.communities.CommunityMemberInfo;
import mineplex.core.communities.CommunityMembershipUpdateEvent; import mineplex.core.communities.CommunityMembershipUpdateEvent;
import mineplex.core.communities.CommunityRole; import mineplex.core.communities.CommunityRole;
import mineplex.core.communities.gui.ActionButton; import mineplex.core.communities.gui.ActionButton;
import mineplex.core.communities.gui.CommunitiesGUIButton;
import mineplex.core.communities.gui.CommunitiesGUIPage; import mineplex.core.communities.gui.CommunitiesGUIPage;
import mineplex.core.communities.gui.overview.CommunityOverviewPage; import mineplex.core.communities.gui.overview.CommunityOverviewPage;
import mineplex.core.itemstack.ItemBuilder; import mineplex.core.itemstack.ItemBuilder;
@ -107,9 +109,20 @@ public class CommunityMembersPage extends CommunitiesGUIPage
members.sort((info1, info2) -> members.sort((info1, info2) ->
{ {
if (info1.isOnline() == info2.isOnline()) if (info1.isOnline() == info2.isOnline())
{
if (info1.Role == info2.Role)
{ {
return info1.Name.compareToIgnoreCase(info2.Name); return info1.Name.compareToIgnoreCase(info2.Name);
} }
else if (info1.Role.ordinal() < info2.Role.ordinal())
{
return -1;
}
else
{
return 1;
}
}
if (info1.isOnline()) if (info1.isOnline())
{ {
@ -142,6 +155,19 @@ public class CommunityMembersPage extends CommunitiesGUIPage
Viewer.updateInventory(); Viewer.updateInventory();
} }
@EventHandler
public void onRequestsUpdate(CommunityJoinRequestsUpdateEvent event)
{
if (event.getCommunity().getId().intValue() != _community.getId().intValue())
{
return;
}
CommunitiesGUIButton button = Buttons.get(4);
button.update();
Inv.setItem(4, button.Button);
Viewer.updateInventory();
}
@EventHandler @EventHandler
public void onMembershipUpdate(CommunityMembershipUpdateEvent event) public void onMembershipUpdate(CommunityMembershipUpdateEvent event)
{ {

View File

@ -7,12 +7,14 @@ import org.bukkit.event.EventHandler;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
import mineplex.core.communities.Community; import mineplex.core.communities.Community;
import mineplex.core.communities.CommunityDisbandEvent; import mineplex.core.communities.CommunityDisbandEvent;
import mineplex.core.communities.CommunityJoinRequestsUpdateEvent;
import mineplex.core.communities.CommunityMemberDataUpdateEvent; import mineplex.core.communities.CommunityMemberDataUpdateEvent;
import mineplex.core.communities.CommunityMembershipUpdateEvent; import mineplex.core.communities.CommunityMembershipUpdateEvent;
import mineplex.core.communities.CommunityRole; import mineplex.core.communities.CommunityRole;
import mineplex.core.communities.CommunitySetting; import mineplex.core.communities.CommunitySetting;
import mineplex.core.communities.CommunitySettingUpdateEvent; import mineplex.core.communities.CommunitySettingUpdateEvent;
import mineplex.core.communities.gui.ActionButton; import mineplex.core.communities.gui.ActionButton;
import mineplex.core.communities.gui.CommunitiesGUIButton;
import mineplex.core.communities.gui.CommunitiesGUIPage; import mineplex.core.communities.gui.CommunitiesGUIPage;
import mineplex.core.communities.gui.overview.CommunityOverviewPage; import mineplex.core.communities.gui.overview.CommunityOverviewPage;
import mineplex.core.itemstack.ItemBuilder; import mineplex.core.itemstack.ItemBuilder;
@ -104,6 +106,19 @@ public class CommunitySettingsPage extends CommunitiesGUIPage
Viewer.updateInventory(); Viewer.updateInventory();
} }
@EventHandler
public void onRequestsUpdate(CommunityJoinRequestsUpdateEvent event)
{
if (event.getCommunity().getId().intValue() != _community.getId().intValue())
{
return;
}
CommunitiesGUIButton button = Buttons.get(4);
button.update();
Inv.setItem(4, button.Button);
Viewer.updateInventory();
}
@EventHandler @EventHandler
public void onMembershipUpdate(CommunityMembershipUpdateEvent event) public void onMembershipUpdate(CommunityMembershipUpdateEvent event)
{ {
@ -121,7 +136,7 @@ public class CommunitySettingsPage extends CommunitiesGUIPage
@EventHandler @EventHandler
public void onSettingsUpdate(CommunitySettingUpdateEvent event) public void onSettingsUpdate(CommunitySettingUpdateEvent event)
{ {
if (event.getCommunity().getId() != _community.getId()) if (event.getCommunity().getId().intValue() != _community.getId().intValue())
{ {
return; return;
} }

View File

@ -5,12 +5,18 @@ import mineplex.serverdata.commands.ServerCommand;
public class CommunityCreate extends ServerCommand public class CommunityCreate extends ServerCommand
{ {
private String _leaderUUID; private String _leaderUUID;
private String _leaderName;
private Integer _leaderId;
private Integer _communityId; private Integer _communityId;
private String _communityName;
public CommunityCreate(String leaderUUID, Integer communityId) public CommunityCreate(String leaderUUID, String leaderName, Integer leaderId, Integer communityId, String communityName)
{ {
_leaderUUID = leaderUUID; _leaderUUID = leaderUUID;
_leaderName = leaderName;
_leaderId = leaderId;
_communityId = communityId; _communityId = communityId;
_communityName = communityName;
} }
public String getLeaderUUID() public String getLeaderUUID()
@ -18,8 +24,23 @@ public class CommunityCreate extends ServerCommand
return _leaderUUID; return _leaderUUID;
} }
public String getLeaderName()
{
return _leaderName;
}
public Integer getLeaderId()
{
return _leaderId;
}
public Integer getCommunityId() public Integer getCommunityId()
{ {
return _communityId; return _communityId;
} }
public String getCommunityName()
{
return _communityName;
}
} }

View File

@ -23,8 +23,11 @@ public class CommunityCreateHandler implements CommandCallback
CommunityCreate update = ((CommunityCreate) command); CommunityCreate update = ((CommunityCreate) command);
UUID leaderUUID = UUID.fromString(update.getLeaderUUID()); UUID leaderUUID = UUID.fromString(update.getLeaderUUID());
Integer communityId = update.getCommunityId(); Integer communityId = update.getCommunityId();
String communityName = update.getCommunityName();
Integer leaderId = update.getLeaderId();
String leaderName = update.getLeaderName();
_manager.handleCommunityCreation(communityId, leaderUUID); _manager.handleCommunityCreation(communityId, communityName, leaderId, leaderUUID, leaderName);
} }
} }
} }

View File

@ -0,0 +1,26 @@
package mineplex.core.communities.redis;
import mineplex.core.communities.CommunityManager;
import mineplex.serverdata.commands.CommandCallback;
import mineplex.serverdata.commands.PlayerJoinCommand;
import mineplex.serverdata.commands.ServerCommand;
public class PlayerJoinHandler implements CommandCallback
{
private CommunityManager _communityManager;
public PlayerJoinHandler(CommunityManager communityManager)
{
_communityManager = communityManager;
}
@Override
public void run(ServerCommand command)
{
if (command instanceof PlayerJoinCommand)
{
PlayerJoinCommand joinCommand = (PlayerJoinCommand)command;
//_communityManager.updateAllMemberData(UUID.fromString(joinCommand.getUuid()), joinCommand.getName());
}
}
}

View File

@ -1,17 +1,18 @@
package mineplex.core.communities.storage; package mineplex.core.communities.storage;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.timing.TimingManager;
import mineplex.core.common.util.Callback; import mineplex.core.common.util.Callback;
import mineplex.core.communities.Community; import mineplex.core.communities.Community;
import mineplex.core.communities.CommunityJoinRequestInfo; import mineplex.core.communities.CommunityJoinRequestInfo;
@ -31,9 +32,9 @@ public class CommunityRepository extends MinecraftRepository
private static final String GET_ALL_COMMUNITIES = "SELECT * FROM communities WHERE region=?;"; private static final String GET_ALL_COMMUNITIES = "SELECT * FROM communities WHERE region=?;";
private static final String GET_COMMUNITY_BY_ID = "SELECT * FROM communities WHERE id=?;"; private static final String GET_COMMUNITY_BY_ID = "SELECT * FROM communities WHERE id=?;";
private static final String GET_COMMUNITY_BY_NAME = "SELECT * FROM communities WHERE name=? AND region=?;"; private static final String GET_COMMUNITY_BY_NAME = "SELECT * FROM communities WHERE name=? AND region=?;";
private static final String GET_COMMUNITY_MEMBERS = "SELECT cm.accountId, cm.communityRole, ac.name, ac.uuid, ac.lastLogin, now(), cm.readingChat, (SELECT COUNT(id) FROM communityMembers WHERE accountId=cm.accountId AND communityRole='LEADER') FROM communityMembers cm INNER JOIN accounts ac ON ac.id=cm.accountId WHERE communityId=?;"; private static final String GET_COMMUNITY_MEMBERS = "SELECT cm.communityId, cm.accountId, cm.communityRole, ac.name, ac.uuid, ac.lastLogin, cm.readingChat FROM communityMembers cm INNER JOIN accounts ac ON ac.id=cm.accountId;";
private static final String GET_COMMUNITY_JOIN_REQUESTS = "SELECT cjr.accountId, ac.name, ac.uuid FROM communityJoinRequests cjr INNER JOIN accounts ac ON ac.id=cjr.accountId WHERE communityId=?;"; private static final String GET_COMMUNITY_JOIN_REQUESTS = "SELECT cjr.communityId, cjr.accountId, ac.name, ac.uuid FROM communityJoinRequests cjr INNER JOIN accounts ac ON ac.id=cjr.accountId;";
private static final String GET_COMMUNITY_SETTINGS = "SELECT settingId, settingValue FROM communitySettings WHERE communityId=?;"; private static final String GET_COMMUNITY_SETTINGS = "SELECT communityId, settingId, settingValue FROM communitySettings;";
private static final String REMOVE_FROM_COMMUNITY = "DELETE FROM communityMembers WHERE accountId=? AND communityId=?;"; private static final String REMOVE_FROM_COMMUNITY = "DELETE FROM communityMembers WHERE accountId=? AND communityId=?;";
private static final String UPDATE_COMMUNITY_ROLE = "UPDATE communityMembers SET communityRole=? WHERE accountId=? AND communityId=?;"; private static final String UPDATE_COMMUNITY_ROLE = "UPDATE communityMembers SET communityRole=? WHERE accountId=? AND communityId=?;";
@ -60,78 +61,6 @@ public class CommunityRepository extends MinecraftRepository
_us = us; _us = us;
} }
public void loadCommunity(int communityId, final Map<Integer, Community> communityMap)
{
try (Connection connection = getConnection())
{
executeQuery(connection, GET_COMMUNITY_BY_ID, resultSet ->
{
if (resultSet.next())
{
final int id = resultSet.getInt("id");
final String cName = resultSet.getString("name");
final Community community = new Community(id, cName);
executeQuery(connection, GET_COMMUNITY_MEMBERS, memberSet ->
{
while (memberSet.next())
{
final int accountId = memberSet.getInt("accountId");
final String name = memberSet.getString("name");
final UUID uuid = UUID.fromString(memberSet.getString("uuid"));
final CommunityRole role = CommunityRole.parseRole(memberSet.getString("communityRole"));
final long timeSinceOnline = memberSet.getTimestamp(6).getTime() - memberSet.getTimestamp(5).getTime();
boolean readingChat = memberSet.getBoolean("readingChat");
final int owns = memberSet.getInt(8);
CommunityMemberInfo info = new CommunityMemberInfo(name, uuid, accountId, role, timeSinceOnline);
PlayerStatus status = _repo.getElement(name);
if (status != null)
{
info.update(name, role, timeSinceOnline, true, status.getServer());
}
info.ReadingChat = readingChat;
info.OwnsCommunity = owns > 0;
community.getMembers().put(info.UUID, info);
}
}, new ColumnInt("communityId", community.getId()));
executeQuery(connection, GET_COMMUNITY_JOIN_REQUESTS, requestSet ->
{
while (requestSet.next())
{
final int accountId = requestSet.getInt("accountId");
final UUID uuid = UUID.fromString(requestSet.getString("uuid"));
final String name = requestSet.getString("name");
community.getJoinRequests().put(uuid, new CommunityJoinRequestInfo(name, uuid, accountId));
}
}, new ColumnInt("communityId", community.getId()));
executeQuery(connection, GET_COMMUNITY_SETTINGS, settingSet ->
{
while (settingSet.next())
{
final int settingId = settingSet.getInt("settingId");
final String value = settingSet.getString("settingValue");
CommunitySetting setting = CommunitySetting.getSetting(settingId);
if (setting != null)
{
setting.parseValueInto(value, community);
}
}
}, new ColumnInt("communityId", community.getId()));
communityMap.put(community.getId(), community);
}
}, new ColumnInt("id", communityId));
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void loadCommunities(final Map<Integer, Community> communityMap) public void loadCommunities(final Map<Integer, Community> communityMap)
{ {
try (Connection connection = getConnection()) try (Connection connection = getConnection())
@ -144,56 +73,6 @@ public class CommunityRepository extends MinecraftRepository
final int id = resultSet.getInt("id"); final int id = resultSet.getInt("id");
final String cName = resultSet.getString("name"); final String cName = resultSet.getString("name");
final Community community = new Community(id, cName); final Community community = new Community(id, cName);
executeQuery(connection, GET_COMMUNITY_MEMBERS, memberSet ->
{
while (memberSet.next())
{
final int accountId = memberSet.getInt("accountId");
final String name = memberSet.getString("name");
final UUID uuid = UUID.fromString(memberSet.getString("uuid"));
final CommunityRole role = CommunityRole.parseRole(memberSet.getString("communityRole"));
final long timeSinceOnline = memberSet.getTimestamp(6).getTime() - memberSet.getTimestamp(5).getTime();
boolean readingChat = memberSet.getBoolean("readingChat");
final int owns = memberSet.getInt(8);
CommunityMemberInfo info = new CommunityMemberInfo(name, uuid, accountId, role, timeSinceOnline);
PlayerStatus status = _repo.getElement(name);
if (status != null)
{
info.update(name, role, timeSinceOnline, true, status.getServer());
}
info.ReadingChat = readingChat;
info.OwnsCommunity = owns > 0;
community.getMembers().put(info.UUID, info);
}
}, new ColumnInt("communityId", community.getId()));
executeQuery(connection, GET_COMMUNITY_JOIN_REQUESTS, requestSet ->
{
while (requestSet.next())
{
final int accountId = requestSet.getInt("accountId");
final UUID uuid = UUID.fromString(requestSet.getString("uuid"));
final String name = requestSet.getString("name");
community.getJoinRequests().put(uuid, new CommunityJoinRequestInfo(name, uuid, accountId));
}
}, new ColumnInt("communityId", community.getId()));
executeQuery(connection, GET_COMMUNITY_SETTINGS, settingSet ->
{
while (settingSet.next())
{
final int settingId = settingSet.getInt("settingId");
final String value = settingSet.getString("settingValue");
CommunitySetting setting = CommunitySetting.getSetting(settingId);
if (setting != null)
{
setting.parseValueInto(value, community);
}
}
}, new ColumnInt("communityId", community.getId()));
resultant.put(community.getId(), community); resultant.put(community.getId(), community);
} }
@ -201,6 +80,63 @@ public class CommunityRepository extends MinecraftRepository
communityMap.clear(); communityMap.clear();
communityMap.putAll(resultant); communityMap.putAll(resultant);
}, new ColumnVarChar("region", 5, _us ? "US" : "EU")); }, new ColumnVarChar("region", 5, _us ? "US" : "EU"));
executeQuery(connection, GET_COMMUNITY_MEMBERS, memberSet ->
{
while (memberSet.next())
{
final int communityId = memberSet.getInt("communityId");
final int accountId = memberSet.getInt("accountId");
final String name = memberSet.getString("name");
final UUID uuid = UUID.fromString(memberSet.getString("uuid"));
final CommunityRole role = CommunityRole.parseRole(memberSet.getString("communityRole"));
final long lastLogin = memberSet.getTimestamp("lastLogin").getTime();
boolean readingChat = memberSet.getBoolean("readingChat");
CommunityMemberInfo info = new CommunityMemberInfo(name, uuid, accountId, role, lastLogin);
info.ReadingChat = readingChat;
Community community = communityMap.get(communityId);
if (community != null)
{
community.getMembers().put(info.UUID, info);
}
}
});
executeQuery(connection, GET_COMMUNITY_JOIN_REQUESTS, requestSet ->
{
while (requestSet.next())
{
final int communityId = requestSet.getInt("communityId");
final int accountId = requestSet.getInt("accountId");
final UUID uuid = UUID.fromString(requestSet.getString("uuid"));
final String name = requestSet.getString("name");
Community community = communityMap.get(communityId);
if (community != null)
{
community.getJoinRequests().put(uuid, new CommunityJoinRequestInfo(name, uuid, accountId));
}
}
});
executeQuery(connection, GET_COMMUNITY_SETTINGS, settingSet ->
{
while (settingSet.next())
{
final int communityId = settingSet.getInt("communityId");
final int settingId = settingSet.getInt("settingId");
final String value = settingSet.getString("settingValue");
Community community = communityMap.get(communityId);
CommunitySetting setting = CommunitySetting.getSetting(settingId);
if (community != null && setting != null)
{
setting.parseValueInto(value, community);
}
}
});
} }
catch (SQLException e) catch (SQLException e)
{ {
@ -208,124 +144,72 @@ public class CommunityRepository extends MinecraftRepository
} }
} }
public void updateMembersAndJoinRequests(LinkedList<Community> communities) public void updateMembers(LinkedList<Community> communities)
{ {
if (communities.isEmpty()) if (communities.isEmpty())
{ {
return; return;
} }
String query = ""; TimingManager.start("member elements");
for (Community c : communities) for (Community c : communities)
{ {
query = query + GET_COMMUNITY_MEMBERS.replace("?", c.getId().toString()) + GET_COMMUNITY_JOIN_REQUESTS.replace("?", c.getId().toString()); List<CommunityMemberInfo> members = new ArrayList<>(c.getMembers().values());
List<PlayerStatus> statuses = _repo.getElementsSequential(members.stream().map(info -> info.UUID.toString()).collect(Collectors.toList()));
for (int i = 0; i < members.size(); i++)
{
CommunityMemberInfo info = members.get(i);
PlayerStatus status = statuses.get(i);
boolean online = false;
String server = "";
if (status != null)
{
online = true;
server = status.getServer();
info.update(System.currentTimeMillis(), online, server);
if (!info.Name.equals(status.getName()))
{
info.updateName(status.getName());
}
}
else
{
if (info.isOnline())
{
info.setOffline();
}
}
}
}
TimingManager.stop("member elements");
} }
if (query.isEmpty()) public void updateJoinRequests(LinkedList<Community> communities)
{
if (communities.isEmpty())
{ {
return; return;
} }
TimingManager.start("request elements");
try (Connection connection = getConnection(); Statement statement = connection.createStatement())
{
statement.executeQuery(query);
for (Community c : communities) for (Community c : communities)
{ {
ResultSet memberSet = statement.getResultSet(); List<CommunityJoinRequestInfo> requests = new ArrayList<>(c.getJoinRequests().values());
while (memberSet.next()) List<PlayerStatus> statuses = _repo.getElementsSequential(requests.stream().map(info -> info.UUID.toString()).collect(Collectors.toList()));
for (int i = 0; i < requests.size(); i++)
{ {
final UUID uuid = UUID.fromString(memberSet.getString("uuid")); CommunityJoinRequestInfo info = requests.get(i);
final String name = memberSet.getString("name"); PlayerStatus status = statuses.get(i);
final CommunityRole role = CommunityRole.parseRole(memberSet.getString("communityRole"));
final long timeSinceOnline = memberSet.getTimestamp(6).getTime() - memberSet.getTimestamp(5).getTime();
//boolean readingChat = memberSet.getBoolean("readingChat");
final int owns = memberSet.getInt(8);
if (c.getMembers().containsKey(uuid))
{
PlayerStatus status = _repo.getElement(name);
boolean online = false;
String server = "";
if (status != null) if (status != null)
{ {
online = true; if (!info.Name.equals(status.getName()))
server = status.getServer();
}
//c.getMembers().get(uuid).ReadingChat = readingChat;
c.getMembers().get(uuid).OwnsCommunity = owns > 0;
c.getMembers().get(uuid).update(name, role, timeSinceOnline, online, server);
}
}
statement.getMoreResults();
ResultSet requestSet = statement.getResultSet();
while (requestSet.next())
{ {
final UUID uuid = UUID.fromString(requestSet.getString("uuid")); info.update(status.getName());
final String name = requestSet.getString("name");
if (c.getJoinRequests().containsKey(uuid))
{
c.getJoinRequests().get(uuid).update(name);
} }
} }
statement.getMoreResults();
} }
} }
catch (SQLException e) TimingManager.stop("request elements");
{
e.printStackTrace();
}
}
public void updateMembers(Map<UUID, CommunityMemberInfo> members, int communityId)
{
executeQuery(GET_COMMUNITY_MEMBERS, memberSet ->
{
while (memberSet.next())
{
final UUID uuid = UUID.fromString(memberSet.getString("uuid"));
final String name = memberSet.getString("name");
final CommunityRole role = CommunityRole.parseRole(memberSet.getString("communityRole"));
final long timeSinceOnline = memberSet.getTimestamp(5).getTime() - memberSet.getTimestamp(4).getTime();
//boolean readingChat = memberSet.getBoolean("readingChat");
final int owns = memberSet.getInt(8);
if (members.containsKey(uuid))
{
PlayerStatus status = _repo.getElement(name);
boolean online = false;
String server = "";
if (status != null)
{
online = true;
server = status.getServer();
}
//members.get(uuid).ReadingChat = readingChat;
members.get(uuid).OwnsCommunity = owns > 0;
members.get(uuid).update(name, role, timeSinceOnline, online, server);
}
}
}, new ColumnInt("communityId", communityId));
}
public void updateJoinRequests(Map<UUID, CommunityJoinRequestInfo> requests, int communityId)
{
executeQuery(GET_COMMUNITY_JOIN_REQUESTS, requestSet ->
{
while (requestSet.next())
{
final UUID uuid = UUID.fromString(requestSet.getString("uuid"));
final String name = requestSet.getString("name");
if (requests.containsKey(uuid))
{
requests.get(uuid).update(name);
}
}
}, new ColumnInt("communityId", communityId));
} }
public void loadInvites(int accountId, List<Integer> invites) public void loadInvites(int accountId, List<Integer> invites)
@ -397,18 +281,19 @@ public class CommunityRepository extends MinecraftRepository
if (resultSet.next()) if (resultSet.next())
{ {
int id = resultSet.getInt(1); int id = resultSet.getInt(1);
executeUpdate(connection, ADD_TO_COMMUNITY, new ColumnInt("accountId", leaderAccount), new ColumnInt("communityId", id), new ColumnVarChar("communityRole", 20, CommunityRole.LEADER.toString())); executeUpdate(connection, ADD_TO_COMMUNITY, null, new ColumnInt("accountId", leaderAccount), new ColumnInt("communityId", id), new ColumnVarChar("communityRole", 20, CommunityRole.LEADER.toString()));
idCallback.run(id); idCallback.run(id);
} }
else else
{ {
idCallback.run(-1); idCallback.run(-1);
} }
}, new ColumnVarChar("name", 15, name), new ColumnVarChar("region", 5, _us ? "US" : "EU")); }, () -> idCallback.run(-1), new ColumnVarChar("name", 15, name), new ColumnVarChar("region", 5, _us ? "US" : "EU"));
} }
catch (SQLException e) catch (SQLException e)
{ {
e.printStackTrace(); e.printStackTrace();
idCallback.run(-1);
} }
} }
@ -416,11 +301,11 @@ public class CommunityRepository extends MinecraftRepository
{ {
try (Connection connection = getConnection()) try (Connection connection = getConnection())
{ {
executeUpdate(connection, "DELETE FROM communities WHERE id=?;", new ColumnInt("id", communityId)); executeUpdate(connection, "DELETE FROM communities WHERE id=?;", null, new ColumnInt("id", communityId));
executeUpdate(connection, "DELETE FROM communitySettings WHERE communityId=?;", new ColumnInt("communityId", communityId)); executeUpdate(connection, "DELETE FROM communitySettings WHERE communityId=?;", null, new ColumnInt("communityId", communityId));
executeUpdate(connection, "DELETE FROM communityMembers WHERE communityId=?;", new ColumnInt("communityId", communityId)); executeUpdate(connection, "DELETE FROM communityMembers WHERE communityId=?;", null, new ColumnInt("communityId", communityId));
executeUpdate(connection, "DELETE FROM communityInvites WHERE communityId=?;", new ColumnInt("communityId", communityId)); executeUpdate(connection, "DELETE FROM communityInvites WHERE communityId=?;", null, new ColumnInt("communityId", communityId));
executeUpdate(connection, "DELETE FROM communityJoinRequests WHERE communityId=?", new ColumnInt("communityId", communityId)); executeUpdate(connection, "DELETE FROM communityJoinRequests WHERE communityId=?", null, new ColumnInt("communityId", communityId));
} }
catch (SQLException e) catch (SQLException e)
{ {

View File

@ -392,8 +392,8 @@ public class PlayerDisguiseManager extends MiniPlugin implements IPacketHandler
CoreClient client = getClientManager().Get(caller); CoreClient client = getClientManager().Get(caller);
client.undisguise(); client.undisguise();
require(FriendManager.class).updatePlayerStatus(disguisedProfile.getName(), null); require(FriendManager.class).updatePlayerStatus(disguisedProfile.getId(), null);
require(FriendManager.class).updatePlayerStatus(originalProfile.getName(), new PlayerStatus(originalProfile.getName(), _serverName)); require(FriendManager.class).updatePlayerStatus(originalProfile.getId(), new PlayerStatus(originalProfile.getId(), originalProfile.getName(), _serverName));
getPreferencesManager().handlePlayerJoin(caller, true); getPreferencesManager().handlePlayerJoin(caller, true);
require(ScoreboardManager.class).handlePlayerJoin(disguise.getOriginalProfile().getName()); require(ScoreboardManager.class).handlePlayerJoin(disguise.getOriginalProfile().getName());
@ -539,8 +539,8 @@ public class PlayerDisguiseManager extends MiniPlugin implements IPacketHandler
callerProfile.getProperties().removeAll(ORIGINAL_UUID_KEY); callerProfile.getProperties().removeAll(ORIGINAL_UUID_KEY);
callerProfile.getProperties().put(ORIGINAL_UUID_KEY, new Property(ORIGINAL_UUID_KEY, caller.getUniqueId().toString())); callerProfile.getProperties().put(ORIGINAL_UUID_KEY, new Property(ORIGINAL_UUID_KEY, caller.getUniqueId().toString()));
require(FriendManager.class).updatePlayerStatus(disguisePlayer.getOriginalProfile().getName(), null); require(FriendManager.class).updatePlayerStatus(disguisePlayer.getOriginalProfile().getId(), null);
require(FriendManager.class).updatePlayerStatus(requestedUsername, new PlayerStatus(requestedUsername, _serverName)); require(FriendManager.class).updatePlayerStatus(disguisePlayer.getProfile().getId(), new PlayerStatus(disguisePlayer.getProfile().getId(), requestedUsername, _serverName));
getPreferencesManager().handlePlayerJoin(caller, true); getPreferencesManager().handlePlayerJoin(caller, true);

View File

@ -1,5 +1,19 @@
package mineplex.core.friend; package mineplex.core.friend;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniDbClientPlugin; import mineplex.core.MiniDbClientPlugin;
import mineplex.core.account.CoreClientManager; import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank; import mineplex.core.common.Rank;
@ -22,19 +36,6 @@ import mineplex.core.preferences.PreferencesManager;
import mineplex.core.updater.UpdateType; import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent; import mineplex.core.updater.event.UpdateEvent;
import mineplex.serverdata.data.PlayerStatus; import mineplex.serverdata.data.PlayerStatus;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
public class FriendManager extends MiniDbClientPlugin<FriendData> public class FriendManager extends MiniDbClientPlugin<FriendData>
{ {
@ -402,14 +403,14 @@ public class FriendManager extends MiniDbClientPlugin<FriendData>
} }
public void updatePlayerStatus(String playerName, PlayerStatus status) public void updatePlayerStatus(UUID playerUUID, PlayerStatus status)
{ {
_repository.updatePlayerStatus(playerName, status); _repository.updatePlayerStatus(playerUUID, status);
} }
public PlayerStatus getStatus(String playerName) public PlayerStatus getStatus(UUID playerUUID)
{ {
return _repository.getStatus(playerName); return _repository.getStatus(playerUUID);
} }
@Override @Override
@ -421,7 +422,7 @@ public class FriendManager extends MiniDbClientPlugin<FriendData>
@Override @Override
public String getQuery(int accountId, String uuid, String name) public String getQuery(int accountId, String uuid, String name)
{ {
return "SELECT tA.Name, status, tA.lastLogin, now() FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget WHERE uuidSource = '" return "SELECT tA.Name, status, tA.lastLogin, now(), uuidTarget FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget WHERE uuidSource = '"
+ uuid + "';"; + uuid + "';";
} }
} }

View File

@ -7,6 +7,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import mineplex.core.database.MinecraftRepository; import mineplex.core.database.MinecraftRepository;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -26,7 +27,7 @@ import mineplex.serverdata.servers.ServerManager;
public class FriendRepository extends MinecraftRepository public class FriendRepository extends MinecraftRepository
{ {
private static String CREATE_FRIEND_TABLE = "CREATE TABLE IF NOT EXISTS accountFriend (id INT NOT NULL AUTO_INCREMENT, uuidSource VARCHAR(100), uuidTarget VARCHAR(100), status VARCHAR(100), PRIMARY KEY (id), UNIQUE INDEX uuidIndex (uuidSource, uuidTarget));"; private static String CREATE_FRIEND_TABLE = "CREATE TABLE IF NOT EXISTS accountFriend (id INT NOT NULL AUTO_INCREMENT, uuidSource VARCHAR(100), uuidTarget VARCHAR(100), status VARCHAR(100), PRIMARY KEY (id), UNIQUE INDEX uuidIndex (uuidSource, uuidTarget));";
private static String RETRIEVE_MULTIPLE_FRIEND_RECORDS = "SELECT uuidSource, tA.Name, status, tA.lastLogin, now() FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget WHERE uuidSource IN "; private static String RETRIEVE_MULTIPLE_FRIEND_RECORDS = "SELECT uuidSource, tA.Name, status, tA.lastLogin, now(), uuidTarget FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget WHERE uuidSource IN ";
private static String ADD_FRIEND_RECORD = "INSERT INTO accountFriend (uuidSource, uuidTarget, status, created) SELECT fA.uuid AS uuidSource, tA.uuid AS uuidTarget, ?, now() FROM accounts as fA LEFT JOIN accounts AS tA ON tA.name = ? WHERE fA.name = ?;"; private static String ADD_FRIEND_RECORD = "INSERT INTO accountFriend (uuidSource, uuidTarget, status, created) SELECT fA.uuid AS uuidSource, tA.uuid AS uuidTarget, ?, now() FROM accounts as fA LEFT JOIN accounts AS tA ON tA.name = ? WHERE fA.name = ?;";
private static String UPDATE_MUTUAL_RECORD = "UPDATE accountFriend AS aF INNER JOIN accounts as fA ON aF.uuidSource = fA.uuid INNER JOIN accounts AS tA ON aF.uuidTarget = tA.uuid SET aF.status = ? WHERE tA.name = ? AND fA.name = ?;"; private static String UPDATE_MUTUAL_RECORD = "UPDATE accountFriend AS aF INNER JOIN accounts as fA ON aF.uuidSource = fA.uuid INNER JOIN accounts AS tA ON aF.uuidTarget = tA.uuid SET aF.status = ? WHERE tA.name = ? AND fA.name = ?;";
private static String DELETE_FRIEND_RECORD = "DELETE aF FROM accountFriend AS aF INNER JOIN accounts as fA ON aF.uuidSource = fA.uuid INNER JOIN accounts AS tA ON aF.uuidTarget = tA.uuid WHERE fA.name = ? AND tA.name = ?;"; private static String DELETE_FRIEND_RECORD = "DELETE aF FROM accountFriend AS aF INNER JOIN accounts as fA ON aF.uuidSource = fA.uuid INNER JOIN accounts AS tA ON aF.uuidTarget = tA.uuid WHERE fA.name = ? AND tA.name = ?;";
@ -95,6 +96,7 @@ public class FriendRepository extends MinecraftRepository
friend.Name = resultSet.getString(2); friend.Name = resultSet.getString(2);
friend.Status = Enum.valueOf(FriendStatusType.class, resultSet.getString(3)); friend.Status = Enum.valueOf(FriendStatusType.class, resultSet.getString(3));
friend.LastSeenOnline = resultSet.getTimestamp(5).getTime() - resultSet.getTimestamp(4).getTime(); friend.LastSeenOnline = resultSet.getTimestamp(5).getTime() - resultSet.getTimestamp(4).getTime();
friend.UUID = UUID.fromString(resultSet.getString(6));
if (!friends.containsKey(uuidSource)) if (!friends.containsKey(uuidSource))
friends.put(uuidSource, new FriendData()); friends.put(uuidSource, new FriendData());
@ -126,6 +128,7 @@ public class FriendRepository extends MinecraftRepository
friend.Name = resultSet.getString(1); friend.Name = resultSet.getString(1);
friend.Status = Enum.valueOf(FriendStatusType.class, resultSet.getString(2)); friend.Status = Enum.valueOf(FriendStatusType.class, resultSet.getString(2));
friend.LastSeenOnline = resultSet.getTimestamp(4).getTime() - resultSet.getTimestamp(3).getTime(); friend.LastSeenOnline = resultSet.getTimestamp(4).getTime() - resultSet.getTimestamp(3).getTime();
friend.UUID = UUID.fromString(resultSet.getString(5));
friend.ServerName = null; friend.ServerName = null;
friend.Online = (friend.ServerName != null); friend.Online = (friend.ServerName != null);
friendData.getFriends().add(friend); friendData.getFriends().add(friend);
@ -144,26 +147,26 @@ public class FriendRepository extends MinecraftRepository
public void loadFriendStatuses(FriendData friendData) public void loadFriendStatuses(FriendData friendData)
{ {
// Generate a set of all friend names // Generate a set of all friend names
Set<String> friendNames = new HashSet<String>(); Set<String> friendUUIDS = new HashSet<>();
for(FriendStatus status : friendData.getFriends()) for(FriendStatus status : friendData.getFriends())
{ {
friendNames.add(status.Name.toLowerCase()); friendUUIDS.add(status.UUID.toString());
} }
// Load PlayerStatus' for friends // Load PlayerStatus' for friends
Collection<PlayerStatus> statuses = _repository.getElements(friendNames); Collection<PlayerStatus> statuses = _repository.getElements(friendUUIDS);
// Load player statuses into a mapping // Load player statuses into a mapping
Map<String, PlayerStatus> playerStatuses = new HashMap<String, PlayerStatus>(); Map<UUID, PlayerStatus> playerStatuses = new HashMap<>();
for(PlayerStatus status : statuses) for(PlayerStatus status : statuses)
{ {
playerStatuses.put(status.getName(), status); playerStatuses.put(status.getUUID(), status);
} }
// Load status information into friend data. // Load status information into friend data.
for (FriendStatus friend : friendData.getFriends()) for (FriendStatus friend : friendData.getFriends())
{ {
PlayerStatus status = playerStatuses.get(friend.Name); PlayerStatus status = playerStatuses.get(friend.UUID);
friend.Online = (status != null); friend.Online = (status != null);
friend.ServerName = (friend.Online) ? status.getServer() : null; friend.ServerName = (friend.Online) ? status.getServer() : null;
} }
@ -174,14 +177,14 @@ public class FriendRepository extends MinecraftRepository
* @return the name that the player matching {@code playerName} * @return the name that the player matching {@code playerName}
* is currently online on, if they are online, null otherwise. * is currently online on, if they are online, null otherwise.
*/ */
public String fetchPlayerServer(String playerName) public String fetchPlayerServer(UUID playerUUID)
{ {
PlayerStatus status = _repository.getElement(playerName.toLowerCase()); PlayerStatus status = _repository.getElement(playerUUID.toString());
return (status == null) ? null : status.getServer(); return (status == null) ? null : status.getServer();
} }
public void updatePlayerStatus(String playerName, PlayerStatus status) public void updatePlayerStatus(UUID playerUUID, PlayerStatus status)
{ {
if (status != null) if (status != null)
{ {
@ -189,12 +192,12 @@ public class FriendRepository extends MinecraftRepository
} }
else else
{ {
_repository.removeElement(playerName.toLowerCase()); _repository.removeElement(playerUUID.toString());
} }
} }
public PlayerStatus getStatus(String playerName) public PlayerStatus getStatus(UUID playerUUID)
{ {
return _repository.getElement(playerName.toLowerCase()); return _repository.getElement(playerUUID.toString());
} }
} }

View File

@ -1,10 +1,13 @@
package mineplex.core.friend.data; package mineplex.core.friend.data;
import java.util.UUID;
import mineplex.core.friend.FriendStatusType; import mineplex.core.friend.FriendStatusType;
public class FriendStatus public class FriendStatus
{ {
public String Name; public String Name;
public UUID UUID;
public String ServerName; public String ServerName;
public boolean Online; public boolean Online;
/** /**

View File

@ -44,7 +44,7 @@ public class EternalTaunt extends TauntGadget
public EternalTaunt(GadgetManager manager) public EternalTaunt(GadgetManager manager)
{ {
super(manager, "Eternal Taunt", UtilText.splitLinesToArray(new String[]{C.cGray + "Although the Eternal has been around forever, he waited to long for a worthy opponent and he turned to bones.", super(manager, "Eternal Taunt", UtilText.splitLinesToArray(new String[]{C.cGray + "Although the Eternal has been around forever, he waited too long for a worthy opponent and he turned to bones.",
"", "",
C.cWhite + "Use /taunt in game to show how long you've been waiting.", C.cWhite + "Use /taunt in game to show how long you've been waiting.",
C.cRed + "Cannot be used while in PvP!"}, LineFormat.LORE), C.cRed + "Cannot be used while in PvP!"}, LineFormat.LORE),

View File

@ -409,7 +409,7 @@ public class ClansManager extends MiniClientPlugin<ClientClan>implements IRelati
_bannerManager.loadBanners(this); _bannerManager.loadBanners(this);
new PersonalServerManager(plugin, _clientManager).setUseInterfaceItem(false); new PersonalServerManager(plugin, _clientManager).setUseInterfaceItem(false);
// new CommunityManager(plugin, _clientManager); new CommunityManager(plugin, _clientManager);
Bukkit.getMessenger().registerOutgoingPluginChannel(plugin, "Replay|Restrict"); Bukkit.getMessenger().registerOutgoingPluginChannel(plugin, "Replay|Restrict");

View File

@ -275,7 +275,7 @@ public class HubManager extends MiniClientPlugin<HubClient> implements IChatMess
new SalesAnnouncementManager(plugin); new SalesAnnouncementManager(plugin);
// new CommunityManager(plugin, _clientManager); new CommunityManager(plugin, _clientManager);
ScoreboardManager scoreboardManager = new ScoreboardManager(plugin) ScoreboardManager scoreboardManager = new ScoreboardManager(plugin)
{ {

View File

@ -5,10 +5,12 @@ import java.util.UUID;
public class PlayerJoinCommand extends ServerCommand public class PlayerJoinCommand extends ServerCommand
{ {
private String _uuid; private String _uuid;
private String _name;
public PlayerJoinCommand(UUID uuid) public PlayerJoinCommand(UUID uuid, String name)
{ {
_uuid = uuid.toString(); _uuid = uuid.toString();
_name = name;
} }
@Override @Override
@ -21,4 +23,9 @@ public class PlayerJoinCommand extends ServerCommand
{ {
return _uuid; return _uuid;
} }
public String getName()
{
return _name;
}
} }

View File

@ -1,6 +1,7 @@
package mineplex.serverdata.data; package mineplex.serverdata.data;
import java.util.Collection; import java.util.Collection;
import java.util.List;
/** /**
* DataRepository is used to store {@link Data} objects in a central database * DataRepository is used to store {@link Data} objects in a central database
@ -18,6 +19,8 @@ public interface DataRepository<T extends Data>
public Collection<T> getElements(Collection<String> dataIds); public Collection<T> getElements(Collection<String> dataIds);
public List<T> getElementsSequential(List<String> dataIds);
public void addElement(T element, int timeout); public void addElement(T element, int timeout);
public void addElement(T element); public void addElement(T element);

View File

@ -1,14 +1,18 @@
package mineplex.serverdata.data; package mineplex.serverdata.data;
import mineplex.serverdata.data.Data; import java.util.UUID;
public class PlayerStatus implements Data public class PlayerStatus implements Data
{ {
// The name of this server. // The uuid of this player.
private UUID _uuid;
public UUID getUUID() { return _uuid; }
// The name of this player.
private String _name; private String _name;
public String getName() { return _name; } public String getName() { return _name; }
// The current message of the day (MOTD) of the server. // The current server occupied by this player.
private String _server; private String _server;
public String getServer() { return _server; } public String getServer() { return _server; }
@ -17,19 +21,18 @@ public class PlayerStatus implements Data
* @param name * @param name
* @param server * @param server
*/ */
public PlayerStatus(String name, String server) public PlayerStatus(UUID uuid, String name, String server)
{ {
_uuid = uuid;
_name = name; _name = name;
_server = server; _server = server;
} }
/** /**
* Unique identifying String ID associated with this {@link PlayerStatus}. * Unique identifying String ID associated with this {@link PlayerStatus}.
*
* Use the lowercase name so we can have case-insensitive lookup
*/ */
public String getDataId() public String getDataId()
{ {
return _name.toLowerCase(); return _uuid.toString();
} }
} }

View File

@ -76,9 +76,14 @@ public abstract class RepositoryBase
} }
} }
protected int executeUpdate(Connection connection, String query, Column<?>...columns) protected int executeUpdate(Connection connection, String query, Runnable onSQLError, Column<?>...columns)
{ {
return executeInsert(connection, query, null, columns); return executeInsert(connection, query, null, onSQLError, columns);
}
protected int executeUpdate(String query, Runnable onSQLError, Column<?>...columns)
{
return executeInsert(query, null, columns);
} }
/** /**
@ -92,7 +97,7 @@ public abstract class RepositoryBase
return executeInsert(query, null, columns); return executeInsert(query, null, columns);
} }
protected int executeInsert(Connection connection, String query, ResultSetCallable callable, Column<?>...columns) protected int executeInsert(Connection connection, String query, ResultSetCallable callable, Runnable onSQLError, Column<?>...columns)
{ {
int affectedRows = 0; int affectedRows = 0;
@ -114,6 +119,33 @@ public abstract class RepositoryBase
} }
} }
catch (SQLException exception) catch (SQLException exception)
{
exception.printStackTrace();
if (onSQLError != null)
{
onSQLError.run();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
return affectedRows;
}
protected int executeInsert(String query, ResultSetCallable callable, Runnable onSQLError, Column<?>...columns)
{
int affectedRows = 0;
// Automatic resource management for handling/closing objects.
try (
Connection connection = getConnection();
)
{
affectedRows = executeInsert(connection, query, callable, onSQLError, columns);
}
catch (SQLException exception)
{ {
exception.printStackTrace(); exception.printStackTrace();
} }
@ -134,7 +166,7 @@ public abstract class RepositoryBase
Connection connection = getConnection(); Connection connection = getConnection();
) )
{ {
affectedRows = executeInsert(connection, query, callable, columns); affectedRows = executeInsert(connection, query, callable, null, columns);
} }
catch (SQLException exception) catch (SQLException exception)
{ {
@ -148,7 +180,7 @@ public abstract class RepositoryBase
return affectedRows; return affectedRows;
} }
protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column<?>...columns) protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Runnable onSQLError, Column<?>...columns)
{ {
try try
{ {
@ -166,6 +198,34 @@ public abstract class RepositoryBase
} }
} }
catch (SQLException exception) catch (SQLException exception)
{
exception.printStackTrace();
if (onSQLError != null)
{
onSQLError.run();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column<?>...columns)
{
executeQuery(statement, callable, null, columns);
}
protected void executeQuery(Connection connection, String query, ResultSetCallable callable, Runnable onSQLError, Column<?>...columns)
{
// Automatic resource management for handling/closing objects.
try (
PreparedStatement preparedStatement = connection.prepareStatement(query)
)
{
executeQuery(preparedStatement, callable, onSQLError, columns);
}
catch (SQLException exception)
{ {
exception.printStackTrace(); exception.printStackTrace();
} }
@ -194,6 +254,25 @@ public abstract class RepositoryBase
} }
} }
protected void executeQuery(String query, ResultSetCallable callable, Runnable onSQLError, Column<?>...columns)
{
// Automatic resource management for handling/closing objects.
try (
Connection connection = getConnection();
)
{
executeQuery(connection, query, callable, onSQLError, columns);
}
catch (SQLException exception)
{
exception.printStackTrace();
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
protected void executeQuery(String query, ResultSetCallable callable, Column<?>...columns) protected void executeQuery(String query, ResultSetCallable callable, Column<?>...columns)
{ {
// Automatic resource management for handling/closing objects. // Automatic resource management for handling/closing objects.

View File

@ -103,6 +103,36 @@ public class RedisDataRepository<T extends Data> extends RedisRepository impleme
return elements; return elements;
} }
@Override
public List<T> getElementsSequential(List<String> dataIds)
{
List<T> elements = new ArrayList<>();
try(Jedis jedis = getResource(false))
{
Pipeline pipeline = jedis.pipelined();
List<Response<String>> responses = new ArrayList<>();
for (String dataId : dataIds)
{
responses.add(pipeline.get(generateKey(dataId)));
}
// Block until all requests have received pipelined responses
pipeline.sync();
for (Response<String> response : responses)
{
String serializedData = response.get();
T element = deserialize(serializedData);
elements.add(element);
}
}
return elements;
}
@Override @Override
public T getElement(String dataId) public T getElement(String dataId)
{ {

View File

@ -407,7 +407,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
addCommand(new TauntCommand(this)); addCommand(new TauntCommand(this));
new PersonalServerManager(plugin, _clientManager).setUseInterfaceItem(false); new PersonalServerManager(plugin, _clientManager).setUseInterfaceItem(false);
// new CommunityManager(plugin, _clientManager); new CommunityManager(plugin, _clientManager);
_scoreboardManager = new ScoreboardManager(_plugin) _scoreboardManager = new ScoreboardManager(_plugin)
{ {