Rework punishment system by deleting the Ban and BanManager and moving everything into Punishment Manager. TODO cache punishments maybe? who knows! add an active field to punishments and fix the ban service to actually unban players

This commit is contained in:
Taah 2022-02-21 16:20:22 -08:00
parent d4578f2255
commit 6f506ac5cb
16 changed files with 295 additions and 381 deletions

View File

@ -2,7 +2,6 @@ package dev.plex;
import dev.plex.admin.Admin;
import dev.plex.admin.AdminList;
import dev.plex.banning.BanManager;
import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData;
import dev.plex.cache.PlayerCache;
@ -49,7 +48,6 @@ public class Plex extends JavaPlugin
private ServiceManager serviceManager;
private PunishmentManager punishmentManager;
private BanManager banManager;
private AdminList adminList;
@ -124,7 +122,7 @@ public class Plex extends JavaPlugin
PlexLog.log("Rank Manager initialized");
punishmentManager = new PunishmentManager();
banManager = new BanManager();
// banManager = new BanManager();
PlexLog.log("Punishment System initialized");
generateWorlds();

View File

@ -1,110 +0,0 @@
package dev.plex.banning;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.RandomStringUtils;
/**
* The ban object
*
* @see BanManager
*/
@Getter
@Setter
@Entity(value = "bans", useDiscriminator = false)
public class Ban
{
/**
* A constructor for Morphia, can't be used
*/
private Ban()
{
}
/**
* Gets the id of the ban (first 8 characters of a UUID + random 6 letters)
*/
@Setter(AccessLevel.NONE)
@Id
private String id;
/**
* The unique ID of the player who was banned
*/
@Setter(AccessLevel.NONE)
@Indexed(options = @IndexOptions(unique = true))
private UUID uuid;
/**
* The unique ID of the person who banned the player (can be null)
*/
@Indexed // have the banner be indexed in the future to get bans issued by a person
private UUID banner;
/**
* The IP of the banned player
*/
private String ip;
/**
* The reason for the ban
*/
private String reason;
/**
* The end date for the ban
*/
private LocalDateTime endDate;
/**
* Whether the ban is active or not
*/
private boolean active;
/**
* Creates a ban object
*
* @param uuid The unique ID of the player being banned
* @param banner The unique ID of the sender banning the player
* @param ip The IP of the player being banned
* @param reason The reason for the ban
* @param endDate When the ban will expire
*/
public Ban(UUID uuid, UUID banner, String ip, String reason, LocalDateTime endDate)
{
this(uuid.toString().substring(0, 8) + "-" + RandomStringUtils.randomAlphabetic(6),
uuid,
banner,
ip,
reason,
endDate);
}
/**
* Creates a ban object
*
* @param id The custom ID of the ban
* @param uuid The unique ID of the player being banned
* @param banner The unique ID of the sender banning the player
* @param ip The IP of the player being banned
* @param reason The reason for the ban
* @param endDate When the ban will expire
*/
public Ban(String id, UUID uuid, UUID banner, String ip, String reason, LocalDateTime endDate)
{
this.uuid = uuid;
this.id = id;
this.banner = banner;
this.ip = ip;
this.reason = reason;
this.endDate = endDate;
this.active = true;
}
}

View File

@ -1,203 +0,0 @@
package dev.plex.banning;
import com.google.common.collect.Lists;
import dev.morphia.query.Query;
import dev.morphia.query.experimental.filters.Filters;
import dev.morphia.query.experimental.updates.UpdateOperators;
import dev.plex.Plex;
import dev.plex.storage.StorageType;
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.util.List;
import java.util.UUID;
public class BanManager
{
private final String SELECT = "SELECT * FROM `bans` WHERE uuid=?";
private final String INSERT = "INSERT INTO `bans` (`banID`, `uuid`, `banner`, `ip`, `reason`, `enddate`, `active`) VALUES (?, ?, ?, ?, ?, ?, ?);";
/**
* Adds the ban to the database
*
* @param ban The ban object
*/
public void executeBan(Ban ban)
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
Plex.get().getMongoConnection().getDatastore().save(ban);
}
else
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, ban.getId());
statement.setString(2, ban.getUuid().toString());
statement.setString(3, ban.getBanner() == null ? "" : ban.getBanner().toString());
statement.setString(4, ban.getIp());
statement.setString(5, ban.getReason());
statement.setLong(6, ban.getEndDate().toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli());
statement.setBoolean(7, ban.isActive());
statement.execute();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
}
/**
* Checks if the unique ID has an active ban in the database
*
* @param uuid The unique ID of the player
* @return true if the unique ID is banned
*/
public boolean isBanned(UUID uuid)
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
return Plex.get().getMongoConnection().getDatastore().find(Ban.class)
.filter(Filters.eq("uuid", uuid.toString())).filter(Filters.eq("active", true)).first() != null;
}
else
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
if (!set.next())
{
return false;
}
while (set.next())
{
if (set.getBoolean("active"))
{
return true;
}
}
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
return false;
}
/**
* Unbans a player if they have an active ban on record
*
* @param uuid The unique ID of the player
*/
public void unban(UUID uuid)
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
Query<Ban> query = Plex.get().getMongoConnection().getDatastore().find(Ban.class).filter(Filters.eq("uuid", uuid.toString())).filter(Filters.eq("active", true));
if (query.first() != null)
{
query.update(UpdateOperators.set("active", false)).execute();
}
}
else
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("UPDATE `bans` SET active=? WHERE uuid=? AND active=?");
statement.setBoolean(1, false);
statement.setString(2, uuid.toString());
statement.setBoolean(3, true);
statement.executeUpdate();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
}
/**
* Unbans a player if they have an active ban on record
*
* @param id Custom ID of the ban
*/
public void unban(String id)
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
Query<Ban> query = Plex.get().getMongoConnection().getDatastore().find(Ban.class).filter(Filters.eq("_id", id)).filter(Filters.eq("active", true));
if (query.first() != null)
{
query.update(UpdateOperators.set("active", false)).execute();
}
}
else
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("UPDATE `bans` SET active=? WHERE banID=?");
statement.setBoolean(1, false);
statement.setString(2, id);
statement.executeUpdate();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
}
/**
* Gets a list of all the current bans active
*
* @return An arraylist of bans
*/
public List<Ban> getActiveBans()
{
List<Ban> bans = Lists.newArrayList();
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
for (Ban ban : Plex.get().getMongoConnection().getDatastore().find(Ban.class).filter(Filters.eq("active", true)))
{
bans.add(ban);
}
}
else
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `bans`");
ResultSet set = statement.executeQuery();
while (set.next())
{
if (set.getBoolean("active"))
{
String id = set.getString("banID");
UUID uuid = UUID.fromString(set.getString("uuid"));
UUID banner = set.getString("banner").isEmpty() ? null : UUID.fromString(set.getString("banner"));
String ip = set.getString("ip");
String reason = set.getString("reason");
LocalDateTime endDate = set.getLong("enddate") != 0 ? LocalDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("enddate")), ZoneId.systemDefault()) : null;
Ban ban = new Ban(id, uuid, banner, ip, reason, endDate);
bans.add(ban);
}
}
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
return bans;
}
}

View File

@ -77,6 +77,7 @@ public class BanCMD extends PlexCommand
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(true);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(tl("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)

View File

@ -0,0 +1,50 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
@CommandParameters(name = "debug", description = "Debug command", usage = "/<command> <redis-reset> [player]")
@CommandPermissions(level = Rank.EXECUTIVE, permission = "plex.debug")
public class DebugCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
if (args[0].equalsIgnoreCase("redis-reset"))
{
Player player = getNonNullPlayer(args[1]);
if (Plex.get().getRedisConnection().getJedis().exists(player.getUniqueId().toString()))
{
Plex.get().getRedisConnection().getJedis().del(player.getUniqueId().toString());
return componentFromString("Successfully reset " + player.getName() + "'s redis punishments!").color(NamedTextColor.YELLOW);
}
return componentFromString("Couldn't find player in redis punishments.");
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -41,12 +41,12 @@ public class UnbanCMD extends PlexCommand
throw new PlayerNotFoundException();
}
if (!plugin.getBanManager().isBanned(targetUUID))
if (!plugin.getPunishmentManager().isBanned(targetUUID))
{
throw new PlayerNotBannedException();
}
plugin.getBanManager().unban(targetUUID);
plugin.getPunishmentManager().unban(targetUUID);
PlexUtils.broadcast(tl("unbanningPlayer", sender.getName(), plexPlayer.getName()));
}
return null;

View File

@ -22,11 +22,17 @@ public class CommandHandler extends PlexBase
commands.add(new OpCMD());
commands.add(new RankCMD());
}
if (plugin.config.getBoolean("debug"))
{
commands.add(new DebugCMD());
}
commands.add(new AdminworldCMD());
commands.add(new AdventureCMD());
commands.add(new BanCMD());
commands.add(new CommandSpyCMD());
commands.add(new CreativeCMD());
commands.add(new FlatlandsCMD());
commands.add(new FreezeCMD());
commands.add(new ListCMD());

View File

@ -1,13 +1,17 @@
package dev.plex.listener.impl;
import dev.plex.banning.Ban;
import dev.plex.cache.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.PunishmentType;
import dev.plex.util.MojangUtils;
import dev.plex.util.PlexUtils;
import java.time.format.DateTimeFormatter;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import java.time.format.DateTimeFormatter;
public class BanListener extends PlexListener
{
private final String banUrl = plugin.config.getString("banning.ban_url");
@ -16,15 +20,16 @@ public class BanListener extends PlexListener
@EventHandler
public void onPreLogin(AsyncPlayerPreLoginEvent event)
{
if (plugin.getBanManager().isBanned(event.getUniqueId()))
if (plugin.getPunishmentManager().isBanned(event.getUniqueId()))
{
for (Ban ban : plugin.getBanManager().getActiveBans())
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getUniqueId());
player.getPunishments().stream().filter(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive()).findFirst().ifPresent(punishment ->
{
String banMessage = PlexUtils.tl("banMessage", banUrl, ban.getReason(),
DATE_FORMAT.format(ban.getEndDate()), ban.getBanner() == null ? "CONSOLE" : ban.getBanner());
String banMessage = PlexUtils.tl("banMessage", banUrl, punishment.getReason(),
DATE_FORMAT.format(punishment.getEndDate()), punishment.getPunisher() == null ? "CONSOLE" : MojangUtils.getInfo(punishment.getPunisher().toString()).getUsername());
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED,
LegacyComponentSerializer.legacyAmpersand().deserialize(banMessage));
}
});
}
}
}

View File

@ -56,11 +56,16 @@ public class PlayerListener extends PlexListener
plexPlayer = DataUtils.getPlayer(player.getUniqueId());
}
PunishedPlayer punishedPlayer;
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
if (!PlayerCache.getPunishedPlayerMap().containsKey(player.getUniqueId()))
{
PlayerCache.getPunishedPlayerMap().put(player.getUniqueId(), new PunishedPlayer(player.getUniqueId()));
punishedPlayer = new PunishedPlayer(player.getUniqueId());
PlayerCache.getPunishedPlayerMap().put(player.getUniqueId(), punishedPlayer);
} else {
punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
}
punishedPlayer.convertPunishments();
assert plexPlayer != null;

View File

@ -1,26 +1,32 @@
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.PunishedPlayerMuteEvent;
import dev.plex.punishment.Punishment;
import dev.plex.util.PlexLog;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
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 lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.stream.Collectors;
@Getter
public class PunishedPlayer extends PlexBase
@ -73,8 +79,7 @@ public class PunishedPlayer extends PlexBase
try
{
file.createNewFile();
}
catch (IOException e)
} catch (IOException e)
{
e.printStackTrace();
}
@ -83,6 +88,48 @@ public class PunishedPlayer extends PlexBase
}
@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();
@ -90,12 +137,18 @@ public class PunishedPlayer extends PlexBase
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);
JSONTokener tokener = new JSONTokener(strObj);
JSONObject object = new JSONObject(tokener);
object.getJSONObject(getUuid()).getJSONArray("punishments").forEach(obj ->
if (strObj.isEmpty() || !strObj.startsWith("{")) return punishments;
JSONObject object = new JSONObject(strObj);
object.getJSONObject(uuid).getJSONArray("punishments").forEach(obj ->
{
Punishment punishment = Punishment.fromJson(obj.toString());
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();
@ -116,8 +169,7 @@ public class PunishedPlayer extends PlexBase
Punishment punishment = Punishment.fromJson(obj.toString());
punishments.add(punishment);
});
}
catch (FileNotFoundException e)
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
@ -130,8 +182,7 @@ public class PunishedPlayer extends PlexBase
try
{
return !FileUtils.readFileToString(file, StandardCharsets.UTF_8).trim().isEmpty();
}
catch (IOException e)
} catch (IOException e)
{
e.printStackTrace();
}

View File

@ -23,7 +23,10 @@ public class Punishment
private PunishmentType type;
private String reason;
private boolean customTime;
private boolean active; //Field is only for bans
private LocalDateTime endDate;
public Punishment(UUID punished, UUID punisher)

View File

@ -4,10 +4,17 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.banning.Ban;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
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;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
@ -18,11 +25,7 @@ import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.stream.Collectors;
public class PunishmentManager extends PlexBase
{
@ -48,8 +51,7 @@ public class PunishmentManager extends PlexBase
writer.append(object.toString(8));
writer.flush();
writer.close();
}
else
} else
{
JSONObject object = new JSONObject();
Map<String, List<String>> punishments = Maps.newHashMap();
@ -71,8 +73,7 @@ public class PunishmentManager extends PlexBase
writer.flush();
writer.close();
}
}
catch (IOException e)
} catch (IOException e)
{
e.printStackTrace();
}
@ -83,22 +84,126 @@ public class PunishmentManager extends PlexBase
try
{
return !FileUtils.readFileToString(file, StandardCharsets.UTF_8).trim().isEmpty();
}
catch (IOException e)
} catch (IOException e)
{
e.printStackTrace();
}
return false;
}
public boolean isBanned(UUID uuid)
{
return PlayerCache.getPunishedPlayerMap().containsKey(uuid) && PlayerCache.getPunishedPlayer(uuid).getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
}
public boolean isBanned(PunishedPlayer player)
{
return isBanned(UUID.fromString(player.getUuid()));
}
public List<Punishment> getActiveBans()
{
List<Punishment> punishments = Lists.newArrayList();
Jedis jedis = Plex.get().getRedisConnection().getJedis();
jedis.keys("*").forEach(key ->
{
try
{
UUID uuid = UUID.fromString(key);
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
object.getJSONObject(uuid.toString()).getJSONArray("punishments").forEach(json ->
{
Punishment punishment = Punishment.fromJson(json.toString());
if (punishment.isActive() && punishment.getType() == PunishmentType.BAN)
{
punishments.add(punishment);
}
});
} catch (IllegalArgumentException e)
{
}
});
return punishments;
}
public void unban(Punishment punishment)
{
this.unban(punishment.getPunished());
}
public void unban(UUID uuid)
{
if (Plex.get().getRedisConnection().isEnabled())
{
Jedis jedis = Plex.get().getRedisConnection().getJedis();
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
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(false);
punishments.set(index, punishment);
});
}
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear();
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
jedis.set(uuid.toString(), object.toString());
}
PunishedPlayer player;
if (PlayerCache.getPunishedPlayerMap().containsKey(uuid))
{
player = PlayerCache.getPunishedPlayer(uuid);
} else
{
player = new PunishedPlayer(uuid);
}
File file = player.getPunishmentsFile();
if (isNotEmpty(file))
{
try (FileInputStream fis = new FileInputStream(file))
{
JSONTokener tokener = new JSONTokener(fis);
JSONObject object = new JSONObject(tokener);
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(false);
punishments.set(index, punishment);
});
}
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear();
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
FileWriter writer = new FileWriter(file);
writer.append(object.toString());
writer.flush();
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
private void issuePunishment(PunishedPlayer player, Punishment punishment)
{
if (punishment.getType() == PunishmentType.BAN)
/*if (punishment.getType() == PunishmentType.BAN)
{
Ban ban = new Ban(punishment.getPunished(), (punishment.getPunisher() == null ? null : punishment.getPunisher()), "", punishment.getReason(), punishment.getEndDate());
Plex.get().getBanManager().executeBan(ban);
// Ban ban = new Ban(punishment.getPunished(), (punishment.getPunisher() == null ? null : punishment.getPunisher()), "", punishment.getReason(), punishment.getEndDate());
// Plex.get().getBanManager().executeBan(ban);
}
else if (punishment.getType() == PunishmentType.FREEZE)
else*/
if (punishment.getType() == PunishmentType.FREEZE)
{
player.setFrozen(true);
LocalDateTime now = LocalDateTime.now();
@ -119,8 +224,7 @@ public class PunishmentManager extends PlexBase
Bukkit.getLogger().info("Unfroze");
}
}.runTaskLater(Plex.get(), 20 * seconds);
}
else if (punishment.getType() == PunishmentType.MUTE)
} else if (punishment.getType() == PunishmentType.MUTE)
{
player.setMuted(true);
LocalDateTime now = LocalDateTime.now();

View File

@ -2,6 +2,7 @@ package dev.plex.services;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.services.impl.BanService;
import dev.plex.services.impl.GameRuleService;
import java.util.List;
import org.bukkit.Bukkit;
@ -12,7 +13,7 @@ public class ServiceManager
public ServiceManager()
{
//registerService(new BanService());
registerService(new BanService());
registerService(new GameRuleService());
}
@ -26,11 +27,11 @@ public class ServiceManager
}
else if (service.isRepeating() && service.isAsynchronous())
{
Bukkit.getScheduler().runTaskTimerAsynchronously(Plex.get(), service::run, 0, 20 * service.repeatInSeconds());
Bukkit.getScheduler().runTaskTimerAsynchronously(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
}
else if (service.isRepeating() && !service.isAsynchronous())
{
Bukkit.getScheduler().runTaskTimer(Plex.get(), service::run, 0, 20 * service.repeatInSeconds());
Bukkit.getScheduler().runTaskTimer(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
}
}
}

View File

@ -1,9 +1,11 @@
package dev.plex.services.impl;
import dev.plex.Plex;
import dev.plex.banning.Ban;
import dev.plex.punishment.Punishment;
import dev.plex.services.AbstractService;
import java.time.LocalDateTime;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
public class BanService extends AbstractService
@ -16,12 +18,14 @@ public class BanService extends AbstractService
@Override
public void run()
{
for (Ban ban : Plex.get().getBanManager().getActiveBans())
for (Punishment punishment : Plex.get().getPunishmentManager().getActiveBans())
{
if (LocalDateTime.now().isAfter(ban.getEndDate()))
if (LocalDateTime.now().isAfter(punishment.getEndDate()))
{
Plex.get().getBanManager().unban(ban.getId());
Bukkit.broadcastMessage("Plex - Unbanned " + Bukkit.getOfflinePlayer(ban.getUuid()).getName());
Plex.get().getPunishmentManager().unban(punishment);
// Plex.get().getBanManager().unban(ban.getId());
// Bukkit.broadcastMessage("Plex - Unbanned " + Bukkit.getOfflinePlayer(ban.getUuid()).getName());
Bukkit.broadcast(Component.text("Plex - Unbanned " + Bukkit.getOfflinePlayer(punishment.getPunished()).getName()));
}
}
}
@ -29,6 +33,6 @@ public class BanService extends AbstractService
@Override
public int repeatInSeconds()
{
return 10;
return 1;
}
}

View File

@ -6,7 +6,6 @@ import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.mapping.MapperOptions;
import dev.plex.Plex;
import dev.plex.banning.Ban;
import dev.plex.player.PlexPlayer;
public class MongoConnection
@ -31,7 +30,6 @@ public class MongoConnection
MongoClient client = MongoClients.create(connectionString);
Datastore datastore = Morphia.createDatastore(client, database, MapperOptions.DEFAULT);
datastore.getMapper().map(PlexPlayer.class);
datastore.getMapper().map(Ban.class);
datastore.ensureIndexes();
plugin.setStorageType(StorageType.MONGODB);
return datastore;

View File

@ -2,13 +2,6 @@ package dev.plex.util;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
@ -16,13 +9,21 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
public class MojangUtils
{
public static AshconInfo getInfo(String name)
public static AshconInfo getInfo(String nameOrUuid)
{
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("https://api.ashcon.app/mojang/v2/user/" + name);
HttpGet get = new HttpGet("https://api.ashcon.app/mojang/v2/user/" + nameOrUuid);
try
{
HttpResponse response = client.execute(get);