-> Ban System done (?)

-> Switch Freeze CMD to use Punishment System
-> Add Mute Event
-> Register new Ban CMD
-> Register Login Listener
-> Add methods to Punishments
-> Service System
-> Have SQL and Mongo create a new table / collection for Bans
-> Added more util methods
This commit is contained in:
spacerocket62 2020-11-09 18:47:03 -08:00
parent 2d18c16358
commit 2790d406ed
22 changed files with 612 additions and 30 deletions

View File

@ -3,6 +3,7 @@ package me.totalfreedom.plex;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.totalfreedom.plex.admin.AdminList; import me.totalfreedom.plex.admin.AdminList;
import me.totalfreedom.plex.banning.BanManager;
import me.totalfreedom.plex.cache.MongoPlayerData; import me.totalfreedom.plex.cache.MongoPlayerData;
import me.totalfreedom.plex.cache.SQLPlayerData; import me.totalfreedom.plex.cache.SQLPlayerData;
import me.totalfreedom.plex.config.Config; import me.totalfreedom.plex.config.Config;
@ -10,6 +11,7 @@ import me.totalfreedom.plex.handlers.CommandHandler;
import me.totalfreedom.plex.handlers.ListenerHandler; import me.totalfreedom.plex.handlers.ListenerHandler;
import me.totalfreedom.plex.punishment.PunishmentManager; import me.totalfreedom.plex.punishment.PunishmentManager;
import me.totalfreedom.plex.rank.RankManager; import me.totalfreedom.plex.rank.RankManager;
import me.totalfreedom.plex.services.ServiceManager;
import me.totalfreedom.plex.storage.MongoConnection; import me.totalfreedom.plex.storage.MongoConnection;
import me.totalfreedom.plex.storage.RedisConnection; import me.totalfreedom.plex.storage.RedisConnection;
import me.totalfreedom.plex.storage.SQLConnection; import me.totalfreedom.plex.storage.SQLConnection;
@ -36,8 +38,10 @@ public class Plex extends JavaPlugin
private SQLPlayerData sqlPlayerData; private SQLPlayerData sqlPlayerData;
private RankManager rankManager; private RankManager rankManager;
private ServiceManager serviceManager;
private PunishmentManager punishmentManager; private PunishmentManager punishmentManager;
private BanManager banManager;
private AdminList adminList; private AdminList adminList;
@ -101,7 +105,14 @@ public class Plex extends JavaPlugin
PlexLog.log("Rank Manager initialized"); PlexLog.log("Rank Manager initialized");
punishmentManager = new PunishmentManager(); punishmentManager = new PunishmentManager();
PlexLog.log("Punishment Manager initialized"); banManager = new BanManager();
PlexLog.log("Punishment System initialized");
serviceManager = new ServiceManager();
PlexLog.log("Service Manager initialized");
serviceManager.startServices();
PlexLog.log("Started " + serviceManager.serviceCount() + " services.");
adminList = new AdminList(); adminList = new AdminList();

View File

@ -0,0 +1,58 @@
package me.totalfreedom.plex.banning;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.RandomStringUtils;
import java.util.Date;
import java.util.UUID;
@Getter
@Setter
@Entity(value = "bans", useDiscriminator = false)
public class Ban
{
@Setter(AccessLevel.NONE)
@Id
private String id;
@Setter(AccessLevel.NONE)
@Indexed(options = @IndexOptions(unique = true))
private final UUID uuid;
@Indexed // have the banner be indexed in the future to get bans issued by a person
private UUID banner;
private String ip;
private String reason;
private Date endDate;
private boolean active;
public Ban(UUID uuid, UUID banner, String ip, String reason, Date endDate)
{
this.uuid = uuid;
this.id = uuid.toString().substring(0, 8) + "-" + RandomStringUtils.randomAlphabetic(6);
this.banner = banner;
this.ip = ip;
this.reason = reason;
this.endDate = endDate;
this.active = true;
}
public Ban(String id, UUID uuid, UUID banner, String reason, Date endDate)
{
this.uuid = uuid;
this.id = id;
this.banner = banner;
this.reason = reason;
this.endDate = endDate;
this.active = true;
}
}

View File

@ -0,0 +1,157 @@
package me.totalfreedom.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.morphia.query.internal.MorphiaCursor;
import me.totalfreedom.plex.Plex;
import me.totalfreedom.plex.storage.StorageType;
import me.totalfreedom.plex.util.PlexLog;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
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`, `reason`, `enddate`, `active`) VALUES (?, ?, ?, ?, ?, ?);";
public void executeBan(Ban ban)
{
if (Plex.get().getStorageType() == StorageType.MONGO)
{
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.getReason().isEmpty() ? "" : ban.getReason());
statement.setLong(5, ban.getEndDate().toInstant().toEpochMilli());
statement.setBoolean(6, ban.isActive());
statement.execute();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public boolean isBanned(UUID uuid)
{
if (Plex.get().getStorageType() == StorageType.MONGO)
{
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();
PlexLog.log("-----------");
PlexLog.log("Next: " + set.next());
PlexLog.log("Active: " + set.getBoolean("active"));
if (!set.next()) return false;
while (set.next())
{
if (set.getBoolean("active")) return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return false;
}
public void unban(UUID uuid)
{
if (Plex.get().getStorageType() == StorageType.MONGO)
{
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=?");
statement.setBoolean(1, false);
statement.setString(2, uuid.toString());
statement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public void unban(String id)
{
if (Plex.get().getStorageType() == StorageType.MONGO)
{
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();
}
}
}
public List<Ban> getActiveBans()
{
List<Ban> bans = Lists.newArrayList();
if (Plex.get().getStorageType() == StorageType.MONGO)
{
MorphiaCursor<Ban> cursor = Plex.get().getMongoConnection().getDatastore().find(Ban.class).filter(Filters.eq("active", true)).iterator();
while (cursor.hasNext())
{
Ban ban = cursor.next();
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 reason = set.getString("reason");
Date endDate = set.getLong("enddate") != 0 ? new Date(set.getLong("enddate")) : null;
Ban ban = new Ban(id, uuid, banner, reason, endDate);
bans.add(ban);
}
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return bans;
}
}

View File

@ -48,7 +48,7 @@ public abstract class PlexCommand extends Command implements TabExecutor, IPlexC
setName(name); setName(name);
setLabel(name); setLabel(name);
setDescription(params.description()); setDescription(params.description());
setUsage(params.usage()); setUsage(params.usage().replace("<command>", name));
if (params.aliases().split(",").length > 0) if (params.aliases().split(",").length > 0)
{ {
setAliases(Arrays.asList(params.aliases().split(","))); setAliases(Arrays.asList(params.aliases().split(",")));

View File

@ -0,0 +1,89 @@
package me.totalfreedom.plex.command.impl;
import com.google.common.collect.ImmutableList;
import me.totalfreedom.plex.Plex;
import me.totalfreedom.plex.banning.Ban;
import me.totalfreedom.plex.cache.DataUtils;
import me.totalfreedom.plex.cache.PlayerCache;
import me.totalfreedom.plex.command.PlexCommand;
import me.totalfreedom.plex.command.annotation.CommandParameters;
import me.totalfreedom.plex.command.annotation.CommandPermissions;
import me.totalfreedom.plex.command.exception.PlayerNotFoundException;
import me.totalfreedom.plex.command.source.CommandSource;
import me.totalfreedom.plex.command.source.RequiredCommandSource;
import me.totalfreedom.plex.player.PlexPlayer;
import me.totalfreedom.plex.player.PunishedPlayer;
import me.totalfreedom.plex.punishment.Punishment;
import me.totalfreedom.plex.punishment.PunishmentType;
import me.totalfreedom.plex.rank.enums.Rank;
import me.totalfreedom.plex.util.PlexUtils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@CommandParameters(usage = "/<command> <player> [reason]", aliases = "offlineban,gtfo", description = "Bans a player, offline or online")
@CommandPermissions(level = Rank.ADMIN, source = RequiredCommandSource.ANY)
public class BanCMD extends PlexCommand
{
public BanCMD() {
super("ban");
}
@Override
public void execute(CommandSource sender, String[] args)
{
if (args.length == 0)
{
sender.send(usage(getUsage()));
return;
}
if (args.length == 1)
{
UUID targetUUID = PlexUtils.getFromName(args[0]);
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
if (isAdmin(plexPlayer))
{
if (!sender.isConsoleSender())
{
PlexPlayer plexPlayer1 = sender.getPlexPlayer();
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()))
{
sender.send("This player is an admin and a higher rank than you.");
return;
}
}
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, !sender.isConsoleSender() ? sender.getPlayer().getUniqueId() : null);
punishment.setType(PunishmentType.BAN);
punishment.setReason("");
punishment.setPunishedUsername(plexPlayer.getName());
punishment.setEndDate(new Date(Instant.now().plusSeconds(10/*PlexUtils.secondsToHours(24)*/).getEpochSecond()));
punishment.setCustomTime(false);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
Bukkit.broadcastMessage(sender.getName() + " - Banning " + plexPlayer.getName());
if (Bukkit.getOfflinePlayer(targetUUID).isOnline())
{
Bukkit.getPlayer(targetUUID).kickPlayer("§cYou've been banned.");
}
}
}
@Override
public List<String> onTabComplete(CommandSource sender, String[] args) {
return args.length == 1 ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -1,7 +1,12 @@
package me.totalfreedom.plex.command.impl; package me.totalfreedom.plex.command.impl;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.time.Instant;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID;
import me.totalfreedom.plex.cache.PlayerCache; import me.totalfreedom.plex.cache.PlayerCache;
import me.totalfreedom.plex.command.PlexCommand; import me.totalfreedom.plex.command.PlexCommand;
import me.totalfreedom.plex.command.annotation.CommandParameters; import me.totalfreedom.plex.command.annotation.CommandParameters;
@ -9,11 +14,13 @@ import me.totalfreedom.plex.command.annotation.CommandPermissions;
import me.totalfreedom.plex.command.exception.CommandArgumentException; import me.totalfreedom.plex.command.exception.CommandArgumentException;
import me.totalfreedom.plex.command.source.CommandSource; import me.totalfreedom.plex.command.source.CommandSource;
import me.totalfreedom.plex.player.PunishedPlayer; import me.totalfreedom.plex.player.PunishedPlayer;
import me.totalfreedom.plex.punishment.Punishment;
import me.totalfreedom.plex.punishment.PunishmentType;
import me.totalfreedom.plex.rank.enums.Rank; import me.totalfreedom.plex.rank.enums.Rank;
import me.totalfreedom.plex.util.PlexUtils; import me.totalfreedom.plex.util.PlexUtils;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandParameters(description = "Freeze/unfreeze a player on the server", usage = "/<command> <player>") @CommandParameters(description = "Freeze a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.ADMIN) @CommandPermissions(level = Rank.ADMIN)
public class FreezeCMD extends PlexCommand public class FreezeCMD extends PlexCommand
{ {
@ -31,9 +38,15 @@ public class FreezeCMD extends PlexCommand
} }
Player player = getNonNullPlayer(args[0]); Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()); PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
punishedPlayer.setFrozen(!punishedPlayer.isFrozen()); Punishment punishment = new Punishment(UUID.fromString(punishedPlayer.getUuid()), sender.isConsoleSender() ? null : sender.getPlayer().getUniqueId());
PlexUtils.broadcast(punishedPlayer.isFrozen() ? tl("frozePlayer", sender.getName(), player.getName()) : punishment.setCustomTime(false);
tl("unfrozePlayer", sender.getName(), player.getName())); punishment.setEndDate(new Date(Instant.now().plusSeconds(10).toEpochMilli()));
punishment.setType(PunishmentType.FREEZE);
punishment.setPunishedUsername(player.getName());
punishment.setReason("");
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(tl("frozePlayer", sender.getName(), player.getName()));
} }
@Override @Override

View File

@ -0,0 +1,34 @@
package me.totalfreedom.plex.event;
import lombok.Getter;
import me.totalfreedom.plex.player.PunishedPlayer;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
@Getter
public class PunishedPlayerMuteEvent extends PunishedPlayerEvent implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
/**
* Status of the Punished Player being frozen before the event's occurrence.
*/
private final boolean muted;
public PunishedPlayerMuteEvent(PunishedPlayer punishedPlayer, boolean muted)
{
super(punishedPlayer);
this.muted = muted;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -3,19 +3,7 @@ package me.totalfreedom.plex.handlers;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import java.util.List; import java.util.List;
import me.totalfreedom.plex.command.PlexCommand; import me.totalfreedom.plex.command.PlexCommand;
import me.totalfreedom.plex.command.impl.AdminCMD; import me.totalfreedom.plex.command.impl.*;
import me.totalfreedom.plex.command.impl.AdventureCMD;
import me.totalfreedom.plex.command.impl.CreativeCMD;
import me.totalfreedom.plex.command.impl.FionnCMD;
import me.totalfreedom.plex.command.impl.FreezeCMD;
import me.totalfreedom.plex.command.impl.NameHistoryCMD;
import me.totalfreedom.plex.command.impl.OpAllCMD;
import me.totalfreedom.plex.command.impl.OpCMD;
import me.totalfreedom.plex.command.impl.PlexCMD;
import me.totalfreedom.plex.command.impl.SpectatorCMD;
import me.totalfreedom.plex.command.impl.SurvivalCMD;
import me.totalfreedom.plex.command.impl.TestCMD;
import me.totalfreedom.plex.command.impl.WorldCMD;
import me.totalfreedom.plex.util.PlexLog; import me.totalfreedom.plex.util.PlexLog;
public class CommandHandler public class CommandHandler
@ -37,6 +25,7 @@ public class CommandHandler
commands.add(new CreativeCMD()); commands.add(new CreativeCMD());
commands.add(new SurvivalCMD()); commands.add(new SurvivalCMD());
commands.add(new SpectatorCMD()); commands.add(new SpectatorCMD());
commands.add(new BanCMD());
PlexLog.log(String.format("Registered %s commands!", commands.size())); PlexLog.log(String.format("Registered %s commands!", commands.size()));
} }
} }

View File

@ -18,6 +18,7 @@ public class ListenerHandler
listeners.add(new WorldListener()); listeners.add(new WorldListener());
listeners.add(new FreezeListener()); listeners.add(new FreezeListener());
listeners.add(new AdminListener()); listeners.add(new AdminListener());
listeners.add(new LoginListener());
PlexLog.log(String.format("Registered %s listeners!", listeners.size())); PlexLog.log(String.format("Registered %s listeners!", listeners.size()));
} }
} }

View File

@ -1,11 +1,17 @@
package me.totalfreedom.plex.listener.impl; package me.totalfreedom.plex.listener.impl;
import me.totalfreedom.plex.cache.PlayerCache; import me.totalfreedom.plex.cache.PlayerCache;
import me.totalfreedom.plex.event.PunishedPlayerFreezeEvent;
import me.totalfreedom.plex.listener.PlexListener; import me.totalfreedom.plex.listener.PlexListener;
import me.totalfreedom.plex.player.PunishedPlayer; import me.totalfreedom.plex.player.PunishedPlayer;
import me.totalfreedom.plex.util.PlexUtils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import java.util.UUID;
public class FreezeListener extends PlexListener public class FreezeListener extends PlexListener
{ {
@EventHandler @EventHandler
@ -17,4 +23,5 @@ public class FreezeListener extends PlexListener
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }

View File

@ -0,0 +1,23 @@
package me.totalfreedom.plex.listener.impl;
import me.totalfreedom.plex.listener.PlexListener;
import me.totalfreedom.plex.util.PlexLog;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
public class LoginListener extends PlexListener
{
//TODO: Customizable MSGS
@EventHandler
public void onPreLogin(AsyncPlayerPreLoginEvent event)
{
PlexLog.log(String.valueOf(plugin.getBanManager().isBanned(event.getUniqueId())));
if (plugin.getBanManager().isBanned(event.getUniqueId()))
{
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, "§cYou're currently banned from this server.\n§cPlease appeal at §6https://forum.totalfreedom.me/");
}
}
}

View File

@ -1,6 +1,8 @@
package me.totalfreedom.plex.listener.impl; package me.totalfreedom.plex.listener.impl;
import java.time.Instant;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date;
import java.util.UUID; import java.util.UUID;
import me.totalfreedom.plex.admin.Admin; import me.totalfreedom.plex.admin.Admin;
import me.totalfreedom.plex.cache.DataUtils; import me.totalfreedom.plex.cache.DataUtils;
@ -106,8 +108,10 @@ public class PlayerListener extends PlexListener
/*Punishment test = new Punishment(player.getUniqueId(), player.getUniqueId()); /*Punishment test = new Punishment(player.getUniqueId(), player.getUniqueId());
test.setPunishedUsername(player.getName()); test.setPunishedUsername(player.getName());
test.setReason("hii"); test.setReason("hii");
test.setType(PunishmentType.FREEZE); test.setType(PunishmentType.BAN);
plugin.getPunishmentManager().insertPunishment(PlayerCache.getPunishedPlayer(player.getUniqueId()), test);*/ test.setEndDate(new Date(Instant.now().plusSeconds(10).getEpochSecond()));
plugin.getPunishmentManager().doPunishment(PlayerCache.getPunishedPlayer(player.getUniqueId()), test);*/
} }

View File

@ -5,6 +5,7 @@ import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.totalfreedom.plex.event.PunishedPlayerFreezeEvent; import me.totalfreedom.plex.event.PunishedPlayerFreezeEvent;
import me.totalfreedom.plex.event.PunishedPlayerMuteEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@Getter @Getter
@ -33,4 +34,14 @@ public class PunishedPlayer
this.frozen = frozen; 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;
}
}
} }

View File

@ -5,6 +5,7 @@ import com.google.gson.Gson;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -23,7 +24,7 @@ public class Punishment
private PunishmentType type; private PunishmentType type;
private String reason; private String reason;
private boolean customTime; private boolean customTime;
private long endDate; private Date endDate;
public Punishment(UUID punished, UUID punisher) public Punishment(UUID punished, UUID punisher)
{ {
@ -35,7 +36,7 @@ public class Punishment
this.type = null; this.type = null;
this.reason = ""; this.reason = "";
this.customTime = false; this.customTime = false;
this.endDate = 0; this.endDate = null;
} }
public String toJSON() public String toJSON()

View File

@ -3,10 +3,16 @@ package me.totalfreedom.plex.punishment;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import me.totalfreedom.plex.Plex; import me.totalfreedom.plex.Plex;
import me.totalfreedom.plex.banning.Ban;
import me.totalfreedom.plex.cache.DataUtils; import me.totalfreedom.plex.cache.DataUtils;
import me.totalfreedom.plex.event.PunishedPlayerFreezeEvent;
import me.totalfreedom.plex.player.PunishedPlayer; import me.totalfreedom.plex.player.PunishedPlayer;
import me.totalfreedom.plex.util.PlexLog; import me.totalfreedom.plex.util.PlexLog;
import me.totalfreedom.plex.util.PlexUtils;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateUtils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.JSONTokener; import org.json.JSONTokener;
@ -15,8 +21,11 @@ import java.io.FileInputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class PunishmentManager public class PunishmentManager
{ {
@ -81,4 +90,53 @@ public class PunishmentManager
return false; return false;
} }
private void issuePunishment(PunishedPlayer player, Punishment punishment)
{
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);
} else if (punishment.getType() == PunishmentType.FREEZE)
{
player.setFrozen(true);
Date now = new Date();
Date then = punishment.getEndDate();
long seconds = TimeUnit.MILLISECONDS.toSeconds(then.getTime() - now.getTime());
new BukkitRunnable() {
@Override
public void run() {
if (!player.isFrozen())
{
this.cancel();
return;
}
player.setFrozen(false);
Bukkit.broadcastMessage(PlexUtils.tl("unfrozePlayer", "Plex", Bukkit.getOfflinePlayer(UUID.fromString(player.getUuid())).getName()));
Bukkit.getLogger().info("Unfroze");
}
}.runTaskLater(Plex.get(), 20 * seconds);
} else if (punishment.getType() == PunishmentType.MUTE)
{
player.setMuted(true);
Date now = new Date();
Date then = punishment.getEndDate();
long seconds = TimeUnit.MILLISECONDS.toSeconds(then.getTime() - now.getTime());
new BukkitRunnable() {
@Override
public void run() {
player.setMuted(false);
}
}.runTaskLater(Plex.get(), 20 * seconds);
}
}
public void doPunishment(PunishedPlayer player, Punishment punishment)
{
issuePunishment(player, punishment);
insertPunishment(player, punishment);
}
} }

View File

@ -0,0 +1,16 @@
package me.totalfreedom.plex.services;
public abstract class AbstractService implements IService
{
private boolean asynchronous;
public AbstractService(boolean async)
{
this.asynchronous = async;
}
public boolean isAsynchronous() {
return asynchronous;
}
}

View File

@ -0,0 +1,9 @@
package me.totalfreedom.plex.services;
public interface IService
{
void run();
int repeatInSeconds();
}

View File

@ -0,0 +1,44 @@
package me.totalfreedom.plex.services;
import com.google.common.collect.Lists;
import me.totalfreedom.plex.Plex;
import me.totalfreedom.plex.services.impl.BanService;
import org.bukkit.Bukkit;
import java.util.List;
public class ServiceManager
{
private final List<AbstractService> services = Lists.newArrayList();
public ServiceManager()
{
registerService(new BanService());
}
public void startServices()
{
for (AbstractService service : services)
{
if (service.isAsynchronous())
{
Bukkit.getScheduler().runTaskTimerAsynchronously(Plex.get(), service::run, 0, 20 * service.repeatInSeconds());
} else {
Bukkit.getScheduler().runTaskTimer(Plex.get(), service::run, 0, 20 * service.repeatInSeconds());
}
}
}
private void registerService(AbstractService service)
{
services.add(service);
}
public int serviceCount()
{
return services.size();
}
}

View File

@ -0,0 +1,32 @@
package me.totalfreedom.plex.services.impl;
import me.totalfreedom.plex.Plex;
import me.totalfreedom.plex.banning.Ban;
import me.totalfreedom.plex.services.AbstractService;
import org.bukkit.Bukkit;
import java.util.Date;
public class BanService extends AbstractService
{
public BanService() {
super(true);
}
@Override
public void run() {
for (Ban ban : Plex.get().getBanManager().getActiveBans())
{
if (new Date().after(ban.getEndDate()))
{
Plex.get().getBanManager().unban(ban.getId());
Bukkit.broadcastMessage("Plex - Unbanned " + Bukkit.getOfflinePlayer(ban.getUuid()).getName());
}
}
}
@Override
public int repeatInSeconds() {
return 10;
}
}

View File

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

View File

@ -52,6 +52,15 @@ public class SQLConnection extends PlexBase
"\t`vanished` BOOLEAN,\n" + "\t`vanished` BOOLEAN,\n" +
"\tPRIMARY KEY (`uuid`)\n" + "\tPRIMARY KEY (`uuid`)\n" +
");").execute(); ");").execute();
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `bans` (\n" +
"\t`banID` VARCHAR,\n" +
"\t`uuid` VARCHAR(46) NOT NULL,\n" +
"\t`banner` VARCHAR(46),\n" +
"\t`reason` VARCHAR,\n" +
"\t`enddate` BIGINT,\n" +
"\t`active` BOOLEAN,\n" +
"\tPRIMARY KEY (`banID`)\n" +
");").execute();
} }
} }
catch (SQLException throwables) catch (SQLException throwables)

View File

@ -6,13 +6,7 @@ import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import me.totalfreedom.plex.Plex; import me.totalfreedom.plex.Plex;
@ -240,4 +234,24 @@ public class PlexUtils
{ {
return ThreadLocalRandom.current().nextInt(start, limit); return ThreadLocalRandom.current().nextInt(start, limit);
} }
public static long getDateNow()
{
return new Date().getTime();
}
public static Date getDateFromLong(long epoch)
{
return new Date(epoch);
}
public static long hoursToSeconds(long hours)
{
return hours * 60 * 60;
}
public static long minutesToSeconds(long minutes)
{
return minutes * 60;
}
} }