so far it is working but the only thing preventing me from going to fully asynchronous calls for punishments is httpd...

This commit is contained in:
Taah 2022-04-04 01:36:50 -07:00
parent 35d436bb61
commit 6f4bc5aec1
38 changed files with 483 additions and 528 deletions

View File

@ -30,6 +30,7 @@ dependencies {
library "dev.morphia.morphia:morphia-core:2.2.6"
library "redis.clients:jedis:4.2.1"
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.commons:commons-lang3:3.12.0"
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.AdminList;
import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.SQLPlayerData;
import dev.plex.cache.player.MongoPlayerData;
import dev.plex.cache.player.PlayerCache;
import dev.plex.cache.player.SQLPlayerData;
import dev.plex.cache.sql.SQLPunishment;
import dev.plex.config.Config;
import dev.plex.handlers.CommandHandler;
import dev.plex.handlers.ListenerHandler;
import dev.plex.module.ModuleManager;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.PunishmentManager;
import dev.plex.rank.RankManager;
import dev.plex.services.ServiceManager;
@ -52,6 +52,7 @@ public class Plex extends JavaPlugin
private MongoPlayerData mongoPlayerData;
private SQLPlayerData sqlPlayerData;
private SQLPunishment sqlPunishment;
private ModuleManager moduleManager;
private RankManager rankManager;
@ -87,10 +88,6 @@ public class Plex extends JavaPlugin
modulesFolder.mkdir();
}
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager = new ModuleManager();
moduleManager.loadAllModules();
moduleManager.loadModules();
@ -104,6 +101,10 @@ public class Plex extends JavaPlugin
// Don't add default entries to indefinite ban file
indefBans.load(false);
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager.enableModules();
system = config.getString("system");
@ -143,6 +144,7 @@ public class Plex extends JavaPlugin
else
{
sqlPlayerData = new SQLPlayerData();
sqlPunishment = new SQLPunishment();
}
new ListenerHandler();
@ -214,7 +216,6 @@ public class Plex extends JavaPlugin
{
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
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))
{
Admin admin = new Admin(UUID.fromString(plexPlayer.getUuid()));

View File

@ -1,6 +1,7 @@
package dev.plex.cache;
import dev.plex.Plex;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import java.util.UUID;
@ -43,6 +44,7 @@ public class DataUtils
return PlayerCache.getPlexPlayerMap().get(uuid);
}
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
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.query.Query;
@ -8,6 +8,7 @@ import dev.morphia.query.experimental.updates.UpdateOperators;
import dev.plex.Plex;
import dev.plex.player.PlexPlayer;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
@ -104,6 +105,11 @@ public class MongoPlayerData
updateOps.execute();
}
public List<PlexPlayer> getPlayers()
{
return datastore.find(PlexPlayer.class).stream().toList();
}
/**
* 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 dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import java.util.Map;
import java.util.UUID;
@ -20,19 +20,19 @@ public class PlayerCache
/**
* 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()
{
return plexPlayerMap;
}
public static PunishedPlayer getPunishedPlayer(UUID uuid)
/*public static PunishedPlayer getPunishedPlayer(UUID uuid)
{
if (!getPunishedPlayerMap().containsKey(uuid))
{
@ -40,7 +40,7 @@ public class PlayerCache
}
return getPunishedPlayerMap().get(uuid);
}
*/
public static PlexPlayer getPlexPlayer(UUID 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.gson.Gson;

View File

@ -0,0 +1,130 @@
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.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.player.PlayerCache;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;

View File

@ -1,6 +1,6 @@
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.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;

View File

@ -1,23 +1,19 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
@ -26,6 +22,10 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@CommandParameters(name = "ban", usage = "/<command> <player> [reason]", aliases = "offlineban,gtfo", description = "Bans a player, offline or online")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.ban", source = RequiredCommandSource.ANY)
@ -40,7 +40,6 @@ public class BanCMD extends PlexCommand
}
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason;
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
@ -62,20 +61,21 @@ 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;
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
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
} else
{
punishment.setReason("No reason provided.");
}
@ -88,13 +88,18 @@ public class BanCMD extends PlexCommand
{
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()));
Bukkit.getScheduler().runTask(Plex.get(), () ->
{
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + punishedPlayer.getUuid());
});
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + plexPlayer.getUuid());
});
return null;
}

View File

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

View File

@ -1,14 +1,13 @@
package dev.plex.command.impl;
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.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
@ -49,8 +48,6 @@ public class KickCMD extends PlexCommand
{
throw new PlayerNotFoundException();
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.KICK);
if (args.length > 1)
@ -64,7 +61,7 @@ public class KickCMD extends PlexCommand
punishment.setCustomTime(false);
punishment.setActive(false);
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()));
player.kick(componentFromString(reason));
return null;

View File

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

View File

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

View File

@ -2,14 +2,13 @@ package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
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.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
@ -65,8 +64,6 @@ public class TempbanCMD extends PlexCommand
{
return messageComponent("playerBanned");
}
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 > 2)
@ -86,7 +83,7 @@ public class TempbanCMD extends PlexCommand
{
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()));
if (player != null)
{

View File

@ -1,6 +1,7 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
@ -11,14 +12,17 @@ import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
import java.util.UUID;
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.entity.Player;
import org.jetbrains.annotations.NotNull;
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")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.ban", source = RequiredCommandSource.ANY)
@ -42,13 +46,16 @@ public class UnbanCMD extends PlexCommand
throw new PlayerNotFoundException();
}
if (!plugin.getPunishmentManager().isBanned(targetUUID))
plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
{
throw new PlayerNotBannedException();
if (!aBoolean)
{
send(sender, MiniMessage.miniMessage().deserialize(new PlayerNotBannedException().getMessage()));
return;
}
plugin.getPunishmentManager().unban(targetUUID);
PlexUtils.broadcast(messageComponent("unbanningPlayer", sender.getName(), plexPlayer.getName()));
});
}
return null;
}

View File

@ -1,12 +1,12 @@
package dev.plex.command.impl;
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.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
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.util.PlexUtils;
import java.util.List;
@ -28,7 +28,7 @@ public class UnfreezeCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (!punishedPlayer.isFrozen())
{
throw new CommandFailException(PlexUtils.messageString("playerNotFrozen"));

View File

@ -1,12 +1,12 @@
package dev.plex.command.impl;
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.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
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.util.PlexUtils;
import java.util.List;
@ -28,7 +28,7 @@ public class UnmuteCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (!punishedPlayer.isMuted())
{
throw new CommandFailException(PlexUtils.messageString("playerNotMuted"));

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,9 @@
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.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import org.bukkit.event.EventHandler;
@ -36,7 +37,7 @@ public class BanListener extends PlexListener
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 ->
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED,
Punishment.generateBanMessage(punishment)));

View File

@ -1,6 +1,6 @@
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.annotation.Toggleable;
import dev.plex.player.PlexPlayer;

View File

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

View File

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

View File

@ -1,18 +1,20 @@
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.util.PlexUtils;
import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
public class MuteListener extends PlexListener
{
@EventHandler
@EventHandler(priority = EventPriority.HIGHEST)
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.setCancelled(true);

View File

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

View File

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

View File

@ -1,8 +1,9 @@
package dev.plex.menu;
import com.google.common.collect.Lists;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.util.menu.AbstractMenu;
import java.util.Collections;
@ -23,11 +24,11 @@ import org.bukkit.inventory.meta.SkullMeta;
public class PunishedPlayerMenu extends AbstractMenu
{
private final PunishedPlayer punishedPlayer;
private final PlexPlayer punishedPlayer;
private final List<Inventory> inventories = Lists.newArrayList();
public PunishedPlayerMenu(PunishedPlayer player)
public PunishedPlayerMenu(PlexPlayer player)
{
super("§c§lPunishments");
this.punishedPlayer = player;
@ -162,7 +163,7 @@ public class PunishedPlayerMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer();
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)
{
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;
import com.google.common.collect.Lists;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.util.menu.AbstractMenu;
import java.util.List;
import org.bukkit.Bukkit;
@ -138,7 +139,7 @@ public class PunishmentMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer();
assert player != null;
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId());
if (punishedPlayer == null)
{
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;
import com.google.common.collect.Lists;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.rank.enums.Rank;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import dev.plex.storage.StorageType;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
@ -16,6 +17,11 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Getter
@Setter
@Entity(value = "players", useDiscriminator = false)
@ -39,11 +45,16 @@ public class PlexPlayer
private boolean vanished;
private boolean commandSpy;
private boolean frozen;
private boolean muted;
private boolean lockedUp;
private long coins;
private String rank;
private List<String> ips;
private List<String> ips = Lists.newArrayList();
private List<Punishment> punishments = Lists.newArrayList();
public PlexPlayer()
{
@ -66,9 +77,8 @@ public class PlexPlayer
this.coins = 0;
this.ips = new ArrayList<>();
this.rank = "";
this.loadPunishments();
}
public String displayName()
@ -84,15 +94,21 @@ public class PlexPlayer
if (player.isOp())
{
return Rank.OP;
}
else
} else
{
return Rank.NONOP;
}
}
else
} else
{
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.format.DateTimeFormatter;
import java.util.UUID;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
@ -29,17 +31,16 @@ public class Punishment
private boolean active; // Field is only for bans
private LocalDateTime endDate;
public Punishment()
{
this.punished = null;
this.punisher = null;
}
public Punishment(UUID punished, UUID punisher)
{
this.punished = punished;
this.punisher = punisher;
this.ip = "";
this.punishedUsername = "";
this.type = null;
this.reason = "";
this.customTime = false;
this.endDate = null;
}
public static Component generateBanMessage(Punishment punishment)

View File

@ -1,28 +1,24 @@
package dev.plex.punishment;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.cache.DataUtils;
import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.Getter;
@ -30,8 +26,6 @@ import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.JSONObject;
import org.json.JSONTokener;
import redis.clients.jedis.Jedis;
public class PunishmentManager extends PlexBase
{
@ -101,9 +95,19 @@ public class PunishmentManager extends PlexBase
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)
{
CompletableFuture.runAsync(() -> {
DataUtils.update(plexPlayer);
});
} else {
Plex.get().getSqlPunishment().insertPunishment(punishment);
}
/*File file = player.getPunishmentsFile();
try
{
@ -130,29 +134,7 @@ public class PunishmentManager extends PlexBase
catch (IOException e)
{
e.printStackTrace();
}
}
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();
}
}*/
}
private boolean isNotEmpty(File file)
@ -168,19 +150,41 @@ public class PunishmentManager extends PlexBase
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()));
}
public List<Punishment> getActiveBans()
public CompletableFuture<List<Punishment>> getActiveBans()
{
List<Punishment> punishments = Lists.newArrayList();
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
return CompletableFuture.supplyAsync(() -> {
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();
});
} else {
CompletableFuture<List<Punishment>> future = new CompletableFuture<>();
Plex.get().getSqlPunishment().getPunishments().whenComplete((punishments, throwable) -> {
future.complete(punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).toList());
});
return future;
}
/*List<Punishment> punishments = Lists.newArrayList();
if (Plex.get().getRedisConnection().isEnabled())
{
@ -229,8 +233,8 @@ public class PunishmentManager extends PlexBase
}
}
}
}
return punishments;
}*/
// return punishments;
}
public void unban(Punishment punishment)
@ -238,9 +242,20 @@ public class PunishmentManager extends PlexBase
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)
{
return CompletableFuture.runAsync(() -> {
PlexPlayer plexPlayer = DataUtils.getPlayer(uuid);
plexPlayer.setPunishments(plexPlayer.getPunishments().stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN)
.peek(punishment -> punishment.setActive(false)).collect(Collectors.toList()));
DataUtils.update(plexPlayer);
});
} else {
return Plex.get().getSqlPunishment().removeBan(uuid);
}
/*if (Plex.get().getRedisConnection().isEnabled())
{
Jedis jedis = Plex.get().getRedisConnection().getJedis();
@ -269,7 +284,7 @@ public class PunishmentManager extends PlexBase
{
e.printStackTrace();
}
}
}*/
}
private void setActive(UUID uuid, JSONObject object, boolean active)
@ -288,7 +303,7 @@ public class PunishmentManager extends PlexBase
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
}
private void issuePunishment(PunishedPlayer player, Punishment punishment)
private void doPunishment(PlexPlayer player, Punishment punishment)
{
if (punishment.getType() == PunishmentType.FREEZE)
{
@ -334,10 +349,10 @@ public class PunishmentManager extends PlexBase
}
}
public void doPunishment(PunishedPlayer player, Punishment punishment)
public void punish(PlexPlayer player, Punishment punishment)
{
issuePunishment(player, punishment);
insertPunishment(player, punishment);
doPunishment(player, punishment);
}
@Data

View File

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

View File

@ -1,47 +1,60 @@
package dev.plex.storage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import dev.plex.Plex;
import dev.plex.PlexBase;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnection extends PlexBase
{
private Connection connection;
private HikariDataSource dataSource;
public Connection getCon()
public SQLConnection()
{
String host = plugin.config.getString("data.central.hostname");
int port = plugin.config.getInt("data.central.port");
String username = plugin.config.getString("data.central.user");
String password = plugin.config.getString("data.central.password");
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
{
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);
}
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");
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);
}
}
catch (SQLException | ClassNotFoundException throwables)
} catch (ClassNotFoundException throwables)
{
throwables.printStackTrace();
}
try
try (Connection con = getCon())
{
if (connection != null)
{
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" +
con.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" +
"`uuid` VARCHAR(46) NOT NULL, " +
"`name` VARCHAR(18), " +
"`login_msg` VARCHAR(70), " +
@ -52,22 +65,32 @@ public class SQLConnection extends PlexBase
"`vanished` BOOLEAN, " +
"`commandspy` BOOLEAN, " +
"PRIMARY KEY (`uuid`));").execute();
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `bans` (" +
"`banID` VARCHAR(46), " +
"`uuid` VARCHAR(46) NOT NULL, " +
"`banner` VARCHAR(46), " +
con.prepareStatement("CREATE TABLE IF NOT EXISTS `punishments` (" +
"`punished` VARCHAR(46) NOT NULL, " +
"`punisher` VARCHAR(46), " +
"`punishedUsername` VARCHAR(16), " +
"`ip` VARCHAR(2000), " +
"`reason` VARCHAR(256), " +
"`enddate` BIGINT, " +
"`type` VARCHAR(30), " +
"`reason` VARCHAR(2000), " +
"`customTime` BOOLEAN, " +
"`active` BOOLEAN, " +
"PRIMARY KEY (`banID`)" +
"`endDate` BIGINT" +
");").execute();
}
}
catch (SQLException throwables)
} catch (SQLException throwables)
{
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.config.Config;
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.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.PluginCommandYamlParser;
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.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
{
private static final Random RANDOM;
@ -85,29 +71,23 @@ public class PlexUtils extends PlexBase
public static void testConnections()
{
if (Plex.get().getSqlConnection().getCon() != null)
try (Connection con = Plex.get().getSqlConnection().getCon())
{
if (Plex.get().getStorageType() == StorageType.MARIADB)
{
PlexLog.log("Successfully enabled MySQL!");
}
else if (Plex.get().getStorageType() == StorageType.SQLITE)
} else if (Plex.get().getStorageType() == StorageType.SQLITE)
{
PlexLog.log("Successfully enabled SQLite!");
}
try
} catch (SQLException e)
{
Plex.get().getSqlConnection().getCon().close();
}
catch (SQLException ignored)
{
}
}
else if (Plex.get().getMongoConnection().getDatastore() != null)
if (Plex.get().getMongoConnection().getDatastore() != null)
{
PlexLog.log("Successfully enabled MongoDB!");
}
}
}
public static boolean isPluginCMD(String cmd, String pluginName)
{
@ -211,12 +191,10 @@ public class PlexUtils extends PlexBase
if (config.getString(path) == null)
{
color = def;
}
else if (ChatColor.getByChar(config.getString(path)) == null)
} else if (ChatColor.getByChar(config.getString(path)) == null)
{
color = def;
}
else
} else
{
color = ChatColor.getByChar(config.getString(path));
}
@ -262,14 +240,13 @@ public class PlexUtils extends PlexBase
private static <T> void readGameRules(World world, String s)
{
String gameRule = s.split(";")[0];
T value = (T)s.split(";")[1];
GameRule<T> rule = (GameRule<T>)GameRule.getByName(gameRule);
T value = (T) s.split(";")[1];
GameRule<T> rule = (GameRule<T>) GameRule.getByName(gameRule);
if (rule != null && check(value).getClass().equals(rule.getType()))
{
world.setGameRule(rule, value);
PlexLog.debug("Setting game rule " + gameRule + " for world " + world.getName() + " with value " + value);
}
else
} else
{
PlexLog.error(String.format("Failed to set game rule %s for world %s with value %s!", gameRule, world.getName().toLowerCase(Locale.ROOT), value));
}
@ -309,7 +286,7 @@ public class PlexUtils extends PlexBase
try
{
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection)u.openConnection();
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
@ -321,8 +298,7 @@ public class PlexUtils extends PlexBase
in.close();
connection.disconnect();
return new JSONParser().parse(content.toString());
}
catch (IOException | ParseException ex)
} catch (IOException | ParseException ex)
{
return null;
}
@ -331,13 +307,13 @@ public class PlexUtils extends PlexBase
public static UUID getFromName(String name)
{
JSONObject profile;
profile = (JSONObject)simpleGET("https://api.ashcon.app/mojang/v2/user/" + name);
profile = (JSONObject) simpleGET("https://api.ashcon.app/mojang/v2/user/" + name);
if (profile == null)
{
PlexLog.error("Profile from Ashcon API returned null!");
return null;
}
String uuidString = (String)profile.get("uuid");
String uuidString = (String) profile.get("uuid");
return UUID.fromString(uuidString);
}
@ -355,14 +331,12 @@ public class PlexUtils extends PlexBase
{
Class<?> clazz = Class.forName(info.getName());
classes.add(clazz);
}
catch (ClassNotFoundException ex)
} catch (ClassNotFoundException ex)
{
PlexLog.error("Unable to find class " + info.getName() + " in " + packageName);
}
});
}
catch (IOException ex)
} catch (IOException ex)
{
PlexLog.error("Something went wrong while fetching classes from " + packageName);
throw new RuntimeException(ex);
@ -379,7 +353,7 @@ public class PlexUtils extends PlexBase
{
if (clazz.getSuperclass() == subType || Arrays.asList(clazz.getInterfaces()).contains(subType))
{
classes.add((Class<? extends T>)clazz);
classes.add((Class<? extends T>) clazz);
}
});
return Collections.unmodifiableSet(classes);