create config

This commit is contained in:
JaTiTV 2022-11-03 02:29:26 +01:00
parent d4f60d78b8
commit 2b5520d115
24 changed files with 2067 additions and 5 deletions

View File

@ -106,11 +106,9 @@ public class SelectConfig {
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);
}

View File

@ -42,9 +42,7 @@ public class SelectMessages {
send.debug(Main.plugin, "§4Select language...");
Long long_ = Long.valueOf(System.currentTimeMillis());
File msg;
msg = new File(Main.getPath(), "languages/" + SelectConfig.language + "_messages.yml");
File msg = new File(Main.getPath(), "languages/" + SelectConfig.language + "_messages.yml");
if (!msg.isFile()) {
send.console(Prefix);
send.console(Prefix + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

113
OpSecurity V3/.gitignore vendored Normal file
View File

@ -0,0 +1,113 @@
# 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/

100
OpSecurity V3/pom.xml Normal file
View File

@ -0,0 +1,100 @@
<?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>1.0-SNAPSHOT</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>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</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>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</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.19.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- t2code -->
<dependency>
<groupId>net.t2code</groupId>
<artifactId>T2CodeLib</artifactId>
<version>13.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,31 @@
package net.t2code.opsecurity;
public class Util {
public static String getInfoText() {
return "";
}
public static String getRequiredT2CodeLibVersion() {
return "13.0";
}
public static String getPrefix() {
return "§8[§T2C§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 "http://dc.t2code.net";
}
}

View File

@ -0,0 +1,123 @@
// This claas was created by JaTiTV
package net.t2code.opsecurity.command;
import net.t2code.opsecurity.Util;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.language.Language;
import net.t2code.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
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 (Config.onlyOPcanUseThePlugin.valueBoolean) {
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<>();
if (sender instanceof Player) {
Player p = (Player) sender;
if (args.length == 1) {
for (String command : arg1.keySet()) {
Boolean passend = true;
for (int i = 0; i < args[0].length(); i++) {
if (args[0].length() >= command.length()) {
passend = false;
} else {
if (args[0].charAt(i) != command.charAt(i)) {
passend = false;
}
}
}
if (hasPermission(p, arg1.get(command)) && passend) {
list.add(command);
}
}
}
if (args.length == 2) {
switch (args[0]) {
case "give":
if (hasPermission(p, arg1.get("give"))) {
for (Player player : Bukkit.getOnlinePlayers()) {
Boolean passend = true;
for (int i = 0; i < args[1].length(); i++) {
if (args[1].length() >= player.getName().length()) {
passend = false;
} else {
if (args[1].charAt(i) != player.getName().charAt(i)) {
passend = false;
}
}
}
if (hasPermission(p, arg1.get(player)) && passend) {
list.add(player.getName());
}
}
}
break;
}
}
}
return list;
}
public static boolean hasPermission(Player player, String permission) {
if (player.isOp()) {
return true;
}
String[] Permissions = permission.split(";");
for (String perm : Permissions) {
if (player.hasPermission(perm)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,80 @@
package net.t2code.opsecurity.command;
import net.t2code.opsecurity.Util;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.language.Language;
import net.t2code.opsecurity.objects.PlayerCash;
import net.t2code.opsecurity.system.Permissions;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
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)) {
T2Csend.sender(sender, Language.noPermissionForOpSec.value);
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 (Config.onlyOPcanUseThePlugin.valueBoolean) {
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 (!PlayerCash.opHashMap.containsKey(player.getName().toLowerCase())) {
sender.sendMessage(Util.getPrefix() + " §4You are not on the Whitelist!");
return;
}
if (!PlayerCash.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, Language.reloadStart.value);
}
if (sender instanceof Player) T2Csend.player((Player) sender, SelectMessages.ReloadEnd);
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + " §6Plugin reload...");
Bukkit.getConsoleSender().sendMessage(Util.getPrefix() + "§8-------------------------------");
Load.loadReload();
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;
}
T2CodeTemplate.sendInfo(sender, Util.getPrefix(), Util.getSpigot(), Util.getDiscord(), Main.autor, Main.version, UpdateAPI.PluginVersionen.get(Main.plugin.getName()).publicVersion);
}
}

View File

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

View File

@ -0,0 +1,195 @@
package net.t2code.opsecurity.config;
import net.t2code.opsecurity.Util;
import net.t2code.opsecurity.config.config.Config;
import net.t2code.opsecurity.config.language.Language;
import net.t2code.opsecurity.config.opWhitelist.OPWhitelist;
import net.t2code.opsecurity.objects.PlayerCash;
import net.t2code.opsecurity.objects.PlayerObject;
import net.t2code.opsecurity.system.Main;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.t2codelib.SPIGOT.system.T2CodeLibMain;
import net.t2code.t2codelib.SPIGOT.system.config.languages.SelectLibMsg;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileSelect {
public static void selectConfig() {
File config = new File(Main.getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
for (Config value : Config.values()) {
switch (value.cEnum) {
case STRING:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueString);
}
value.valueString = yamlConfiguration.getString(value.path);
break;
case SOUND:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueString);
}
try {
value.valueString = yamlConfiguration.getString(value.path);
} catch (Exception ex) {
T2Csend.console("§4\n§4\n§4\n" + SelectLibMsg.soundNotFound.replace("[prefix]", Util.getPrefix())
.replace("[sound]", "§8" + value.path + ": §6" + yamlConfiguration.getString(value.path)) + "§4\n§4\n§4\n");
}
break;
case BOOLEAN:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueBoolean);
}
value.valueBoolean = yamlConfiguration.getBoolean(value.path);
break;
case INTEGER:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueInt);
}
value.valueInt = yamlConfiguration.getInt(value.path);
break;
}
}
try {
yamlConfiguration.save(config);
} catch (IOException e) {
e.printStackTrace();
}
}
private static ArrayList<String> defaultLanguages = new ArrayList<>(Arrays.asList("german", "english"));
public static void selectLanguage() {
long long_ = System.currentTimeMillis();
File directory = new File(Main.getPath(), "languages");
if (!directory.exists()) {
for (String language : defaultLanguages) {
File config = new File(Main.getPath(), "languages/" + language + ".yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
for (Language value : Language.values()) {
if (!yamlConfiguration.contains(value.path)) {
switch (language) {
case "german":
yamlConfiguration.set(value.path, value.german);
break;
case "english":
yamlConfiguration.set(value.path, value.english);
break;
}
}
}
T2Csend.debugmsg(Main.getPlugin(),"save: "+language);
try {
yamlConfiguration.save(config);
} catch (IOException e) {
e.printStackTrace();
}
}
}
String selectMSG;
File config = new File(Main.getPath(), "languages/" + Config.language + ".yml");
if (!config.isFile()) {
T2Csend.console(Util.getPrefix());
T2Csend.console(Util.getPrefix() + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
T2Csend.console(Util.getPrefix() + " §4The selected §c" + Config.language.valueString + " §4language file was not found.");
T2Csend.console(Util.getPrefix() + " §6The default language §eEnglish §6is used!");
T2Csend.console(Util.getPrefix() + " §4!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
T2Csend.console(Util.getPrefix());
config = new File(Main.getPath(), "languages/" + "english_messages.yml");
selectMSG = "english";
} else selectMSG = Config.language.valueString;
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
for (Language value : Language.values()) {
value.value = yamlConfiguration.getString(value.path);
}
T2Csend.console(Util.getPrefix() + " §2Language successfully selected to: §6" + selectMSG + " §7- §e" + (System.currentTimeMillis() - long_) + "ms");
}
public static void selectOpWhitelist() {
File config = new File(Main.getPath(), "opWhitelist.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
for (OPWhitelist value : OPWhitelist.values()) {
switch (value.cEnum) {
case BOOLEAN:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueBoolean);
}
value.valueBoolean = yamlConfiguration.getBoolean(value.path);
break;
case STRINGLIST:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueBoolean);
}
value.valueStringList = yamlConfiguration.getStringList(value.path);
break;
case PLAYERLIST:
if (!yamlConfiguration.contains(value.pathPlayerListPath)) {
yamlConfiguration.set(value.pathPlayerName.replace("KEY", "player1"), value.valuePlayerName);
yamlConfiguration.set(value.pathPlayerUuid.replace("KEY", "player1"), value.valuePlayerUuid);
yamlConfiguration.set(value.pathPlayerName.replace("KEY", "player2"), value.valuePlayerName);
yamlConfiguration.set(value.pathPlayerUuid.replace("KEY", "player2"), value.valuePlayerUuid);
}
for (String key : yamlConfiguration.getConfigurationSection(value.pathPlayerListPath).getKeys(false)) {
PlayerObject playerObject = new PlayerObject(
yamlConfiguration.getString(value.pathPlayerName.replace("KEY", key)),
yamlConfiguration.getString(value.pathPlayerUuid.replace("KEY", key).replace("-", "")));
PlayerCash.opHashMap.put(key, playerObject);
}
break;
}
}
try {
yamlConfiguration.save(config);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void selectPermissionWhitelist() {
File config = new File(Main.getPath(), "permissionWhitelist.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(config);
for (OPWhitelist value : OPWhitelist.values()) {
switch (value.cEnum) {
case BOOLEAN:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueBoolean);
}
value.valueBoolean = yamlConfiguration.getBoolean(value.path);
break;
case STRINGLIST:
if (!yamlConfiguration.contains(value.path)) {
yamlConfiguration.set(value.path, value.valueBoolean);
}
value.valueStringList = yamlConfiguration.getStringList(value.path);
break;
case PLAYERLIST:
if (!yamlConfiguration.contains(value.pathPlayerListPath)) {
yamlConfiguration.set(value.pathPlayerName.replace("KEY", "player1"), value.valuePlayerName);
yamlConfiguration.set(value.pathPlayerUuid.replace("KEY", "player1"), value.valuePlayerUuid);
yamlConfiguration.set(value.pathPlayerName.replace("KEY", "player2"), value.valuePlayerName);
yamlConfiguration.set(value.pathPlayerUuid.replace("KEY", "player2"), value.valuePlayerUuid);
}
for (String key : yamlConfiguration.getConfigurationSection(value.pathPlayerListPath).getKeys(false)) {
PlayerObject playerObject = new PlayerObject(
yamlConfiguration.getString(value.pathPlayerName.replace("KEY", key)),
yamlConfiguration.getString(value.pathPlayerUuid.replace("KEY", key).replace("-", "")));
PlayerCash.opHashMap.put(key, playerObject);
}
break;
}
}
try {
yamlConfiguration.save(config);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,53 @@
package net.t2code.opsecurity.config.config;
import net.t2code.opsecurity.config.ConfigParam;
import net.t2code.t2codelib.SPIGOT.api.minecraftVersion.T2CmcVersion;
public enum Config {
language("Plugin.Language", "english", ConfigParam.STRING),
onlyOPcanUseThePlugin("Plugin.OnlyOPcanUseThePlugin", true, ConfigParam.BOOLEAN),
checkOnJoin("Check.OnJoin", true, ConfigParam.BOOLEAN),
checkOnInteract("Check.OnInteract", true, ConfigParam.BOOLEAN),
checkOnCommand("Check.OnCommand", true, ConfigParam.BOOLEAN),
checkOnChat("Check.OnChat", true, ConfigParam.BOOLEAN),
checkTimerEnable("Check.Timer.Enable", true, ConfigParam.BOOLEAN),
checkTimerRefreshInSec("Check.Timer.RefreshInSec", 60, ConfigParam.INTEGER),
kickCommand("Kick.Command", "minecraft:kick [player] [reason]", ConfigParam.STRING),
notifyJoinWarning("Notify.JoinWarn.Enable", true, ConfigParam.BOOLEAN),
notifySoundEnable("Notify.SoundEnable", true, ConfigParam.BOOLEAN),
notifySoundValue("Notify.SoundEnable", sound(), ConfigParam.SOUND);
public String path;
public String valueString;
public Integer valueInt;
public Boolean valueBoolean;
public ConfigParam cEnum;
Config(String path, String value, ConfigParam cEnum) {
this.path = path;
this.valueString = value;
this.cEnum = cEnum;
}
Config(String path, Integer value, ConfigParam cEnum) {
this.path = path;
this.valueInt = value;
this.cEnum = cEnum;
}
Config(String path, Boolean value, ConfigParam cEnum) {
this.path = path;
this.valueBoolean = value;
this.cEnum = cEnum;
}
public static String sound(){
if (T2CmcVersion.isMc1_8()){
return "NOTE_PIANO";
} else if (T2CmcVersion.isMc1_9()||T2CmcVersion.isMc1_10()||T2CmcVersion.isMc1_11()||T2CmcVersion.isMc1_12()){
return "BLOCK_NOTE_HARP";
} else return "BLOCK_NOTE_BLOCK_HARP";
}
}

View File

@ -0,0 +1,97 @@
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.system.Permissions;
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;
public class Converter {
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");
YamlConfiguration yamlConfigurationOld = YamlConfiguration.loadConfiguration(configOld);
File opConfig = new File(Main.getPath(), "opWhitelist.yml");
YamlConfiguration opYml = YamlConfiguration.loadConfiguration(opConfig);
File permConfig = new File(Main.getPath(), "permissionWhitelist.yml");
YamlConfiguration permYml = YamlConfiguration.loadConfiguration(permConfig);
Config.language.valueString = yamlConfigurationOld.getString("Plugin.language");
Config.onlyOPcanUseThePlugin.valueBoolean = yamlConfigurationOld.getBoolean("Plugin.OnlyOPcanUseThePlugin");
Config.checkOnJoin.valueBoolean = yamlConfigurationOld.getBoolean("Check.OnJoin");
Config.checkOnInteract.valueBoolean = yamlConfigurationOld.getBoolean("Check.OnInteract");
Config.checkOnCommand.valueBoolean = yamlConfigurationOld.getBoolean("Check.OnCommand");
Config.checkOnChat.valueBoolean = yamlConfigurationOld.getBoolean("Check.OnChat");
Config.checkTimerEnable.valueBoolean = yamlConfigurationOld.getBoolean("Check.Timer.Enable");
Config.checkTimerRefreshInSec.valueInt = yamlConfigurationOld.getInt("Check.Timer.RefreshTime_inSec");
Config.kickCommand.valueString = yamlConfigurationOld.getString("Kick.Command");
Config.notifyJoinWarning.valueBoolean = yamlConfigurationOld.getBoolean("Notify.JoinWarn.Enable");
Config.notifySoundEnable.valueBoolean = yamlConfigurationOld.getBoolean("Notify.Sound.Enable");
Config.notifySoundValue.valueString = yamlConfigurationOld.getString("Notify.Sound.Sound");
OPWhitelist.enable.valueBoolean = yamlConfigurationOld.getBoolean("OP_Whitelist.Enable");
OPWhitelist.playerMustBeOnlineToOp.valueBoolean = yamlConfigurationOld.getBoolean("OP_Whitelist.PlayerMustBeOnlineToOp");
OPWhitelist.noOpPlayerDeopEnable.valueBoolean = yamlConfigurationOld.getBoolean("OP_Whitelist.noOpPlayerDeop.Enable");
OPWhitelist.noOpPlayerDeopPlayerSendMessage.valueBoolean = yamlConfigurationOld.getBoolean("OP_Whitelist.noOpPlayerDeop.PlayerSendMessage");
OPWhitelist.noOpPlayerKickEnable.valueBoolean = yamlConfigurationOld.getBoolean("OP_Whitelist.noOpPlayerKick.Enable");
OPWhitelist.customCommandsEnable.valueBoolean = yamlConfigurationOld.getBoolean("OP_Whitelist.customCommands.Enable");
OPWhitelist.customCommandsCommands.valueStringList = yamlConfigurationOld.getStringList("OP_Whitelist.customCommands.Commands");
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) {
opYml.set("opWhitelist.whitelist.KEY.name".replace("KEY", playerObject.playerName), playerObject.playerName);
opYml.set("opWhitelist.whitelist.KEY.uuid".replace("KEY", playerObject.playerName), playerObject.uuid);
}
PermissionWhitelist.enable.valueBoolean = yamlConfigurationOld.getBoolean("Permission_Whitelist.Enable");
PermissionWhitelist.permissions.valueStringList = yamlConfigurationOld.getStringList("Permission_Whitelist.Permissions");
PermissionWhitelist.playerWithPermissionKick.valueBoolean = yamlConfigurationOld.getBoolean("Permission_Whitelist.PlayerWhithPermission_kick");
PermissionWhitelist.customCommandsEnable.valueBoolean = yamlConfigurationOld.getBoolean("Permission_Whitelist.customCommands.Enable");
PermissionWhitelist.customCommandsCommands.valueStringList = yamlConfigurationOld.getStringList("Permission_Whitelist.customCommands.Commands");
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();
}
}
}
}

View File

@ -0,0 +1,81 @@
package net.t2code.opsecurity.config.language;
public enum Language {
soundNotFound("plugin.soundNotFound",null,
"[prefix] <dark_red>Der Sound <gold>[sound]</gold> wurde nicht gefunden! Bitte überprüfe die Einstellungen.</dark_red>",
"[prefix] <dark_red>The sound <gold>[sound]</gold> could not be found! Please check your settings.</dark_red>"),
noPermission("plugin.NoPermission",null,
"<dark_red>Keine Berechtigung!</dark_red>",
"<dark_red>No Permission!</dark_red>"),
noPermissionForOpSec("plugin.NoPermission",null,
"[prefix] <red>Du hast keine Berechtigung für OPSecurity!</red>",
"[prefix] <red>You do not have permission for OPSecurity!</red>"),
PlayerMustBeOnlineToOp("plugin.PlayerMustBeOnlineToOp",null,
"[prefix] <dark_red>Der Spieler muss online sein, um OP zu erhalten!</dark_red>",
"[prefix] <dark_red>Player must be online to get op!</dark_red>"),
reloadStart("plugin.reload.start",null,
"[prefix] <gold>Plugin wird neu geladen...</gold>",
"[prefix] <gold>Plugin is reloaded...</gold>"),
reloadEnd("plugin.reload.end",null,
"[prefix] <green>Plugin wurde erfolgreich neu geladen.</green>",
"[prefix] <green>Plugin was successfully reloaded.</green>"),
opWhitelistOpCommand("opWhitelist.opCommand",null,
"[prefix] <dark_red>Der angegebene Spieler befindet sich nicht auf der OP_Whitelist!</dark_red>",
"[prefix] <dark_red>The specified player is not on the OP_Whitelist!</dark_red>"),
opWhitelistConsoleOnJoin("opWhitelist.consoleOnJoin",null,
"[prefix] <dark_red>Spieler <gold>[player]</gold> ist dem Server beigetreten, befindet sich aber nicht auf der OP_Whitelist!</dark_red>",
"[prefix] <dark_red>Player <gold>[player]</gold> is joined to the server but is not on the OP_Whitelist!</dark_red>"),
opWhitelistDeop("opWhitelist.deop",null,
"[prefix] <dark_red>Dir wurde OP entfernt da du dazu keine Permission besitzt.</dark_red>",
"[prefix] <dark_red>You have been removed from OP because you do not have permission.</dark_red>"),
opWhitelistConsoleDeop("opWhitelist.consoleDeop",null,
"[prefix] <dark_red>Spieler <gold>[player]</gold> wurde OP entfernt da er nicht auf der Spielerliste steht!</dark_red>",
"[prefix] <dark_red>Player <gold>[player]</gold> was removed OP because he is not on the playerlist!</dark_red>"),
opWhitelistKick("opWhitelist.kick",null,
"<dark_red>Du hast op bist dazu aber nicht berechtigt, deswegen wurdest du gekickt!</dark_red>",
"<dark_red>You have op but are not authorized to do so, that's why you were kicked!</dark_red>"),
opWhitelistConsoleKick("opWhitelist.consoleKick",null,
"[prefix] <dark_red>Spieler <gold>[player]</gold> wurde gekickt, da er nicht auf der OP_Whitelist steht!</dark_red>",
"[prefix] <dark_red>Player <gold>[player]</gold> was kicked because he is not on the OP_Whitelist!</dark_red>"),
permissionWhitelistConsoleOnJoin("permissionWhitelist.consoleOnJoin",null,
"[prefix] <dark_red>Player <gold>[player]</gold> hat die Permission <gold>[perm]</gold> und ist dazu nicht berechtigt! <gold>[player]</gold> ist nicht in der Spielerliste!</dark_red>",
"[prefix] <dark_red>Player <gold>[player]</gold> has permission <gold>[perm]</gold> and is not authorized to do so! <gold>[player]</gold> is not on the Player list!</dark_red>"),
permissionWhitelistKick("permissionWhitelist.kick",null,
"<dark_red>Du wurdest gekickt, da du Permissions besitzt, für die du keine Berechtigung besitzt!</dark_red>",
"<dark_red>You were kicked because you have permissions to which you do not have permission!</dark_red>"),
permissionWhitelistConsoleKick("permissionWhitelist.consoleKick",null,
"[prefix] <dark_red>Spieler <gold>[player]</gold> hat die Permission <gold>[perm]</gold> und ist dazu nicht berechtigt! Daher wurde er gekickt! <gold>[player]</gold> ist nicht in der Spielerliste!</dark_red>",
"[prefix] <dark_red>Player <gold>[player]</gold> has permission <gold>[perm]</gold> and is not authorized to do so! Therefore he was kicked! <gold>[player]</gold> is not on the Player list!</dark_red>"),
exactKickReason("console.exactKickReason", null,
"[prefix] <dark_red>Genauer Grund:</dark_red> <gold>[reason]</gold>",
"[prefix] <dark_red>Exact reason:</dark_red> <gold>[reason]</gold>");
public String path;
public String value;
public String german;
public String english;
Language(String path,String value, String german,String english) {
this.path = path;
this.value=value;
this.german = german;
this.english = english;
}
}

View File

@ -0,0 +1,49 @@
package net.t2code.opsecurity.config.opWhitelist;
import net.t2code.opsecurity.config.ConfigParam;
import java.util.Arrays;
import java.util.List;
public enum OPWhitelist {
enable("opWhitelist.enable", false, ConfigParam.BOOLEAN),
playerMustBeOnlineToOp("opWhitelist.playerMustBeOnlineToOp", true, ConfigParam.BOOLEAN),
noOpPlayerDeopEnable("opWhitelist.enable", true, ConfigParam.BOOLEAN),
noOpPlayerDeopPlayerSendMessage("opWhitelist.noOpPlayerDeop.playerSendMessage", true, ConfigParam.BOOLEAN),
noOpPlayerKickEnable("opWhitelist.noOpPlayerKick.enable", true, ConfigParam.BOOLEAN),
customCommandsEnable("opWhitelist.customCommands.enable", false, ConfigParam.BOOLEAN),
customCommandsCommands("opWhitelist.customCommands.commands", Arrays.asList("kick [player] &4You have op but are not authorized to do so, that's why you were kicked!")
, ConfigParam.STRINGLIST),
player("opWhitelist.whitelist","opWhitelist.whitelist.KEY.name", "opWhitelist.whitelist.KEY.uuid", "PlayerName", "00000000000000000000000000000000", ConfigParam.PLAYERLIST);
public String path;
public String pathPlayerListPath;
public String pathPlayerName;
public String pathPlayerUuid;
public String valuePlayerName;
public String valuePlayerUuid;
public List<String> valueStringList;
public Boolean valueBoolean;
public ConfigParam cEnum;
OPWhitelist(String listPath,String pathPlayerName, String pathUuid, String playerName, String uuid, ConfigParam cEnum) {
this.pathPlayerListPath = listPath;
this.pathPlayerName = pathPlayerName;
this.pathPlayerUuid = pathUuid;
this.valuePlayerName = playerName;
this.valuePlayerUuid = uuid;
this.cEnum = cEnum;
}
OPWhitelist(String path, List<String> value, ConfigParam cEnum) {
this.path = path;
this.valueStringList = value;
this.cEnum = cEnum;
}
OPWhitelist(String path, Boolean value, ConfigParam cEnum) {
this.path = path;
this.valueBoolean = value;
this.cEnum = cEnum;
}
}

View File

@ -0,0 +1,47 @@
package net.t2code.opsecurity.config.permissionWhitelist;
import net.t2code.opsecurity.config.ConfigParam;
import java.util.Arrays;
import java.util.List;
public enum PermissionWhitelist {
enable("permissionWhitelist.enable", false, ConfigParam.BOOLEAN),
playerWithPermissionKick("permissionWhitelist.playerWithPermissionKick", true, ConfigParam.BOOLEAN),
permissions("permissionWhitelist.permissions", Arrays.asList("*", "t2c.opsecurity.admin"), ConfigParam.STRINGLIST),
customCommandsEnable("permissionWhitelist.customCommands.enable", false, ConfigParam.BOOLEAN),
customCommandsCommands("permissionWhitelist.customCommands.commands", Arrays.asList("lp user [player] permission unset *", "lp user [player] permission unset t2c.opsecurity.admin")
, ConfigParam.STRINGLIST),
player("permissionWhitelist.whitelist", "permissionWhitelist.whitelist.KEY.name", "permissionWhitelist.whitelist.KEY.uuid", "PlayerName", "00000000000000000000000000000000", ConfigParam.PLAYERLIST);
public String path;
public String pathPlayerListPath;
public String pathPlayerName;
public String pathPlayerUuid;
public String valuePlayerName;
public String valuePlayerUuid;
public List<String> valueStringList;
public Boolean valueBoolean;
public ConfigParam cEnum;
PermissionWhitelist(String listPath, String pathPlayerName, String pathUuid, String playerName, String uuid, ConfigParam cEnum) {
this.pathPlayerListPath = listPath;
this.pathPlayerName = pathPlayerName;
this.pathPlayerUuid = pathUuid;
this.valuePlayerName = playerName;
this.valuePlayerUuid = uuid;
this.cEnum = cEnum;
}
PermissionWhitelist(String path, List<String> value, ConfigParam cEnum) {
this.path = path;
this.valueStringList = value;
this.cEnum = cEnum;
}
PermissionWhitelist(String path, Boolean value, ConfigParam cEnum) {
this.path = path;
this.valueBoolean = value;
this.cEnum = cEnum;
}
}

View File

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

View File

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

View File

@ -0,0 +1,43 @@
package net.t2code.opsecurity.system;
import net.t2code.opsecurity.Util;
import net.t2code.opsecurity.config.FileSelect;
import net.t2code.opsecurity.config.config.Converter;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Csend;
import net.t2code.t2codelib.SPIGOT.api.messages.T2Ctemplate;
import net.t2code.t2codelib.SPIGOT.api.plugins.T2CpluginCheck;
import net.t2code.t2codelib.SPIGOT.api.plugins.T2CpluginManager;
import net.t2code.t2codelib.SPIGOT.api.update.T2CupdateAPI;
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_ = T2Ctemplate.onLoadHeader(Util.getPrefix(), autor, version, Util.getSpigot(), Util.getDiscord());
if (T2CpluginCheck.opSec()){
T2CpluginManager.disable("OPSecurity");
T2Csend.warning(plugin,"OPSecurity has been deactivated, because T2C-OPSecurity is a newer version!");
}
try {
Converter.convert();
} catch (Exception ex){
plugin.getLogger().log(Level.SEVERE,ex.getMessage());
ex.printStackTrace();
}
FileSelect.selectConfig();
FileSelect.selectLanguage();
FileSelect.selectOpWhitelist();
FileSelect.selectPermissionWhitelist();
//plugin.getCommand("t2c-opsecurity").setExecutor(new CmdExecuter());
Permissions.register();
T2CupdateAPI.onUpdateCheck(plugin, Util.getPrefix(), Util.getSpigotID(), Util.getDiscord());
Metrics.Bstats(plugin, Util.getBstatsID());
T2Ctemplate.onLoadFooter(Util.getPrefix(), long_);
}
}

View File

@ -0,0 +1,77 @@
package net.t2code.opsecurity.system;
import lombok.Getter;
import net.t2code.opsecurity.Util;
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.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;
t2codeLib = true;
Load.onLoad(plugin,autor,version);
}
@Override
public void onDisable() {
// Plugin shutdown logic
if (t2codeLib) 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;
}
}
}

View File

@ -0,0 +1,844 @@
// This claas was created by JaTiTV
package net.t2code.opsecurity.system;
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(JavaPlugin plugin, int pluginId) {
Metrics metrics = new Metrics(plugin, 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

@ -0,0 +1,32 @@
package net.t2code.opsecurity.system;
import net.t2code.t2codelib.SPIGOT.api.register.T2Cregister;
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() {
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

@ -0,0 +1,19 @@
Plugin:
Language: english
OnlyOPcanUseThePlugin: true
Check:
OnJoin: true
OnInteract: true
OnCommand: true
OnChat: true
Timer:
Enable: true
RefreshInSec: 60
Kick:
Command: minecraft:kick [player] [reason]
Notify:
JoinWarn:
Enable: true
Sound:
Enable: true
Sound: BLOCK_NOTE_BLOCK_HARP

View File

@ -0,0 +1,20 @@
opWhitelist:
enable: false
playerMustBeOnlineToOp: true
noOpPlayerDeop:
enable: true
playerSendMessage: true
noOpPlayerKick:
enable: true
customCommands:
enable: false
commands:
- kick [player] &4You have op but are not authorized to do so, that's why you
were kicked!
whitelist:
player1:
name: 'PlayerName'
uuid: '00000000000000000000000000000000'
player2:
name: 'PlayerName'
uuid: '00000000000000000000000000000000'

View File

@ -0,0 +1,18 @@
permissionWhitelist:
enable: false
playerWithPermissionKick: true
permissions:
- '*'
- opsecurity.admin
customCommands:
enable: false
commands:
- lp user [player] permission unset *
- lp user [player] permission unset opsecurity.admin
whitelist:
player1:
name: 'PlayerName'
uuid: '00000000000000000000000000000000'
player2:
name: 'PlayerName'
uuid: '00000000000000000000000000000000'

View File

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