Compare commits

..

No commits in common. "main" and "2.4.0_Snapshot_2" have entirely different histories.

59 changed files with 627 additions and 4462 deletions

View File

@ -1,65 +0,0 @@
<p align="center">
<img src="https://i.imgur.com/eONeN6b.png" width="300">
</p>
---
# Links
* [Download](https://www.spigotmc.org/resources/opwhitelist.90739/)
* [Discord](http://dc.T2Code.net)
<img src="https://i.imgur.com/k2NgnGj.png" width="600">
### English
With OPSecurity you can specify usernames that are allowed to have OP or certain permissions. If someone enters the server with OP who is not on this whitelist, Optional can be kicked or have OP removed.
This plugin also protects players from getting OP via unauthorized ways, e.g. hacked client, because only players who are on the OP whitelist can get OP with the command /op.
You can also use a timer that checks every few seconds (adjustable) if there is a player with OP or a permission on the server who is not on the whitelist.
Please note that you can only give OP via the console to players who are on the whitelist!
Features:
- Protection against op hacks
- Protection for specific permissions
- Decide who may have OP
- Even via console protects OP Security
Just come to the support Discord for further questions.
---
### German
Mit OPSecurity kannst du Benutzernamen angeben Die OP oder bestimmte Permissions besitzen dürfen. Wenn jemand mit OP den Server betritt, der nicht auf dieser Whitelist steht, kann Optional gekickt werden oder OP entfernt bekommen.
Dieses Plugin schützt des Weiteren davor, dass Spieler sich OP über nicht erlaubte Wege besorgen, z.B. Hacked Client, denn nur Spieler die auf der OP Whitelist stehen können mit dem Befehl /op OP bekommen.
Es kann auch ein Timer verwendet werden der aller paar Sekunden (einstellbar) prüft ob sich ein Spieler mit OP oder einer Permission auf dem Server befindet dersich nicht auf der Whitelist befindet.
Beachte bitte, dass man auch über die Console nur Spielern OP geben kann die auf der Whitelist stehen!
Features:
- Schutz vor OP Hacks
- Schutz für bestimmte permissions
- Entscheide wer OP haben darf
- Selbst über Konsole schützt OP Security
Komm für weitere Fragen einfach auf den Support Discord.
<img src="https://i.imgur.com/wNDEjg9.png" width="600">
opsecurity.admin | For all Commands.
opsecurity.notify | Players with this permission will receive notifications fromOPSecurity.
/opsecurity | /opwl
/opsecurity help - Open the help.
/opsecurity info - See the current plugin version.
/opsecurity reload - Reloads the Plugin.
<img src="https://i.imgur.com/YbDziZO.png" width="600">
---
<img src="https://bstats.org/signatures/bukkit/OPWhitelist.svg" width="600">
<img src="https://i.imgur.com/HoZSt7c.png" width="600">

View File

@ -1,32 +0,0 @@
package de.jatitv.opsecurity;
public class Util {
public static String getInfoText() {
return "";
}
public static String getRequiredT2CodeLibVersion() {
return "13.0";
}
public static String getPrefix() {
return "§8[§2OP§4Security§8]";
}
public static Integer getSpigotID() {
return 90739;
}
public static Integer getBstatsID() {
return 10858;
}
public static String getSpigot() {
return "https://www.spigotmc.org/resources/" + getSpigotID();
}
public static String getDiscord() {
return net.t2code.t2codelib.Util.getDiscord();
}
}

View File

@ -1,136 +0,0 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.objects.PlayerObject;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.yaml.T2Cconfig;
import org.bukkit.Sound;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class SelectConfig {
// Config
public static Integer configVersion;
public static Boolean updateCheckOnJoin;
public static String language;
public static Boolean onlyOpCanUseThePlugin;
public static Boolean checkOnJoin;
public static Boolean checkOnInteract;
public static Boolean checkOnCommand;
public static Boolean checkOnChat;
public static String kickCommand;
public static Boolean notifyWarn;
public static Boolean notifySoundEnable;
public static Sound notifySound;
public static String notifySoundInput;
public static Boolean timerEnable;
public static int refreshTime;
public static Boolean opWhitelistEnable;
public static Boolean playerMustBeOnlineToOp;
public static Boolean noOPPlayerDeop;
public static Boolean sendPlayerDEOPmsg;
public static Boolean noOpPlayerKick;
public static Boolean customCommandEnable;
public static List<String> customKickCommand;
public static Boolean permissionWhitelistEnable;
public static List<String> permissions;
public static Boolean playerWhithPermissionKick;
public static Boolean permCommandEnable;
public static List<String> permCommand;
//help
public static void Help(CommandSender sender) {
if (!sender.hasPermission(Permissions.help)) {
sender.sendMessage(Util.getPrefix() + " §cYou do not have permission for OPSecurity! §7<" + Permissions.help + ">");
return;
}
sender.sendMessage(Util.getPrefix() + " §8----- §2OP§4Security §chelp §8-----");
sender.sendMessage(Util.getPrefix());
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity reload§8' §eReload the Plugin.");
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity help§8' §eOpens this help.");
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity info§8' §eCall the info about §2OP§4Security§e.");
sender.sendMessage(Util.getPrefix());
sender.sendMessage(Util.getPrefix() + " §8----------------------------");
}
public static void onSelect() {
File configYML = new File(Main.getPlugin().getDataFolder().getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(configYML);
Main.getOpHashMap().clear();
Main.getPermissionHashMap().clear();
configVersion = yamlConfiguration.getInt("ConfigVersion");
updateCheckOnJoin = yamlConfiguration.getBoolean("Plugin.UpdateCheckOnJoin");
language = yamlConfiguration.getString("Plugin.language");
onlyOpCanUseThePlugin = yamlConfiguration.getBoolean("Plugin.OnlyOPcanUseThePlugin");
checkOnJoin = yamlConfiguration.getBoolean("Check.OnJoin");
checkOnInteract = yamlConfiguration.getBoolean("Check.OnInteract");
checkOnCommand = yamlConfiguration.getBoolean("Check.OnCommand");
checkOnChat = yamlConfiguration.getBoolean("Check.OnChat");
timerEnable = yamlConfiguration.getBoolean("Check.Timer.Enable");
refreshTime = yamlConfiguration.getInt("Check.Timer.RefreshTime_inSec");
kickCommand = yamlConfiguration.getString("Kick.Command");
notifyWarn = yamlConfiguration.getBoolean("Notify.JoinWarn.Enable");
notifySoundEnable = yamlConfiguration.getBoolean("Notify.Sound.Enable");
notifySoundInput = yamlConfiguration.getString("Notify.Sound.Sound");
opWhitelistEnable = yamlConfiguration.getBoolean("OP_Whitelist.Enable");
playerMustBeOnlineToOp = yamlConfiguration.getBoolean("OP_Whitelist.PlayerMustBeOnlineToOp");
ArrayList<PlayerObject> opWhitelist = new ArrayList<>();
for (String key : yamlConfiguration.getConfigurationSection("OP_Whitelist.Whitelist").getKeys(false)) {
PlayerObject player = new PlayerObject(
yamlConfiguration.getString("OP_Whitelist.Whitelist." + key + ".UUID").replace("-", ""));
opWhitelist.add(player);
Main.getOpHashMap().put(key.toLowerCase(), player);
}
noOPPlayerDeop = yamlConfiguration.getBoolean("OP_Whitelist.noOpPlayerDeop.Enable");
sendPlayerDEOPmsg = yamlConfiguration.getBoolean("OP_Whitelist.noOpPlayerDeop.PlayerSendMessage");
noOpPlayerKick = yamlConfiguration.getBoolean("OP_Whitelist.noOpPlayerKick.Enable");
customCommandEnable = yamlConfiguration.getBoolean("OP_Whitelist.customCommands.Enable");
customKickCommand = yamlConfiguration.getStringList("OP_Whitelist.customCommands.Commands");
permissionWhitelistEnable = yamlConfiguration.getBoolean("Permission_Whitelist.Enable");
permissions = yamlConfiguration.getStringList("Permission_Whitelist.Permissions");
ArrayList<PlayerObject> permWhitelist = new ArrayList<>();
for (String key : yamlConfiguration.getConfigurationSection("Permission_Whitelist.Whitelist").getKeys(false)) {
PlayerObject player = new PlayerObject(
yamlConfiguration.getString("Permission_Whitelist.Whitelist." + key + ".UUID").replace("-", ""));
permWhitelist.add(player);
Main.getPermissionHashMap().put(key.toLowerCase(), player);
}
playerWhithPermissionKick = yamlConfiguration.getBoolean("Permission_Whitelist.PlayerWhithPermission_kick");
permCommandEnable = yamlConfiguration.getBoolean("Permission_Whitelist.customCommands.Enable");
permCommand = yamlConfiguration.getStringList("Permission_Whitelist.customCommands.Commands");
}
public static void sound() {
notifySound = T2Cconfig.checkSound(CreateConfig.Notify_Sound_1_8, CreateConfig.Notify_Sound_1_9_to_1_12, CreateConfig.Notify_Sound_from_1_13, notifySoundInput, Util.getPrefix());
}
}

View File

@ -1,161 +0,0 @@
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.commands.T2Ccmd;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Creplace;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class Check {
public static Boolean onCheck(Player player, Boolean join) {
if (SelectConfig.opWhitelistEnable) {
if (player.isOp()) {
if (opWhitelist(player)) {
return false;
}
if (join) {
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleOnJoin.replace("[player]", player.getName())));
}
if (SelectConfig.notifyWarn) {
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
if (join) {
notifyperm.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleOnJoin.replace("[player]", player.getName())));
} else notifyperm.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
if (SelectConfig.notifySoundEnable) {
notifyperm.playSound(player.getLocation(), SelectConfig.notifySound, 3, 1);
}
}
}
}
if (SelectConfig.noOpPlayerKick && SelectConfig.noOPPlayerDeop) {
player.setOp(false);
T2Ccmd.console(SelectConfig.kickCommand.replace("[player]", player.getName())
.replace("[reason]", T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_kick + "\n" + "\n" + SelectMessages.OP_deop)));
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
} else {
if (SelectConfig.noOpPlayerKick) {
T2Ccmd.console(SelectConfig.kickCommand.replace("[player]", player.getName()).replace("[reason]", T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_kick)));
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
notifyperm.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleKick.replace("[player]", player.getName())
+ "\n" + SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
}
}
}
if (SelectConfig.noOPPlayerDeop) {
player.setOp(false);
if (SelectConfig.sendPlayerDEOPmsg) {
new BukkitRunnable() {
@Override
public void run() {
player.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_deop));
}
}.runTaskLater(Main.getPlugin(), 5L);
}
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
notifyperm.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
}
}
}
}
if (SelectConfig.customCommandEnable) {
for (String cmd : SelectConfig.customKickCommand) {
T2Ccmd.console(T2Creplace.replace(Util.getPrefix(), cmd.replace("[player]", player.getName())));
}
}
return true;
}
}
if (SelectConfig.permissionWhitelistEnable) {
for (String s : SelectConfig.permissions) {
if (player.hasPermission(s)) {
if (!permWhitelist(player)) {
if (join) {
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_consoleOnJoin.replace("[player]", player.getName()).replace("[perm]", s)));
}
if (SelectConfig.notifyWarn) {
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
if (join) {
notifyperm.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_consoleOnJoin.replace("[player]",
player.getName()).replace("[perm]", s)));
} else notifyperm.sendMessage(T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_consoleKick.replace("[player]",
player.getName()).replace("[perm]", s)));
if (SelectConfig.notifySoundEnable) {
notifyperm.playSound(player.getLocation(), SelectConfig.notifySound, 3, 1);
}
}
}
}
if (SelectConfig.playerWhithPermissionKick && SelectConfig.permCommandEnable) {
T2Ccmd.console(SelectConfig.kickCommand.replace("[player]", player.getName()).replace("[reason]", T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_kick)));
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_consoleKick.replace("[player]",
player.getName()).replace("[perm]", s)));
for (String cmd : SelectConfig.permCommand) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), cmd.replace("[player]", player.getName()).replace("[perm]", s));
}
}
if (SelectConfig.playerWhithPermissionKick) {
T2Ccmd.console(SelectConfig.kickCommand.replace("[player]", player.getName()).replace("[reason]", T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_kick)));
T2Csend.console(T2Creplace.replace(Util.getPrefix(), SelectMessages.Perm_consoleKick.replace("[player]",
player.getName()).replace("[perm]", s)));
}
if (SelectConfig.permCommandEnable) {
for (String cmd : SelectConfig.permCommand) {
T2Ccmd.console(cmd.replace("[player]", player.getName()).replace("[perm]", s));
}
}
return true;
}
}
}
}
return false;
}
private static Boolean opWhitelist(Player player) {
if (Main.getOpHashMap().containsKey(player.getName().toLowerCase())) {
if (Main.getOpHashMap().get(player.getName().toLowerCase()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
return true;
} else {
T2Csend.console(SelectMessages.ExactReason.replace("[reason]", "Player UUID: " + player.getUniqueId().toString() + " not whitelisted"));
return false;
}
} else {
T2Csend.console(SelectMessages.ExactReason.replace("[reason]", "Player name: " + player.getName() + " not whitelisted"));
return false;
}
}
private static Boolean permWhitelist(Player player) {
if (Main.getPermissionHashMap().containsKey(player.getName().toLowerCase())) {
if (Main.getPermissionHashMap().get(player.getName().toLowerCase()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
return true;
} else {
T2Csend.console(SelectMessages.ExactReason.replace("[reason]", "Player UUID: " + player.getUniqueId().toString() + " not whitelisted"));
return false;
}
} else {
T2Csend.console(SelectMessages.ExactReason.replace("[reason]", "Player name: " + player.getName() + " not whitelisted"));
return false;
}
}
}

View File

@ -1,96 +0,0 @@
package de.jatitv.opsecurity.system;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.objects.PlayerObject;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
public final class Main extends JavaPlugin {
private static List<String> autor;
private static String version;
private static Main plugin;
private static boolean enable;
public static File getPath() {
return plugin.getDataFolder();
}
private static HashMap<String, PlayerObject> opHashMap = new HashMap<String, PlayerObject>();
private static HashMap<String, PlayerObject> permissionHashMap = new HashMap<String, PlayerObject>();
@Override
public void onEnable() {
// Plugin startup logic
plugin = this;
try {
enable();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void enable() {
autor = plugin.getDescription().getAuthors();
version = plugin.getDescription().getVersion();
if (pluginNotFound("T2CodeLib", 96388, Util.getRequiredT2CodeLibVersion())) return;
Load.onLoad(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getSpigotID(), Util.getDiscord(), Util.getBstatsID());
enable = true;
}
@Override
public void onDisable() {
// Plugin shutdown logic
if (enable) T2Ctemplate.onDisable(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord());
}
public static Boolean pluginNotFound(String pl, Integer spigotID, String ver) {
if (Bukkit.getPluginManager().getPlugin(pl) == null) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4could not be found. Please download it here: "
+ "§6https://spigotmc.org/resources/" + pl + "." + spigotID + " §4to be able to use this plugin.");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
} else {
String plVer = Bukkit.getPluginManager().getPlugin(pl).getDescription().getVersion();
if (ver.contains("_")) {
if (!plVer.equals(ver)) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4is out of date! This plugin requires the version §2"
+ ver + " §4of §6" + pl + " §4Please use this version! Please download it here or contact us in Discord: §6https://spigotmc.org/resources/"
+ pl + "." + spigotID + " Or contact us in Discord: http://dc.t2code.net");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
}
return false;
}
String[] split = plVer.split("_");
if (Double.parseDouble(split[0]) < Double.parseDouble(ver)) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4is out of date! This plugin requires at least version §2"
+ ver + " §4of §6" + pl + " §4Please update it here: §6https://spigotmc.org/resources/" + pl + "." + spigotID
+ " §4to use this version of " + plugin.getDescription().getName() + ".");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
}
return false;
}
}
public static Main getPlugin() {
return plugin;
}
public static HashMap<String, PlayerObject> getOpHashMap() {
return opHashMap;
}
public static HashMap<String, PlayerObject> getPermissionHashMap() {
return permissionHashMap;
}
}

View File

@ -1,846 +0,0 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.system;
import de.jatitv.opsecurity.Util;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
public class Metrics {
public static void Bstats() {
int pluginId = Util.getBstatsID(); // <-- Replace with the id of your plugin!
Metrics metrics = new Metrics(Main.getPlugin(), pluginId);
}
private final Plugin plugin;
private final MetricsBase metricsBase;
/**
* Creates a new Metrics instance.
*
* @param plugin Your plugin instance.
* @param serviceId The id of the service. It can be found at <a
* href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(JavaPlugin plugin, int serviceId) {
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
if (!config.isSet("serverUuid")) {
config.addDefault("enabled", true);
config.addDefault("serverUuid", UUID.randomUUID().toString());
config.addDefault("logFailedRequests", false);
config.addDefault("logSentData", false);
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config
.options()
.header(
"bStats (https://bStats.org) collects some basic information for plugin authors, like how\n"
+ "many people use their plugin and their total player count. It's recommended to keep bStats\n"
+ "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n"
+ "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n"
+ "anonymous.")
.copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) {
}
}
// Load the data
boolean enabled = config.getBoolean("enabled", true);
String serverUUID = config.getString("serverUuid");
boolean logErrors = config.getBoolean("logFailedRequests", false);
boolean logSentData = config.getBoolean("logSentData", false);
boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false);
metricsBase =
new MetricsBase(
"bukkit",
serverUUID,
serviceId,
enabled,
this::appendPlatformData,
this::appendServiceData,
submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),
plugin::isEnabled,
(message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),
(message) -> this.plugin.getLogger().log(Level.INFO, message),
logErrors,
logSentData,
logResponseStatusText);
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
metricsBase.addCustomChart(chart);
}
private void appendPlatformData(JsonObjectBuilder builder) {
builder.appendField("playerAmount", getPlayerAmount());
builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0);
builder.appendField("bukkitVersion", Bukkit.getVersion());
builder.appendField("bukkitName", Bukkit.getName());
builder.appendField("javaVersion", System.getProperty("java.version"));
builder.appendField("osName", System.getProperty("os.name"));
builder.appendField("osArch", System.getProperty("os.arch"));
builder.appendField("osVersion", System.getProperty("os.version"));
builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
}
private void appendServiceData(JsonObjectBuilder builder) {
builder.appendField("pluginVersion", plugin.getDescription().getVersion());
}
private int getPlayerAmount() {
try {
// Around MC 1.8 the return type was changed from an array to a collection,
// This fixes java.lang.NoSuchMethodError:
// org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
return onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
// Just use the new method if the reflection failed
return Bukkit.getOnlinePlayers().size();
}
}
public static class MetricsBase {
/** The version of the Metrics class. */
public static final String METRICS_VERSION = "2.2.1";
private static final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics"));
private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
private final String platform;
private final String serverUuid;
private final int serviceId;
private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;
private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;
private final Consumer<Runnable> submitTaskConsumer;
private final Supplier<Boolean> checkServiceEnabledSupplier;
private final BiConsumer<String, Throwable> errorLogger;
private final Consumer<String> infoLogger;
private final boolean logErrors;
private final boolean logSentData;
private final boolean logResponseStatusText;
private final Set<CustomChart> customCharts = new HashSet<>();
private final boolean enabled;
/**
* Creates a new MetricsBase class instance.
*
* @param platform The platform of the service.
* @param serviceId The id of the service.
* @param serverUuid The server uuid.
* @param enabled Whether or not data sending is enabled.
* @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
* appends all platform-specific data.
* @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
* appends all service-specific data.
* @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be
* used to delegate the data collection to a another thread to prevent errors caused by
* concurrency. Can be {@code null}.
* @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.
* @param errorLogger A consumer that accepts log message and an error.
* @param infoLogger A consumer that accepts info log messages.
* @param logErrors Whether or not errors should be logged.
* @param logSentData Whether or not the sent data should be logged.
* @param logResponseStatusText Whether or not the response status text should be logged.
*/
public MetricsBase(
String platform,
String serverUuid,
int serviceId,
boolean enabled,
Consumer<JsonObjectBuilder> appendPlatformDataConsumer,
Consumer<JsonObjectBuilder> appendServiceDataConsumer,
Consumer<Runnable> submitTaskConsumer,
Supplier<Boolean> checkServiceEnabledSupplier,
BiConsumer<String, Throwable> errorLogger,
Consumer<String> infoLogger,
boolean logErrors,
boolean logSentData,
boolean logResponseStatusText) {
this.platform = platform;
this.serverUuid = serverUuid;
this.serviceId = serviceId;
this.enabled = enabled;
this.appendPlatformDataConsumer = appendPlatformDataConsumer;
this.appendServiceDataConsumer = appendServiceDataConsumer;
this.submitTaskConsumer = submitTaskConsumer;
this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;
this.errorLogger = errorLogger;
this.infoLogger = infoLogger;
this.logErrors = logErrors;
this.logSentData = logSentData;
this.logResponseStatusText = logResponseStatusText;
checkRelocation();
if (enabled) {
startSubmitting();
}
}
public void addCustomChart(CustomChart chart) {
this.customCharts.add(chart);
}
private void startSubmitting() {
final Runnable submitTask =
() -> {
if (!enabled || !checkServiceEnabledSupplier.get()) {
// Submitting data or service is disabled
scheduler.shutdown();
return;
}
if (submitTaskConsumer != null) {
submitTaskConsumer.accept(this::submitData);
} else {
this.submitData();
}
};
// Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution
// of requests on the
// bStats backend. To circumvent this problem, we introduce some randomness into the initial
// and second delay.
// WARNING: You must not modify and part of this Metrics class, including the submit delay or
// frequency!
// WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it!
long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);
scheduler.scheduleAtFixedRate(
submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
}
private void submitData() {
final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();
appendPlatformDataConsumer.accept(baseJsonBuilder);
final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();
appendServiceDataConsumer.accept(serviceJsonBuilder);
JsonObjectBuilder.JsonObject[] chartData =
customCharts.stream()
.map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))
.filter(Objects::nonNull)
.toArray(JsonObjectBuilder.JsonObject[]::new);
serviceJsonBuilder.appendField("id", serviceId);
serviceJsonBuilder.appendField("customCharts", chartData);
baseJsonBuilder.appendField("service", serviceJsonBuilder.build());
baseJsonBuilder.appendField("serverUUID", serverUuid);
baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION);
JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();
scheduler.execute(
() -> {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logErrors) {
errorLogger.accept("Could not submit bStats metrics data", e);
}
}
});
}
private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
if (logSentData) {
infoLogger.accept("Sent bStats metrics data: " + data.toString());
}
String url = String.format(REPORT_URL, platform);
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("User-Agent", "Metrics-Service/1");
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData);
}
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
if (logResponseStatusText) {
infoLogger.accept("Sent data to bStats and received response: " + builder);
}
}
/** Checks that the class was properly relocated. */
private void checkRelocation() {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null
|| !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little
// "trick" ... :D
final String defaultPackage =
new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
final String examplePackage =
new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure no one just copy & pastes the example and uses the wrong package
// names
if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)
|| MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
/**
* Gzips the given string.
*
* @param str The string to gzip.
* @return The gzipped string.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return outputStream.toByteArray();
}
}
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()});
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public abstract static class CustomChart {
private final String chartId;
protected CustomChart(String chartId) {
if (chartId == null) {
throw new IllegalArgumentException("chartId must not be null");
}
this.chartId = chartId;
}
public JsonObjectBuilder.JsonObject getRequestJsonObject(
BiConsumer<String, Throwable> errorLogger, boolean logErrors) {
JsonObjectBuilder builder = new JsonObjectBuilder();
builder.appendField("chartId", chartId);
try {
JsonObjectBuilder.JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
builder.appendField("data", data);
} catch (Throwable t) {
if (logErrors) {
errorLogger.accept("Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return builder.build();
}
protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;
}
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("value", value).build();
}
}
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("value", value).build();
}
}
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
/**
* An extremely simple JSON builder.
*
* <p>While this class is neither feature-rich nor the most performant one, it's sufficient enough
* for its use-case.
*/
public static class JsonObjectBuilder {
private StringBuilder builder = new StringBuilder();
private boolean hasAtLeastOneField = false;
public JsonObjectBuilder() {
builder.append("{");
}
/**
* Appends a null field to the JSON.
*
* @param key The key of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendNull(String key) {
appendFieldUnescaped(key, "null");
return this;
}
/**
* Appends a string field to the JSON.
*
* @param key The key of the field.
* @param value The value of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, String value) {
if (value == null) {
throw new IllegalArgumentException("JSON value must not be null");
}
appendFieldUnescaped(key, "\"" + escape(value) + "\"");
return this;
}
/**
* Appends an integer field to the JSON.
*
* @param key The key of the field.
* @param value The value of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, int value) {
appendFieldUnescaped(key, String.valueOf(value));
return this;
}
/**
* Appends an object to the JSON.
*
* @param key The key of the field.
* @param object The object.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, JsonObject object) {
if (object == null) {
throw new IllegalArgumentException("JSON object must not be null");
}
appendFieldUnescaped(key, object.toString());
return this;
}
/**
* Appends a string array to the JSON.
*
* @param key The key of the field.
* @param values The string array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, String[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values)
.map(value -> "\"" + escape(value) + "\"")
.collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends an integer array to the JSON.
*
* @param key The key of the field.
* @param values The integer array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, int[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends an object array to the JSON.
*
* @param key The key of the field.
* @param values The integer array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, JsonObject[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends a field to the object.
*
* @param key The key of the field.
* @param escapedValue The escaped value of the field.
*/
private void appendFieldUnescaped(String key, String escapedValue) {
if (builder == null) {
throw new IllegalStateException("JSON has already been built");
}
if (key == null) {
throw new IllegalArgumentException("JSON key must not be null");
}
if (hasAtLeastOneField) {
builder.append(",");
}
builder.append("\"").append(escape(key)).append("\":").append(escapedValue);
hasAtLeastOneField = true;
}
/**
* Builds the JSON string and invalidates this builder.
*
* @return The built JSON string.
*/
public JsonObject build() {
if (builder == null) {
throw new IllegalStateException("JSON has already been built");
}
JsonObject object = new JsonObject(builder.append("}").toString());
builder = null;
return object;
}
/**
* Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
*
* <p>This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'.
* Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n").
*
* @param value The value to escape.
* @return The escaped value.
*/
private static String escape(String value) {
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '"') {
builder.append("\\\"");
} else if (c == '\\') {
builder.append("\\\\");
} else if (c <= '\u000F') {
builder.append("\\u000").append(Integer.toHexString(c));
} else if (c <= '\u001F') {
builder.append("\\u00").append(Integer.toHexString(c));
} else {
builder.append(c);
}
}
return builder.toString();
}
/**
* A super simple representation of a JSON object.
*
* <p>This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not
* allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,
* JsonObject)}.
*/
public static class JsonObject {
private final String value;
private JsonObject(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
}
}

View File

@ -1,32 +0,0 @@
package de.jatitv.opsecurity.system;
import net.t2code.t2codelib.SPIGOT.api.register.T2Cregister;
import org.bukkit.permissions.PermissionDefault;
public class Permissions {
public static final String key = "opsecurity.";
public static final String notify = key + "notify";
public static final String updatemsg = key + "updatemsg";
public static final String reload = key + "command.reload";
public static final String info = key + "command.info";
public static final String help = key + "command.help";
public static final String admin = key + "admin";
public static final PermissionDefault op = PermissionDefault.OP;
public static final PermissionDefault notOp = PermissionDefault.NOT_OP;
protected static void register() {
T2Cregister.permission(notify, op, Main.getPlugin());
T2Cregister.permissionDescription(notify,"Players with this permission get the update message when joining if an update is available",Main.getPlugin());
T2Cregister.permission(updatemsg, op, Main.getPlugin());
T2Cregister.permission(reload, op, Main.getPlugin());
T2Cregister.permission(info, op, Main.getPlugin());
T2Cregister.permission(help, op, Main.getPlugin());
T2Cregister.permission(admin, op, notify, true, Main.getPlugin());
T2Cregister.permission(admin, op, updatemsg, true, Main.getPlugin());
T2Cregister.permission(admin, op, reload, true, Main.getPlugin());
T2Cregister.permission(admin, op, info, true, Main.getPlugin());
T2Cregister.permission(admin, op, help, true, Main.getPlugin());
}
}

View File

@ -1,846 +0,0 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.system;
import de.jatitv.opsecurity.Util;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
public class Metrics {
public static void Bstats() {
int pluginId = Util.getBstatsID(); // <-- Replace with the id of your plugin!
Metrics metrics = new Metrics(Main.getPlugin(), pluginId);
}
private final Plugin plugin;
private final MetricsBase metricsBase;
/**
* Creates a new Metrics instance.
*
* @param plugin Your plugin instance.
* @param serviceId The id of the service. It can be found at <a
* href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(JavaPlugin plugin, int serviceId) {
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
if (!config.isSet("serverUuid")) {
config.addDefault("enabled", true);
config.addDefault("serverUuid", UUID.randomUUID().toString());
config.addDefault("logFailedRequests", false);
config.addDefault("logSentData", false);
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config
.options()
.header(
"bStats (https://bStats.org) collects some basic information for plugin authors, like how\n"
+ "many people use their plugin and their total player count. It's recommended to keep bStats\n"
+ "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n"
+ "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n"
+ "anonymous.")
.copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) {
}
}
// Load the data
boolean enabled = config.getBoolean("enabled", true);
String serverUUID = config.getString("serverUuid");
boolean logErrors = config.getBoolean("logFailedRequests", false);
boolean logSentData = config.getBoolean("logSentData", false);
boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false);
metricsBase =
new MetricsBase(
"bukkit",
serverUUID,
serviceId,
enabled,
this::appendPlatformData,
this::appendServiceData,
submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),
plugin::isEnabled,
(message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),
(message) -> this.plugin.getLogger().log(Level.INFO, message),
logErrors,
logSentData,
logResponseStatusText);
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
metricsBase.addCustomChart(chart);
}
private void appendPlatformData(JsonObjectBuilder builder) {
builder.appendField("playerAmount", getPlayerAmount());
builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0);
builder.appendField("bukkitVersion", Bukkit.getVersion());
builder.appendField("bukkitName", Bukkit.getName());
builder.appendField("javaVersion", System.getProperty("java.version"));
builder.appendField("osName", System.getProperty("os.name"));
builder.appendField("osArch", System.getProperty("os.arch"));
builder.appendField("osVersion", System.getProperty("os.version"));
builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
}
private void appendServiceData(JsonObjectBuilder builder) {
builder.appendField("pluginVersion", plugin.getDescription().getVersion());
}
private int getPlayerAmount() {
try {
// Around MC 1.8 the return type was changed from an array to a collection,
// This fixes java.lang.NoSuchMethodError:
// org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
return onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
// Just use the new method if the reflection failed
return Bukkit.getOnlinePlayers().size();
}
}
public static class MetricsBase {
/** The version of the Metrics class. */
public static final String METRICS_VERSION = "2.2.1";
private static final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics"));
private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
private final String platform;
private final String serverUuid;
private final int serviceId;
private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;
private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;
private final Consumer<Runnable> submitTaskConsumer;
private final Supplier<Boolean> checkServiceEnabledSupplier;
private final BiConsumer<String, Throwable> errorLogger;
private final Consumer<String> infoLogger;
private final boolean logErrors;
private final boolean logSentData;
private final boolean logResponseStatusText;
private final Set<CustomChart> customCharts = new HashSet<>();
private final boolean enabled;
/**
* Creates a new MetricsBase class instance.
*
* @param platform The platform of the service.
* @param serviceId The id of the service.
* @param serverUuid The server uuid.
* @param enabled Whether or not data sending is enabled.
* @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
* appends all platform-specific data.
* @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
* appends all service-specific data.
* @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be
* used to delegate the data collection to a another thread to prevent errors caused by
* concurrency. Can be {@code null}.
* @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.
* @param errorLogger A consumer that accepts log message and an error.
* @param infoLogger A consumer that accepts info log messages.
* @param logErrors Whether or not errors should be logged.
* @param logSentData Whether or not the sent data should be logged.
* @param logResponseStatusText Whether or not the response status text should be logged.
*/
public MetricsBase(
String platform,
String serverUuid,
int serviceId,
boolean enabled,
Consumer<JsonObjectBuilder> appendPlatformDataConsumer,
Consumer<JsonObjectBuilder> appendServiceDataConsumer,
Consumer<Runnable> submitTaskConsumer,
Supplier<Boolean> checkServiceEnabledSupplier,
BiConsumer<String, Throwable> errorLogger,
Consumer<String> infoLogger,
boolean logErrors,
boolean logSentData,
boolean logResponseStatusText) {
this.platform = platform;
this.serverUuid = serverUuid;
this.serviceId = serviceId;
this.enabled = enabled;
this.appendPlatformDataConsumer = appendPlatformDataConsumer;
this.appendServiceDataConsumer = appendServiceDataConsumer;
this.submitTaskConsumer = submitTaskConsumer;
this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;
this.errorLogger = errorLogger;
this.infoLogger = infoLogger;
this.logErrors = logErrors;
this.logSentData = logSentData;
this.logResponseStatusText = logResponseStatusText;
checkRelocation();
if (enabled) {
startSubmitting();
}
}
public void addCustomChart(CustomChart chart) {
this.customCharts.add(chart);
}
private void startSubmitting() {
final Runnable submitTask =
() -> {
if (!enabled || !checkServiceEnabledSupplier.get()) {
// Submitting data or service is disabled
scheduler.shutdown();
return;
}
if (submitTaskConsumer != null) {
submitTaskConsumer.accept(this::submitData);
} else {
this.submitData();
}
};
// Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution
// of requests on the
// bStats backend. To circumvent this problem, we introduce some randomness into the initial
// and second delay.
// WARNING: You must not modify and part of this Metrics class, including the submit delay or
// frequency!
// WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it!
long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);
scheduler.scheduleAtFixedRate(
submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
}
private void submitData() {
final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();
appendPlatformDataConsumer.accept(baseJsonBuilder);
final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();
appendServiceDataConsumer.accept(serviceJsonBuilder);
JsonObjectBuilder.JsonObject[] chartData =
customCharts.stream()
.map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))
.filter(Objects::nonNull)
.toArray(JsonObjectBuilder.JsonObject[]::new);
serviceJsonBuilder.appendField("id", serviceId);
serviceJsonBuilder.appendField("customCharts", chartData);
baseJsonBuilder.appendField("service", serviceJsonBuilder.build());
baseJsonBuilder.appendField("serverUUID", serverUuid);
baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION);
JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();
scheduler.execute(
() -> {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logErrors) {
errorLogger.accept("Could not submit bStats metrics data", e);
}
}
});
}
private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
if (logSentData) {
infoLogger.accept("Sent bStats metrics data: " + data.toString());
}
String url = String.format(REPORT_URL, platform);
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("User-Agent", "Metrics-Service/1");
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData);
}
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
if (logResponseStatusText) {
infoLogger.accept("Sent data to bStats and received response: " + builder);
}
}
/** Checks that the class was properly relocated. */
private void checkRelocation() {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null
|| !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little
// "trick" ... :D
final String defaultPackage =
new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
final String examplePackage =
new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure no one just copy & pastes the example and uses the wrong package
// names
if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)
|| MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
/**
* Gzips the given string.
*
* @param str The string to gzip.
* @return The gzipped string.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return outputStream.toByteArray();
}
}
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()});
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
// Skip this invalid
continue;
}
allSkipped = false;
valuesBuilder.appendField(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
public abstract static class CustomChart {
private final String chartId;
protected CustomChart(String chartId) {
if (chartId == null) {
throw new IllegalArgumentException("chartId must not be null");
}
this.chartId = chartId;
}
public JsonObjectBuilder.JsonObject getRequestJsonObject(
BiConsumer<String, Throwable> errorLogger, boolean logErrors) {
JsonObjectBuilder builder = new JsonObjectBuilder();
builder.appendField("chartId", chartId);
try {
JsonObjectBuilder.JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
builder.appendField("data", data);
} catch (Throwable t) {
if (logErrors) {
errorLogger.accept("Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return builder.build();
}
protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;
}
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("value", value).build();
}
}
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("value", value).build();
}
}
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
/**
* An extremely simple JSON builder.
*
* <p>While this class is neither feature-rich nor the most performant one, it's sufficient enough
* for its use-case.
*/
public static class JsonObjectBuilder {
private StringBuilder builder = new StringBuilder();
private boolean hasAtLeastOneField = false;
public JsonObjectBuilder() {
builder.append("{");
}
/**
* Appends a null field to the JSON.
*
* @param key The key of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendNull(String key) {
appendFieldUnescaped(key, "null");
return this;
}
/**
* Appends a string field to the JSON.
*
* @param key The key of the field.
* @param value The value of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, String value) {
if (value == null) {
throw new IllegalArgumentException("JSON value must not be null");
}
appendFieldUnescaped(key, "\"" + escape(value) + "\"");
return this;
}
/**
* Appends an integer field to the JSON.
*
* @param key The key of the field.
* @param value The value of the field.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, int value) {
appendFieldUnescaped(key, String.valueOf(value));
return this;
}
/**
* Appends an object to the JSON.
*
* @param key The key of the field.
* @param object The object.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, JsonObject object) {
if (object == null) {
throw new IllegalArgumentException("JSON object must not be null");
}
appendFieldUnescaped(key, object.toString());
return this;
}
/**
* Appends a string array to the JSON.
*
* @param key The key of the field.
* @param values The string array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, String[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values)
.map(value -> "\"" + escape(value) + "\"")
.collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends an integer array to the JSON.
*
* @param key The key of the field.
* @param values The integer array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, int[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends an object array to the JSON.
*
* @param key The key of the field.
* @param values The integer array.
* @return A reference to this object.
*/
public JsonObjectBuilder appendField(String key, JsonObject[] values) {
if (values == null) {
throw new IllegalArgumentException("JSON values must not be null");
}
String escapedValues =
Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(","));
appendFieldUnescaped(key, "[" + escapedValues + "]");
return this;
}
/**
* Appends a field to the object.
*
* @param key The key of the field.
* @param escapedValue The escaped value of the field.
*/
private void appendFieldUnescaped(String key, String escapedValue) {
if (builder == null) {
throw new IllegalStateException("JSON has already been built");
}
if (key == null) {
throw new IllegalArgumentException("JSON key must not be null");
}
if (hasAtLeastOneField) {
builder.append(",");
}
builder.append("\"").append(escape(key)).append("\":").append(escapedValue);
hasAtLeastOneField = true;
}
/**
* Builds the JSON string and invalidates this builder.
*
* @return The built JSON string.
*/
public JsonObject build() {
if (builder == null) {
throw new IllegalStateException("JSON has already been built");
}
JsonObject object = new JsonObject(builder.append("}").toString());
builder = null;
return object;
}
/**
* Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
*
* <p>This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'.
* Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n").
*
* @param value The value to escape.
* @return The escaped value.
*/
private static String escape(String value) {
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '"') {
builder.append("\\\"");
} else if (c == '\\') {
builder.append("\\\\");
} else if (c <= '\u000F') {
builder.append("\\u000").append(Integer.toHexString(c));
} else if (c <= '\u001F') {
builder.append("\\u00").append(Integer.toHexString(c));
} else {
builder.append(c);
}
}
return builder.toString();
}
/**
* A super simple representation of a JSON object.
*
* <p>This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not
* allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,
* JsonObject)}.
*/
public static class JsonObject {
private final String value;
private JsonObject(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
}
}

View File

@ -1,113 +0,0 @@
# User-specific stuff
.idea/
*.iml
*.ipr
*.iws
# IntelliJ
out/
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.flattened-pom.xml
# Common working directory
run/

View File

@ -1,95 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.t2code</groupId>
<artifactId>T2C-OPSecurity</artifactId>
<version>3.3_DEV-24</version>
<packaging>jar</packaging>
<name>T2C-OPSecurity</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>${project.artifactId}_${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<!-- spigot -->
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<!-- t2code -->
<repository>
<id>T2Code</id>
<url>https://repo.t2code.net/repository/T2Code/</url>
</repository>
</repositories>
<dependencies>
<!-- spigot -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.20-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- t2code -->
<dependency>
<groupId>net.t2code</groupId>
<artifactId>T2CodeLib</artifactId>
<version>16.7</version>
<classifier>dev-24</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
</dependencies>
</project>

View File

@ -1,61 +0,0 @@
package net.t2code.opsecurity.API;
import net.t2code.opsecurity.check.OpCheck;
import net.t2code.opsecurity.check.PermissionCheck;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.config.permissionWhitelist.PermissionWhitelist;
import net.t2code.opsecurity.objects.PlayerCache;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class T2COpSecAPI {
public static boolean checkOPWhiteList(Player player) {
if (!(boolean) OPWhitelist.VALUES.enable.getValue()) return true;
String debug = T2C_Debug.debugCode();
return OpCheck.opWhitelist(player, debug);
}
public static boolean checkPermissionWhiteList(Player player, String debug) {
if (!(boolean) PermissionWhitelist.VALUES.enable.getValue()) return true;
return PermissionCheck.permWhitelist(player, debug);
}
public static T2COpSecAPIPlayerStatus detailCheckOPWhiteList(Player player) {
if (!(boolean) OPWhitelist.VALUES.enable.getValue()) return T2COpSecAPIPlayerStatus.playerOnOpWhitelist;
List<String> nameList = new ArrayList<>();
List<String> uuidList = new ArrayList<>();
for (Map.Entry<String, PlayerObject> playerObject : PlayerCache.getOpHashMap().entrySet()) {
nameList.add(playerObject.getValue().playerName);
uuidList.add(playerObject.getValue().uuid);
}
if (!nameList.contains(player.getName())) {
return T2COpSecAPIPlayerStatus.playerNameNotOnTheOpWhitelist;
}
if (!uuidList.contains(player.getUniqueId().toString().replace("-", ""))) {
return T2COpSecAPIPlayerStatus.playerUuidNotOnTheOpWhitelist;
}
return T2COpSecAPIPlayerStatus.playerOnOpWhitelist;
}
public static T2COpSecAPIPlayerStatus detailCheckPermissionWhiteList(Player player) {
if (!(boolean)PermissionWhitelist.VALUES.enable.getValue()) return T2COpSecAPIPlayerStatus.playerOnPermissionWhitelist;
List<String> nameList = new ArrayList<>();
List<String> uuidList = new ArrayList<>();
for (Map.Entry<String, PlayerObject> playerObject : PlayerCache.getPermissionHashMap().entrySet()) {
nameList.add(playerObject.getValue().playerName);
uuidList.add(playerObject.getValue().uuid);
}
if (!nameList.contains(player.getName())) {
return T2COpSecAPIPlayerStatus.playerNameNotOnThePermissionWhitelist;
}
if (!uuidList.contains(player.getUniqueId().toString().replace("-", ""))) {
return T2COpSecAPIPlayerStatus.playerUuidNotOnThePermissionWhitelist;
}
return T2COpSecAPIPlayerStatus.playerOnPermissionWhitelist;
}
}

View File

@ -1,10 +0,0 @@
package net.t2code.opsecurity.API;
public enum T2COpSecAPIPlayerStatus {
playerOnOpWhitelist,
playerNameNotOnTheOpWhitelist,
playerUuidNotOnTheOpWhitelist,
playerOnPermissionWhitelist,
playerNameNotOnThePermissionWhitelist,
playerUuidNotOnThePermissionWhitelist
}

View File

@ -1,110 +0,0 @@
package net.t2code.opsecurity.check;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.language.Languages;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.events.Events;
import net.t2code.opsecurity.objects.PlayerCache;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.BungeeSenderReceiver;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.commands.T2C_Cmd;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Send;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.Map;
public class OpCheck {
public static Boolean onCheck(Player player, Boolean join, String debug) {
if (!(boolean) OPWhitelist.VALUES.enable.getValue()) return false;
if (!player.isOp()) return false;
if (opWhitelist(player, debug)) return false;
if (join) T2C_Send.console(Languages.VALUES.opWhitelistNotifyOnJoin.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
Bukkit.getScheduler().runTask(Main.getPlugin(), new Runnable() {
@Override
public void run() {
execute(player, join, debug);
}
});
return true;
}
private static void execute(Player player, Boolean join, String debug) {
if ((boolean)Config.VALUES.notifyJoinWarning.getValue() && join) {
if ((boolean)Config.VALUES.notifyBungee.getValue()) {
BungeeSenderReceiver.sendToBungee(Languages.VALUES.opWhitelistNotifyOnJoin.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
} else
Events.notifyPlayer(Languages.VALUES.opWhitelistNotifyOnJoin.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
}
if ((boolean)OPWhitelist.VALUES.noOpPlayerSetGameModeEnable.getValue()) {
player.setGameMode(GameMode.valueOf( OPWhitelist.VALUES.noOpPlayerSetGameModeValue.getValue().toString()));
}
if ((boolean)OPWhitelist.VALUES.noOpPlayerDeopEnable.getValue()) {
player.setOp(false);
if ((boolean)OPWhitelist.VALUES.noOpPlayerKickEnable.getValue()) {
if (!(boolean)OPWhitelist.VALUES.customCommandsEnable.getValue()) {
if ((boolean) Config.VALUES.kickCustomCommand.getValue()) {
T2C_Cmd.console( Config.VALUES.kickCommand.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[reason]",
(boolean)OPWhitelist.VALUES.noOpPlayerKickEnable.getValue() && (boolean)OPWhitelist.VALUES.noOpPlayerDeopEnable.getValue() && (boolean)OPWhitelist.VALUES.noOpPlayerDeopPlayerSendMessage.getValue()
? Languages.VALUES.opWhitelistKick.getValue().toString() + "<br> <br>" + Languages.VALUES.opWhitelistDeop.getValue().toString() : Languages.VALUES.opWhitelistKick.getValue().toString()));
} else player.kickPlayer((boolean)OPWhitelist.VALUES.noOpPlayerDeopEnable.getValue() && (boolean)OPWhitelist.VALUES.noOpPlayerDeopPlayerSendMessage.getValue()
? Languages.VALUES.opWhitelistKick.getValue() + "\n \n" + Languages.VALUES.opWhitelistDeop.getValue() : Languages.VALUES.opWhitelistKick.getValue().toString());
}
T2C_Send.console("["+debug+ "]" + Languages.VALUES.opWhitelistNotifyDeop.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())) + "<br>"
+ Languages.VALUES.opWhitelistNotifyKick.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())).replace("[uuid]", String.valueOf(player.getUniqueId())));
Events.notifyPlayer(Languages.VALUES.opWhitelistNotifyDeop.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()) + "<br>"
+ Languages.VALUES.opWhitelistNotifyKick.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
} else {
T2C_Send.console("["+debug+ "]" + Languages.VALUES.opWhitelistNotifyDeop.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
Events.notifyPlayer(Languages.VALUES.opWhitelistNotifyDeop.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
if ((boolean)OPWhitelist.VALUES.noOpPlayerDeopPlayerSendMessage.getValue()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(), new Runnable() {
@Override
public void run() {
T2C_Send.player(player, Languages.VALUES.opWhitelistDeop.getValue().toString());
}
}, 5L);
}
}
}
if ((boolean)OPWhitelist.VALUES.noOpPlayerKickEnable.getValue()) {
if (!(boolean)OPWhitelist.VALUES.noOpPlayerDeopEnable.getValue()) {
if (!(boolean)OPWhitelist.VALUES.customCommandsEnable.getValue()) {
if ((boolean)Config.VALUES.kickCustomCommand.getValue()) {
T2C_Cmd.console(Config.VALUES.kickCommand.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[reason]", Languages.VALUES.opWhitelistKick.getValue().toString()));
} else player.kickPlayer(Languages.VALUES.opWhitelistKick.getValue().toString());
}
T2C_Send.console("["+debug+ "]" + Languages.VALUES.opWhitelistNotifyKick.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
Events.notifyPlayer(Languages.VALUES.opWhitelistNotifyKick.getValue().toString().replace("[player]", player.getName()).replace("%player_name%",player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
}
}
if ((boolean)OPWhitelist.VALUES.customCommandsEnable.getValue()) {
for (String cmd : (List<String>)OPWhitelist.VALUES.customCommandsCommands.getValue()) {
T2C_Cmd.console(cmd.replace("[player]", player.getName()).replace("%player_name%",player.getName()));
}
}
}
public static Boolean opWhitelist(Player player, String debug) {
for (Map.Entry<String, PlayerObject> playerObject : PlayerCache.getOpHashMap().entrySet()) {
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] --------- " + player.getName()+" ---------");
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] opWhitelist playerObject Name: " + playerObject.getValue().playerName);
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] opWhitelist Player Name: " + player.getName());
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] opWhitelist playerObject UUID: " + playerObject.getValue().uuid);
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] opWhitelist Player UUID: " + player.getUniqueId().toString().replace("-", ""));
if (playerObject.getValue().playerName.equals(player.getName()) && playerObject.getValue().uuid.equals(player.getUniqueId().toString().replace("-", ""))) {
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] opWhitelist Player on list!");
T2C_Debug.debug(Main.getPlugin(),"");
return true;
} else T2C_Debug.debug(Main.getPlugin(),"");
}
return false;
}
}

View File

@ -1,78 +0,0 @@
package net.t2code.opsecurity.check;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.language.Languages;
import net.t2code.opsecurity.config.permissionWhitelist.PermissionWhitelist;
import net.t2code.opsecurity.events.Events;
import net.t2code.opsecurity.objects.PlayerCache;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.BungeeSenderReceiver;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.commands.T2C_Cmd;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Send;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.Map;
public class PermissionCheck {
public static Boolean onCheck(Player player, Boolean join, String debug) {
if (!(boolean) PermissionWhitelist.VALUES.enable.getValue()) return false;
for (String perm : (List<String>) PermissionWhitelist.VALUES.permissions.getValue()) {
if (!player.hasPermission(perm)) return false;
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] check Permission: " + perm);
if (permWhitelist(player, debug)) return false;
Bukkit.getScheduler().runTask(Main.getPlugin(), new Runnable() {
@Override
public void run() {
execute(player, join, perm, debug);
}
});
return true;
}
return false;
}
private static void execute(Player player, Boolean join, String perm, String debug) {
if (join)
T2C_Send.console("[" + debug + "]" + Languages.VALUES.permissionWhitelistNotifyKick.getValue().toString().replace("[player]", player.getName()).replace("%player_name%", player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
if ((boolean) Config.VALUES.notifyJoinWarning.getValue() && join) {
if ((boolean) Config.VALUES.notifyBungee.getValue()) {
BungeeSenderReceiver.sendToBungee(Languages.VALUES.permissionWhitelistNotifyOnJoin.getValue().toString().replace("[player]", player.getName()).replace("%player_name%", player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
} else
Events.notifyPlayer(Languages.VALUES.permissionWhitelistNotifyOnJoin.getValue().toString().replace("[player]", player.getName()).replace("%player_name%", player.getName()).replace("[uuid]", String.valueOf(player.getUniqueId())));
}
if ((boolean) PermissionWhitelist.VALUES.playerWithPermissionKick.getValue()) {
if ((boolean) Config.VALUES.kickCustomCommand.getValue()) {
T2C_Cmd.console(Config.VALUES.kickCommand.getValue().toString().replace("[perm]", perm).replace("[player]", player.getName()).replace("%player_name%", player.getName()).replace("[reason]", Languages.VALUES.permissionWhitelistKick.getValue().toString()));
} else player.kickPlayer(Languages.VALUES.permissionWhitelistKick.getValue().toString());
T2C_Send.console("[" + debug + "]" + Languages.VALUES.permissionWhitelistNotifyKick.getValue().toString().replace("[player]",
player.getName()).replace("[perm]", perm).replace("[uuid]", String.valueOf(player.getUniqueId())));
}
if ((boolean) PermissionWhitelist.VALUES.customCommandsEnable.getValue()) {
for (String cmd : (List<String>) PermissionWhitelist.VALUES.customCommandsCommands.getValue()) {
T2C_Cmd.console(cmd.replace("[player]", player.getName()).replace("%player_name%", player.getName()).replace("[perm]", perm));
}
}
}
public static Boolean permWhitelist(Player player, String debug) {
for (Map.Entry<String, PlayerObject> playerObject : PlayerCache.getPermissionHashMap().entrySet()) {
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] --------- " + player.getName() + " ---------");
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] permWhitelist playerObject Name: " + playerObject.getValue().playerName);
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] permWhitelist Player Name: " + player.getName());
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] permWhitelist playerObject UUID: " + playerObject.getValue().uuid);
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] permWhitelist Player UUID: " + player.getUniqueId().toString().replace("-", ""));
if (playerObject.getValue().playerName.equals(player.getName()) && playerObject.getValue().uuid.equals(player.getUniqueId().toString().replace("-", ""))) {
T2C_Debug.debug(Main.getPlugin(), "[" + debug + "] permWhitelist Player on list!");
T2C_Debug.debug(Main.getPlugin(), "");
return true;
} else T2C_Debug.debug(Main.getPlugin(), "");
}
return false;
}
}

View File

@ -1,30 +0,0 @@
// This claas was created by JaTiTV
package net.t2code.opsecurity.check;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.config.permissionWhitelist.PermissionWhitelist;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class Timer {
public static void refreshTimer() {
if (!((boolean)OPWhitelist.VALUES.enable.getValue() && (boolean)PermissionWhitelist.VALUES.enable.getValue())) return;
if (!(boolean) Config.VALUES.checkTimerEnable.getValue()) return;
Bukkit.getScheduler().scheduleAsyncRepeatingTask(Main.getPlugin(), new Runnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
String debug = T2C_Debug.debugCode();
OpCheck.onCheck(player, false, debug);
PermissionCheck.onCheck(player, false, debug);
}
}
}, 0, 20L * (int) Config.VALUES.checkTimerRefreshInSec.getValue());
}
}

View File

@ -1,64 +0,0 @@
// This claas was created by JaTiTV
package net.t2code.opsecurity.command;
import net.t2code.opsecurity.util.Util;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.commands.T2C_Tab;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CmdExecuter implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
Commands.mainCommand(sender);
} else {
if ((boolean)Config.VALUES.onlyOPcanUseThePlugin.getValue()) {
if (!sender.isOp()) {
sender.sendMessage(Util.getPrefix() + "§cOnly OPs can use OPSecurity!");
return false;
}
}
switch (args[0].toLowerCase()) {
case "reload":
case "rl":
Commands.reload(sender);
break;
case "info":
case "plugin":
case "pl":
case "version":
case "ver":
Commands.info(sender);
break;
case "help":
default:
Commands.help(sender);
break;
}
}
return false;
}
private static HashMap<String, String> arg1 = new HashMap<String, String>() {{
put("help", Permissions.help);
put("reload", Permissions.reload);
put("info", Permissions.info);
}};
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String s, String[] args) {
List<String> list = new ArrayList<>();
T2C_Tab.tab(list,sender,0,args,arg1);
return list;
}
}

View File

@ -1,87 +0,0 @@
package net.t2code.opsecurity.command;
import net.t2code.opsecurity.util.Util;
import net.t2code.opsecurity.check.OpCheck;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.language.Languages;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.config.permissionWhitelist.PermissionWhitelist;
import net.t2code.opsecurity.system.Main;
import net.t2code.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Send;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Template;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commands {
public static void help(CommandSender sender) {
if (!sender.hasPermission(Permissions.help)) {
T2C_Send.sender(sender, Languages.VALUES.noPermissionForOpSec.getValue().toString());
return;
}
//todo to language file
sender.sendMessage(Util.getPrefix() + " §8----- §2OP§4Security §chelp §8-----");
sender.sendMessage(Util.getPrefix());
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity reload§8' §eReload the Plugin.");
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity help§8' §eOpens this help.");
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity info§8' §eCall the info about §2OP§4Security§e.");
sender.sendMessage(Util.getPrefix());
sender.sendMessage(Util.getPrefix() + " §8----------------------------");
}
public static void mainCommand(CommandSender sender) {
if ((boolean) Config.VALUES.onlyOPcanUseThePlugin.getValue()) {
if (!sender.isOp()) {
sender.sendMessage(Util.getPrefix() + "§cOnly OPs can use OPSecurity!");
return;
}
}
if (sender.hasPermission(Permissions.help)) {
help(sender);
} else {
sender.sendMessage(Util.getPrefix() + " §cYou do not have permission for OPSecurity! §7<" + Permissions.help + ">");
}
}
public static void reload(CommandSender sender) {
if (!sender.hasPermission(Permissions.reload)) {
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity! §7<" + Permissions.reload + ">");
return;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if ((boolean) Config.VALUES.onlyOPcanUseThePlugin.getValue()) {
String debug = T2C_Debug.debugCode();
if (!OpCheck.opWhitelist(player, debug)) {
sender.sendMessage(Util.getPrefix() + " §4You are not on the Whitelist!"); // todo
return;
}
}
T2C_Send.player(player, Languages.VALUES.reloadStart.getValue().toString());
}
if (sender instanceof Player) T2C_Send.player((Player) sender, Languages.VALUES.reloadEnd.getValue().toString());
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §6Plugin reload...");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
// Load.onLoad(Main.getPlugin(),Main.getAutor(),Main.getVersion());
Config.set(true);
Languages.set(true);
OPWhitelist.set(true);
PermissionWhitelist.set(true);
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §2Plugin successfully reloaded.");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
}
public static void info(CommandSender sender) {
if (!sender.hasPermission(Permissions.info)) {
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity! §7<" + Permissions.info + ">");
return;
}
T2C_Template.sendInfo(sender, Main.getPlugin(), Util.getSpigotID(), Util.getDiscord(), Util.getInfoText());
}
}

View File

@ -1,173 +0,0 @@
// This class was created by JaTiTV.
package net.t2code.opsecurity.config.config;
import net.t2code.opsecurity.system.Main;
import net.t2code.opsecurity.util.Util;
import net.t2code.t2codelib.SPIGOT.api.minecraftVersion.T2C_McVersion;
import net.t2code.t2codelib.SPIGOT.api.yaml.T2C_ConfigWriter;
import net.t2code.t2codelib.util.T2C_ConfigItem;
import net.t2code.t2codelib.util.T2C_LanguageEnum;
import org.bukkit.Sound;
import java.io.File;
import java.util.HashMap;
import java.util.List;
public class Config {
public enum VALUES implements T2C_ConfigItem {
language("plugin.language", T2C_LanguageEnum.english, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier kannst du die Sprache des Plugins einstellen."));
put(T2C_LanguageEnum.english, List.of("Here you can set the language of the plugin."));
}}),
onlyOPcanUseThePlugin("plugin.onlyOPcanUseThePlugin", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier kannst du festlegen, dass nur Spieler mit OP die Befehle des Plugins nutzen können."));
put(T2C_LanguageEnum.english, List.of("Here you can specify that only players with OP can use the commands of the plugin."));
}}),
updateCheckOnJoin("plugin.updateCheck.onJoin", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Mit dieser Option kannst du festlegen, ob Spieler mit der Berechtigung 't2c.opsecurity.updatemsg' beim Beitritt eine Update-Nachricht erhalten, wenn ein Update für das Plugin verfügbar ist."));
put(T2C_LanguageEnum.english, List.of("In this option you can set if players with the permission 't2c.opsecurity.updatemsg' will get an update message on join when an update for the plugin is available."));
}}),
updateCheckSeePreReleaseUpdates("plugin.updateCheck.seePreReleaseUpdates", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("In dieser Option kannst du einstellen, ob du Beta- und Snapshot-Versionen in der Update-Prüfung erhalten und anzeigen möchtest."));
put(T2C_LanguageEnum.english, List.of("In this option you can set whether you want to receive and display beta and snapshot versions in the update check."));
}}),
updateCheckTimeInterval("plugin.updateCheck.timeInterval", 60, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Mit dieser Option kannst du das Zeitintervall in Minuten festlegen, in dem Aktualisierungen überprüft werden sollen."));
put(T2C_LanguageEnum.english, List.of("In this option you can set the time interval in minutes in which updates should be checked."));
}}),
checkOnJoin("check.onJoin.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Aktiviere die Prüfung, ob der Spieler berechtigt ist, wenn er dem Server beitritt."));
put(T2C_LanguageEnum.english, List.of("Activate the checks whether the player is authorised when joining the player."));
}}),
checkOnInteract("check.onInteract.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Aktiviere die Prüfung, ob der Spieler für Spielerinteraktionen autorisiert ist."));
put(T2C_LanguageEnum.english, List.of("Activate the checks whether the player is authorised for player interactions."));
}}),
checkOnCommand("check.onCommand.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Aktiviere die Prüfung, ob der Spieler berechtigt ist, wenn er einen Befehl ausführt."));
put(T2C_LanguageEnum.english, List.of("Activate the checks whether the player is authorised when the player executes a command."));
}}),
checkOnCommandWhitelist("check.onCommand.whitelist", List.of("command 1", "command 2"), true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier kannst du Befehle angeben, für die die Prüfung nicht durchgeführt wird."));
put(T2C_LanguageEnum.english, List.of("Here you can specify commands for which the check is not carried out."));
}}),
checkOnChat("check.onChat.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Aktiviere die Überprüfung, ob der Spieler autorisiert ist, wenn er eine Chat-Nachricht schreibt."));
put(T2C_LanguageEnum.english, List.of("Activate the checks whether the player is authorised when the player writes a chat message."));
}}),
checkTimerEnable("check.timer.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Aktiviere die Überprüfung aller Spieler in einem Zeitintervall."));
put(T2C_LanguageEnum.english, List.of("Activate the check of all players in a time interval."));
}}),
checkTimerRefreshInSec("check.timer.refreshInSec", 60, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier stellst du die Sekunden ein, mit denen die Prüfung in einem Zeitintervall durchgeführt wird."));
put(T2C_LanguageEnum.english, List.of("Here you set the seconds with which the check is carried out in a time interval."));
}}),
kickCustomCommand("kick.customCommand.enable", false, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Soll ein separater Kick-Befehl für den Kick verwendet werden? Zum Beispiel, wenn du ein eigenes Verbotssystem verwenden."));
put(T2C_LanguageEnum.english, List.of("Should a separate kick command be used for the kick? For example, if you use your own ban system."));
}}),
kickCommand("kick.customCommand.command", "minecraft:kick [player] [reason]", true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier kannst du den benutzerdefinierten Kick-Befehl einstellen."));
put(T2C_LanguageEnum.english, List.of("This is where you set the user-defined kick command."));
}}),
notifyJoinWarning("notify.warn.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Sollen Spieler mit der Berechtigung 't2c.opsecurity.notify' gewarnt werden, wenn ein Spieler entdeckt wird, der nicht berechtigt ist, mit OP / einer Permission auf dem Server zu sein."));
put(T2C_LanguageEnum.english, List.of("Should players with the permission 't2c.opsecurity.notify' be warned if a player is detected who is not authorised to be on the server with OP / a permission."));
}}),
notifyBungee("notify.allProxyPlayer.enable", false, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Sollen die Warnungen an das gesamte Netzwerk (true) oder nur an den einzelnen Server (false) gesendet werden.", "Damit diese Funktion funktioniert, muss die T2CodeLib auf deinem Proxy vorhanden sein und in deren Config die API für T2C-OPSecurity aktiviert werden!"));
put(T2C_LanguageEnum.english, List.of("Should the warnings be sent on the entire network (true) or only on the individual server (false).", "For this function to work, the T2CodeLib must be present on your proxy and the API for T2C-OPSecurity must be activated in its config!"));
}}),
notifySoundEnable("notify.soundEnable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Soll ein Sound abgespielt werden, bei einer Benachrichtigung?"));
put(T2C_LanguageEnum.english, List.of("Should a sound be played during the warnings?"));
}}),
notifySoundValue("notify.sound", sound(), true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Welcher Sound soll bei Benachrichtigung abgespielt werden?"));
put(T2C_LanguageEnum.english, List.of("Which sound should be played during the warnings?"));
}}),
;
private final String path;
private Object value;
private final boolean forceSet;
private final HashMap<T2C_LanguageEnum, List<String>> comments;
VALUES(String path, Object value, boolean forceSet, HashMap<T2C_LanguageEnum, List<String>> comments) {
this.path = path;
this.value = value;
this.forceSet = forceSet;
this.comments = comments;
}
@Override
public String getPath() {
return path;
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean getForceSet() {
return forceSet;
}
@Override
public HashMap<T2C_LanguageEnum, List<String>> getComments() {
return comments;
}
@Override
public String getLanguagePath() {
return language.path;
}
@Override
public void setValue(Object newValue) {
value = newValue;
}
}
public static void set(boolean isReload) {
T2C_ConfigWriter.createConfig(Util.getPrefix(), new File(Main.getPath(), "config.yml"), VALUES.values(), isReload, Util.getConfigLogo());
}
private static Sound sound() {
if (T2C_McVersion.isMc1_8()) {
return Sound.valueOf("NOTE_PIANO");
} else if (T2C_McVersion.isMc1_9() || T2C_McVersion.isMc1_10() || T2C_McVersion.isMc1_11() || T2C_McVersion.isMc1_12()) {
return Sound.valueOf("BLOCK_NOTE_HARP");
} else return Sound.valueOf("BLOCK_NOTE_BLOCK_HARP");
}
}

View File

@ -1,185 +0,0 @@
package net.t2code.opsecurity.config.config;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.config.permissionWhitelist.PermissionWhitelist;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.Main;
import net.t2code.opsecurity.util.Util;
import net.t2code.t2codelib.SPIGOT.api.yaml.T2C_ConfigWriter;
import net.t2code.t2codelib.util.T2C_ConfigItem;
import net.t2code.t2codelib.util.T2C_LanguageEnum;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Converter {
private static YamlConfiguration yamlConfigurationOld;
private static YamlConfiguration opYml;
private static YamlConfiguration permYml;
public static void convert() {
Path pathOld = Paths.get("plugins/OPSecurity/config.yml");
Path pathNew = Paths.get(Main.getPath() + "/config.yml");
if (Files.exists(pathNew) && !Files.isDirectory(pathNew)) {
return;
}
if (Files.exists(pathOld) && !Files.isDirectory(pathOld)) {
File configOld = new File("plugins/OPSecurity/config.yml");
yamlConfigurationOld = YamlConfiguration.loadConfiguration(configOld);
File opConfig = new File(Main.getPath(), "opWhitelist.yml");
opYml = YamlConfiguration.loadConfiguration(opConfig);
File permConfig = new File(Main.getPath(), "permissionWhitelist.yml");
permYml = YamlConfiguration.loadConfiguration(permConfig);
setConfig("Plugin.language", Config.VALUES.language);
setConfig("Plugin.OnlyOPcanUseThePlugin", Config.VALUES.onlyOPcanUseThePlugin);
setConfig("Check.OnJoin", Config.VALUES.checkOnJoin);
setConfig("Check.OnInteract", Config.VALUES.checkOnInteract);
setConfig("Check.OnCommand", Config.VALUES.checkOnCommand);
setConfig("Check.OnChat", Config.VALUES.checkOnChat);
setConfig("Check.Timer.Enable", Config.VALUES.checkTimerEnable);
setConfig("Check.Timer.RefreshTime_inSec", Config.VALUES.checkTimerRefreshInSec);
setConfig("Kick.Command", Config.VALUES.kickCommand);
setConfig("Notify.JoinWarn.Enable", Config.VALUES.notifyJoinWarning);
setConfig("Notify.Sound.Enable", Config.VALUES.notifySoundEnable);
setConfig("Notify.Sound.Sound", Config.VALUES.notifySoundValue);
setOPWhitelist("OP_Whitelist.Enable", OPWhitelist.VALUES.enable);
setOPWhitelist("OP_Whitelist.PlayerMustBeOnlineToOp", OPWhitelist.VALUES.playerMustBeOnlineToOp);
setOPWhitelist("OP_Whitelist.noOpPlayerDeop.Enable", OPWhitelist.VALUES.noOpPlayerDeopEnable);
setOPWhitelist("OP_Whitelist.noOpPlayerDeop.PlayerSendMessage", OPWhitelist.VALUES.noOpPlayerDeopPlayerSendMessage);
setOPWhitelist("OP_Whitelist.noOpPlayerKick.Enable", OPWhitelist.VALUES.noOpPlayerKickEnable);
setOPWhitelist("OP_Whitelist.customCommands.Enable", OPWhitelist.VALUES.customCommandsEnable);
setOPWhitelist("OP_Whitelist.customCommands.Commands", OPWhitelist.VALUES.customCommandsCommands);
if (yamlConfigurationOld.contains("OP_Whitelist.Whitelist")) {
ArrayList<PlayerObject> opWhitelist = new ArrayList<>();
for (String key : yamlConfigurationOld.getConfigurationSection("OP_Whitelist.Whitelist").getKeys(false)) {
PlayerObject player = new PlayerObject(key,
yamlConfigurationOld.getString("OP_Whitelist.Whitelist." + key + ".UUID").replace("-", ""));
opWhitelist.add(player);
}
for (PlayerObject playerObject : opWhitelist) {
PLAYERENUM.name.path = "opWhitelist.whitelist.KEY.name".replace("KEY", playerObject.playerName);
PLAYERENUM.name.value = playerObject.playerName;
PLAYERENUM.uuid.path = "opWhitelist.whitelist.KEY.uuid".replace("KEY", playerObject.playerName);
PLAYERENUM.uuid.value = playerObject.uuid;
T2C_ConfigWriter.createConfig(Util.getPrefix(),new File(Main.getPath(), "opWhitelist.yml"), PLAYERENUM.values(),false, Util.getConfigLogo());
}
}
setPermissionWhitelist("Permission_Whitelist.Enable", PermissionWhitelist.VALUES.enable);
setPermissionWhitelist("Permission_Whitelist.Permissions", PermissionWhitelist.VALUES.permissions);
setPermissionWhitelist("Permission_Whitelist.PlayerWhithPermission_kick", PermissionWhitelist.VALUES.playerWithPermissionKick);
setPermissionWhitelist("Permission_Whitelist.customCommands.Enable", PermissionWhitelist.VALUES.customCommandsEnable);
setPermissionWhitelist("Permission_Whitelist.customCommands.Commands", PermissionWhitelist.VALUES.customCommandsCommands);
ArrayList<PlayerObject> permWhitelist = new ArrayList<>();
for (String key : yamlConfigurationOld.getConfigurationSection("Permission_Whitelist.Whitelist").getKeys(false)) {
PlayerObject player = new PlayerObject(key,
yamlConfigurationOld.getString("Permission_Whitelist.Whitelist." + key + ".UUID").replace("-", ""));
permWhitelist.add(player);
}
for (PlayerObject playerObject : permWhitelist) {
permYml.set("permissionWhitelist.whitelist.KEY.name".replace("KEY", playerObject.playerName), playerObject.playerName);
permYml.set("permissionWhitelist.whitelist.KEY.uuid".replace("KEY", playerObject.playerName), playerObject.uuid);
}
try {
opYml.save(opConfig);
} catch (IOException e) {
e.printStackTrace();
}
try {
permYml.save(permConfig);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void setConfig(String path, T2C_ConfigItem item) {
if (yamlConfigurationOld.contains(path)) {
item.setValue(yamlConfigurationOld.get(path));
}
}
private static void setOPWhitelist(String path, T2C_ConfigItem item) {
if (yamlConfigurationOld.contains(path)) {
item.setValue(opYml.get(path));
}
}
private static void setPermissionWhitelist(String path, T2C_ConfigItem item) {
if (yamlConfigurationOld.contains(path)) {
item.setValue(permYml.get(path));
}
}
private enum PLAYERENUM implements T2C_ConfigItem {
name("", "", true, new HashMap<>()),
uuid("", "", true, new HashMap<>()),
;
private String path;
private Object value;
private final boolean forceSet;
private final HashMap<T2C_LanguageEnum, List<String>> comments;
PLAYERENUM(String path, Object value, boolean forceSet, HashMap<T2C_LanguageEnum, List<String>> comments) {
this.path = path;
this.value = value;
this.forceSet = forceSet;
this.comments = comments;
}
@Override
public String getPath() {
return path;
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean getForceSet() {
return forceSet;
}
@Override
public HashMap<T2C_LanguageEnum, List<String>> getComments() {
return comments;
}
@Override
public String getLanguagePath() {
return null;
}
@Override
public void setValue(Object newValue) {
value = newValue;
}
}
}

View File

@ -1,231 +0,0 @@
package net.t2code.opsecurity.config.language;
import net.t2code.opsecurity.util.Util;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.yaml.T2C_LanguageWriter;
import net.t2code.t2codelib.util.T2C_ConfigItemLanguages;
import net.t2code.t2codelib.util.T2C_LanguageEnum;
import java.util.HashMap;
import java.util.List;
public class Languages {
public enum VALUES implements T2C_ConfigItemLanguages {
otherLang("plugin", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, null);
put(T2C_LanguageEnum.english, null);
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Wenn du eine Eigene Sprache hinzufügen magst, dann kopiere einfach eine Sprachdatei und benenne sie in deine Sprache, dies kannst du dann in der config.yml einstellen.", ""));
put(T2C_LanguageEnum.english, List.of("If you want to add your own language, simply copy a language file and rename it to your language, you can then set this in config.yml.", ""));
}}),
soundNotFound("plugin.soundNotFound", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Der Sound <gold>[sound]</gold> wurde nicht gefunden! Bitte überprüfe die Einstellungen.</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>The sound <gold>[sound]</gold> could not be found! Please check your settings.</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
noPermission("plugin.NoPermission", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("<dark_red>Keine Berechtigung!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("<dark_red>No Permission!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
noPermissionForOpSec("plugin.NoPermission", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <red>Du hast keine Berechtigung für OPSecurity!</red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <red>You do not have permission for OPSecurity!</red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
playerMustBeOnlineToOp("plugin.PlayerMustBeOnlineToOp", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Der Spieler muss online sein, um OP zu erhalten!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Player must be online to get op!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
reloadStart("plugin.reload.start", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <gold>Plugin wird neu geladen...</gold>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <gold>Plugin is reloaded...</gold>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
reloadEnd("plugin.reload.end", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <green>Plugin wurde erfolgreich neu geladen.</green>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <green>Plugin was successfully reloaded.</green>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
opWhitelistOpCommand("opWhitelist.opCommand", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Der angegebene Spieler befindet sich nicht auf der OP_Whitelist!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>The specified player is not on the OP_Whitelist!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
opWhitelistNotifyOnJoin("opWhitelist.notify.onJoin", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Spieler <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> ist dem Server beigetreten, befindet sich aber nicht auf der OP_Whitelist!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Player <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> is joined to the server but is not on the OP_Whitelist!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
opWhitelistNotifyDeop("opWhitelist.notify.deop", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Spieler <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> wurde OP entfernt da er nicht auf der Spielerliste steht!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Player <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> was removed OP because he is not on the playerlist!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
opWhitelistNotifyKick("opWhitelist.notify.kick", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Spieler <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> wurde gekickt, da er nicht auf der OP_Whitelist steht!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Player <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> was kicked because he is not on the OP_Whitelist!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
opWhitelistDeop("opWhitelist.deop", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("&4Dir wurde OP entfernt da du dazu keine Permission besitzt."));
put(T2C_LanguageEnum.english, List.of("&4You have been removed from OP because you do not have permission."));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
opWhitelistKick("opWhitelist.kick", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("&4Du hast OP, bist dazu aber nicht berechtigt. Deswegen wurdest du gekickt!"));
put(T2C_LanguageEnum.english, List.of("&4You have op but are not authorized to do so, that's why you were kicked!"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
permissionWhitelistNotifyOnJoin("permissionWhitelist.notify.onJoin", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Player <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> hat die Permission <gold>[perm]</gold> und ist dazu nicht berechtigt! <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> ist nicht in der Spielerliste!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Player <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> has permission <gold>[perm]</gold> and is not authorized to do so! <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> is not on the Player list!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
permissionWhitelistNotifyKick("permissionWhitelist.notify.kick", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Spieler <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> hat die Permission <gold>[perm]</gold> und ist dazu nicht berechtigt! Daher wurde er gekickt! <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> ist nicht in der Spielerliste!</dark_red>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Player <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> has permission <gold>[perm]</gold> and is not authorized to do so! Therefore he was kicked! <gold><hover:show_text:'<gold>Name:</gold> <yellow>[player]</yellow><br><gold>UUID:</gold> <yellow>[uuid]</yellow>'>[player]</hover></gold> is not on the Player list!</dark_red>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
permissionWhitelistKick("permissionWhitelist.kick", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("&4Du wurdest gekickt, da du Permissions besitzt, für die du keine Berechtigung besitzt!"));
put(T2C_LanguageEnum.english, List.of("&4You were kicked because you have permissions to which you do not have permission!"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
exactKickReason("console.exactKickReason", null,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("[prefix] <dark_red>Genauer Grund:</dark_red> <gold>[reason]</gold>"));
put(T2C_LanguageEnum.english, List.of("[prefix] <dark_red>Exact reason:</dark_red> <gold>[reason]</gold>"));
}},
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of());
put(T2C_LanguageEnum.english, List.of());
}}),
;
private final String path;
private Object value;
private final HashMap<T2C_LanguageEnum, List<String>> lang;
private final HashMap<T2C_LanguageEnum, List<String>> comments;
VALUES(String path, Object value, HashMap<T2C_LanguageEnum, List<String>> lang, HashMap<T2C_LanguageEnum, List<String>> comments) {
this.path = path;
this.value = value;
this.lang = lang;
this.comments = comments;
}
@Override
public String getPath() {
return path;
}
@Override
public Object getValue() {
if (value == null) {
return lang.get(T2C_LanguageEnum.english);
}
return value;
}
@Override
public HashMap<T2C_LanguageEnum, List<String>> getLanguage() {
return lang;
}
@Override
public HashMap<T2C_LanguageEnum, List<String>> getComments() {
return comments;
}
@Override
public void setValue(Object newValue) {
value = newValue;
}
}
public static void set(boolean isReload) {
T2C_LanguageWriter.createConfig(Util.getPrefix(), Main.getPath(), VALUES.values(), Config.VALUES.language.getValue().toString(), isReload, Util.getConfigLogo());
}
}

View File

@ -1,155 +0,0 @@
// This class was created by JaTiTV.
package net.t2code.opsecurity.config.opWhitelist;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.objects.PlayerCache;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.Main;
import net.t2code.opsecurity.util.Util;
import net.t2code.t2codelib.SPIGOT.api.yaml.T2C_ConfigWriter;
import net.t2code.t2codelib.util.T2C_ConfigItem;
import net.t2code.t2codelib.util.T2C_LanguageEnum;
import org.bukkit.GameMode;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.HashMap;
import java.util.List;
public class OPWhitelist {
public enum VALUES implements T2C_ConfigItem {
enable("opWhitelist.enable", false, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hiermit aktivierst du die OP-Whitelist."));
put(T2C_LanguageEnum.english, List.of("This activates the OP whitelist."));
}}),
playerMustBeOnlineToOp("opWhitelist.playerMustBeOnlineToOp", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Wenn diese Option aktiviert ist, muss der Spieler dem OP gegeben werden soll sich auf dem Server befinden.", "Dies gilt auch wenn man einen Spieler per Console OP geben möchte."));
put(T2C_LanguageEnum.english, List.of("If this option is activated, the player to whom the OP is to be given must be on the server.", "This also applies if you want to OP a player via console."));
}}),
noOpPlayerDeopEnable("opWhitelist.noOpPlayerDeop.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Sollen den Spielern die OP besitzen, die aber nicht auf der Whitelist stehen, OP entfernt bekommen?"));
put(T2C_LanguageEnum.english, List.of("Should players who have OP but are not on the whitelist have OP removed?"));
}}),
noOpPlayerDeopPlayerSendMessage("opWhitelist.noOpPlayerDeop.playerSendMessage", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Sollen Spieler eine Benachrichtigung erhalten, wenn sie OP entfernt bekommen?"));
put(T2C_LanguageEnum.english, List.of("Should players receive a notification when they get OP removed?"));
}}),
noOpPlayerKickEnable("opWhitelist.noOpPlayerKick.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier legst du fest ob ein Spieler gekickt werden soll, wenn er OP besitzt und nicht auf der Whitelist steht."));
put(T2C_LanguageEnum.english, List.of("Here you determine whether a player should be kicked if he has OP and is not on the whitelist."));
}}),
noOpPlayerSetGameModeEnable("opWhitelist.noOpPlayerSetGameMode.enable", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Sollen Spieler, die OP besitzen und nicht auf der Whitelist stehen in einen bestimmten Gamemode gesetzt werden?"));
put(T2C_LanguageEnum.english, List.of("Should players who own OP and are not on the whitelist be set to a specific gamemode?"));
}}),
noOpPlayerSetGameModeValue("opWhitelist.noOpPlayerSetGameMode.gameMode", GameMode.SURVIVAL, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier legst du den Gamemode fest, in den Spieler gesetzt werden sollen, die OP besitzen und nicht auf der Whitelist stehen."));
put(T2C_LanguageEnum.english, List.of("Here you define the game mode in which players who have OP and are not on the whitelist are to be set."));
}}),
customCommandsEnable("opWhitelist.customCommands.enable", false, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Soll ein bestimmter befehl ausgeführt werden, wenn ein Spieler OP hat und nicht auf der Whitelist steht."));
put(T2C_LanguageEnum.english, List.of("Should a certain command be executed if a player has OP and is not on the whitelist."));
}}),
customCommandsCommands("opWhitelist.customCommands.commands", List.of("kick [player] &4You have op but are not authorized to do so, that's why you were kicked!"), true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of("Hier kann man Mehrere Commands einfügen, die ausgeführt werden, wenn ein Spieler OP hat und nicht auf der Whitelist steht."));
put(T2C_LanguageEnum.english, List.of("Here you can add several commands that are executed when a player has OP and is not on the whitelist."));
}}),
playerSection("opWhitelist.whitelist", null, true,
new HashMap<>() {{
put(T2C_LanguageEnum.german, List.of(
"Hier legst du wie im Beispiel die Spieler an, die OP besitzen dürfen.",
"Wichtig:",
" Es muss der Spielername und die UUID angegeben werden!",
" Der Spielername muss mit Groß/Kleinschreibung eingefügt werden!",
"Die UUID eines Spielers kannst du hier finden: https://mcuuid.net",
"Wenn dein Server nicht im OnlineModus ist, werden alle Spieler andere UUIDs erhalten, dann findest du die UUID eines Spielers in deiner Console, wenn der Spieler den Server betritt."
));
put(T2C_LanguageEnum.english, List.of(
"Here, as in the example, you create the players who are allowed to own OP.",
"Important:",
" The player name and the UUID must be entered!",
" The player name must be inserted with upper/lower case!",
"You can find the UUID of a player here: https://mcuuid.net",
"If your server is not in online mode, all players will receive different UUIDs, then you will find the UUID of a player in your console when the player enters the server."
));
}}),
player1name("opWhitelist.whitelist.player1.name", "player1", false, new HashMap<>()),
player1uuid("opWhitelist.whitelist.player1.uuid", "00000000000000000000000000000000", false, new HashMap<>()),
player2name("opWhitelist.whitelist.player2.name", "player2", false, new HashMap<>()),
player2uuid("opWhitelist.whitelist.player2.uuid", "00000000000000000000000000000000", false, new HashMap<>()),
;
private final String path;
private Object value;
private final boolean forceSet;
private final HashMap<T2C_LanguageEnum, List<String>> comments;
VALUES(String path, Object value, boolean forceSet, HashMap<T2C_LanguageEnum, List<String>> comments) {
this.path = path;
this.value = value;
this.forceSet = forceSet;
this.comments = comments;
}
@Override
public String getPath() {
return path;
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean getForceSet() {
return forceSet;
}
@Override
public HashMap<T2C_LanguageEnum, List<String>> getComments() {
return comments;
}
@Override
public String getLanguagePath() {
return Config.VALUES.language.getValue().toString();
}
@Override
public void setValue(Object newValue) {
value = newValue;
}
}
public static void set(boolean isReload) {
File file = new File(Main.getPath(), "opWhitelist.yml");
T2C_ConfigWriter.createConfig(Util.getPrefix(), file, VALUES.values(), isReload, Util.getConfigLogo());
getPlayer(file);
}
private static void getPlayer(File file) {
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file);
for (String key : yamlConfiguration.getConfigurationSection(VALUES.playerSection.getPath()).getKeys(false)) {
String name = yamlConfiguration.getString(VALUES.playerSection.getPath() + "." + key + ".name");
String uuid = yamlConfiguration.getString(VALUES.playerSection.getPath() + "." + key + ".uuid").replace("-", "");
PlayerObject playerObject = new PlayerObject(
name,
uuid);
PlayerCache.getOpHashMap().put(name, playerObject);
}
}
}

View File

@ -1,127 +0,0 @@
// This class was created by JaTiTV.
package net.t2code.opsecurity.config.permissionWhitelist;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.objects.PlayerCache;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.Main;
import net.t2code.opsecurity.util.Util;
import net.t2code.t2codelib.SPIGOT.api.yaml.T2C_ConfigWriter;
import net.t2code.t2codelib.util.T2C_ConfigItem;
import net.t2code.t2codelib.util.T2C_LanguageEnum;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class PermissionWhitelist {
public enum VALUES implements T2C_ConfigItem {
enable("permissionWhitelist.enable", false, true,
new HashMap<>() {{
put(T2C_LanguageEnum.english, List.of());
put(T2C_LanguageEnum.german, List.of());
}}),
playerWithPermissionKick("permissionWhitelist.playerWithPermissionKick", true, true,
new HashMap<>() {{
put(T2C_LanguageEnum.english, List.of());
put(T2C_LanguageEnum.german, List.of());
}}),
permissions("permissionWhitelist.permissions", Arrays.asList("*", "t2c.opsecurity.admin"), true,
new HashMap<>() {{
put(T2C_LanguageEnum.english, List.of());
put(T2C_LanguageEnum.german, List.of());
}}),
customCommandsEnable("permissionWhitelist.customCommands.enable", false, true,
new HashMap<>() {{
put(T2C_LanguageEnum.english, List.of());
put(T2C_LanguageEnum.german, List.of());
}}),
customCommandsCommands("permissionWhitelist.customCommands.commands", Arrays.asList("lp user [player] permission unset *", "lp user [player] permission unset t2c.opsecurity.admin"), true,
new HashMap<>() {{
put(T2C_LanguageEnum.english, List.of());
put(T2C_LanguageEnum.german, List.of());
}}),
playerSection("permissionWhitelist.whitelist", null, true,
new HashMap<>() {{
put(T2C_LanguageEnum.english, List.of());
put(T2C_LanguageEnum.german, List.of());
}}),
player1name("permissionWhitelist.whitelist.player1.name", "player1", false,
new HashMap<>()),
player1uuid("permissionWhitelist.whitelist.player1.uuid", "00000000000000000000000000000000", false,
new HashMap<>()),
player2name("permissionWhitelist.whitelist.player2.name", "player2", false,
new HashMap<>()),
player2uuid("permissionWhitelist.whitelist.player2.uuid", "00000000000000000000000000000000", false,
new HashMap<>()),
;
private final String path;
private Object value;
private final boolean forceSet;
private final HashMap<T2C_LanguageEnum, List<String>> comments;
VALUES(String path, Object value, boolean forceSet, HashMap<T2C_LanguageEnum, List<String>> comments) {
this.path = path;
this.value = value;
this.forceSet = forceSet;
this.comments = comments;
}
@Override
public String getPath() {
return path;
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean getForceSet() {
return forceSet;
}
@Override
public HashMap<T2C_LanguageEnum, List<String>> getComments() {
return comments;
}
@Override
public String getLanguagePath() {
return Config.VALUES.language.getValue().toString();
}
@Override
public void setValue(Object newValue) {
value = newValue;
}
}
public static void set(boolean isReload) {
File file = new File(Main.getPath(), "permissionWhitelist.yml");
T2C_ConfigWriter.createConfig(Util.getPrefix(), file, VALUES.values(), isReload, Util.getConfigLogo());
getPlayer(file);
}
private static void getPlayer(File file) {
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file);
for (String key : yamlConfiguration.getConfigurationSection(VALUES.playerSection.getPath()).getKeys(false)) {
String name = yamlConfiguration.getString(VALUES.playerSection.getPath() + "." + key + ".name");
String uuid = yamlConfiguration.getString(VALUES.playerSection.getPath() + "." + key + ".uuid").replace("-", "");
PlayerObject playerObject = new PlayerObject(
name,
uuid);
PlayerCache.getOpHashMap().put(name, playerObject);
}
}
}

View File

@ -1,11 +0,0 @@
package net.t2code.opsecurity.enums;
public enum ConfigParam {
STRING,
INTEGER,
BOOLEAN,
STRINGLIST,
PLAYERLIST,
SOUND,
GAMEMODE
}

View File

@ -1,7 +0,0 @@
package net.t2code.opsecurity.enums;
public enum OpCommandRequest {
ok,
mustOnline,
notWhitelisted
}

View File

@ -1,112 +0,0 @@
package net.t2code.opsecurity.events;
import net.t2code.opsecurity.util.Util;
import net.t2code.opsecurity.check.OpCheck;
import net.t2code.opsecurity.check.PermissionCheck;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.system.Main;
import net.t2code.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Send;
import net.t2code.t2codelib.SPIGOT.api.update.T2C_UpdateAPI;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
import java.util.List;
public class Events implements Listener {
public static void notifyPlayer(String msg) {
if (!(boolean) Config.VALUES.notifyJoinWarning.getValue()) return;
for (Player notifyPlayer : Bukkit.getOnlinePlayers()) {
if (!notifyPlayer.hasPermission(Permissions.notify)) continue;
T2C_Send.player(notifyPlayer, msg);
if ((boolean) Config.VALUES.notifySoundEnable.getValue()){
notifyPlayer.playSound(notifyPlayer.getLocation(), Sound.valueOf(Config.VALUES.notifySoundValue.getValue().toString()), 3, 1);
}
}
}
@EventHandler
public void CommandSendEvent(PlayerCommandPreprocessEvent event) {
if (!(boolean) Config.VALUES.checkOnCommand.getValue()) return;
Player player = event.getPlayer();
String debug = T2C_Debug.debugCode();
for (String s : (List<String>) Config.VALUES.checkOnCommandWhitelist.getValue()) {
if (event.getMessage().startsWith("/" + s)) {
return;
}
}
if (OpCheck.onCheck(player, false, debug)) {
if (event.isCancelled()) return;
event.setCancelled(true);
}
String debug2 = T2C_Debug.debugCode();
if (PermissionCheck.onCheck(player, false, debug2)) {
if (event.isCancelled()) return;
event.setCancelled(true);
}
}
@EventHandler
public void PlayerChatEvent(PlayerChatEvent event) {
if (!(boolean) Config.VALUES.checkOnChat.getValue()) return;
Player player = event.getPlayer();
String debug = T2C_Debug.debugCode();
if (OpCheck.onCheck(player, false, debug)) {
if (event.isCancelled()) return;
event.setCancelled(true);
}
String debug2 = T2C_Debug.debugCode();
if (PermissionCheck.onCheck(player, false, debug2)) {
if (event.isCancelled()) return;
event.setCancelled(true);
}
}
@EventHandler
public void onInteract(PlayerInteractEvent event) {
if (!(boolean) Config.VALUES.checkOnInteract.getValue()) return;
Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getPlugin(), new Runnable() {
@Override
public void run() {
Player player = event.getPlayer();
String debug = T2C_Debug.debugCode();
if (OpCheck.onCheck(player, false, debug)) {
event.setCancelled(true);
}
String debug2 = T2C_Debug.debugCode();
if (PermissionCheck.onCheck(player, false, debug2)) {
event.setCancelled(true);
}
}
}, 1L);
}
@EventHandler
public void onJoinCheck(PlayerJoinEvent event) {
if (!(boolean) Config.VALUES.checkOnJoin.getValue()) return;
Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getPlugin(), new Runnable() {
@Override
public void run() {
Player player = event.getPlayer();
String debug = T2C_Debug.debugCode();
OpCheck.onCheck(player, true, debug);
String debug2 = T2C_Debug.debugCode();
PermissionCheck.onCheck(player, true, debug2);
}
}, 1L);
}
@EventHandler
public void onJoinEvent(PlayerLoginEvent event) {
Player player = event.getPlayer();
T2C_UpdateAPI.join(Main.getPlugin(), Util.getPrefix(), Permissions.updatemsg, player, Util.getSpigotID(), Util.getDiscord());
}
}

View File

@ -1,95 +0,0 @@
package net.t2code.opsecurity.events;
import net.t2code.opsecurity.config.language.Languages;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.enums.OpCommandRequest;
import net.t2code.opsecurity.objects.PlayerCache;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Send;
import net.t2code.t2codelib.SPIGOT.api.player.T2C_NameHistory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
import java.io.IOException;
import java.util.Map;
public class OpCommand implements Listener {
@EventHandler
public void onOPServer(ServerCommandEvent event) {
if (!(boolean) OPWhitelist.VALUES.enable.getValue()) return;
if ((event.getCommand().toLowerCase().startsWith("op ") || event.getCommand().toLowerCase().startsWith("minecraft:op "))) {
switch (isNotOPWTL(event.getCommand())) {
case mustOnline:
T2C_Send.sender(event.getSender(), Languages.VALUES.playerMustBeOnlineToOp.getValue().toString());
event.setCancelled(true);
break;
case notWhitelisted:
T2C_Send.sender(event.getSender(), Languages.VALUES.opWhitelistOpCommand.getValue());
event.setCancelled(true);
break;
}
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
if (!(boolean) OPWhitelist.VALUES.enable.getValue()) return;
if ((event.getMessage().toLowerCase().startsWith("/op ") || event.getMessage().toLowerCase().startsWith("/minecraft:op "))) {
switch (isNotOPWTL(event.getMessage())) {
case mustOnline:
T2C_Send.player(event.getPlayer(), Languages.VALUES.playerMustBeOnlineToOp.getValue().toString());
event.setCancelled(true);
break;
case notWhitelisted:
T2C_Send.player(event.getPlayer(), Languages.VALUES.opWhitelistOpCommand.getValue().toString());
event.setCancelled(true);
break;
}
}
}
private OpCommandRequest isNotOPWTL(String command) {
if (command.charAt(0) == '/') command = command.replaceFirst("/", "");
String arg = command.replace("op ", "");
Player target = Bukkit.getPlayer(arg);
if ((boolean)OPWhitelist.VALUES.playerMustBeOnlineToOp.getValue()) {
if (target == null) return OpCommandRequest.mustOnline;
if (!opWhitelist(target.getName(), target.getUniqueId().toString())) return OpCommandRequest.notWhitelisted;
}
String targetUUID;
if (target != null) {
targetUUID = target.getUniqueId().toString();
} else {
try {
targetUUID = T2C_NameHistory.NameLookup.getPlayerUUID(arg);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (!opWhitelist(arg, targetUUID)) return OpCommandRequest.notWhitelisted;
return OpCommandRequest.ok;
}
private static Boolean opWhitelist(String playerName, String playerUuid) {
for (Map.Entry<String, PlayerObject> playerObject : PlayerCache.getOpHashMap().entrySet()) {
T2C_Debug.debug(Main.getPlugin(), "--------- " + playerName);
T2C_Debug.debug(Main.getPlugin(),"opWhitelist (op command) playerObject Name: "+playerObject.getValue().playerName );
T2C_Debug.debug(Main.getPlugin(),"opWhitelist (op command) Player Name: "+ playerName );
T2C_Debug.debug(Main.getPlugin(),"opWhitelist (op command) playerObject UUID: "+playerObject.getValue().uuid );
T2C_Debug.debug(Main.getPlugin(),"opWhitelist (op command) Player UUID: "+ playerUuid );
if (playerObject.getValue().playerName.equals(playerName) && playerObject.getValue().uuid.equals(playerUuid.replace("-", ""))) {
T2C_Debug.debug(Main.getPlugin(),"opWhitelist (op command) on list!");
return true;
}
}
return false;
}
}

View File

@ -1,38 +0,0 @@
// This claas was created by JaTiTV
package net.t2code.opsecurity.events;
import net.t2code.opsecurity.util.Util;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Send;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
public class PlugManCommand implements Listener {
@EventHandler
public void onOPServer(ServerCommandEvent event) {
if ((event.getCommand().toLowerCase().contains("plugman disable") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman reload") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman unload") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman restart") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
) {
event.setCancelled(true);
T2C_Send.console(Util.getPrefix() + " §4OPSecurity cannot be deactivated!");
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
if (event.getMessage().toLowerCase().startsWith("/plugman disable") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase())
|| (event.getMessage().toLowerCase().startsWith("/plugman reload") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getMessage().toLowerCase().startsWith("/plugman unload") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getMessage().toLowerCase().startsWith("/plugman restart") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
) {
event.setCancelled(true);
T2C_Send.player(event.getPlayer(), Util.getPrefix() + " §4OPSecurity cannot be deactivated!");
}
}
}

View File

@ -1,13 +0,0 @@
package net.t2code.opsecurity.objects;
import lombok.Getter;
import java.util.HashMap;
public class PlayerCache {
@Getter
private static HashMap<String, PlayerObject> opHashMap = new HashMap<String, PlayerObject>();
@Getter
private static HashMap<String, PlayerObject> permissionHashMap = new HashMap<String, PlayerObject>();
}

View File

@ -1,11 +0,0 @@
package net.t2code.opsecurity.objects;
public class PlayerObject {
public String playerName;
public String uuid;
public PlayerObject(String playerName, String uuid) {
this.playerName = playerName;
this.uuid = uuid;
}
}

View File

@ -1,42 +0,0 @@
package net.t2code.opsecurity.system;
import net.t2code.opsecurity.events.Events;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.util.T2C_Util;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import java.io.*;
public class BungeeSenderReceiver implements PluginMessageListener {
public static void sendToBungee(String information) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(stream);
try {
output.writeUTF(information.toString());
} catch (IOException e) {
e.printStackTrace();
}
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendPluginMessage(Main.getPlugin(), T2C_Util.getPluginChannel_OPSecurity(), stream.toByteArray());
return;
}
}
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(message));
T2C_Debug.debug(Main.getPlugin(), "stream: " + stream.toString());
try {
String subChannel = stream.readUTF();
String information = stream.readUTF();
if (subChannel.equals(T2C_Util.getPluginSubChannel_Console())) {
Events.notifyPlayer(information);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,57 +0,0 @@
package net.t2code.opsecurity.system;
import net.t2code.opsecurity.util.Util;
import net.t2code.opsecurity.check.Timer;
import net.t2code.opsecurity.command.CmdExecuter;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.config.Converter;
import net.t2code.opsecurity.config.language.Languages;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.config.permissionWhitelist.PermissionWhitelist;
import net.t2code.opsecurity.events.Events;
import net.t2code.opsecurity.events.OpCommand;
import net.t2code.opsecurity.events.PlugManCommand;
import net.t2code.t2codelib.SPIGOT.api.debug.T2C_Debug;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Template;
import net.t2code.t2codelib.SPIGOT.api.register.T2C_Register;
import net.t2code.t2codelib.SPIGOT.api.update.T2C_UpdateAPI;
import net.t2code.t2codelib.SPIGOT.system.config.config.T2C_LibConfig;
import net.t2code.t2codelib.util.T2C_Util;
import org.bukkit.Bukkit;
import java.util.List;
import java.util.logging.Level;
public class Load {
public static void onLoad(Main plugin, List<String> autor, String version) {
long long_ = T2C_Template.onLoadHeader(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord());
try {
Converter.convert();
} catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE, ex.getMessage());
ex.printStackTrace();
}
Config.set(false);
Languages.set(false);
OPWhitelist.set(false);
PermissionWhitelist.set(false);
plugin.getCommand("t2c-opsecurity").setExecutor(new CmdExecuter());
T2C_Register.listener(new OpCommand(), plugin);
T2C_Register.listener(new PlugManCommand(), plugin);
T2C_Register.listener(new Events(), plugin);
if ((boolean) T2C_LibConfig.VALUES.proxy.getValue()) {
Bukkit.getMessenger().registerOutgoingPluginChannel(plugin, T2C_Util.getPluginChannel_OPSecurity());
T2C_Debug.debug(plugin, "registerIncomingPluginChannel §e:" + T2C_Util.getPluginChannel_OPSecurity());
}
Timer.refreshTimer();
Permissions.register();
T2C_UpdateAPI.onUpdateCheck(plugin, Util.getPrefix(), Util.getGit(), Util.getSpigotID(), Util.getDiscord(), (boolean) Config.VALUES.updateCheckOnJoin.getValue(),
(boolean) Config.VALUES.updateCheckSeePreReleaseUpdates.getValue(), (int) Config.VALUES.updateCheckTimeInterval.getValue());
Metrics.Bstats(plugin, Util.getBstatsID());
T2C_Template.onLoadFooter(Util.getPrefix(), long_);
}
}

View File

@ -1,91 +0,0 @@
package net.t2code.opsecurity.system;
import lombok.Getter;
import net.t2code.opsecurity.util.Util;
import net.t2code.t2codelib.SPIGOT.api.messages.T2C_Template;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
public final class Main extends JavaPlugin {
public static File getPath() {
return plugin.getDataFolder();
}
@Getter
private static Boolean t2codeLib = false;
@Getter
private static String version;
@Getter
private static List<String> autor;
@Getter
private static Main plugin;
@Override
public void onEnable() {
// Plugin startup logic
plugin = this;
autor = this.getDescription().getAuthors();
version = this.getDescription().getVersion();
if (pluginNotFound("T2CodeLib", 96388, Util.getRequiredT2CodeLibVersion())) return;
load();
}
private static void load(){
if (!Bukkit.getPluginManager().getPlugin("T2CodeLib").isEnabled()){
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() {
@Override
public void run() {
load();
}
},5L);
return;
}
t2codeLib = true;
Load.onLoad(plugin,autor,version);
}
@Override
public void onDisable() {
// Plugin shutdown logic
if (t2codeLib) T2C_Template.onDisable(Util.getPrefix(),plugin);
}
private static Boolean pluginNotFound(String pl, Integer spigotID, String ver) {
if (Bukkit.getPluginManager().getPlugin(pl) == null || !Bukkit.getPluginManager().isPluginEnabled(pl)) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4could not be found. Please download it here: "
+ "§6https://spigotmc.org/resources/" + pl + "." + spigotID + " §4to be able to use this plugin.");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
} else {
String plVer = Bukkit.getPluginManager().getPlugin(pl).getDescription().getVersion();
if (ver.contains("_")) {
if (!plVer.equals(ver)) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4is out of date! This plugin requires the version §2"
+ ver + " §4of §6" + pl + " §4Please use this version! Please download it here or contact us in Discord: §6https://spigotmc.org/resources/"
+ pl + "." + spigotID + " Or contact us in Discord: http://dc.t2code.net");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
}
return false;
}
String[] split = plVer.split("_");
if (Double.parseDouble(split[0]) < Double.parseDouble(ver)) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4is out of date! This plugin requires at least version §2"
+ ver + " §4of §6" + pl + " §4Please update it here: §6https://spigotmc.org/resources/" + pl + "." + spigotID
+ " §4to use this version of " + plugin.getDescription().getName() + ".");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
}
return false;
}
}
}

View File

@ -1,32 +0,0 @@
package net.t2code.opsecurity.system;
import net.t2code.t2codelib.SPIGOT.api.register.T2C_Register;
import org.bukkit.permissions.PermissionDefault;
public class Permissions {
public static final String key = "t2c.opsecurity.";
public static final String notify = key + "notify";
public static final String updatemsg = key + "updatemsg";
public static final String reload = key + "command.reload";
public static final String info = key + "command.info";
public static final String help = key + "command.help";
public static final String admin = key + "admin";
public static final PermissionDefault op = PermissionDefault.OP;
public static final PermissionDefault notOp = PermissionDefault.NOT_OP;
protected static void register() {
T2C_Register.permission(notify, op, Main.getPlugin());
T2C_Register.permissionDescription(notify,"Players with this permission get the update message when joining if an update is available",Main.getPlugin());
T2C_Register.permission(updatemsg, op, Main.getPlugin());
T2C_Register.permission(reload, op, Main.getPlugin());
T2C_Register.permission(info, op, Main.getPlugin());
T2C_Register.permission(help, op, Main.getPlugin());
T2C_Register.permission(admin, op, notify, true, Main.getPlugin());
T2C_Register.permission(admin, op, updatemsg, true, Main.getPlugin());
T2C_Register.permission(admin, op, reload, true, Main.getPlugin());
T2C_Register.permission(admin, op, info, true, Main.getPlugin());
T2C_Register.permission(admin, op, help, true, Main.getPlugin());
}
}

View File

@ -1,40 +0,0 @@
package net.t2code.opsecurity.util;
import lombok.Getter;
import net.t2code.t2codelib.util.T2C_Util;
import java.util.ArrayList;
import java.util.Arrays;
public class Util {
@Getter
private static String infoText = "";
@Getter
private static String requiredT2CodeLibVersion = "16.7";
@Getter
private static String prefix = "§8[§4T2C§8-§2OP§4Security§8]";
@Getter
private static Integer spigotID = 90739;
@Getter
private static String git = "JaTiTV/T2C-OPSecurity";
@Getter
private static Integer bstatsID = 10858;
@Getter
private static String spigot = "https://spigotmc.org/resources/" + getSpigotID();
@Getter
private static String discord = "http://dc.t2code.net";
public static String[] getConfigLogo() {
ArrayList<String> arrayList = new ArrayList<>(T2C_Util.getConfigT2CodeLogo());
arrayList.addAll(Arrays.asList("", "# Spigot: " + spigot));
return arrayList.toArray(new String[0]);
}
}

View File

@ -1,16 +0,0 @@
name: T2C-OPSecurity
provides: [OPSecurity]
version: '${project.version}'
main: net.t2code.opsecurity.system.Main
api-version: 1.13
load: STARTUP
prefix: T2C-OPSecurity
authors: [ JaTiTV ]
softdepend:
- T2CodeLib
commands:
t2c-opsecurity:
aliases: [opsec, opsecurity]

View File

@ -1,19 +1,15 @@
<p align="center">
<img src="https://i.imgur.com/TjwVdDO.png" width="300">
<img src="https://i.imgur.com/eONeN6b.png" width="300">
</p>
---
# Links
* [Spigot](https://www.spigotmc.org/resources/t2c-opsecurity-permission-security-1-8-x-1-19-x.90739/)
* [Download](https://www.spigotmc.org/resources/opwhitelist.90739/)
* [Discord](http://dc.T2Code.net)
<img src="https://i.imgur.com/k2NgnGj.png" width="600">
---
<img src="https://i.imgur.com/9ahfmOG.png" width="600">
With OPSecurity you can specify usernames that are allowed to have OP or certain permissions.
If someone enters the server with OP who is not on this whitelist, Optional can be kicked or have OP removed.
### English
With OPSecurity you can specify usernames that are allowed to have OP or certain permissions. If someone enters the server with OP who is not on this whitelist, Optional can be kicked or have OP removed.
This plugin also protects players from getting OP via unauthorized ways, e.g. hacked client, because only players who are on the OP whitelist can get OP with the command /op.
@ -21,7 +17,7 @@ You can also use a timer that checks every few seconds (adjustable) if there is
Please note that you can only give OP via the console to players who are on the whitelist!
**Features:**
Features:
- Protection against op hacks
- Protection for specific permissions
- Decide who may have OP
@ -29,41 +25,40 @@ Please note that you can only give OP via the console to players who are on the
Just come to the support Discord for further questions.
---
### German
Mit OPSecurity kannst du Benutzernamen angeben Die OP oder bestimmte Permissions besitzen dürfen. Wenn jemand mit OP den Server betritt, der nicht auf dieser Whitelist steht, kann Optional gekickt werden oder OP entfernt bekommen.
**You can use MiniMessage:**
Dieses Plugin schützt des Weiteren davor, dass Spieler sich OP über nicht erlaubte Wege besorgen, z.B. Hacked Client, denn nur Spieler die auf der OP Whitelist stehen können mit dem Befehl /op OP bekommen.
Wiki: https://docs.adventure.kyori.net/minimessage/format.html
Es kann auch ein Timer verwendet werden der aller paar Sekunden (einstellbar) prüft ob sich ein Spieler mit OP oder einer Permission auf dem Server befindet dersich nicht auf der Whitelist befindet.
WebUI: https://webui.adventure.kyori.net
Beachte bitte, dass man auch über die Console nur Spielern OP geben kann die auf der Whitelist stehen!
Features:
- Schutz vor OP Hacks
- Schutz für bestimmte permissions
- Entscheide wer OP haben darf
- Selbst über Konsole schützt OP Security
<img src="https://i.imgur.com/55BlvCg.png" width="600">
Komm für weitere Fragen einfach auf den Support Discord.
**/t2c-opsecurity** | **/opsecurity** | **/opsec**
<img src="https://i.imgur.com/wNDEjg9.png" width="600">
**/t2c-opsecurity help** - Open the help.
opsecurity.admin | For all Commands.
opsecurity.notify | Players with this permission will receive notifications fromOPSecurity.
**/t2c-opsecurity info** - See the current plugin version.
/opsecurity | /opwl
**/t2c-opsecurity reload** - Reloads the Plugin.
/opsecurity help - Open the help.
/opsecurity info - See the current plugin version.
*t2c.opsecurity.notify* - Permission for ingame notifications when a player joins that is not on the whitelist
*t2c.opsecurity.updatemsg* - Update Check on join
*t2c.opsecurity.command.reload* - Reload command
*t2c.opsecurity.command.info* - Info command
*t2c.opsecurity.command.help* - Help command
*t2c.opsecurity.admin* - All permissions of T2C-OPSecurity
/opsecurity reload - Reloads the Plugin.
<img src="https://i.imgur.com/YbDziZO.png" width="600">
---
<img src="https://i.imgur.com/HoZSt7c.png" width="600">
<img src="https://bstats.org/signatures/bukkit/OPWhitelist.svg" width="600">

View File

@ -6,7 +6,7 @@
<groupId>de.jatitv</groupId>
<artifactId>OPSecurity</artifactId>
<version>2.4.3</version>
<version>2.4.0_Snapshot_2</version>
<packaging>jar</packaging>
<name>OPSecurity</name>
@ -73,8 +73,7 @@
<dependency>
<groupId>net.t2code</groupId>
<artifactId>T2CodeLib</artifactId>
<version>DEV-13.0</version>
<classifier>dev-5</classifier>
<version>10.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,34 @@
package de.jatitv.opsecurity;
public class Util {
private static double requiredT2CodeLibVersion = 10.1;
private static String Prefix = "§8[§2OP§4Security§8]";
private static Integer SpigotID = 90739;
private static Integer BstatsID = 10858;
private static String Spigot = "https://www.spigotmc.org/resources/" + SpigotID;
private static String Discord = "http://dc.t2code.net";
public static double getRequiredT2CodeLibVersion() {
return requiredT2CodeLibVersion;
}
public static String getPrefix() {
return Prefix;
}
public static Integer getSpigotID() {
return SpigotID;
}
public static Integer getBstatsID() {
return BstatsID;
}
public static String getSpigot() {
return Spigot;
}
public static String getDiscord() {
return Discord;
}
}

View File

@ -23,7 +23,7 @@ public class CmdExecuter implements CommandExecutor, TabCompleter {
if (args.length == 0) {
Commands.mainCommand(sender);
} else {
if (SelectConfig.onlyOpCanUseThePlugin) {
if (SelectConfig.OnlyOPcanUseThePlugin) {
if (!sender.isOp()) {
sender.sendMessage(Util.getPrefix() + "§cOnly OPs can use OPSecurity!");
return false;

View File

@ -6,16 +6,22 @@ import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Load;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.t2code.lib.Spigot.Lib.messages.T2CodeTemplate;
import net.t2code.lib.Spigot.Lib.messages.send;
import net.t2code.lib.Spigot.Lib.update.UpdateAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.List;
public class Commands {
public static void mainCommand(CommandSender sender) {
if (SelectConfig.onlyOpCanUseThePlugin) {
if (SelectConfig.OnlyOPcanUseThePlugin) {
if (!sender.isOp()) {
sender.sendMessage(Util.getPrefix() + "§cOnly OPs can use OPSecurity!");
return;
@ -23,29 +29,27 @@ public class Commands {
}
if (sender.hasPermission(Permissions.help)) {
SelectConfig.Help(sender);
} else {
sender.sendMessage(Util.getPrefix() + " §cYou do not have permission for OPSecurity! §7<" + Permissions.help + ">");
}
} else sender.sendMessage(Util.getPrefix() + " §cYou do not have permission for OPSecurity!");
}
public static void reload(CommandSender sender) {
if (!sender.hasPermission(Permissions.reload)) {
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity! §7<" + Permissions.reload + ">");
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity!");
return;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!Main.getOpHashMap().containsKey(player.getName().toLowerCase())) {
if (!Main.opHashMap.containsKey(player.getName().toLowerCase())) {
sender.sendMessage(Util.getPrefix() + " §4You are not on the Whitelist!");
return;
}
if (!Main.getOpHashMap().get(player.getName().toLowerCase()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
if (!Main.opHashMap.get(player.getName().toLowerCase()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
sender.sendMessage(Util.getPrefix() + " §4You are not on the Whitelist!");
return;
}
T2Csend.player(player, SelectMessages.ReloadStart);
send.player(player, SelectMessages.ReloadStart);
}
if (sender instanceof Player) T2Csend.player((Player) sender, SelectMessages.ReloadEnd);
if (sender instanceof Player) send.player((Player) sender, SelectMessages.ReloadEnd);
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §6Plugin reload...");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
@ -58,9 +62,9 @@ public class Commands {
public static void info(CommandSender sender) {
if (!sender.hasPermission(Permissions.info)) {
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity! §7<" + Permissions.info + ">");
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity!");
return;
}
T2Ctemplate.sendInfo(sender,Main.getPlugin(),Util.getSpigotID(),Util.getDiscord(),Util.getInfoText());
T2CodeTemplate.sendInfo(sender, Util.getPrefix(), Util.getSpigot(), Util.getDiscord(), Main.autor, Main.version, UpdateAPI.PluginVersionen.get(Main.plugin.getName()).publicVersion);
}
}

View File

@ -3,7 +3,7 @@ package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.NameHistory;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.messages.send;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
@ -49,9 +49,10 @@ public class ConfigConvert {
}
private static void configConvert() {
File config = new File(Main.getPlugin().getDataFolder().getPath(), "config.yml");
File config = new File(Main.plugin.getDataFolder().getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
if (yamlConfiguration.get("ConfigVersion") == null) {
try {
if (yamlConfiguration.get("Plugin.language") != null) {
@ -106,10 +107,13 @@ public class ConfigConvert {
}
}
List<String> oldOPs = yamlConfiguration.getStringList("OP_Whitelist.Whitelist");
yamlConfiguration.set("OP_Whitelist.Whitelist", null);
convertPlayer("OP_Whitelist.Whitelist", "OP_Whitelist.Whitelist.", oldOPs, yamlConfiguration);
List<String> oldPerms = yamlConfiguration.getStringList("Permission_Whitelist.Player");
yamlConfiguration.set("Permission_Whitelist.Player", null);
convertPlayer("Permission_Whitelist.Player", "Permission_Whitelist.Whitelist.", oldPerms, yamlConfiguration);
@ -118,14 +122,16 @@ public class ConfigConvert {
} catch (IOException tac) {
tac.printStackTrace();
}
}
}
public static void convert(String oldConfig, String newConfig) {
T2Csend.console(Util.getPrefix() + " §5Convert: §4" + oldConfig + " §5--> §2" + newConfig);
send.console(Util.getPrefix() + " §5Convert: §4" + oldConfig + " §5--> §2" + newConfig);
}
public static void convert(String config, String oldConfig, String newConfig) {
T2Csend.console(Util.getPrefix() + " §5Convert: §e" + config + " §4" + oldConfig + " §5--> §2" + newConfig);
send.console(Util.getPrefix() + " §5Convert: §e" + config + " §4" + oldConfig + " §5--> §2" + newConfig);
}
private static void convertPlayer(String oldPath, String newPath, List<String> oldPlayer, YamlConfiguration yamlConfiguration) {
@ -133,7 +139,7 @@ public class ConfigConvert {
try {
String uuid = NameHistory.getPlayerUUID(Player);
if (uuid == null) {
T2Csend.warning(Main.getPlugin(),
send.warning(Main.plugin,
"The UUID of the player §6" + Player + " §ecould not be found. Please check the config.yml and / or if the player exists / if the player name is correct!");
convert("config.yml", oldPath + ": " + Player, newPath + ": " + Player + ": UUID: Player UUID not found!");
yamlConfiguration.set(newPath + Player + ".UUID", "Player UUID not found!");
@ -150,6 +156,7 @@ public class ConfigConvert {
private static void renameLanguages() {
String replace = Main.getPath().toString() + "/languages/";
Path messagesDEold = Paths.get(Main.getPath() + "/languages/de_DE_Messages.yml");
Path messagesDE = Paths.get(Main.getPath() + "/languages/german_messages.yml");
if(Files.exists(messagesDEold) && !Files.isDirectory(messagesDEold)) {

View File

@ -3,7 +3,7 @@
package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.minecraftVersion.T2CmcVersion;
import net.t2code.lib.Spigot.Lib.minecraftVersion.MCVersion;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
@ -68,7 +68,7 @@ public class CreateConfig {
public static void configCreate() {
Bukkit.getConsoleSender().sendMessage(Prefix + "§4config.yml load...");
File configYML = new File(Main.getPlugin().getDataFolder().getPath(), "config.yml");
File configYML = new File(Main.plugin.getDataFolder().getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(configYML);
yamlConfiguration.set("ConfigVersion", ConfigVersion);
@ -88,12 +88,13 @@ public class CreateConfig {
set("Notify.JoinWarn.Enable", Notify_Warn, yamlConfiguration);
set("Notify.Sound.Enable", Notify_Sound_Enable, yamlConfiguration);
if (T2CmcVersion.isMc1_8()) {
if (MCVersion.minecraft1_8) {
set("Notify.Sound.Sound", Notify_Sound_1_8, yamlConfiguration);
} else if (T2CmcVersion.isMc1_9() || T2CmcVersion.isMc1_10() || T2CmcVersion.isMc1_11() || T2CmcVersion.isMc1_12()) {
} else if (MCVersion.minecraft1_9 || MCVersion.minecraft1_10 || MCVersion.minecraft1_11 || MCVersion.minecraft1_12) {
set("Notify.Sound.Sound", Notify_Sound_1_9_to_1_12, yamlConfiguration);
} else set("Notify.Sound.Sound", Notify_Sound_from_1_13, yamlConfiguration);
set("OP_Whitelist.Enable", OP_Whitelist_Enable, yamlConfiguration);
set("OP_Whitelist.PlayerMustBeOnlineToOp", PlayerMustBeOnlineToOp, yamlConfiguration);
if (yamlConfiguration.get("OP_Whitelist.Whitelist") == null) {
@ -101,6 +102,7 @@ public class CreateConfig {
set("OP_Whitelist.Whitelist." + OP_Whitelist_P2 + ".UUID", OP_Whitelist_P2UUID, yamlConfiguration);
}
set("OP_Whitelist.noOpPlayerDeop.Enable", no_OP_Player_deop, yamlConfiguration);
set("OP_Whitelist.noOpPlayerDeop.PlayerSendMessage", sendPlayerDEOPmsg, yamlConfiguration);
set("OP_Whitelist.noOpPlayerKick.Enable", no_OP_Player_kick, yamlConfiguration);
@ -115,6 +117,7 @@ public class CreateConfig {
set("Permission_Whitelist.Whitelist." + Perm_Whitelist_P2 + ".UUID", Perm_Whitelist_P2UUID, yamlConfiguration);
}
set("Permission_Whitelist.PlayerWhithPermission_kick", PlayerWhithPermission_kick, yamlConfiguration);
set("Permission_Whitelist.customCommands.Enable", Perm_Command_enable, yamlConfiguration);
set("Permission_Whitelist.customCommands.Commands", Perm_Command, yamlConfiguration);
@ -124,6 +127,7 @@ public class CreateConfig {
//set("LuckPerms_Whitelist.Whitelist", LP_Whitelist, yamlConfiguration);
try {
yamlConfiguration.save(configYML);
} catch (IOException e) {

View File

@ -0,0 +1,145 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.objects.PlayerObject;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.Permissions;
import net.t2code.lib.Spigot.Lib.yamlConfiguration.Config;
import org.bukkit.Sound;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class SelectConfig {
// Config
public static Integer ConfigVersion;
public static Boolean UpdateCheckOnJoin;
public static String language;
public static Boolean OnlyOPcanUseThePlugin;
public static Boolean CheckOnJoin;
public static Boolean CheckOnInteract;
public static Boolean CheckOnCommand;
public static Boolean CheckOnChat;
public static String KickCommand;
public static Boolean Notify_Warn;
public static Boolean Notify_Sound_Enable;
public static Sound Notify_Sound;
public static String Notify_Sound_input;
public static Boolean Timer_Enable;
public static int RefreshTime;
public static Boolean OP_Whitelist_Enable;
public static Boolean PlayerMustBeOnlineToOp;
public static Boolean no_OP_Player_deop;
public static Boolean sendPlayerDEOPmsg;
public static Boolean no_OP_Player_kick;
public static Boolean customCommand_Enable;
public static List<String> customKickCommand;
public static Boolean Permission_Whitelist_Enable;
public static List<String> permissions;
public static Boolean PlayerWhithPermission_kick;
public static Boolean Perm_Command_enable;
public static List<String> Perm_Command;
public static Boolean LP_Enable;
public static Boolean LP_AllowFromConsole;
public static List<String> LP_Whitelist;
//help
public static void Help(CommandSender sender) {
if (sender.hasPermission(Permissions.help)) {
sender.sendMessage(Util.getPrefix() + "§cYou do not have permission for OPSecurity!");
return;
}
sender.sendMessage(Util.getPrefix() + " §8----- §2OP§4Security §chelp §8-----");
sender.sendMessage(Util.getPrefix());
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity reload§8' §eReload the Plugin.");
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity help§8' §eOpens this help.");
sender.sendMessage(Util.getPrefix() + " §8'§b/opsecurity info§8' §eCall the info about §2OP§4Security§e.");
sender.sendMessage(Util.getPrefix());
sender.sendMessage(Util.getPrefix() + " §8----------------------------");
}
public static void onSelect() {
File configYML = new File(Main.plugin.getDataFolder().getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(configYML);
Main.opHashMap.clear();
Main.permissionHashMap.clear();
ConfigVersion = yamlConfiguration.getInt("ConfigVersion");
UpdateCheckOnJoin = yamlConfiguration.getBoolean("Plugin.UpdateCheckOnJoin");
language = yamlConfiguration.getString("Plugin.language");
OnlyOPcanUseThePlugin = yamlConfiguration.getBoolean("Plugin.OnlyOPcanUseThePlugin");
CheckOnJoin = yamlConfiguration.getBoolean("Check.OnJoin");
CheckOnInteract = yamlConfiguration.getBoolean("Check.OnInteract");
CheckOnCommand = yamlConfiguration.getBoolean("Check.OnCommand");
CheckOnChat = yamlConfiguration.getBoolean("Check.OnChat");
Timer_Enable = yamlConfiguration.getBoolean("Check.Timer.Enable");
RefreshTime = yamlConfiguration.getInt("Check.Timer.RefreshTime_inSec");
KickCommand = yamlConfiguration.getString("Kick.Command");
Notify_Warn = yamlConfiguration.getBoolean("Notify.JoinWarn.Enable");
Notify_Sound_Enable = yamlConfiguration.getBoolean("Notify.Sound.Enable");
Notify_Sound_input = yamlConfiguration.getString("Notify.Sound.Sound");
OP_Whitelist_Enable = yamlConfiguration.getBoolean("OP_Whitelist.Enable");
PlayerMustBeOnlineToOp = yamlConfiguration.getBoolean("OP_Whitelist.PlayerMustBeOnlineToOp");
ArrayList<PlayerObject> opWhitelist = new ArrayList<>();
for (String key : yamlConfiguration.getConfigurationSection("OP_Whitelist.Whitelist").getKeys(false)) {
PlayerObject player = new PlayerObject(
yamlConfiguration.getString("OP_Whitelist.Whitelist." + key + ".UUID").replace("-", ""));
opWhitelist.add(player);
Main.opHashMap.put(key.toLowerCase(), player);
}
no_OP_Player_deop = yamlConfiguration.getBoolean("OP_Whitelist.noOpPlayerDeop.Enable");
sendPlayerDEOPmsg = yamlConfiguration.getBoolean("OP_Whitelist.noOpPlayerDeop.PlayerSendMessage");
no_OP_Player_kick = yamlConfiguration.getBoolean("OP_Whitelist.noOpPlayerKick.Enable");
customCommand_Enable = yamlConfiguration.getBoolean("OP_Whitelist.customCommands.Enable");
customKickCommand = yamlConfiguration.getStringList("OP_Whitelist.customCommands.Commands");
Permission_Whitelist_Enable = yamlConfiguration.getBoolean("Permission_Whitelist.Enable");
permissions = yamlConfiguration.getStringList("Permission_Whitelist.Permissions");
ArrayList<PlayerObject> permWhitelist = new ArrayList<>();
for (String key : yamlConfiguration.getConfigurationSection("Permission_Whitelist.Whitelist").getKeys(false)) {
PlayerObject player = new PlayerObject(
yamlConfiguration.getString("Permission_Whitelist.Whitelist." + key + ".UUID").replace("-", ""));
permWhitelist.add(player);
Main.permissionHashMap.put(key.toLowerCase(), player);
}
PlayerWhithPermission_kick = yamlConfiguration.getBoolean("Permission_Whitelist.PlayerWhithPermission_kick");
Perm_Command_enable = yamlConfiguration.getBoolean("Permission_Whitelist.customCommands.Enable");
Perm_Command = yamlConfiguration.getStringList("Permission_Whitelist.customCommands.Commands");
LP_Enable = yamlConfiguration.getBoolean("LuckPerms_Whitelist.Enable");
LP_AllowFromConsole = yamlConfiguration.getBoolean("LuckPerms_Whitelist.AllowFromConsole");
LP_Whitelist = yamlConfiguration.getStringList("LuckPerms_Whitelist.Whitelist");
}
public static void sound() {
Notify_Sound = Config.checkSound(CreateConfig.Notify_Sound_1_8, CreateConfig.Notify_Sound_1_9_to_1_12, CreateConfig.Notify_Sound_from_1_13, Notify_Sound_input, Util.getPrefix());
}
}

View File

@ -5,7 +5,7 @@ package de.jatitv.opsecurity.config.languages;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.messages.send;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
@ -14,8 +14,8 @@ import java.io.IOException;
public class LanguagesCreate {
public static void messagesCreate() {
T2Csend.debug(Main.getPlugin(),"§4Language files are created / updated...");
long long_ = System.currentTimeMillis();
send.debug(Main.plugin,"§4Language files are created / updated...");
Long long_ = Long.valueOf(System.currentTimeMillis());
File messagesDE = new File(Main.getPath(), "languages/german_messages.yml");
YamlConfiguration yamlConfigurationDE = YamlConfiguration.loadConfiguration(messagesDE);
@ -37,6 +37,7 @@ public class LanguagesCreate {
set("Permission_Whitelist.consoleKick", MSG.DE_Perm_consoleKick, yamlConfigurationDE);
set("Console.ExactKickReason", MSG.DE_ExactKickReason, yamlConfigurationDE);
try {
yamlConfigurationDE.save(messagesDE);
} catch (IOException e) {
@ -94,7 +95,7 @@ public class LanguagesCreate {
} catch (IOException e) {
e.printStackTrace();
}
T2Csend.console(Util.getPrefix() + " §2Language files were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_) + "ms");
send.console(Util.getPrefix() + " §2Language files were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_.longValue()) + "ms");
}
private static void set(String path, String value, YamlConfiguration config) {

View File

@ -6,8 +6,8 @@ package de.jatitv.opsecurity.config.languages;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Creplace;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.messages.send;
import net.t2code.lib.Spigot.Lib.replace.Replace;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
@ -39,19 +39,19 @@ public class SelectMessages {
public static void selectCreate(String Prefix) {
T2Csend.debug(Main.getPlugin(), "§4Select language...");
long long_ = System.currentTimeMillis();
send.debug(Main.plugin, "§4Select language...");
Long long_ = Long.valueOf(System.currentTimeMillis());
File msg;
msg = new File(Main.getPath(), "languages/" + SelectConfig.language + "_messages.yml");
if (!msg.isFile()) {
T2Csend.console(Prefix);
T2Csend.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
T2Csend.console(Prefix + " §4The selected §c" + SelectConfig.language + " §4language file was not found.");
T2Csend.console(Prefix + " §6The default language §eEnglish §6is used!");
T2Csend.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
T2Csend.console(Prefix);
send.console(Prefix);
send.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
send.console(Prefix + " §4The selected §c" + SelectConfig.language + " §4language file was not found.");
send.console(Prefix + " §6The default language §eEnglish §6is used!");
send.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
send.console(Prefix);
msg = new File(Main.getPath(), "languages/" + "english_messages.yml");
selectMSG = "english";
} else selectMSG = SelectConfig.language;
@ -76,10 +76,11 @@ public class SelectMessages {
Perm_consoleKick = select("Permission_Whitelist.consoleKick", yamlConfiguration);
ExactReason = select("Console.ExactKickReason", yamlConfiguration);
T2Csend.console(Prefix + " §2Language successfully selected to: §6" + selectMSG + " §7- §e" + (System.currentTimeMillis() - long_) + "ms");
send.console(Prefix + " §2Language successfully selected to: §6" + selectMSG + " §7- §e" + (System.currentTimeMillis() - long_.longValue()) + "ms");
}
private static String select(String path, YamlConfiguration yamlConfiguration) {
return T2Creplace.replace(Util.getPrefix(),yamlConfiguration.getString(path));
return Replace.replace(Util.getPrefix(),yamlConfiguration.getString(path));
}
}

View File

@ -0,0 +1,167 @@
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.Permissions;
import net.t2code.lib.Spigot.Lib.commands.Cmd;
import net.t2code.lib.Spigot.Lib.messages.send;
import net.t2code.lib.Spigot.Lib.replace.Replace;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class Check {
public static Boolean onCheck(Player player, Boolean join) {
if (SelectConfig.OP_Whitelist_Enable) {
if (player.isOp()) {
if (opWhitelist(player)) {
return false;
}
if (join) {
send.console(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleOnJoin.replace("[player]", player.getName())));
}
if (SelectConfig.Notify_Warn) {
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
if (join) {
notifyperm.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleOnJoin.replace("[player]", player.getName())));
} else notifyperm.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
if (SelectConfig.Notify_Sound_Enable) {
notifyperm.playSound(player.getLocation(), SelectConfig.Notify_Sound, 3, 1);
}
}
}
}
if (SelectConfig.no_OP_Player_kick && SelectConfig.no_OP_Player_deop) {
player.setOp(false);
Cmd.console(SelectConfig.KickCommand.replace("[player]", player.getName())
.replace("[reason]", Replace.replace(Util.getPrefix(),SelectMessages.OP_kick + "\n" + "\n" + SelectMessages.OP_deop)));
send.console(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
return true;
} else {
if (SelectConfig.no_OP_Player_kick) {
Cmd.console(SelectConfig.KickCommand.replace("[player]", player.getName()).replace("[reason]", Replace.replace(Util.getPrefix(),SelectMessages.OP_kick)));
send.console(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
notifyperm.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleKick.replace("[player]", player.getName())
+ "\n" + SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
}
}
return true;
}
if (SelectConfig.no_OP_Player_deop) {
player.setOp(false);
if (SelectConfig.sendPlayerDEOPmsg) {
new BukkitRunnable() {
@Override
public void run() {
player.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.OP_deop));
}
}.runTaskLater(Main.plugin, 5L);
}
send.console(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
notifyperm.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
}
}
return true;
}
}
if (SelectConfig.customCommand_Enable) {
new BukkitRunnable() {
@Override
public void run() {
for (String cmd : SelectConfig.customKickCommand) {
Cmd.console(Replace.replace(Util.getPrefix(),cmd.replace("[player]", player.getName())));
}
}
}.runTaskLater(Main.plugin, 5L);
return true;
}
}
}
if (SelectConfig.Permission_Whitelist_Enable) {
for (String s : SelectConfig.permissions) {
if (player.hasPermission(s)) {
if (!permWhitelist(player)) {
if (join) {
send.console(Replace.replace(Util.getPrefix(),SelectMessages.Perm_consoleOnJoin.replace("[player]", player.getName()).replace("[perm]", s)));
}
if (SelectConfig.Notify_Warn) {
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission(Permissions.notify)) {
if (join) {
notifyperm.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.Perm_consoleOnJoin.replace("[player]",
player.getName()).replace("[perm]", s)));
} else notifyperm.sendMessage(Replace.replace(Util.getPrefix(),SelectMessages.Perm_consoleKick.replace("[player]",
player.getName()).replace("[perm]", s)));
if (SelectConfig.Notify_Sound_Enable) {
notifyperm.playSound(player.getLocation(), SelectConfig.Notify_Sound, 3, 1);
}
}
}
}
if (SelectConfig.PlayerWhithPermission_kick && SelectConfig.Perm_Command_enable) {
Cmd.console(SelectConfig.KickCommand.replace("[player]", player.getName()).replace("[reason]", Replace.replace(Util.getPrefix(),SelectMessages.Perm_kick)));
send.console(Replace.replace(Util.getPrefix(),SelectMessages.Perm_consoleKick.replace("[player]",
player.getName()).replace("[perm]", s)));
for (String cmd : SelectConfig.Perm_Command) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), cmd.replace("[player]", player.getName()).replace("[perm]", s));
}
return true;
}
if (SelectConfig.PlayerWhithPermission_kick) {
Cmd.console(SelectConfig.KickCommand.replace("[player]", player.getName()).replace("[reason]", Replace.replace(Util.getPrefix(),SelectMessages.Perm_kick)));
send.console(Replace.replace(Util.getPrefix(),SelectMessages.Perm_consoleKick.replace("[player]",
player.getName()).replace("[perm]", s)));
return true;
}
if (SelectConfig.Perm_Command_enable) {
for (String cmd : SelectConfig.Perm_Command) {
Cmd.console(cmd.replace("[player]", player.getName()).replace("[perm]", s));
}
return true;
}
return true;
}
}
}
}
return false;
}
private static Boolean opWhitelist(Player player) {
if (Main.opHashMap.containsKey(player.getName().toLowerCase())) {
if (Main.opHashMap.get(player.getName().toLowerCase()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
return true;
} else {
send.console(SelectMessages.ExactReason.replace("[reason]", "Player UUID: " + player.getUniqueId().toString() + " not whitelisted"));
return false;
}
} else {
send.console(SelectMessages.ExactReason.replace("[reason]", "Player name: " + player.getName() + " not whitelisted"));
return false;
}
}
private static Boolean permWhitelist(Player player) {
if (Main.permissionHashMap.containsKey(player.getName().toLowerCase())) {
if (Main.permissionHashMap.get(player.getName().toLowerCase()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
return true;
} else {
send.console(SelectMessages.ExactReason.replace("[reason]", "Player UUID: " + player.getUniqueId().toString() + " not whitelisted"));
return false;
}
} else {
send.console(SelectMessages.ExactReason.replace("[reason]", "Player name: " + player.getName() + " not whitelisted"));
return false;
}
}
}

View File

@ -5,7 +5,7 @@ package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.update.T2CupdateAPI;
import net.t2code.lib.Spigot.Lib.update.UpdateAPI;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.*;
@ -15,21 +15,20 @@ public class Events implements org.bukkit.event.Listener {
@EventHandler
public void CommandSendEvent(PlayerCommandPreprocessEvent event) {
if (SelectConfig.checkOnCommand) {
if (SelectConfig.CheckOnCommand) {
Player player = event.getPlayer();
if (Check.onCheck(player, false)) {
if (event.isCancelled()) return;
event.setCancelled(true);
}
event.setCancelled(Check.onCheck(player, false));
}
}
@EventHandler
public void PlayerChatEvent(PlayerChatEvent event) {
if (SelectConfig.checkOnChat) {
if (SelectConfig.CheckOnChat) {
Player player = event.getPlayer();
if (Check.onCheck(player, false)) {
if (event.isCancelled()) return;
if (event.isCancelled()) {
return;
}
event.setCancelled(true);
}
}
@ -37,33 +36,33 @@ public class Events implements org.bukkit.event.Listener {
@EventHandler
public void onInteract(PlayerInteractEvent event) {
if (SelectConfig.checkOnInteract) {
if (SelectConfig.CheckOnInteract) {
Player player = event.getPlayer();
new BukkitRunnable() {
@Override
public void run() {
event.setCancelled(Check.onCheck(player, false));
}
}.runTaskLater(Main.getPlugin(), 1L);
}.runTaskLater(Main.plugin, 1L);
}
}
@EventHandler
public void onJoinCheck(PlayerJoinEvent event) {
if (SelectConfig.checkOnJoin) {
if (SelectConfig.CheckOnJoin) {
Player player = event.getPlayer();
new BukkitRunnable() {
@Override
public void run() {
Check.onCheck(player, true);
}
}.runTaskLater(Main.getPlugin(), 1L);
}.runTaskLater(Main.plugin, 1L);
}
}
@EventHandler
public void onJoinEvent(PlayerLoginEvent event) {
Player player = event.getPlayer();
T2CupdateAPI.join(Main.getPlugin(), Util.getPrefix(), "opsecurity.updatemsg", player, Util.getSpigotID(), Util.getDiscord());
UpdateAPI.join(Main.plugin, Util.getPrefix(), "opsecurity.updatemsg", player, Util.getSpigot(), Util.getDiscord());
}
}

View File

@ -3,14 +3,21 @@
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import net.t2code.lib.Spigot.Lib.replace.Replace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
import java.util.Iterator;
public class LPCommand implements Listener {
/*
private boolean LPCheck(String command) {
if (command.charAt(0) == '/') {
command = command.replaceFirst("/", "");
@ -76,6 +83,4 @@ public class LPCommand implements Listener {
event.setCancelled(true);
}
}
*/
}

View File

@ -7,8 +7,8 @@ import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.NameHistory;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Creplace;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.messages.send;
import net.t2code.lib.Spigot.Lib.replace.Replace;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -21,68 +21,67 @@ import org.bukkit.event.server.ServerCommandEvent;
public class OPCommand implements Listener {
@EventHandler
public void onOPServer(ServerCommandEvent event) {
if ((event.getCommand().toLowerCase().startsWith("op ") || event.getCommand().toLowerCase().startsWith("minecraft:op ")) && SelectConfig.opWhitelistEnable) {
switch (this.isNotOPWTL(event.getCommand())) {
case 1:
T2Csend.sender(event.getSender(), Util.getPrefix() + " " + SelectMessages.PlayerMustBeOnlineToOp);
event.setCancelled(true);
break;
case 2:
T2Csend.sender(event.getSender(), (T2Creplace.replace(Util.getPrefix(), Util.getPrefix() + " " + SelectMessages.OP_opCommand)));
event.setCancelled(true);
break;
}
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
if (SelectConfig.opWhitelistEnable) {
if ((event.getMessage().toLowerCase().startsWith("/op ") || event.getMessage().toLowerCase().startsWith("/minecraft:op "))) {
switch (this.isNotOPWTL(event.getMessage())) {
case 1:
T2Csend.sender(event.getPlayer(), Util.getPrefix() + " " + SelectMessages.PlayerMustBeOnlineToOp);
event.setCancelled(true);
break;
case 2:
T2Csend.player(event.getPlayer(), T2Creplace.replace(Util.getPrefix(), Util.getPrefix() + " " + SelectMessages.OP_opCommand));
event.setCancelled(true);
break;
}
}
}
}
private int isNotOPWTL(String command) {
if (!command.contains("op")) return 0;
if (command.charAt(0) == '/') command = command.replaceFirst("/", "");
String arg = command.replace("op ", "");
if (SelectConfig.playerMustBeOnlineToOp) {
if (Main.getOpHashMap().containsKey(arg.toLowerCase())) {
if (SelectConfig.PlayerMustBeOnlineToOp) {
if (Main.opHashMap.containsKey(arg.toLowerCase())) {
Player target = Bukkit.getPlayer(arg);
if (target == null) {
return 1;
}
if (Main.getOpHashMap().get(target.getName().toLowerCase()).UUID.equals(target.getUniqueId().toString().replace("-", ""))) {
if (Main.opHashMap.get(target.getName().toLowerCase()).UUID.equals(target.getUniqueId().toString().replace("-", ""))) {
return 0;
} else return 2;
} else return 2;
} else {
if (Main.getOpHashMap().containsKey(arg.toLowerCase())) {
if (Main.opHashMap.containsKey(arg.toLowerCase())) {
String targetUUID = null;
try {
targetUUID = NameHistory.getPlayerUUID(arg);
} catch (IOException e) {
e.printStackTrace();
}
if (Main.getOpHashMap().get(arg.toLowerCase()).UUID.equals(targetUUID)) {
if (Main.opHashMap.get(arg.toLowerCase()).UUID.equals(targetUUID)) {
return 0;
} else return 2;
} else return 2;
}
}
@EventHandler
public void onOPServer(ServerCommandEvent event) {
if ((event.getCommand().toLowerCase().startsWith("op ") || event.getCommand().toLowerCase().startsWith("minecraft:op ")) && SelectConfig.OP_Whitelist_Enable) {
switch (this.isNotOPWTL(event.getCommand())) {
case 1:
send.sender(event.getSender(), Util.getPrefix() + " " + SelectMessages.PlayerMustBeOnlineToOp);
event.setCancelled(true);
break;
case 2:
send.sender(event.getSender(), (Replace.replace(Util.getPrefix(), Util.getPrefix() + " " + SelectMessages.OP_opCommand)));
event.setCancelled(true);
break;
}
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
if (SelectConfig.OP_Whitelist_Enable) {
if ((event.getMessage().toLowerCase().startsWith("/op ") || event.getMessage().toLowerCase().startsWith("/minecraft:op "))) {
switch (this.isNotOPWTL(event.getMessage())) {
case 1:
send.sender(event.getPlayer(), Util.getPrefix() + " " + SelectMessages.PlayerMustBeOnlineToOp);
event.setCancelled(true);
break;
case 2:
send.player(event.getPlayer(), Replace.replace(Util.getPrefix(), Util.getPrefix() + " " + SelectMessages.OP_opCommand));
event.setCancelled(true);
break;
}
}
}
}
}

View File

@ -4,7 +4,7 @@ package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.lib.Spigot.Lib.messages.send;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
@ -12,27 +12,28 @@ import org.bukkit.event.server.ServerCommandEvent;
public class PlugManCommand implements Listener {
@EventHandler
public void onOPServer(ServerCommandEvent event) {
if ((event.getCommand().toLowerCase().contains("plugman disable") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman reload") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman unload") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman restart") && event.getCommand().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
if ((event.getCommand().toLowerCase().contains("plugman disable") && event.getCommand().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman reload") && event.getCommand().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman unload") && event.getCommand().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
|| (event.getCommand().toLowerCase().contains("plugman restart") && event.getCommand().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
) {
event.setCancelled(true);
T2Csend.console(Util.getPrefix() + " §4OPSecurity cannot be deactivated!");
send.console(Util.getPrefix() + " §4OPSecurity cannot be deactivated!");
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
if (event.getMessage().toLowerCase().startsWith("/plugman disable") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase())
|| (event.getMessage().toLowerCase().startsWith("/plugman reload") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getMessage().toLowerCase().startsWith("/plugman unload") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
|| (event.getMessage().toLowerCase().startsWith("/plugman restart") && event.getMessage().toLowerCase().contains(Main.getPlugin().getDescription().getName().toLowerCase()))
if (event.getMessage().toLowerCase().startsWith("/plugman disable") && event.getMessage().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase())
|| (event.getMessage().toLowerCase().startsWith("/plugman reload") && event.getMessage().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
|| (event.getMessage().toLowerCase().startsWith("/plugman unload") && event.getMessage().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
|| (event.getMessage().toLowerCase().startsWith("/plugman restart") && event.getMessage().toLowerCase().contains(Main.plugin.getDescription().getName().toLowerCase()))
) {
event.setCancelled(true);
T2Csend.player(event.getPlayer(), Util.getPrefix() + " §4OPSecurity cannot be deactivated!");
send.player(event.getPlayer(), Util.getPrefix() + " §4OPSecurity cannot be deactivated!");
}
}
}

View File

@ -11,16 +11,16 @@ import org.bukkit.entity.Player;
public class Timer {
public static void RefreshTimer() {
if (SelectConfig.opWhitelistEnable || SelectConfig.permissionWhitelistEnable) {
if (SelectConfig.timerEnable) {
int Count = Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.getPlugin(), new Runnable() {
if (SelectConfig.OP_Whitelist_Enable || SelectConfig.Permission_Whitelist_Enable) {
if (SelectConfig.Timer_Enable) {
int Count = Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
Check.onCheck(player, false);
}
}
}, 0, SelectConfig.refreshTime * 20L);
}, 0, SelectConfig.RefreshTime * 20L);
}
}
}

View File

@ -13,24 +13,25 @@ import de.jatitv.opsecurity.listener.Events;
import de.jatitv.opsecurity.listener.OPCommand;
import de.jatitv.opsecurity.listener.PlugManCommand;
import de.jatitv.opsecurity.listener.Timer;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import net.t2code.t2codelib.SPIGOT.api.register.T2Cregister;
import net.t2code.t2codelib.SPIGOT.api.update.T2CupdateAPI;
import net.t2code.lib.Spigot.Lib.messages.T2CodeTemplate;
import net.t2code.lib.Spigot.Lib.register.Register;
import net.t2code.lib.Spigot.Lib.update.UpdateAPI;
import net.t2code.lib.Spigot.system.Metrics;
import java.util.List;
public class Load {
public static void onLoad(String prefix, List<String> autor, String version, String spigot, int spigotID, String discord, int bstatsID) {
Long long_ = T2Ctemplate.onLoadHeader(prefix, autor, version, spigot, discord);
T2CupdateAPI.onUpdateCheck(Main.getPlugin(), prefix, spigotID, discord);
Metrics.Bstats();
Long long_ = T2CodeTemplate.onLoadHeader(prefix, autor, version, spigot, discord);
UpdateAPI.onUpdateCheck(Main.plugin, prefix, spigot, spigotID, discord);
Metrics.Bstats(Main.plugin, bstatsID);
loadReload();
Permissions.register();
Main.getPlugin().getCommand("opsecurity").setExecutor(new CmdExecuter());
T2Cregister.listener(new Events(), Main.getPlugin());
T2Cregister.listener(new OPCommand(), Main.getPlugin());
T2Cregister.listener(new PlugManCommand(), Main.getPlugin());
T2Ctemplate.onLoadFooter(prefix, long_);
Main.plugin.getCommand("opsecurity").setExecutor(new CmdExecuter());
Register.listener(new Events(), Main.plugin);
Register.listener(new OPCommand(), Main.plugin);
Register.listener(new PlugManCommand(), Main.plugin);
T2CodeTemplate.onLoadFooter(prefix, long_);
}
public static void loadReload() {
@ -60,6 +61,7 @@ public class Load {
} catch (Exception e) {
e.printStackTrace();
}
try {
Timer.RefreshTimer();
} catch (Exception e) {

View File

@ -0,0 +1,70 @@
package de.jatitv.opsecurity.system;
import de.jatitv.opsecurity.Util;
import de.jatitv.opsecurity.objects.PlayerObject;
import net.t2code.lib.Spigot.Lib.messages.T2CodeTemplate;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
public final class Main extends JavaPlugin {
public static List<String> autor;
public static String version;
public static Main plugin;
private static boolean enable;
public static File getPath() {
return plugin.getDataFolder();
}
public static HashMap<String, PlayerObject> opHashMap = new HashMap<String, PlayerObject>();
public static HashMap<String, PlayerObject> permissionHashMap = new HashMap<String, PlayerObject>();
@Override
public void onEnable() {
// Plugin startup logic
plugin = this;
try {
enable();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void enable() {
autor = plugin.getDescription().getAuthors();
version = plugin.getDescription().getVersion();
if (pluginNotFound("T2CodeLib", 96388, Util.getRequiredT2CodeLibVersion())) return;
Load.onLoad(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getSpigotID(), Util.getDiscord(), Util.getBstatsID());
enable = true;
}
@Override
public void onDisable() {
// Plugin shutdown logic
if (enable) T2CodeTemplate.onDisable(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord());
}
public static Boolean pluginNotFound(String pl, Integer spigotID, double ver) {
if (Bukkit.getPluginManager().getPlugin(pl) == null) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4could not be found. Please download it here: " +
"§6https://spigotmc.org/resources/" + pl + "." + spigotID + " §4to be able to use this plugin.");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
} else {
if (Double.parseDouble(Objects.requireNonNull(Bukkit.getPluginManager().getPlugin(pl)).getDescription().getVersion()) < ver) {
plugin.getLogger().log(Level.SEVERE, "Plugin can not be loaded!");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §e" + pl + " §4is out of date! This plugin requires at least version §2" + ver + " §4of §6" + pl + " §4Please update it here: §6https://spigotmc.org/resources/" + pl + "." + spigotID + " §4to use this version of " + plugin.getDescription().getName() + ".");
Main.plugin.getPluginLoader().disablePlugin(Main.plugin);
return true;
}
return false;
}
}
}

View File

@ -17,6 +17,7 @@ import java.util.UUID;
public class NameHistory {
/**
* The URL from Mojang API that provides the JSON String in response.
*/

View File

@ -0,0 +1,33 @@
package de.jatitv.opsecurity.system;
import net.t2code.lib.Spigot.Lib.register.Register;
import org.bukkit.permissions.PermissionDefault;
public class Permissions {
public static final String key = "opsecurity.";
public static final String notify = key + "notify";
public static final String updatemsg = key + "updatemsg";
public static final String reload = key + "command.reload";
public static final String info = key + "command.info";
public static final String help = key + "command.help";
public static final String admin = key + "admin";
public static final PermissionDefault op = PermissionDefault.OP;
public static final PermissionDefault notOp = PermissionDefault.NOT_OP;
protected static void register() {
Register.permission(notify, op, Main.plugin);
Register.permissionDescription(notify,"Players with this permission get the update message when joining if an update is available",Main.plugin);
Register.permission(updatemsg, op, Main.plugin);
Register.permission(reload, op, Main.plugin);
Register.permission(info, op, Main.plugin);
Register.permission(help, op, Main.plugin);
Register.permission(admin, op, notify, true, Main.plugin);
Register.permission(admin, op, updatemsg, true, Main.plugin);
Register.permission(admin, op, reload, true, Main.plugin);
Register.permission(admin, op, info, true, Main.plugin);
Register.permission(admin, op, help, true, Main.plugin);
}
}

View File

@ -1,6 +1,6 @@
// This claas was created by JaTiTV
package net.t2code.opsecurity.system;
package de.jatitv.opsecurity.util;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
@ -27,10 +27,6 @@ import java.util.zip.GZIPOutputStream;
public class Metrics {
public static void Bstats(JavaPlugin plugin, int pluginId) {
Metrics metrics = new Metrics(plugin, pluginId);
}
private final Plugin plugin;
private final MetricsBase metricsBase;