Add tempbans

This commit is contained in:
Telesphoreo 2022-02-26 00:24:11 -06:00
parent 8b4a5d64a0
commit 817cb03dca
10 changed files with 259 additions and 59 deletions

View File

@ -88,7 +88,7 @@ public class BanCMD extends PlexCommand
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)
{
player.kick(componentFromString("&cYou've been banned."));
player.kick(Punishment.generateBanMessage(punishment));
}
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + punishedPlayer.getUuid());
return null;

View File

@ -0,0 +1,101 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
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.PlayerNotBannedException;
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.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;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "tempban", usage = "/<command> <player> <time> [reason]", description = "Temporarily ban a player")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.tempban", source = RequiredCommandSource.ANY)
public class TempbanCMD extends PlexCommand
{
@Override
public Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length <= 1)
{
return usage();
}
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason;
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
Player player = Bukkit.getPlayer(targetUUID);
if (isAdmin(plexPlayer))
{
if (!isConsole(sender))
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()))
{
return messageComponent("higherRankThanYou");
}
}
}
if (plugin.getPunishmentManager().isBanned(targetUUID))
{
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)
{
reason = StringUtils.join(args, " ", 2, args.length);
punishment.setReason(reason);
}
else
{
punishment.setReason("No reason provided.");
}
punishment.setPunishedUsername(plexPlayer.getName());
punishment.setEndDate(PlexUtils.parseDateOffset(args[1]));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && checkTab(sender, Rank.ADMIN, "plex.tempban") ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -46,6 +46,7 @@ public class CommandHandler extends PlexBase
commands.add(new SpectatorCMD());
commands.add(new SurvivalCMD());
commands.add(new TagCMD());
commands.add(new TempbanCMD());
commands.add(new UnbanCMD());
commands.add(new UnfreezeCMD());
commands.add(new UnmuteCMD());

View File

@ -3,19 +3,13 @@ package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
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.Component;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
public class BanListener extends PlexListener
{
private final String banUrl = plugin.config.getString("banning.ban_url");
private final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a");
@EventHandler
public void onPreLogin(AsyncPlayerPreLoginEvent event)
{
@ -23,12 +17,8 @@ public class BanListener extends PlexListener
{
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getUniqueId());
player.getPunishments().stream().filter(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive()).findFirst().ifPresent(punishment ->
{
Component banMessage = PlexUtils.messageComponent("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,
banMessage);
});
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED,
Punishment.generateBanMessage(punishment)));
}
}
}

View File

@ -38,7 +38,9 @@ public class ChatListener extends PlexListener
{
renderer.hasPrefix = true;
renderer.prefix = prefix;
} else {
}
else
{
renderer.hasPrefix = false;
renderer.prefix = null;
}

View File

@ -2,13 +2,18 @@ package dev.plex.punishment;
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;
import dev.plex.Plex;
import dev.plex.util.MojangUtils;
import dev.plex.util.PlexUtils;
import dev.plex.util.adapter.LocalDateTimeDeserializer;
import dev.plex.util.adapter.LocalDateTimeSerializer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
@Getter
@Setter
@ -25,7 +30,7 @@ public class Punishment
private String reason;
private boolean customTime;
private boolean active; //Field is only for bans
private boolean active; // Field is only for bans
private LocalDateTime endDate;
@ -42,6 +47,15 @@ public class Punishment
this.endDate = null;
}
private static final String banUrl = Plex.get().config.getString("banning.ban_url");
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a");
public static Component generateBanMessage(Punishment punishment)
{
return PlexUtils.messageComponent("banMessage", banUrl, punishment.getReason(),
DATE_FORMAT.format(punishment.getEndDate()), punishment.getPunisher() == null ? "CONSOLE" : MojangUtils.getInfo(punishment.getPunisher().toString()).getUsername());
}
public String toJSON()
{
return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer()).create().toJson(this);

View File

@ -4,11 +4,36 @@ 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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
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.*;
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.command.Command;
import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.entity.Player;
@ -17,16 +42,6 @@ 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.SQLException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
public class PlexUtils extends PlexBase
{
public static Map<String, ChatColor> CHAT_COLOR_NAMES;
@ -36,6 +51,16 @@ public class PlexUtils extends PlexBase
"f5cd54c4-3a24-4213-9a56-c06c49594dff" // Taahh
);
private static final Random RANDOM;
private static final List<String> regxList = new ArrayList<>()
{{
add("y");
add("mo");
add("w");
add("d");
add("h");
add("m");
add("s");
}};
static
{
@ -60,17 +85,20 @@ public class PlexUtils extends PlexBase
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
{
Plex.get().getSqlConnection().getCon().close();
} catch (SQLException ignored)
}
catch (SQLException ignored)
{
}
} else if (Plex.get().getMongoConnection().getDatastore() != null)
}
else if (Plex.get().getMongoConnection().getDatastore() != null)
{
PlexLog.log("Successfully enabled MongoDB!");
}
@ -147,16 +175,66 @@ public class PlexUtils extends PlexBase
return f;
}
private static long a(String parse)
{
StringBuilder sb = new StringBuilder();
regxList.forEach(obj ->
{
if (parse.endsWith(obj))
{
sb.append(parse.split(obj)[0]);
}
});
return Long.parseLong(sb.toString());
}
private static TimeUnit verify(String arg)
{
TimeUnit unit = null;
for (String c : regxList)
{
if (arg.endsWith(c))
{
switch (c)
{
case "y" -> unit = TimeUnit.YEAR;
case "mo" -> unit = TimeUnit.MONTH;
case "w" -> unit = TimeUnit.WEEK;
case "d" -> unit = TimeUnit.DAY;
case "h" -> unit = TimeUnit.HOUR;
case "m" -> unit = TimeUnit.MINUTE;
case "s" -> unit = TimeUnit.SECOND;
}
break;
}
}
return (unit != null) ? unit : TimeUnit.DAY;
}
public static LocalDateTime parseDateOffset(String... time)
{
Instant instant = Instant.now();
for (String arg : time)
{
instant = instant.plusSeconds(verify(arg).get() * a(arg));
}
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault().getRules().getOffset(instant));
}
public static ChatColor getChatColorFromConfig(Config config, ChatColor def, String path)
{
ChatColor color;
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));
}
@ -188,13 +266,14 @@ public class PlexUtils extends PlexBase
for (String s : Plex.get().config.getStringList("worlds." + world.getName().toLowerCase(Locale.ROOT) + ".gameRules"))
{
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));
}
@ -236,7 +315,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;
@ -248,7 +327,8 @@ 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;
}
@ -257,13 +337,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);
}

View File

@ -0,0 +1,24 @@
package dev.plex.util;
public enum TimeUnit
{
SECOND(1L),
MINUTE(SECOND.get() * 60L),
HOUR(MINUTE.get() * 60L),
DAY(HOUR.get() * 24L),
WEEK(DAY.get() * 7L),
MONTH(DAY.get() * 30L),
YEAR(MONTH.get() * 12L);
private final long time;
TimeUnit(long time)
{
this.time = time;
}
public long get()
{
return time;
}
}

View File

@ -1,5 +1,5 @@
# Plex Configuration File
# For documentation, please visit: https://docs.plex.us.org
# For documentation, please visit: https://plex.us.org
server:
name: "Plexus"
@ -42,7 +42,7 @@ data:
port: 6379
password: ""
# See https://docs.plex.us.org/docs/customization/config#worlds for documentation
# See https://plex.us.org/docs/customization/config#worlds for documentation
worlds:
flatlands:
name: "Flatlands"

View File

@ -1,20 +1,14 @@
# Plex Messages File
# Reference https://docs.adventure.kyori.net/minimessage/format.html
# This file uses the MiniMessage system.
# Documentation available at https://docs.adventure.kyori.net/minimessage/format.html
# Messages in here will be placed in for certain commands, actions, etc.
# Warning: not all commands have customizable messages
# Base color - the main color prefix; will be used following each of the messages below
# Broadcast color - the color used when broadcasting a message
# Error color - the color of an error; will be used when an error is thrown from a command
baseColor: "7"
broadcastColor: "b"
errorColor: "c"
# Variables <v> - these are code-defined replacements for things that should be inserted into messages. (e.g. names, statuses, numbers)
# if any of these variables are supposed to be used within a message, some documentation is provided to give more context to what the variables indicate.
# you are unable to change the order the variables are used due to it being a code-side functionality.
# if you are wishing to change these messages it's recommended you use the same amount of variables as stated in the documentation, however it's not required.
# If any of these variables are supposed to be used within a message, some documentation is provided to give more context to what the variables indicate.
# You are unable to change the order the variables are used due to it being a code-side functionality.
# If you are wishing to change these messages it's recommended you use the same amount of variables as stated in the documentation, however it's not required.
# 1. Appeal URL
# 2. Reason
@ -44,14 +38,12 @@ frozePlayer: "<aqua><v> - Froze <v>"
# 1. The person who is unfreezing
# 2. The person who has been unfrozen
unfrozePlayer: "<aqua><v> - Unfroze <v>"
# 1. The person who is freezing
# 2. The person who has been frozen
mutedPlayer: "<aqua><v> - Muted <v>"
# 1. The person who is unfreezing
# 2. The person who has been unfrozen
unmutedPlayer: "<aqua><v> - Unmuted <v>"
noPermission: "<red>You cannot use this command!"
# 1. The rank required to use the command
noPermissionRank: "<red>You must be at least <v> to use this command!"
@ -107,17 +99,13 @@ banningPlayer: "<red><v> - Banning <v>"
# 1. The command sender
# 2. The player
unbanningPlayer: "<aqua><v> - Unbanning <v>"
playerNotBanned: "<red>That player is not banned!"
playerNotFrozen: "<red>That player is not frozen!"
playerNotMuted: "<red>That player is not muted!"
playerBanned: "<red>That player is already banned!"
playerFrozen: "<red>That player is already frozen!"
playerMuted: "<red>That player is already muted!"
muted: "<red>You are currently muted!"
muted: "<red>You are currently muted - STFU!"
teleportedToWorldSpawn: "<aqua>Teleporting to the local spawn"
toggleCommandSpy: "CommandSpy has been"
enabled: "enabled."