Merge pull request #9 from plexusorg/punishments

so far it is working but the only thing preventing me from going to f…
This commit is contained in:
Telesphoreo 2022-04-05 13:15:46 -05:00 committed by GitHub
commit 2fcf44c6a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 456 additions and 598 deletions

View File

@ -30,6 +30,7 @@ dependencies {
library "dev.morphia.morphia:morphia-core:2.2.6" library "dev.morphia.morphia:morphia-core:2.2.6"
library "redis.clients:jedis:4.2.1" library "redis.clients:jedis:4.2.1"
library "org.mariadb.jdbc:mariadb-java-client:3.0.4" library "org.mariadb.jdbc:mariadb-java-client:3.0.4"
library "com.zaxxer:HikariCP:5.0.1"
library "org.apache.httpcomponents:httpclient:4.5.13" library "org.apache.httpcomponents:httpclient:4.5.13"
library "org.apache.commons:commons-lang3:3.12.0" library "org.apache.commons:commons-lang3:3.12.0"
library "org.apache.maven.resolver:maven-resolver-api:1.7.3" library "org.apache.maven.resolver:maven-resolver-api:1.7.3"

View File

@ -3,15 +3,15 @@ package dev.plex;
import dev.plex.admin.Admin; import dev.plex.admin.Admin;
import dev.plex.admin.AdminList; import dev.plex.admin.AdminList;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData; import dev.plex.cache.player.MongoPlayerData;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.cache.SQLPlayerData; import dev.plex.cache.player.SQLPlayerData;
import dev.plex.cache.sql.SQLPunishment;
import dev.plex.config.Config; import dev.plex.config.Config;
import dev.plex.handlers.CommandHandler; import dev.plex.handlers.CommandHandler;
import dev.plex.handlers.ListenerHandler; import dev.plex.handlers.ListenerHandler;
import dev.plex.module.ModuleManager; import dev.plex.module.ModuleManager;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.PunishmentManager; import dev.plex.punishment.PunishmentManager;
import dev.plex.rank.RankManager; import dev.plex.rank.RankManager;
import dev.plex.services.ServiceManager; import dev.plex.services.ServiceManager;
@ -49,6 +49,7 @@ public class Plex extends JavaPlugin
private RedisConnection redisConnection; private RedisConnection redisConnection;
private MongoPlayerData mongoPlayerData; private MongoPlayerData mongoPlayerData;
private SQLPlayerData sqlPlayerData; private SQLPlayerData sqlPlayerData;
private SQLPunishment sqlPunishment;
private ModuleManager moduleManager; private ModuleManager moduleManager;
private RankManager rankManager; private RankManager rankManager;
private ServiceManager serviceManager; private ServiceManager serviceManager;
@ -77,10 +78,6 @@ public class Plex extends JavaPlugin
modulesFolder.mkdir(); modulesFolder.mkdir();
} }
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager = new ModuleManager(); moduleManager = new ModuleManager();
moduleManager.loadAllModules(); moduleManager.loadAllModules();
moduleManager.loadModules(); moduleManager.loadModules();
@ -94,6 +91,10 @@ public class Plex extends JavaPlugin
// Don't add default entries to indefinite ban file // Don't add default entries to indefinite ban file
indefBans.load(false); indefBans.load(false);
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager.enableModules(); moduleManager.enableModules();
system = config.getString("system"); system = config.getString("system");
@ -133,6 +134,7 @@ public class Plex extends JavaPlugin
else else
{ {
sqlPlayerData = new SQLPlayerData(); sqlPlayerData = new SQLPlayerData();
sqlPunishment = new SQLPunishment();
} }
new ListenerHandler(); new ListenerHandler();
@ -204,7 +206,6 @@ public class Plex extends JavaPlugin
{ {
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId()); PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
PlayerCache.getPunishedPlayerMap().put(player.getUniqueId(), new PunishedPlayer(player.getUniqueId()));
if (plugin.getRankManager().isAdmin(plexPlayer)) if (plugin.getRankManager().isAdmin(plexPlayer))
{ {
Admin admin = new Admin(UUID.fromString(plexPlayer.getUuid())); Admin admin = new Admin(UUID.fromString(plexPlayer.getUuid()));

View File

@ -1,6 +1,7 @@
package dev.plex.cache; package dev.plex.cache;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType; import dev.plex.storage.StorageType;
import java.util.UUID; import java.util.UUID;
@ -43,6 +44,7 @@ public class DataUtils
return PlayerCache.getPlexPlayerMap().get(uuid); return PlayerCache.getPlexPlayerMap().get(uuid);
} }
if (Plex.get().getStorageType() == StorageType.MONGODB) if (Plex.get().getStorageType() == StorageType.MONGODB)
{ {
return Plex.get().getMongoPlayerData().getByUUID(uuid); return Plex.get().getMongoPlayerData().getByUUID(uuid);

View File

@ -1,4 +1,4 @@
package dev.plex.cache; package dev.plex.cache.player;
import dev.morphia.Datastore; import dev.morphia.Datastore;
import dev.morphia.query.Query; import dev.morphia.query.Query;
@ -8,6 +8,7 @@ import dev.morphia.query.experimental.updates.UpdateOperators;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.UUID; import java.util.UUID;
/** /**
@ -104,6 +105,11 @@ public class MongoPlayerData
updateOps.execute(); updateOps.execute();
} }
public List<PlexPlayer> getPlayers()
{
return datastore.find(PlexPlayer.class).stream().toList();
}
/** /**
* Saves the player's information in the database * Saves the player's information in the database

View File

@ -1,8 +1,8 @@
package dev.plex.cache; package dev.plex.cache.player;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -20,19 +20,18 @@ public class PlayerCache
/** /**
* A key/value pair where the key is the unique ID of the Punished Player * A key/value pair where the key is the unique ID of the Punished Player
*/ */
private static final Map<UUID, PunishedPlayer> punishedPlayerMap = Maps.newHashMap(); // private static final Map<UUID, PunishedPlayer> punishedPlayerMap = Maps.newHashMap();
public static Map<UUID, PunishedPlayer> getPunishedPlayerMap()
{
return punishedPlayerMap;
}
// public static Map<UUID, PunishedPlayer> getPunishedPlayerMap()
// {
// return punishedPlayerMap;
// }
public static Map<UUID, PlexPlayer> getPlexPlayerMap() public static Map<UUID, PlexPlayer> getPlexPlayerMap()
{ {
return plexPlayerMap; return plexPlayerMap;
} }
public static PunishedPlayer getPunishedPlayer(UUID uuid) /*public static PunishedPlayer getPunishedPlayer(UUID uuid)
{ {
if (!getPunishedPlayerMap().containsKey(uuid)) if (!getPunishedPlayerMap().containsKey(uuid))
{ {
@ -40,7 +39,7 @@ public class PlayerCache
} }
return getPunishedPlayerMap().get(uuid); return getPunishedPlayerMap().get(uuid);
} }
*/
public static PlexPlayer getPlexPlayer(UUID uuid) public static PlexPlayer getPlexPlayer(UUID uuid)
{ {
return getPlexPlayerMap().get(uuid); return getPlexPlayerMap().get(uuid);

View File

@ -1,4 +1,4 @@
package dev.plex.cache; package dev.plex.cache.player;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;

View File

@ -0,0 +1,134 @@
package dev.plex.cache.sql;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.util.PlexLog;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class SQLPunishment
{
private static final String SELECT = "SELECT * FROM `punishments` WHERE punished=?";
private static final String SELECT_BY = "SELECT * FROM `punishments` WHERE punisher=?";
private static final String INSERT = "INSERT INTO `punishments` (`punished`, `punisher`, `punishedUsername`, `ip`, `type`, `reason`, `customTime`, `active`, `endDate`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String UPDATE_BAN = "UPDATE `punishments` SET active=? WHERE active=? AND punished=? AND type=?";
public CompletableFuture<List<Punishment>> getPunishments()
{
return CompletableFuture.supplyAsync(() ->
{
List<Punishment> punishments = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `punishments`");
ResultSet set = statement.executeQuery();
while (set.next())
{
Punishment punishment = new Punishment(UUID.fromString(set.getString("punished")), UUID.fromString(set.getString("punisher")));
punishment.setActive(set.getBoolean("active"));
punishment.setType(PunishmentType.valueOf(set.getString("type")));
punishment.setCustomTime(set.getBoolean("customTime"));
punishment.setPunishedUsername(set.getString("punishedUsername"));
punishment.setEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("endDate")), ZoneId.systemDefault()));
punishment.setReason(set.getString("reason"));
punishment.setIp(set.getString("ip"));
punishments.add(punishment);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return punishments;
});
}
public List<Punishment> getPunishments(UUID uuid)
{
List<Punishment> punishments = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
Punishment punishment = new Punishment(UUID.fromString(set.getString("punished")), set.getString("punisher") == null ? null : UUID.fromString(set.getString("punisher")));
punishment.setActive(set.getBoolean("active"));
punishment.setType(PunishmentType.valueOf(set.getString("type")));
punishment.setCustomTime(set.getBoolean("customTime"));
punishment.setPunishedUsername(set.getString("punishedUsername"));
punishment.setEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("endDate")), ZoneId.systemDefault()));
punishment.setReason(set.getString("reason"));
punishment.setIp(set.getString("ip"));
punishments.add(punishment);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return punishments;
}
public CompletableFuture<Void> insertPunishment(Punishment punishment)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PlexLog.debug("Running execute punishment on " + punishment.getPunished().toString());
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, punishment.getPunished().toString());
statement.setString(2, punishment.getPunisher() == null ? null : punishment.getPunisher().toString());
statement.setString(3, punishment.getPunishedUsername());
statement.setString(4, punishment.getIp());
statement.setString(5, punishment.getType().name());
statement.setString(6, punishment.getReason());
statement.setBoolean(7, punishment.isCustomTime());
statement.setBoolean(8, punishment.isActive());
statement.setLong(9, punishment.getEndDate().toInstant(ZoneOffset.UTC).toEpochMilli());
PlexLog.debug("Executing punishment");
statement.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
}
public CompletableFuture<Void> removeBan(UUID uuid)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE_BAN);
statement.setBoolean(1, false);
statement.setBoolean(2, true);
statement.setString(3, uuid.toString());
statement.setString(4, PunishmentType.BAN.name());
statement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
}
}

View File

@ -2,7 +2,7 @@ package dev.plex.command;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException; import dev.plex.command.exception.CommandFailException;

View File

@ -1,6 +1,6 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;

View File

@ -1,15 +1,14 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException; import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource; import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType; import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
@ -40,7 +39,6 @@ public class BanCMD extends PlexCommand
} }
UUID targetUUID = PlexUtils.getFromName(args[0]); UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason;
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID)) if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{ {
@ -62,39 +60,46 @@ public class BanCMD extends PlexCommand
} }
} }
if (plugin.getPunishmentManager().isBanned(targetUUID)) plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
{ {
return messageComponent("playerBanned"); if (aBoolean)
} {
send(sender, messageComponent("playerBanned"));
return;
}
String reason;
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN);
if (args.length > 1)
{
reason = StringUtils.join(args, " ", 1, args.length);
punishment.setReason(reason);
}
else
{
punishment.setReason("No reason provided.");
}
punishment.setPunishedUsername(plexPlayer.getName());
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
if (player != null)
{
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
}
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
Bukkit.getScheduler().runTask(Plex.get(), () ->
{
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
});
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + plexPlayer.getUuid());
});
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN);
if (args.length > 1)
{
reason = StringUtils.join(args, " ", 1, args.length);
punishment.setReason(reason);
}
else
{
punishment.setReason("No reason provided.");
}
punishment.setPunishedUsername(plexPlayer.getName());
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
if (player != null)
{
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
}
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + punishedPlayer.getUuid());
return null; return null;
} }

View File

@ -1,12 +1,11 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType; import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
@ -32,7 +31,7 @@ public class FreezeCMD extends PlexCommand
return usage(); return usage();
} }
Player player = getNonNullPlayer(args[0]); Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = getPlexPlayer(player);
if (punishedPlayer.isFrozen()) if (punishedPlayer.isFrozen())
{ {
@ -61,7 +60,7 @@ public class FreezeCMD extends PlexCommand
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim()); punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason(""); punishment.setReason("");
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment); plugin.getPunishmentManager().punish(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("frozePlayer", sender.getName(), player.getName())); PlexUtils.broadcast(messageComponent("frozePlayer", sender.getName(), player.getName()));
return null; return null;
} }

View File

@ -1,14 +1,13 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException; import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource; import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType; import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
@ -49,8 +48,6 @@ public class KickCMD extends PlexCommand
{ {
throw new PlayerNotFoundException(); throw new PlayerNotFoundException();
} }
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender)); Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.KICK); punishment.setType(PunishmentType.KICK);
if (args.length > 1) if (args.length > 1)
@ -64,7 +61,7 @@ public class KickCMD extends PlexCommand
punishment.setCustomTime(false); punishment.setCustomTime(false);
punishment.setActive(false); punishment.setActive(false);
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim()); punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment); plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("kickedPlayer", sender.getName(), plexPlayer.getName())); PlexUtils.broadcast(messageComponent("kickedPlayer", sender.getName(), plexPlayer.getName()));
player.kick(componentFromString(reason)); player.kick(componentFromString(reason));
return null; return null;

View File

@ -1,12 +1,11 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import java.util.List; import java.util.List;
@ -28,7 +27,7 @@ public class LockupCMD extends PlexCommand
return usage(); return usage();
} }
Player player = getNonNullPlayer(args[0]); Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (isAdmin(getPlexPlayer(player))) if (isAdmin(getPlexPlayer(player)))
{ {

View File

@ -1,12 +1,11 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType; import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
@ -32,7 +31,7 @@ public class MuteCMD extends PlexCommand
return usage(); return usage();
} }
Player player = getNonNullPlayer(args[0]); Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (punishedPlayer.isMuted()) if (punishedPlayer.isMuted())
{ {
@ -61,7 +60,7 @@ public class MuteCMD extends PlexCommand
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim()); punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason(""); punishment.setReason("");
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment); plugin.getPunishmentManager().punish(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("mutedPlayer", sender.getName(), player.getName())); PlexUtils.broadcast(messageComponent("mutedPlayer", sender.getName(), player.getName()));
return null; return null;
} }

View File

@ -2,14 +2,13 @@ package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException; import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource; import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType; import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
@ -65,8 +64,6 @@ public class TempbanCMD extends PlexCommand
{ {
return messageComponent("playerBanned"); return messageComponent("playerBanned");
} }
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender)); Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN); punishment.setType(PunishmentType.BAN);
if (args.length > 2) if (args.length > 2)
@ -86,7 +83,7 @@ public class TempbanCMD extends PlexCommand
{ {
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim()); punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
} }
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment); plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName())); PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null) if (player != null)
{ {

View File

@ -1,6 +1,7 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
@ -11,14 +12,17 @@ import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID;
@CommandParameters(name = "unban", usage = "/<command> <player>", description = "Unbans a player, offline or online") @CommandParameters(name = "unban", usage = "/<command> <player>", description = "Unbans a player, offline or online")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.ban", source = RequiredCommandSource.ANY) @CommandPermissions(level = Rank.ADMIN, permission = "plex.ban", source = RequiredCommandSource.ANY)
@ -41,14 +45,17 @@ public class UnbanCMD extends PlexCommand
throw new PlayerNotFoundException(); throw new PlayerNotFoundException();
} }
if (!plugin.getPunishmentManager().isBanned(targetUUID)) plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
{ {
throw new PlayerNotBannedException(); PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID);
} if (!aBoolean)
{
PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID); send(sender, MiniMessage.miniMessage().deserialize(new PlayerNotBannedException().getMessage()));
plugin.getPunishmentManager().unban(targetUUID); return;
PlexUtils.broadcast(messageComponent("unbanningPlayer", sender.getName(), plexPlayer.getName())); }
plugin.getPunishmentManager().unban(targetUUID);
PlexUtils.broadcast(messageComponent("unbanningPlayer", sender.getName(), plexPlayer.getName()));
});
} }
return null; return null;
} }

View File

@ -1,12 +1,12 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException; import dev.plex.command.exception.CommandFailException;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import java.util.List; import java.util.List;
@ -28,7 +28,7 @@ public class UnfreezeCMD extends PlexCommand
return usage(); return usage();
} }
Player player = getNonNullPlayer(args[0]); Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (!punishedPlayer.isFrozen()) if (!punishedPlayer.isFrozen())
{ {
throw new CommandFailException(PlexUtils.messageString("playerNotFrozen")); throw new CommandFailException(PlexUtils.messageString("playerNotFrozen"));

View File

@ -1,12 +1,12 @@
package dev.plex.command.impl; package dev.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand; import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters; import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions; import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException; import dev.plex.command.exception.CommandFailException;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import java.util.List; import java.util.List;
@ -28,7 +28,7 @@ public class UnmuteCMD extends PlexCommand
return usage(); return usage();
} }
Player player = getNonNullPlayer(args[0]); Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (!punishedPlayer.isMuted()) if (!punishedPlayer.isMuted())
{ {
throw new CommandFailException(PlexUtils.messageString("playerNotMuted")); throw new CommandFailException(PlexUtils.messageString("playerNotMuted"));

View File

@ -1,7 +1,8 @@
package dev.plex.event; package dev.plex.event;
import dev.plex.player.PunishedPlayer;
import java.util.UUID; import java.util.UUID;
import dev.plex.player.PlexPlayer;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -17,7 +18,7 @@ public abstract class PunishedPlayerEvent extends PlayerEvent implements Cancell
/** /**
* The player who was punished * The player who was punished
*/ */
protected PunishedPlayer punishedPlayer; protected PlexPlayer punishedPlayer;
/** /**
* Whether the event was cancelled * Whether the event was cancelled
@ -29,9 +30,9 @@ public abstract class PunishedPlayerEvent extends PlayerEvent implements Cancell
* Creates an event object * Creates an event object
* *
* @param punishedPlayer The player who was punished * @param punishedPlayer The player who was punished
* @see PunishedPlayer * @see PlexPlayer
*/ */
protected PunishedPlayerEvent(PunishedPlayer punishedPlayer) protected PunishedPlayerEvent(PlexPlayer punishedPlayer)
{ {
super(Bukkit.getPlayer(UUID.fromString(punishedPlayer.getUuid()))); super(Bukkit.getPlayer(UUID.fromString(punishedPlayer.getUuid())));
this.punishedPlayer = punishedPlayer; this.punishedPlayer = punishedPlayer;

View File

@ -1,6 +1,6 @@
package dev.plex.event; package dev.plex.event;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import lombok.Getter; import lombok.Getter;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
@ -24,7 +24,7 @@ public class PunishedPlayerFreezeEvent extends PunishedPlayerEvent implements Ca
* @param punishedPlayer The player who was punished * @param punishedPlayer The player who was punished
* @param frozen The new frozen status * @param frozen The new frozen status
*/ */
public PunishedPlayerFreezeEvent(PunishedPlayer punishedPlayer, boolean frozen) public PunishedPlayerFreezeEvent(PlexPlayer punishedPlayer, boolean frozen)
{ {
super(punishedPlayer); super(punishedPlayer);
this.frozen = frozen; this.frozen = frozen;

View File

@ -1,6 +1,6 @@
package dev.plex.event; package dev.plex.event;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import lombok.Getter; import lombok.Getter;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
@ -24,7 +24,7 @@ public class PunishedPlayerLockupEvent extends PunishedPlayerEvent implements Ca
* @param punishedPlayer The player who was punished * @param punishedPlayer The player who was punished
* @param lockedUp The new muted status * @param lockedUp The new muted status
*/ */
public PunishedPlayerLockupEvent(PunishedPlayer punishedPlayer, boolean lockedUp) public PunishedPlayerLockupEvent(PlexPlayer punishedPlayer, boolean lockedUp)
{ {
super(punishedPlayer); super(punishedPlayer);
this.lockedUp = lockedUp; this.lockedUp = lockedUp;

View File

@ -1,6 +1,6 @@
package dev.plex.event; package dev.plex.event;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import lombok.Getter; import lombok.Getter;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
@ -24,7 +24,7 @@ public class PunishedPlayerMuteEvent extends PunishedPlayerEvent implements Canc
* @param punishedPlayer The player who was punished * @param punishedPlayer The player who was punished
* @param muted The new muted status * @param muted The new muted status
*/ */
public PunishedPlayerMuteEvent(PunishedPlayer punishedPlayer, boolean muted) public PunishedPlayerMuteEvent(PlexPlayer punishedPlayer, boolean muted)
{ {
super(punishedPlayer); super(punishedPlayer);
this.muted = muted; this.muted = muted;

View File

@ -1,8 +1,9 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache; import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType; import dev.plex.punishment.PunishmentType;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -36,7 +37,7 @@ public class BanListener extends PlexListener
if (plugin.getPunishmentManager().isBanned(event.getUniqueId())) if (plugin.getPunishmentManager().isBanned(event.getUniqueId()))
{ {
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getUniqueId()); PlexPlayer player = DataUtils.getPlayer(event.getUniqueId());
player.getPunishments().stream().filter(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive()).findFirst().ifPresent(punishment -> player.getPunishments().stream().filter(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive()).findFirst().ifPresent(punishment ->
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED,
Punishment.generateBanMessage(punishment))); Punishment.generateBanMessage(punishment)));

View File

@ -1,6 +1,6 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import dev.plex.listener.annotation.Toggleable; import dev.plex.listener.annotation.Toggleable;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;

View File

@ -1,6 +1,6 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;

View File

@ -1,8 +1,9 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache; import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
@ -11,7 +12,7 @@ public class FreezeListener extends PlexListener
@EventHandler @EventHandler
public void onPlayerMove(PlayerMoveEvent e) public void onPlayerMove(PlayerMoveEvent e)
{ {
PunishedPlayer player = PlayerCache.getPunishedPlayer(e.getPlayer().getUniqueId()); PlexPlayer player = DataUtils.getPlayer(e.getPlayer().getUniqueId());
if (player.isFrozen()) if (player.isFrozen())
{ {
e.setCancelled(true); e.setCancelled(true);

View File

@ -1,18 +1,20 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache; import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import io.papermc.paper.event.player.AsyncChatEvent; import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
public class MuteListener extends PlexListener public class MuteListener extends PlexListener
{ {
@EventHandler @EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncChatEvent event) public void onChat(AsyncChatEvent event)
{ {
if (PlayerCache.getPunishedPlayer(event.getPlayer().getUniqueId()).isMuted()) if (DataUtils.getPlayer(event.getPlayer().getUniqueId()).isMuted())
{ {
event.getPlayer().sendMessage(PlexUtils.messageComponent("muted")); event.getPlayer().sendMessage(PlexUtils.messageComponent("muted"));
event.setCancelled(true); event.setCancelled(true);

View File

@ -1,12 +1,11 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.cache.DataUtils; import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData; import dev.plex.cache.player.MongoPlayerData;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.cache.SQLPlayerData; import dev.plex.cache.player.SQLPlayerData;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.util.PlexLog; import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import java.util.Arrays; import java.util.Arrays;
@ -24,9 +23,6 @@ import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerListener extends PlexListener public class PlayerListener extends PlexListener
{ {
private final MongoPlayerData mongoPlayerData = plugin.getMongoPlayerData() != null ? plugin.getMongoPlayerData() : null;
private final SQLPlayerData sqlPlayerData = plugin.getSqlPlayerData() != null ? plugin.getSqlPlayerData() : null;
// setting up a player's data // setting up a player's data
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerSetup(PlayerJoinEvent event) public void onPlayerSetup(PlayerJoinEvent event)
@ -71,12 +67,9 @@ public class PlayerListener extends PlexListener
plexPlayer.setName(player.getName()); plexPlayer.setName(player.getName());
DataUtils.update(plexPlayer); DataUtils.update(plexPlayer);
} }
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer);
} }
if (plexPlayer.isLockedUp())
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
punishedPlayer.convertPunishments();
if (punishedPlayer.isLockedUp())
{ {
player.openInventory(player.getInventory()); player.openInventory(player.getInventory());
} }
@ -107,7 +100,7 @@ public class PlayerListener extends PlexListener
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInventoryClose(InventoryCloseEvent event) public void onPlayerInventoryClose(InventoryCloseEvent event)
{ {
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getPlayer().getUniqueId()); PlexPlayer player = DataUtils.getPlayer(event.getPlayer().getUniqueId());
if (player.isLockedUp()) if (player.isLockedUp())
{ {
Bukkit.getScheduler().runTaskLater(plugin, () -> event.getPlayer().openInventory(event.getInventory()), 1L); Bukkit.getScheduler().runTaskLater(plugin, () -> event.getPlayer().openInventory(event.getInventory()), 1L);
@ -117,7 +110,7 @@ public class PlayerListener extends PlexListener
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) public void onInventoryClick(InventoryClickEvent event)
{ {
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getWhoClicked().getUniqueId()); PlexPlayer player = DataUtils.getPlayer(event.getWhoClicked().getUniqueId());
if (player.isLockedUp()) if (player.isLockedUp())
{ {
event.setCancelled(true); event.setCancelled(true);

View File

@ -1,7 +1,7 @@
package dev.plex.listener.impl; package dev.plex.listener.impl;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.cache.PlayerCache; import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener; import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;

View File

@ -1,8 +1,9 @@
package dev.plex.menu; package dev.plex.menu;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import dev.plex.cache.PlayerCache; import dev.plex.cache.DataUtils;
import dev.plex.player.PunishedPlayer; import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.util.menu.AbstractMenu; import dev.plex.util.menu.AbstractMenu;
import java.util.Collections; import java.util.Collections;
@ -23,11 +24,11 @@ import org.bukkit.inventory.meta.SkullMeta;
public class PunishedPlayerMenu extends AbstractMenu public class PunishedPlayerMenu extends AbstractMenu
{ {
private final PunishedPlayer punishedPlayer; private final PlexPlayer punishedPlayer;
private final List<Inventory> inventories = Lists.newArrayList(); private final List<Inventory> inventories = Lists.newArrayList();
public PunishedPlayerMenu(PunishedPlayer player) public PunishedPlayerMenu(PlexPlayer player)
{ {
super("§c§lPunishments"); super("§c§lPunishments");
this.punishedPlayer = player; this.punishedPlayer = player;
@ -162,7 +163,7 @@ public class PunishedPlayerMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta(); SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer(); OfflinePlayer player = meta.getOwningPlayer();
assert player != null; assert player != null;
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPlexPlayer(player.getUniqueId());
if (punishedPlayer == null) if (punishedPlayer == null)
{ {
event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead."); event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead.");

View File

@ -1,8 +1,9 @@
package dev.plex.menu; package dev.plex.menu;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import dev.plex.cache.PlayerCache; import dev.plex.cache.DataUtils;
import dev.plex.player.PunishedPlayer; import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.util.menu.AbstractMenu; import dev.plex.util.menu.AbstractMenu;
import java.util.List; import java.util.List;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -138,7 +139,7 @@ public class PunishmentMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta(); SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer(); OfflinePlayer player = meta.getOwningPlayer();
assert player != null; assert player != null;
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId()); PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId());
if (punishedPlayer == null) if (punishedPlayer == null)
{ {
event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead."); event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead.");

View File

@ -1,13 +1,14 @@
package dev.plex.player; package dev.plex.player;
import com.google.common.collect.Lists;
import dev.morphia.annotations.Entity; import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id; import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions; import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed; import dev.morphia.annotations.Indexed;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.rank.enums.Rank; import dev.plex.rank.enums.Rank;
import java.util.ArrayList; import dev.plex.storage.StorageType;
import java.util.List;
import java.util.UUID;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@ -16,6 +17,11 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Getter @Getter
@Setter @Setter
@Entity(value = "players", useDiscriminator = false) @Entity(value = "players", useDiscriminator = false)
@ -39,11 +45,16 @@ public class PlexPlayer
private boolean vanished; private boolean vanished;
private boolean commandSpy; private boolean commandSpy;
private boolean frozen;
private boolean muted;
private boolean lockedUp;
private long coins; private long coins;
private String rank; private String rank;
private List<String> ips; private List<String> ips = Lists.newArrayList();
private List<Punishment> punishments = Lists.newArrayList();
public PlexPlayer() public PlexPlayer()
{ {
@ -66,9 +77,8 @@ public class PlexPlayer
this.coins = 0; this.coins = 0;
this.ips = new ArrayList<>();
this.rank = ""; this.rank = "";
this.loadPunishments();
} }
public String displayName() public String displayName()
@ -95,4 +105,12 @@ public class PlexPlayer
return Rank.valueOf(rank.toUpperCase()); return Rank.valueOf(rank.toUpperCase());
} }
} }
public void loadPunishments()
{
if (Plex.get().getStorageType() != StorageType.MONGODB)
{
this.setPunishments(Plex.get().getSqlPunishment().getPunishments(UUID.fromString(this.getUuid())).stream().filter(punishment -> punishment.getPunished().equals(UUID.fromString(this.getUuid()))).collect(Collectors.toList()));
}
}
} }

View File

@ -1,221 +0,0 @@
package dev.plex.player;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.event.PunishedPlayerFreezeEvent;
import dev.plex.event.PunishedPlayerLockupEvent;
import dev.plex.event.PunishedPlayerMuteEvent;
import dev.plex.punishment.Punishment;
import dev.plex.util.PlexLog;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
@Getter
public class PunishedPlayer extends PlexBase
{
//everything in here will be stored in redis
@Setter(AccessLevel.NONE)
private String uuid;
private boolean muted;
private boolean frozen;
private boolean lockedUp;
public PunishedPlayer(UUID playerUUID)
{
this.uuid = playerUUID.toString();
this.muted = false;
this.frozen = false;
this.lockedUp = false;
}
public void setFrozen(boolean frozen)
{
PunishedPlayerFreezeEvent e = new PunishedPlayerFreezeEvent(this, this.frozen);
Bukkit.getServer().getPluginManager().callEvent(e);
if (!e.isCancelled())
{
this.frozen = frozen;
}
}
public void setMuted(boolean muted)
{
PunishedPlayerMuteEvent e = new PunishedPlayerMuteEvent(this, this.muted);
Bukkit.getServer().getPluginManager().callEvent(e);
if (!e.isCancelled())
{
this.muted = muted;
}
}
public void setLockedUp(boolean lockedUp)
{
PunishedPlayerLockupEvent e = new PunishedPlayerLockupEvent(this, this.lockedUp);
Bukkit.getServer().getPluginManager().callEvent(e);
if (!e.isCancelled())
{
this.lockedUp = lockedUp;
Player self = Bukkit.getPlayer(UUID.fromString(this.uuid));
if (self != null)
{
self.openInventory(self.getInventory());
}
}
}
public File getPunishmentsFile()
{
File folder = new File(Plex.get().getDataFolder() + File.separator + "punishments");
if (!folder.exists())
{
folder.mkdir();
}
File file = new File(folder, getUuid() + ".json");
if (!file.exists())
{
try
{
file.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return file;
}
@SneakyThrows
public void convertPunishments()
{
if (!plugin.getRedisConnection().isEnabled())
{
return;
}
List<Punishment> punishments = Lists.newArrayList();
File file = getPunishmentsFile();
//Converting from File to Redis
if (isNotEmpty(file))
{
PlexLog.debug("Starting converting punishments from file to Redis for " + uuid + "...");
JSONTokener tokener = new JSONTokener(new FileInputStream(file));
JSONObject object = new JSONObject(tokener);
JSONArray array = object.getJSONObject(getUuid()).getJSONArray("punishments");
for (int i = 0; i < array.toList().size(); i++)
{
Punishment punishment = Punishment.fromJson(array.get(i).toString());
punishments.add(punishment);
}
PlexLog.debug("Successfully converted all file punishments into array (" + punishments.size() + ")");
if (!punishments.isEmpty())
{
Map<String, List<String>> filesList = Maps.newHashMap();
filesList.put("punishments", punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
JSONObject obj = new JSONObject().put(uuid, filesList);
if (plugin.getRedisConnection().getJedis().exists(uuid))
{
PlexLog.debug("File and Redis Matches? " + plugin.getRedisConnection().getJedis().get(uuid).equalsIgnoreCase(obj.toString()));
if (!plugin.getRedisConnection().getJedis().get(uuid).equalsIgnoreCase(obj.toString()))
{
plugin.getRedisConnection().getJedis().set(uuid, obj.toString());
PlexLog.debug("Updated Redis Punishments to match with file");
}
}
else
{
plugin.getRedisConnection().getJedis().set(uuid, obj.toString());
}
}
}
}
@SneakyThrows
public List<Punishment> getPunishments()
{
List<Punishment> punishments = Lists.newArrayList();
if (plugin.getRedisConnection().isEnabled())
{
PlexLog.debug("Getting punishments from Redis...");
if (!plugin.getRedisConnection().getJedis().exists(uuid))
{
return punishments;
}
String strObj = plugin.getRedisConnection().getJedis().get(uuid);
if (strObj.isEmpty() || !strObj.startsWith("{"))
{
return punishments;
}
JSONObject object = new JSONObject(strObj);
object.getJSONObject(uuid).getJSONArray("punishments").forEach(obj ->
{
JSONObject converted = new JSONObject(obj.toString());
if (converted.isNull("active"))
{
converted.put("active", false);
}
Punishment punishment = Punishment.fromJson(converted.toString());
punishments.add(punishment);
});
plugin.getRedisConnection().getJedis().close();
return punishments;
}
File file = getPunishmentsFile();
if (isNotEmpty(file))
{
try
{
PlexLog.debug("Getting punishments from locally stored JSON files...");
JSONTokener tokener = new JSONTokener(new FileInputStream(file));
JSONObject object = new JSONObject(tokener);
object.getJSONObject(getUuid()).getJSONArray("punishments").forEach(obj ->
{
Punishment punishment = Punishment.fromJson(obj.toString());
punishments.add(punishment);
});
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
return punishments;
}
private boolean isNotEmpty(File file)
{
try
{
return !FileUtils.readFileToString(file, StandardCharsets.UTF_8).trim().isEmpty();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
}

View File

@ -9,6 +9,8 @@ import dev.plex.util.adapter.LocalDateTimeSerializer;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.UUID; import java.util.UUID;
import lombok.Data;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@ -29,17 +31,16 @@ public class Punishment
private boolean active; // Field is only for bans private boolean active; // Field is only for bans
private LocalDateTime endDate; private LocalDateTime endDate;
public Punishment()
{
this.punished = null;
this.punisher = null;
}
public Punishment(UUID punished, UUID punisher) public Punishment(UUID punished, UUID punisher)
{ {
this.punished = punished; this.punished = punished;
this.punisher = punisher; this.punisher = punisher;
this.ip = "";
this.punishedUsername = "";
this.type = null;
this.reason = "";
this.customTime = false;
this.endDate = null;
} }
public static Component generateBanMessage(Punishment punishment) public static Component generateBanMessage(Punishment punishment)

View File

@ -1,27 +1,24 @@
package dev.plex.punishment; package dev.plex.punishment;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.PlexBase; import dev.plex.PlexBase;
import dev.plex.cache.PlayerCache; import dev.plex.cache.DataUtils;
import dev.plex.player.PunishedPlayer; import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import dev.plex.util.PlexLog; import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils; import dev.plex.util.PlexUtils;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.Data; import lombok.Data;
import lombok.Getter; import lombok.Getter;
@ -29,8 +26,6 @@ import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.JSONTokener;
import redis.clients.jedis.Jedis;
public class PunishmentManager extends PlexBase public class PunishmentManager extends PlexBase
{ {
@ -100,57 +95,19 @@ public class PunishmentManager extends PlexBase
return this.indefiniteBans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUsernames().contains(username)); return this.indefiniteBans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUsernames().contains(username));
} }
public void insertPunishment(PunishedPlayer player, Punishment punishment) public void issuePunishment(PlexPlayer plexPlayer, Punishment punishment)
{ {
File file = player.getPunishmentsFile(); plexPlayer.getPunishments().add(punishment);
if (Plex.get().getStorageType() == StorageType.MONGODB)
try
{ {
if (isNotEmpty(file)) CompletableFuture.runAsync(() ->
{ {
JSONTokener tokener = new JSONTokener(new FileInputStream(file)); DataUtils.update(plexPlayer);
JSONObject object = new JSONObject(tokener); });
object.getJSONObject(punishment.getPunished().toString()).getJSONArray("punishments").put(punishment.toJSON());
addToRedis(player, file, object);
}
else
{
JSONObject object = new JSONObject();
Map<String, List<String>> punishments = Maps.newHashMap();
List<String> punishmentList = Lists.newArrayList();
punishmentList.add(punishment.toJSON());
punishments.put("punishments", punishmentList);
object.put(punishment.getPunished().toString(), punishments);
addToRedis(player, file, object);
}
} }
catch (IOException e) else
{ {
e.printStackTrace(); Plex.get().getSqlPunishment().insertPunishment(punishment);
}
}
private void addToRedis(PunishedPlayer player, File file, JSONObject object)
{
try
{
if (plugin.getRedisConnection().isEnabled())
{
plugin.getRedisConnection().getJedis().set(player.getUuid(), object.toString());
PlexLog.debug("Added " + player.getUuid() + "'s punishment to the Redis database.");
plugin.getRedisConnection().getJedis().close();
}
FileWriter writer = new FileWriter(file);
writer.append(object.toString(8));
writer.flush();
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
} }
} }
@ -167,69 +124,45 @@ public class PunishmentManager extends PlexBase
return false; return false;
} }
public boolean isBanned(UUID uuid) public CompletableFuture<Boolean> isAsyncBanned(UUID uuid)
{ {
return PlayerCache.getPunishedPlayer(uuid).getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive()); return CompletableFuture.supplyAsync(() ->
{
PlexPlayer player = DataUtils.getPlayer(uuid);
player.loadPunishments();
return player.getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
});
} }
public boolean isBanned(PunishedPlayer player) public boolean isBanned(UUID uuid)
{
return DataUtils.getPlayer(uuid).getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
}
public boolean isBanned(PlexPlayer player)
{ {
return isBanned(UUID.fromString(player.getUuid())); return isBanned(UUID.fromString(player.getUuid()));
} }
public List<Punishment> getActiveBans() public CompletableFuture<List<Punishment>> getActiveBans()
{ {
List<Punishment> punishments = Lists.newArrayList(); if (Plex.get().getStorageType() == StorageType.MONGODB)
if (Plex.get().getRedisConnection().isEnabled())
{ {
Jedis jedis = Plex.get().getRedisConnection().getJedis(); return CompletableFuture.supplyAsync(() ->
for (String key : jedis.keys("*"))
{ {
try List<PlexPlayer> players = Plex.get().getMongoPlayerData().getPlayers();
{ return players.stream().map(PlexPlayer::getPunishments).flatMap(Collection::stream).filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).toList();
UUID uuid = UUID.fromString(key); });
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
for (Object json : object.getJSONObject(uuid.toString()).getJSONArray("punishments"))
{
Punishment punishment = Punishment.fromJson(json.toString());
if (punishment.isActive() && punishment.getType() == PunishmentType.BAN)
{
punishments.add(punishment);
}
}
}
catch (IllegalArgumentException ignored)
{
}
}
} }
else else
{ {
File fileDir = new File(plugin.getDataFolder() + File.separator + "punishments"); CompletableFuture<List<Punishment>> future = new CompletableFuture<>();
for (File file : Objects.requireNonNull(fileDir.listFiles())) Plex.get().getSqlPunishment().getPunishments().whenComplete((punishments, throwable) ->
{ {
if (isNotEmpty(file)) future.complete(punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).toList());
{ });
try (FileInputStream fis = new FileInputStream(file)) return future;
{
JSONTokener tokener = new JSONTokener(fis);
JSONObject object = new JSONObject(tokener);
object.keySet().stream().findFirst().ifPresent(key ->
{
JSONObject obj = object.getJSONObject(key);
punishments.addAll(obj.getJSONArray("punishments").toList().stream().map(Object::toString).map(Punishment::fromJson).filter(punishment -> punishment.isActive() && punishment.getType() == PunishmentType.BAN).toList());
});
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
} }
return punishments;
} }
public void unban(Punishment punishment) public void unban(Punishment punishment)
@ -237,57 +170,25 @@ public class PunishmentManager extends PlexBase
this.unban(punishment.getPunished()); this.unban(punishment.getPunished());
} }
public void unban(UUID uuid) public CompletableFuture<Void> unban(UUID uuid)
{ {
if (Plex.get().getRedisConnection().isEnabled()) if (Plex.get().getStorageType() == StorageType.MONGODB)
{ {
Jedis jedis = Plex.get().getRedisConnection().getJedis(); return CompletableFuture.runAsync(() ->
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
setActive(uuid, object, false);
jedis.set(uuid.toString(), object.toString());
}
PunishedPlayer player = PlayerCache.getPunishedPlayer(uuid);
File file = player.getPunishmentsFile();
if (isNotEmpty(file))
{
try (FileInputStream fis = new FileInputStream(file))
{ {
JSONTokener tokener = new JSONTokener(fis); PlexPlayer plexPlayer = DataUtils.getPlayer(uuid);
JSONObject object = new JSONObject(tokener); plexPlayer.setPunishments(plexPlayer.getPunishments().stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN)
setActive(uuid, object, false); .peek(punishment -> punishment.setActive(false)).collect(Collectors.toList()));
FileWriter writer = new FileWriter(file); DataUtils.update(plexPlayer);
writer.append(object.toString());
writer.flush();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void setActive(UUID uuid, JSONObject object, boolean active)
{
List<Punishment> punishments = object.getJSONObject(uuid.toString()).getJSONArray("punishments").toList().stream().map(obj -> Punishment.fromJson(obj.toString())).collect(Collectors.toList());
while (punishments.stream().anyMatch(punishment -> punishment.isActive() && punishment.getType() == PunishmentType.BAN))
{
punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).findFirst().ifPresent(punishment ->
{
int index = punishments.indexOf(punishment);
punishment.setActive(active);
punishments.set(index, punishment);
}); });
} }
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear(); else
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList())); {
return Plex.get().getSqlPunishment().removeBan(uuid);
}
} }
private void issuePunishment(PunishedPlayer player, Punishment punishment) private void doPunishment(PlexPlayer player, Punishment punishment)
{ {
if (punishment.getType() == PunishmentType.FREEZE) if (punishment.getType() == PunishmentType.FREEZE)
{ {
@ -333,10 +234,10 @@ public class PunishmentManager extends PlexBase
} }
} }
public void doPunishment(PunishedPlayer player, Punishment punishment) public void punish(PlexPlayer player, Punishment punishment)
{ {
issuePunishment(player, punishment); issuePunishment(player, punishment);
insertPunishment(player, punishment); doPunishment(player, punishment);
} }
@Data @Data

View File

@ -3,10 +3,11 @@ package dev.plex.services.impl;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.punishment.Punishment; import dev.plex.punishment.Punishment;
import dev.plex.services.AbstractService; import dev.plex.services.AbstractService;
import java.time.LocalDateTime;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import java.time.LocalDateTime;
public class BanService extends AbstractService public class BanService extends AbstractService
{ {
public BanService() public BanService()
@ -17,14 +18,17 @@ public class BanService extends AbstractService
@Override @Override
public void run() public void run()
{ {
for (Punishment punishment : Plex.get().getPunishmentManager().getActiveBans()) Plex.get().getPunishmentManager().getActiveBans().whenComplete((punishments, throwable) ->
{ {
if (LocalDateTime.now().isAfter(punishment.getEndDate())) punishments.forEach(punishment ->
{ {
Plex.get().getPunishmentManager().unban(punishment); if (LocalDateTime.now().isAfter(punishment.getEndDate()))
Bukkit.broadcast(Component.text("Plex - Unbanned " + Bukkit.getOfflinePlayer(punishment.getPunished()).getName())); {
} Plex.get().getPunishmentManager().unban(punishment);
} Bukkit.broadcast(Component.text("Plex - Unbanned " + Bukkit.getOfflinePlayer(punishment.getPunished()).getName()));
}
});
});
} }
@Override @Override

View File

@ -1,73 +1,100 @@
package dev.plex.storage; package dev.plex.storage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import dev.plex.Plex; import dev.plex.Plex;
import dev.plex.PlexBase; import dev.plex.PlexBase;
import javax.sql.DataSource;
import java.io.File; import java.io.File;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
public class SQLConnection extends PlexBase public class SQLConnection extends PlexBase
{ {
private Connection connection; private HikariDataSource dataSource;
public Connection getCon() public SQLConnection()
{ {
String host = plugin.config.getString("data.central.hostname"); String host = plugin.config.getString("data.central.hostname");
int port = plugin.config.getInt("data.central.port"); int port = plugin.config.getInt("data.central.port");
String username = plugin.config.getString("data.central.user"); String username = plugin.config.getString("data.central.user");
String password = plugin.config.getString("data.central.password"); String password = plugin.config.getString("data.central.password");
String database = plugin.config.getString("data.central.db"); String database = plugin.config.getString("data.central.db");
HikariConfig config = new HikariConfig();
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
this.dataSource = new HikariDataSource();
dataSource.setMaxLifetime(15000);
dataSource.setIdleTimeout(15000 * 2);
dataSource.setConnectionTimeout(15000 * 4);
dataSource.setMinimumIdle(2);
dataSource.setMaximumPoolSize(10);
try try
{ {
if (plugin.config.getString("data.central.storage").equalsIgnoreCase("sqlite")) if (plugin.config.getString("data.central.storage").equalsIgnoreCase("sqlite"))
{ {
connection = DriverManager.getConnection("jdbc:sqlite:" + new File(plugin.getDataFolder(), "database.db").getAbsolutePath()); dataSource.setJdbcUrl("jdbc:sqlite:" + new File(plugin.getDataFolder(), "database.db").getAbsolutePath());
plugin.setStorageType(StorageType.SQLITE); plugin.setStorageType(StorageType.SQLITE);
} }
else if (plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb")) else if (plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb"))
{ {
Class.forName("org.mariadb.jdbc.Driver"); Class.forName("org.mariadb.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mariadb://" + host + ":" + port + "/" + database, username, password); dataSource.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + database);
dataSource.setUsername(username);
dataSource.setPassword(password);
Plex.get().setStorageType(StorageType.MARIADB); Plex.get().setStorageType(StorageType.MARIADB);
} }
} }
catch (SQLException | ClassNotFoundException throwables) catch (ClassNotFoundException throwables)
{ {
throwables.printStackTrace(); throwables.printStackTrace();
} }
try try (Connection con = getCon())
{ {
if (connection != null) con.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" +
{ "`uuid` VARCHAR(46) NOT NULL, " +
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" + "`name` VARCHAR(18), " +
"`uuid` VARCHAR(46) NOT NULL, " + "`login_msg` VARCHAR(70), " +
"`name` VARCHAR(18), " + "`prefix` VARCHAR(45), " +
"`login_msg` VARCHAR(70), " + "`rank` VARCHAR(20), " +
"`prefix` VARCHAR(45), " + "`ips` VARCHAR(2000), " +
"`rank` VARCHAR(20), " + "`coins` BIGINT, " +
"`ips` VARCHAR(2000), " + "`vanished` BOOLEAN, " +
"`coins` BIGINT, " + "`commandspy` BOOLEAN, " +
"`vanished` BOOLEAN, " + "PRIMARY KEY (`uuid`));").execute();
"`commandspy` BOOLEAN, " + con.prepareStatement("CREATE TABLE IF NOT EXISTS `punishments` (" +
"PRIMARY KEY (`uuid`));").execute(); "`punished` VARCHAR(46) NOT NULL, " +
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `bans` (" + "`punisher` VARCHAR(46), " +
"`banID` VARCHAR(46), " + "`punishedUsername` VARCHAR(16), " +
"`uuid` VARCHAR(46) NOT NULL, " + "`ip` VARCHAR(2000), " +
"`banner` VARCHAR(46), " + "`type` VARCHAR(30), " +
"`ip` VARCHAR(2000), " + "`reason` VARCHAR(2000), " +
"`reason` VARCHAR(256), " + "`customTime` BOOLEAN, " +
"`enddate` BIGINT, " + "`active` BOOLEAN, " +
"`active` BOOLEAN, " + "`endDate` BIGINT" +
"PRIMARY KEY (`banID`)" + ");").execute();
");").execute();
}
} }
catch (SQLException throwables) catch (SQLException throwables)
{ {
throwables.printStackTrace(); throwables.printStackTrace();
} }
return connection; }
public Connection getCon()
{
try
{
return dataSource.getConnection();
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
} }
} }

View File

@ -6,39 +6,11 @@ import dev.plex.Plex;
import dev.plex.PlexBase; import dev.plex.PlexBase;
import dev.plex.config.Config; import dev.plex.config.Config;
import dev.plex.storage.StorageType; import dev.plex.storage.StorageType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit; import org.bukkit.*;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.PluginCommandYamlParser; import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -47,6 +19,20 @@ import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
public class PlexUtils extends PlexBase public class PlexUtils extends PlexBase
{ {
private static final Random RANDOM; private static final Random RANDOM;
@ -85,7 +71,7 @@ public class PlexUtils extends PlexBase
public static void testConnections() public static void testConnections()
{ {
if (Plex.get().getSqlConnection().getCon() != null) try (Connection con = Plex.get().getSqlConnection().getCon())
{ {
if (Plex.get().getStorageType() == StorageType.MARIADB) if (Plex.get().getStorageType() == StorageType.MARIADB)
{ {
@ -95,17 +81,13 @@ public class PlexUtils extends PlexBase
{ {
PlexLog.log("Successfully enabled SQLite!"); PlexLog.log("Successfully enabled SQLite!");
} }
try
{
Plex.get().getSqlConnection().getCon().close();
}
catch (SQLException ignored)
{
}
} }
else if (Plex.get().getMongoConnection().getDatastore() != null) catch (SQLException e)
{ {
PlexLog.log("Successfully enabled MongoDB!"); if (Plex.get().getMongoConnection().getDatastore() != null)
{
PlexLog.log("Successfully enabled MongoDB!");
}
} }
} }