Move to T2Code Git

This commit is contained in:
JaTiTV 2021-12-29 03:28:50 +01:00
commit 1c13254972
29 changed files with 3222 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

113
.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/

64
README.md Normal file
View File

@ -0,0 +1,64 @@
<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">

74
pom.xml Normal file
View File

@ -0,0 +1,74 @@
<?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>de.jatitv</groupId>
<artifactId>opsecurity</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>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>
<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>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,151 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.cmdManagement;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
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) {
String version = Main.plugin.getDescription().getVersion();
if (args.length == 0) {
Commands.mainCommand(sender);
} else {
if (SelectConfig.OnlyOPcanUseThePlugin) {
if (sender.isOp()) {
switch (args[0].toLowerCase()) {
case "reload":
case "rl":
if (sender.hasPermission("opsecurity.command.reload")) {
Commands.reload(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
break;
case "info":
case "plugin":
case "pl":
case "version":
case "ver":
if (sender.hasPermission("opsecurity.command.info")) {
Commands.info(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
break;
case "help":
default:
if (sender.hasPermission("opsecurity.command.help")) {
SelectConfig.Help(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
break;
}
} else sender.sendMessage(Main.Prefix + "§cOnly OPs can use OPSecurity!");
} else {
switch (args[0].toLowerCase()) {
case "reload":
case "rl":
if (sender.hasPermission("opsecurity.command.reload")) {
Commands.reload(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
break;
case "info":
case "plugin":
case "pl":
case "version":
case "ver":
if (sender.hasPermission("opsecurity.command.info")) {
Commands.info(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
break;
case "help":
default:
if (sender.hasPermission("opsecurity.command.help")) {
SelectConfig.Help(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
break;
}
}
}
return false;
}
private static HashMap<String, String> arg1 = new HashMap<String, String>() {{
put("help", "opsecurity.admin");
put("reload", "opsecurity.admin");
put("info", "opsecurity.admin");
}};
@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,100 @@
package de.jatitv.opsecurity.cmdManagement;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Load;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.TextBuilder;
import de.jatitv.opsecurity.util.send;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class Commands {
private static Plugin plugin = Main.plugin;
private static String Prefix = Main.Prefix;
private static String Autor = String.valueOf(Main.Autor);
private static String Version = Main.Version;
private static String Spigot = Main.Spigot;
private static String Discord = Main.Discord;
public static void mainCommand(CommandSender sender) {
if (SelectConfig.OnlyOPcanUseThePlugin) {
if (sender.isOp()) {
if (sender.hasPermission("opsecurity.admin")) {
SelectConfig.Help(sender);
} else sender.sendMessage(Main.Prefix + "§cYou do not have permission for OPSecurity!");
} else sender.sendMessage(Main.Prefix + "§cOnly OPs can use OPSecurity!");
} else {
if (sender.hasPermission("opsecurity.admin")) {
SelectConfig.Help(sender);
} else sender.sendMessage(Main.Prefix + " §cYou do not have permission for OPSecurity!");
}
}
public static void reload(CommandSender sender) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (Main.opHashMap.containsKey(player.getName())) {
if (Main.opHashMap.get(player.getName()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
send.player(player, SelectMessages.ReloadStart);
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§6Plugin reload...");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
Load.loadReload();
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + " §2Plugin successfully reloaded.");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
send.player(player, SelectMessages.ReloadEnd);
} else sender.sendMessage(Main.Prefix + " §4You are not on the Whitelist!");
} else sender.sendMessage(Main.Prefix + " §4You are not on the Whitelist!");
} else {
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + " §6Plugin reload...");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
Load.loadReload();
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + " §2Plugin successfully reloaded.");
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§8-------------------------------");
}
}
public static void info(CommandSender sender) {
sender.sendMessage(Main.Prefix + "§8-------- §4Plugin-Info §8--------");
sender.sendMessage(Main.Prefix + "§2This plugin was developed by §9JaTiTV");
sender.sendMessage(Main.Prefix + "§2");
sender.sendMessage(Main.Prefix + "§2Twitch: §ehttps://www.twitch.tv/jatitv");
sender.sendMessage(Main.Prefix + "§2Support-Discord: §e" + Main.Discord);
sender.sendMessage(Main.Prefix + "§2Spigot: §e" + Main.Spigot);
sender.sendMessage(Main.Prefix + "§2");
sender.sendMessage(Main.Prefix + "§2Version: §6" + Main.plugin.getDescription().getVersion());
sender.sendMessage(Main.Prefix + "§8-----------------------------");
}
public static void info(CommandSender sender, Boolean onlyOP) {
Player player = (Player) sender;
sender.sendMessage(Prefix + "§4======= §8[§4Command§9GUI§8] §4=======");
sender.sendMessage(Prefix + " §2Autor: §6" + String.valueOf(Autor).replace("[", "").replace("]", ""));
if (Main.update_version.equalsIgnoreCase(Version)) {
sender.sendMessage(Prefix + " §2Version: §6" + Version);
} else {
sender.sendMessage(Prefix + " §6A new version was found!");
TextComponent comp = new TextBuilder(Prefix + " §6Your version: §c" + Version + " §7- §6Current version: §a" + Main.update_version)
.addHover("§6You can download it here: §e" + Main.Spigot).addClickEvent(ClickEvent.Action.OPEN_URL, Main.Spigot).build();
player.spigot().sendMessage(comp);
TextComponent comp2 = new TextBuilder(Prefix + " §6You can find more information on Discord.")
.addHover("§e" + Main.Discord).addClickEvent(ClickEvent.Action.OPEN_URL, Main.Discord).build();
player.spigot().sendMessage(comp2);
}
sender.sendMessage(Prefix + " §2Spigot: §6" + Spigot);
sender.sendMessage(Prefix + " §2Discord: §6" + Discord);
sender.sendMessage(Prefix + "§4======= §8[§4Command§9GUI§8] §4=======");
}
}

View File

@ -0,0 +1,194 @@
package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.system.NameHistory;
import de.jatitv.opsecurity.util.send;
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.List;
public class ConfigConvert {
public static void convert() {
try {
renameConfig();
} catch (Exception e) {
e.printStackTrace();
}
try {
configConvert();
} catch (Exception e) {
e.printStackTrace();
}
try {
renameLanguages();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void renameConfig() {
Path configOld = Paths.get(Main.getPath() + "/Config.yml");
Path config = Paths.get(Main.getPath() + "/config.yml");
if(Files.exists(configOld) && !Files.isDirectory(configOld)) {
if(Files.exists(config) && !Files.isDirectory(config)) {
return;
}
String replace = Main.getPath().toString() + "/";
send.convert(configOld.toString().replace(replace, ""), config.toString().replace(replace, ""));
try {
Files.move(configOld, config);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void configConvert() {
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) {
switch (yamlConfiguration.getString("Plugin.language")) {
case "de_DE":
yamlConfiguration.set("Plugin.language", "german");
send.convert("config.yml", "Plugin.language: de_DE", "Plugin.language: german");
try {
yamlConfiguration.save(config);
} catch (IOException tac) {
tac.printStackTrace();
}
break;
case "en_EN":
yamlConfiguration.set("Plugin.language", "english");
send.convert("config.yml", "Plugin.language: en_EN", "Plugin.language: english");
try {
yamlConfiguration.save(config);
} catch (IOException tac) {
tac.printStackTrace();
}
break;
case "no_NO":
yamlConfiguration.set("Plugin.language", "norwegian");
send.convert("config.yml", "Plugin.language: no_NO", "Plugin.language: norwegian");
try {
yamlConfiguration.save(config);
} catch (IOException tac) {
tac.printStackTrace();
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (yamlConfiguration.get("Timer") != null){
Boolean enable = yamlConfiguration.getBoolean("Timer.Enable");
Integer time = yamlConfiguration.getInt("Timer.RefreshTime_inSec");
yamlConfiguration.set("Check.Timer.Enable", enable);
send.convert("config.yml", "Timer.Enable: " + enable, "Check.Timer.Enable: " + enable);
yamlConfiguration.set("Check.Timer.RefreshTime_inSec", time);
send.convert("config.yml", "Timer.RefreshTime_inSec: " + time, "Check.Timer.RefreshTime_inSec: " + time);
yamlConfiguration.set("Timer", null);
try {
yamlConfiguration.save(config);
} catch (IOException tac) {
tac.printStackTrace();
}
}
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);
try {
yamlConfiguration.save(config);
} catch (IOException tac) {
tac.printStackTrace();
}
}
}
private static void convertPlayer(String oldPath, String newPath, List<String> oldPlayer, YamlConfiguration yamlConfiguration) {
for (String Player : oldPlayer) {
try {
String uuid = NameHistory.getPlayerUUID(Player);
if (uuid == null) {
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!");
send.convert("config.yml", oldPath + ": " + Player, newPath + ": " + Player + ": UUID: Player UUID not found!");
yamlConfiguration.set(newPath + Player + ".UUID", "Player UUID not found!");
} else {
send.convert("config.yml", oldPath + ": " + Player, newPath + ": " + Player + ": UUID: " + uuid);
yamlConfiguration.set(newPath + Player + ".UUID", uuid);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
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)) {
if(Files.exists(messagesDE) && !Files.isDirectory(messagesDE)) {
return;
}
send.convert(messagesDEold.toString().replace(replace, ""), messagesDE.toString().replace(replace, ""));
try {
Files.move(messagesDEold, messagesDE);
} catch (IOException e) {
e.printStackTrace();
}
}
Path messagesENold = Paths.get(Main.getPath() + "/languages/en_EN_Messages.yml");
Path messagesEN = Paths.get(Main.getPath() + "/languages/english_messages.yml");
if(Files.exists(messagesENold) && !Files.isDirectory(messagesENold)) {
if(Files.exists(messagesEN) && !Files.isDirectory(messagesEN)) {
return;
}
send.convert(messagesENold.toString().replace(replace, ""), messagesEN.toString().replace(replace, ""));
try {
Files.move(messagesENold, messagesEN);
} catch (IOException e) {
e.printStackTrace();
}
}
Path messagesNOold = Paths.get(Main.getPath() + "/languages/no_NO_Messages.yml");
Path messagesNO = Paths.get(Main.getPath() + "/languages/norwegian_messages.yml");
if(Files.exists(messagesNOold) && !Files.isDirectory(messagesNOold)) {
if(Files.exists(messagesNO) && !Files.isDirectory(messagesNO)) {
return;
}
send.convert(messagesNOold.toString().replace(replace, ""), messagesNO.toString().replace(replace, ""));
try {
Files.move(messagesNOold, messagesNO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,167 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.system.Main;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class CreateConfig {
public static Integer ConfigVersion = 2;
public static Boolean UpdateCheckOnJoin = true;
public static String Prefix = "§8[§2OP§4Security§8] ";
public static String language = "english";
public static Boolean OnlyOPcanUseThePlugin = true;
public static Boolean CheckOnJoin = true;
public static Boolean CheckOnInteract = true;
public static Boolean CheckOnCommand = true;
public static Boolean CheckOnChat = true;
public static String KickCommand = "minecraft:kick [player] [reason]";
public static Boolean Notify_Warn = true;
public static Boolean Notify_Sound_Enable = true;
public static String Notify_Sound_1_8 = "NOTE_PIANO";
public static String Notify_Sound_1_9_to_1_12 = "BLOCK_NOTE_HARP";
public static String Notify_Sound_from_1_13 = "BLOCK_NOTE_BLOCK_HARP";
public static Boolean Timer_Enable = true;
public static int RefreshTime = 60;
public static Boolean OP_Whitelist_Enable = false;
public static Boolean PlayerMustBeOnlineToOp = true;
public static String OP_Whitelist_P1 = "player1";
public static String OP_Whitelist_P1UUID = "00000000000000000000000000000000";
public static String OP_Whitelist_P2 = "player2";
public static String OP_Whitelist_P2UUID = "00000000000000000000000000000000";
public static Boolean no_OP_Player_deop = true;
public static Boolean sendPlayerDEOPmsg = true;
public static Boolean no_OP_Player_kick = true;
public static Boolean customCommand_Enable = false;
public static List<String> customKickCommand = Arrays.asList("kick [player] &4You have op but are not authorized to do so, that's why you were kicked!");
public static Boolean Permission_Whitelist_Enable = false;
public static List<String> Permissions = Arrays.asList("*", "opsecurity.admin");
public static String Perm_Whitelist_P1 = "player1";
public static String Perm_Whitelist_P1UUID = "00000000000000000000000000000000";
public static String Perm_Whitelist_P2 = "player2";
public static String Perm_Whitelist_P2UUID = "00000000000000000000000000000000";
public static Boolean PlayerWhithPermission_kick = true;
public static Boolean Perm_Command_enable = false;
public static List<String> Perm_Command = Arrays.asList("lp user [player] permission unset *", "lp user [player] permission unset opsecurity.admin");
public static Boolean LP_Enable = false;
public static Boolean LP_AllowFromConsole = false;
public static List<String> LP_Whitelist = Arrays.asList("player1", "player2");
public static void configCreate() {
Bukkit.getConsoleSender().sendMessage(Prefix + "§4config.yml load...");
File configYML = new File(Main.plugin.getDataFolder().getPath(), "config.yml");
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(configYML);
yamlConfiguration.set("ConfigVersion", ConfigVersion);
set("Plugin.UpdateCheckOnJoin", UpdateCheckOnJoin, yamlConfiguration);
set("Plugin.language", language, yamlConfiguration);
set("Plugin.OnlyOPcanUseThePlugin", OnlyOPcanUseThePlugin, yamlConfiguration);
set("Check.OnJoin", CheckOnJoin, yamlConfiguration);
set("Check.OnInteract", CheckOnInteract, yamlConfiguration);
set("Check.OnCommand", CheckOnCommand, yamlConfiguration);
set("Check.OnChat", CheckOnChat, yamlConfiguration);
set("Check.Timer.Enable", Timer_Enable, yamlConfiguration);
set("Check.Timer.RefreshTime_inSec", RefreshTime, yamlConfiguration);
set("Kick.Command", KickCommand, yamlConfiguration);
set("Notify.JoinWarn.Enable", Notify_Warn, yamlConfiguration);
set("Notify.Sound.Enable", Notify_Sound_Enable, yamlConfiguration);
if (Main.minecraft1_8) {
set("Notify.Sound.Sound", Notify_Sound_1_8, yamlConfiguration);
} else if (Main.minecraft1_9 || Main.minecraft1_10 || Main.minecraft1_11 || Main.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) {
set("OP_Whitelist.Whitelist." + OP_Whitelist_P1 + ".UUID", OP_Whitelist_P1UUID, yamlConfiguration);
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);
set("OP_Whitelist.customCommands.Enable", customCommand_Enable, yamlConfiguration);
set("OP_Whitelist.customCommands.Commands", customKickCommand, yamlConfiguration);
set("Permission_Whitelist.Enable", Permission_Whitelist_Enable, yamlConfiguration);
set("Permission_Whitelist.Permissions", Permissions, yamlConfiguration);
if (yamlConfiguration.get("Permission_Whitelist.Whitelist") == null) {
set("Permission_Whitelist.Whitelist." + Perm_Whitelist_P1 + ".UUID", Perm_Whitelist_P1UUID, yamlConfiguration);
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);
//set("LuckPerms_Whitelist.Enable", LP_Enable, yamlConfiguration);
//set("LuckPerms_Whitelist.AllowFromConsole", LP_AllowFromConsole, yamlConfiguration);
//set("LuckPerms_Whitelist.Whitelist", LP_Whitelist, yamlConfiguration);
try {
yamlConfiguration.save(configYML);
} catch (IOException e) {
e.printStackTrace();
}
Bukkit.getConsoleSender().sendMessage(Prefix + "§2Config.yml loaded successfully.");
}
private static void set(String path, String value, YamlConfiguration config) {
if (!config.contains(path)) {
config.set(path, value);
}
}
private static void set(String path, Integer value, YamlConfiguration config) {
if (!config.contains(path)) {
config.set(path, value);
}
}
private static void set(String path, Double value, YamlConfiguration config) {
if (!config.contains(path)) {
config.set(path, value);
}
}
private static void set(String path, Boolean value, YamlConfiguration config) {
if (!config.contains(path)) {
config.set(path, value);
}
}
private static void set(String path, List value, YamlConfiguration config) {
if (!config.contains(path)) {
config.set(path, value);
}
}
}

View File

@ -0,0 +1,155 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.config.config;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.objects.PlayerObject;
import de.jatitv.opsecurity.system.Main;
import org.bukkit.Bukkit;
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) {
sender.sendMessage(Main.Prefix + " §8----- §2OP§4Security §chelp §8-----");
sender.sendMessage(Main.Prefix);
sender.sendMessage(Main.Prefix + " §8'§b/opsecurity reload§8' §eReload the Plugin.");
sender.sendMessage(Main.Prefix + " §8'§b/opsecurity help§8' §eOpens this help.");
sender.sendMessage(Main.Prefix + " §8'§b/opsecurity info§8' §eCall the info about §2OP§4Security§e.");
sender.sendMessage(Main.Prefix);
sender.sendMessage(Main.Prefix + " §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, 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, 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() {
String soundNotify;
if (Main.minecraft1_8) {
soundNotify = CreateConfig.Notify_Sound_1_8;
} else if (Main.minecraft1_9 || Main.minecraft1_10 || Main.minecraft1_11 || Main.minecraft1_12) {
soundNotify = CreateConfig.Notify_Sound_1_9_to_1_12;
} else soundNotify = CreateConfig.Notify_Sound_from_1_13;
try {
Sound sound_Notify = Sound.valueOf(Notify_Sound_input);
if (sound_Notify != null) {
Notify_Sound = sound_Notify;
}
} catch (Exception e) {
Bukkit.getConsoleSender().sendMessage("§4\n§4\n§4\n" + SelectMessages.SoundNotFound.replace("[prefix]", Main.Prefix)
.replace("[sound]", "§8PlayerNotFound: §6" + Notify_Sound_input) + "§4\n§4\n§4\n");
Notify_Sound = Sound.valueOf(soundNotify);
}
}
}

View File

@ -0,0 +1,101 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.config.languages;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.send;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
public class LanguagesCreate {
public static void messagesCreate() {
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);
set("Plugin.SoundNotFound", MSG.DE_SoundNotFound, yamlConfigurationDE);
set("Plugin.NoPermission", MSG.DE_NoPermission, yamlConfigurationDE);
set("Plugin.PlayerMustBeOnlineToOp", MSG.DE_PlayerMustBeOnlineToOp, yamlConfigurationDE);
set("Plugin.Reload.Start", MSG.DE_ReloadStart, yamlConfigurationDE);
set("Plugin.Reload.End", MSG.DE_ReloadEnd, yamlConfigurationDE);
set("OP_Whitelist.opCommand", MSG.DE_OP_opCommand, yamlConfigurationDE);
set("OP_Whitelist.consoleOnJoin", MSG.DE_OP_consoleOnJoin, yamlConfigurationDE);
set("OP_Whitelist.deop", MSG.DE_OP_deop, yamlConfigurationDE);
set("OP_Whitelist.consoleDeop", MSG.DE_OP_consoleDeop, yamlConfigurationDE);
set("OP_Whitelist.kick", MSG.DE_OP_kick, yamlConfigurationDE);
set("OP_Whitelist.consoleKick", MSG.DE_OP_consoleKick, yamlConfigurationDE);
set("Permission_Whitelist.consoleOnJoin", MSG.DE_Perm_consoleOnJoin, yamlConfigurationDE);
set("Permission_Whitelist.kick", MSG.DE_Perm_kick, yamlConfigurationDE);
set("Permission_Whitelist.consoleKick", MSG.DE_Perm_consoleKick, yamlConfigurationDE);
try {
yamlConfigurationDE.save(messagesDE);
} catch (IOException e) {
e.printStackTrace();
}
File messagesEN = new File(Main.getPath(), "languages/english_messages.yml");
YamlConfiguration yamlConfigurationEN = YamlConfiguration.loadConfiguration(messagesEN);
set("Plugin.SoundNotFound", MSG.EN_SoundNotFound, yamlConfigurationEN);
set("Plugin.NoPermission", MSG.EN_NoPermission, yamlConfigurationEN);
set("Plugin.PlayerMustBeOnlineToOp", MSG.EN_PlayerMustBeOnlineToOp, yamlConfigurationEN);
set("Plugin.Reload.Start", MSG.EN_ReloadStart, yamlConfigurationEN);
set("Plugin.Reload.End", MSG.EN_ReloadEnd, yamlConfigurationEN);
set("OP_Whitelist.opCommand", MSG.EN_OP_opCommand, yamlConfigurationEN);
set("OP_Whitelist.consoleOnJoin", MSG.EN_OP_consoleOnJoin, yamlConfigurationEN);
set("OP_Whitelist.deop", MSG.EN_OP_deop, yamlConfigurationEN);
set("OP_Whitelist.consoleDeop", MSG.EN_OP_consoleDeop, yamlConfigurationEN);
set("OP_Whitelist.kick", MSG.EN_OP_kick, yamlConfigurationEN);
set("OP_Whitelist.consoleKick", MSG.EN_OP_consoleKick, yamlConfigurationEN);
set("Permission_Whitelist.consoleOnJoin", MSG.EN_Perm_consoleOnJoin, yamlConfigurationEN);
set("Permission_Whitelist.kick", MSG.EN_Perm_kick, yamlConfigurationEN);
set("Permission_Whitelist.consoleKick", MSG.EN_Perm_consoleKick, yamlConfigurationEN);
try {
yamlConfigurationEN.save(messagesEN);
} catch (IOException e) {
e.printStackTrace();
}
File messagesNO = new File(Main.getPath(), "languages/norwegian_messages.yml");
YamlConfiguration yamlConfigurationNO = YamlConfiguration.loadConfiguration(messagesNO);
set("Plugin.SoundNotFound", MSG.NO_SoundNotFound, yamlConfigurationNO);
set("Plugin.NoPermission", MSG.NO_NoPermission, yamlConfigurationNO);
set("Plugin.PlayerMustBeOnlineToOp", MSG.NO_PlayerMustBeOnlineToOp, yamlConfigurationNO);
set("Plugin.Reload.Start", MSG.NO_ReloadStart, yamlConfigurationNO);
set("Plugin.Reload.End", MSG.NO_ReloadEnd, yamlConfigurationNO);
set("OP_Whitelist.opCommand", MSG.NO_OP_opCommand, yamlConfigurationNO);
set("OP_Whitelist.consoleOnJoin", MSG.NO_OP_consoleOnJoin, yamlConfigurationNO);
set("OP_Whitelist.deop", MSG.NO_OP_deop, yamlConfigurationNO);
set("OP_Whitelist.consoleDeop", MSG.NO_OP_consoleDeop, yamlConfigurationNO);
set("OP_Whitelist.kick", MSG.NO_OP_kick, yamlConfigurationNO);
set("OP_Whitelist.consoleKick", MSG.NO_OP_consoleKick, yamlConfigurationNO);
set("Permission_Whitelist.consoleOnJoin", MSG.NO_Perm_consoleOnJoin, yamlConfigurationNO);
set("Permission_Whitelist.kick", MSG.NO_Perm_kick, yamlConfigurationNO);
set("Permission_Whitelist.consoleKick", MSG.NO_Perm_consoleKick, yamlConfigurationNO);
try {
yamlConfigurationNO.save(messagesNO);
} catch (IOException e) {
e.printStackTrace();
}
send.console(Main.Prefix + " §2Language files were successfully created / updated." + " §7- §e" + (System.currentTimeMillis() - long_.longValue()) + "ms");
}
private static void set(String path, String value, YamlConfiguration config) {
if (!config.contains(path)) {
config.set(path, value);
}
}
}

View File

@ -0,0 +1,69 @@
package de.jatitv.opsecurity.config.languages;
public class MSG {
//EN
public static String EN_SoundNotFound = "[prefix] &4The sound &6[sound] &4could not be found! Please check your settings.";
public static String EN_NoPermission = "&4No Permission!";
public static String EN_PlayerMustBeOnlineToOp = "&4Player must be online to get op!";
public static String EN_ReloadStart = "[prefix] &6Plugin is reloaded...";
public static String EN_ReloadEnd = "[prefix] &2Plugin was successfully reloaded.";
public static String EN_OP_opCommand = "&4The specified player is not on the OP_Whitelist!";
public static String EN_OP_consoleOnJoin = "&4Player &6[player] &4is joined to the server but is not on the OP_Whitelist!";
public static String EN_OP_deop = "&4You have been removed from OP because you do not have permission.";
public static String EN_OP_consoleDeop = "&4Player &6[player] &4 was removed OP because he is not on the playerlist!";
public static String EN_OP_kick = "&4You have op but are not authorized to do so, that's why you were kicked!";
public static String EN_OP_consoleKick = "&4Player &6[player] &4was kicked because he is not on the OP_Whitelist!";
public static String EN_Perm_consoleOnJoin = "&4Player &6[player] &4has permission &6[perm] &4and is not authorized to do so! &6[player] &4is not on the Player list!";
public static String EN_Perm_kick = "&4You were kicked because you have permissions to which you do not have permission!";
public static String EN_Perm_consoleKick = "&4Player &6[player] &4has permission &6[perm] &4and is not authorized to do so! Therefore he was kicked! &6[player] &4is not on the Player list!";
public static String EN_LuckPerms = "&4You are not allowed to execute LuckPerms commands!";
//DE
public static String DE_SoundNotFound = "[prefix] &4Der Sound &6[sound] &4wurde nicht gefunden! Bitte überprüfe die Einstellungen.";
public static String DE_NoPermission = "&4Keine Berechtigung!";
public static String DE_PlayerMustBeOnlineToOp = "&4Der Spieler muss online sein, um OP zu erhalten!";
public static String DE_ReloadStart = "[prefix] &6Plugin wird neu geladen...";
public static String DE_ReloadEnd = "[prefix] &2Plugin wurde erfolgreich neu geladen.";
public static String DE_OP_opCommand = "&4Der angegebene Spieler befindet sich nicht auf der OP_Whitelist!";
public static String DE_OP_consoleOnJoin = "&4Spieler &6[player] &4ist dem Server beigetreten, befindet sich aber nicht auf der OP_Whitelist!";
public static String DE_OP_deop = "&4You have been removed from OP because you do not have permission.\n" +
"&4Dir wurde OP entfernt da du dazu keine Permission besitzt.";
public static String DE_OP_consoleDeop = "&4Spieler &6[player] &4 wurde OP entfernt da er nicht auf der Spielerliste steht!";
public static String DE_OP_kick = "&4You have op but are not authorized to do so, that's why you were kicked\n" +
"&4Du hast op bist dazu aber nicht berechtigt, deswegen wurdest du gekickt!";
public static String DE_OP_consoleKick = "&4Spieler &6[player] &4wurde gekickt, da er nicht auf der OP_Whitelist steht!";
public static String DE_Perm_consoleOnJoin = "&4Player &6[player] &4hat die Permission &6[perm] &4und ist dazu nicht berechtigt! &6[player] &4ist nicht in der Spielerliste!";
public static String DE_Perm_kick = "&4You were kicked because you have permissions to which you do not have permission!\n" +
"&4Du wurdest gekickt, da du Permissions besitzt, für die du keine Berechtigung besitzt!";
public static String DE_Perm_consoleKick = "&4Spieler &6[player] &4hat die Permission &6[perm] &4und ist dazu nicht berechtigt! Daher wurde er gekickt! &6[player] &4ist nicht in der Spielerliste!";
public static String DE_LuckPerms = "&4Du darfst keine LuckPerms Commands ausführen!";
//NO
public static String NO_SoundNotFound = "[prefix] &4Lydeffekten &6[sound] &4ble ikke funnet! Sjekk instillingene dine.";
public static String NO_NoPermission = "&4Ingen tillatelse!";
public static String NO_PlayerMustBeOnlineToOp = "&4Spilleren må være online for å komme i gang!";
public static String NO_ReloadStart = "[prefix] &6Pluginet blir relastet...";
public static String NO_ReloadEnd = "[prefix] &2Pluginet har blitt lastet inn på nytt.";
public static String NO_OP_opCommand = "&4Denne spilleren er ikke del av OP_Whitelist!";
public static String NO_OP_consoleOnJoin = "&4Spiller &6[player] &4is ble med i spillet, men er ikke i OP_Whitelist!";
public static String NO_OP_deop = "&4You have been removed from OP because you do not have permission.\n" +
"&4Du har blitt fjernet fra OP fordi du ikke har tillatelse.";
public static String NO_OP_consoleDeop = "&4Spiller &6[player] &4ble fjernet fra OP fordi han ikke er i spillerlisten!";
public static String NO_OP_kick = "&4You have op but are not authorized to do so, that's why you were kicked\n" +
"&4Du er ikke på OP whitelist, så du ble sparket ut!";
public static String NO_OP_consoleKick = "&4Spiller &6[player] &4ble sparket ut fordi han ikke er på OP_Whitelist!";
public static String NO_Perm_consoleOnJoin = "&4Spiller &6[player] &4har tillatelsen &6[perm] &4og er ikke godkjent til dette! &6[player] &4er ikke en spiller på Spiller listen! Sparket ut: &4Du ble sparket ut fordi du har tillatelse til noe du ikke er tillatt!";
public static String NO_Perm_kick = "&4You were kicked because you have permissions to which you do not have permission!\n" +
"&4Du har blitt sparket fordi du har tillatelse til noe du ikke har tilgang til!";
public static String NO_Perm_consoleKick = "&4Spiller &6[player] &4har tillatelsen &6[perm] &4og er ikke godkjent til dette! Derfor ble han sparket ut! &6[player] &4er ikke på Spiller listen!";
public static String NO_LuckPerms = "&4Du har ikke lov til å utføre LuckPerms-kommandoer!";
}

View File

@ -0,0 +1,80 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.config.languages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.Replace;
import de.jatitv.opsecurity.util.send;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
public class SelectMessages {
public static String selectMSG;
public static String SoundNotFound;
public static String NoPermission;
public static String PlayerMustBeOnlineToOp;
public static String ReloadStart;
public static String ReloadEnd;
public static String OP_opCommand ;
public static String OP_consoleOnJoin ;
public static String OP_deop;
public static String OP_consoleDeop ;
public static String OP_kick;
public static String OP_consoleKick ;
public static String Perm_consoleOnJoin ;
public static String Perm_kick;
public static String Perm_consoleKick;
public static String LuckPerms;
public static void selectCreate(String Prefix) {
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()) {
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;
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(msg);
SoundNotFound = select("Plugin.SoundNotFound", yamlConfiguration);
NoPermission = select("Plugin.NoPermission", yamlConfiguration);
ReloadStart = select("Plugin.Reload.Start", yamlConfiguration);
ReloadEnd = select("Plugin.Reload.End", yamlConfiguration);
PlayerMustBeOnlineToOp = select("Plugin.PlayerMustBeOnlineToOp", yamlConfiguration);
OP_opCommand = select("OP_Whitelist.opCommand", yamlConfiguration);
OP_deop = select("OP_Whitelist.deop", yamlConfiguration);
OP_consoleDeop = select("OP_Whitelist.consoleDeop", yamlConfiguration);
OP_consoleOnJoin = select("OP_Whitelist.consoleOnJoin", yamlConfiguration);
OP_kick = select("OP_Whitelist.kick", yamlConfiguration);
OP_consoleKick = select("OP_Whitelist.consoleKick", yamlConfiguration);
Perm_consoleOnJoin = select("Permission_Whitelist.consoleOnJoin", yamlConfiguration);
Perm_kick = select("Permission_Whitelist.kick", yamlConfiguration);
Perm_consoleKick = select("Permission_Whitelist.consoleKick", yamlConfiguration);
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 Replace.replace(yamlConfiguration.getString(path));
}
}

View File

@ -0,0 +1,153 @@
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.Replace;
import de.jatitv.opsecurity.util.Cmd;
import de.jatitv.opsecurity.util.send;
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)) {
if (join) {
send.console(Replace.replace(SelectMessages.OP_consoleOnJoin.replace("[player]", player.getName())));
}
if (SelectConfig.Notify_Warn) {
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission("opsecurity.notify")) {
if (join) {
notifyperm.sendMessage(Replace.replace(SelectMessages.OP_consoleOnJoin.replace("[player]", player.getName())));
} else notifyperm.sendMessage(Replace.replace(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(SelectMessages.OP_kick + "\n" + "\n" + SelectMessages.OP_deop)));
send.console(Replace.replace(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(SelectMessages.OP_kick)));
send.console(Replace.replace(SelectMessages.OP_consoleKick.replace("[player]", player.getName())));
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission("opsecurity.notify")) {
notifyperm.sendMessage(Replace.replace(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(SelectMessages.OP_deop));
}
}.runTaskLater(Main.plugin, 5L);
}
send.console(Replace.replace(SelectMessages.OP_consoleDeop.replace("[player]", player.getName())));
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission("opsecurity.notify")) {
notifyperm.sendMessage(Replace.replace(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(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(SelectMessages.Perm_consoleOnJoin.replace("[player]", player.getName()).replace("[perm]", s)));
}
if (SelectConfig.Notify_Warn) {
for (Player notifyperm : Bukkit.getOnlinePlayers()) {
if (notifyperm.hasPermission("opsecurity.notify")) {
if (join) {
notifyperm.sendMessage(Replace.replace(SelectMessages.Perm_consoleOnJoin.replace("[player]",
player.getName()).replace("[perm]", s)));
} else notifyperm.sendMessage(Replace.replace(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(SelectMessages.Perm_kick)));
send.console(Replace.replace(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(SelectMessages.Perm_kick)));
send.console(Replace.replace(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())) {
if (Main.opHashMap.get(player.getName()).UUID.equals(player.getUniqueId().toString().replace("-", ""))) {
return true;
} else return false;
} else return false;
}
private static Boolean permWhitelist(Player player) {
if (Main.permissionHashMap.containsKey(player.getName())) {
if (Main.permissionHashMap.get(player.getName()).UUID.equals(player.getUniqueId().toString().replace("-",""))) {
return true;
} else return false;
} else return false;
}
}

View File

@ -0,0 +1,81 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.TextBuilder;
import de.jatitv.opsecurity.util.UpdateChecker;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.*;
import org.bukkit.scheduler.BukkitRunnable;
public class Events implements org.bukkit.event.Listener {
@EventHandler
public void CommandSendEvent(PlayerCommandPreprocessEvent event) {
if (SelectConfig.CheckOnCommand) {
Player player = event.getPlayer();
event.setCancelled(Check.onCheck(player, false));
}
}
@EventHandler
public void PlayerChatEvent(PlayerChatEvent event) {
if (SelectConfig.CheckOnChat) {
Player player = event.getPlayer();
if (Check.onCheck(player, false)){
if (event.isCancelled()){
return;
}
event.setCancelled(true);
}
}
}
@EventHandler
public void onInteract(PlayerInteractEvent event) {
if (SelectConfig.CheckOnInteract) {
Player player = event.getPlayer();
new BukkitRunnable() {
@Override
public void run() {
event.setCancelled(Check.onCheck(player, false));
}
}.runTaskLater(Main.plugin, 1L);
}
}
@EventHandler
public void onJoinCheck(PlayerJoinEvent event) {
if (SelectConfig.CheckOnJoin) {
Player player = event.getPlayer();
new BukkitRunnable() {
@Override
public void run() {
Check.onCheck(player, true);
}
}.runTaskLater(Main.plugin, 1L);
}
}
@EventHandler
public void onJoinEvent(PlayerLoginEvent event) {
Player player = event.getPlayer();
String foundVersion = Main.plugin.getDescription().getVersion();
if (player.hasPermission("opsecurity.updatemsg") || player.isOp()) {
if (!foundVersion.equals(Main.update_version)) {
if (SelectConfig.UpdateCheckOnJoin) {
new BukkitRunnable() {
@Override
public void run() {
UpdateChecker.sendUpdateMsg(Main.Prefix, foundVersion, Main.update_version, player);
}
}.runTaskLater(Main.plugin, 200L);
}
}
}
}
}

View File

@ -0,0 +1,85 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.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("/", "");
}
Iterator inter = SelectConfig.LP_Whitelist.iterator();
String lpwtl;
do {
if (!inter.hasNext()) {
return true;
}
lpwtl = (String) inter.next();
} while (!command.equalsIgnoreCase("lp " + lpwtl) &&
!command.equalsIgnoreCase("luckperms " + lpwtl) &&
!command.equalsIgnoreCase("permissions " + lpwtl) &&
!command.equalsIgnoreCase("perms " + lpwtl) &&
!command.equalsIgnoreCase("perm " + lpwtl) &&
!command.equalsIgnoreCase("lpb " + lpwtl) &&
!command.equalsIgnoreCase("luckpermsbungee " + lpwtl) &&
!command.equalsIgnoreCase("lpv " + lpwtl) &&
!command.equalsIgnoreCase("luckpermsvelocity " + lpwtl));
return false;
}
@EventHandler
public void onOPServer(ServerCommandEvent event) {
if (SelectConfig.LP_AllowFromConsole) {
if (!(event.getSender() instanceof Player)) {
return;
}
}
if ((event.getCommand().toLowerCase().startsWith("lp ") ||
event.getCommand().toLowerCase().startsWith("luckperms ") ||
event.getCommand().toLowerCase().startsWith("permissions ") ||
event.getCommand().toLowerCase().startsWith("perms ") ||
event.getCommand().toLowerCase().startsWith("perm ") ||
event.getCommand().toLowerCase().startsWith("lpb ") ||
event.getCommand().toLowerCase().startsWith("luckpermsbungee ") ||
event.getCommand().toLowerCase().startsWith("lpv ") ||
event.getCommand().toLowerCase().startsWith("luckpermsvelocity ")) && SelectConfig.LP_Enable
&& this.LPCheck(event.getCommand())) {
event.getSender().sendMessage(Replace.replace(Main.Prefix + SelectMessages.OP_opCommand));
event.setCancelled(true);
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
if (SelectConfig.LP_AllowFromConsole) {
if (!(event.getPlayer() instanceof Player)) {
return;
}
}
if ((event.getPlayer().isOp() || event.getPlayer().hasPermission("*")) &&
event.getMessage().toLowerCase().startsWith("/lp ") ||
event.getMessage().toLowerCase().startsWith("/luckperms ") ||
event.getMessage().toLowerCase().startsWith("/permissions ") ||
event.getMessage().toLowerCase().startsWith("/perms ") ||
event.getMessage().toLowerCase().startsWith("/lpb ") ||
event.getMessage().toLowerCase().startsWith("/luckpermsbungee ") ||
event.getMessage().toLowerCase().startsWith("/lpv ") ||
event.getMessage().toLowerCase().startsWith("/luckpermsvelocity ") && SelectConfig.OP_Whitelist_Enable && this.LPCheck(event.getMessage())) {
event.getPlayer().sendMessage(Replace.replace(Main.Prefix + SelectMessages.OP_opCommand));
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,88 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.listener;
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 de.jatitv.opsecurity.util.Replace;
import de.jatitv.opsecurity.util.send;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import java.io.IOException;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
public class OPCommand implements Listener {
private int isNotOPWTL(String command) {
if (command.charAt(0) == '/') command = command.replaceFirst("/", "");
String arg = command.replace("op ", "");
String targetUUID = null;
if (SelectConfig.PlayerMustBeOnlineToOp) {
if (Main.opHashMap.containsKey(arg)) {
Player target = Bukkit.getPlayer(arg);
if (target == null) {
return 1;
}
if (Main.opHashMap.get(target.getName()).UUID.equals(target.getUniqueId().toString().replace("-", ""))) {
return 0;
} else return 2;
} else return 2;
} else {
if (Main.opHashMap.containsKey(arg)) {
try {
targetUUID = NameHistory.getPlayerUUID(arg);
} catch (IOException e) {
e.printStackTrace();
}
if (Main.opHashMap.get(arg).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(), Main.Prefix + " " + SelectMessages.PlayerMustBeOnlineToOp);
event.setCancelled(true);
break;
case 2:
send.sender(event.getSender(), (Replace.replace(Main.Prefix + " " + 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(), Main.Prefix + " " + SelectMessages.PlayerMustBeOnlineToOp);
event.setCancelled(true);
break;
case 2:
send.player(event.getPlayer(), Replace.replace( Main.Prefix + " " + SelectMessages.OP_opCommand));
event.setCancelled(true);
break;
}
}
}
}
}

View File

@ -0,0 +1,39 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.system.Main;
import de.jatitv.opsecurity.util.send;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerCommandSendEvent;
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.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);
send.console(Main.Prefix+ " §4OPSecurity cannot be deactivated!");
}
}
@EventHandler
public void onOpPlayer(PlayerCommandPreprocessEvent event) {
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);
send.player(event.getPlayer(), Main.Prefix+ " §4OPSecurity cannot be deactivated!");
}
}
}

View File

@ -0,0 +1,27 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.listener;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.system.Main;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class Timer {
public static void RefreshTimer() {
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);
}
}
}
}

View File

@ -0,0 +1,9 @@
package de.jatitv.opsecurity.objects;
public class PlayerObject {
public String UUID;
public PlayerObject(String UUID){
this.UUID = UUID;
}
}

View File

@ -0,0 +1,67 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.system;
import de.jatitv.opsecurity.config.config.ConfigConvert;
import de.jatitv.opsecurity.config.config.CreateConfig;
import de.jatitv.opsecurity.config.languages.LanguagesCreate;
import de.jatitv.opsecurity.config.languages.SelectMessages;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.listener.Timer;
import de.jatitv.opsecurity.util.send;
import java.util.List;
public class Load {
public static void onLoad(String Prefix, List Autor, String Version, String Spigot, String Discord) {
send.console(Prefix + " §2-------------- §2OP§4Security §2--------------");
send.console(Prefix + " §2Autor: §6JaTiTV");
send.console(Prefix + " §2Version: §6" + Version);
send.console(Prefix + " §2Spigot: §6" + Spigot);
send.console(Prefix + " §2Discord: §6" + Discord);
send.console(Prefix + " §2");
send.console(Prefix + " §4Plugin load...");
send.console(Prefix + " §8-------------------------------");
loadReload();
send.console(Prefix + " §8-------------------------------");
send.console(Prefix + " §2Plugin loaded successfully.");
send.console(Prefix + " §2-----------------------------------------");
}
public static void loadReload() {
ConfigConvert.convert();
try {
CreateConfig.configCreate();
} catch (Exception e) {
e.printStackTrace();
}
try {
SelectConfig.onSelect();
} catch (Exception e) {
e.printStackTrace();
}
try {
LanguagesCreate.messagesCreate();
} catch (Exception e) {
e.printStackTrace();
}
try {
SelectMessages.selectCreate(Main.Prefix);
} catch (Exception e) {
e.printStackTrace();
}
try {
SelectConfig.sound();
} catch (Exception e) {
e.printStackTrace();
}
try {
Timer.RefreshTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,105 @@
package de.jatitv.opsecurity.system;
import de.jatitv.opsecurity.cmdManagement.CmdExecuter;
import de.jatitv.opsecurity.config.config.SelectConfig;
import de.jatitv.opsecurity.listener.Events;
import de.jatitv.opsecurity.listener.OPCommand;
import de.jatitv.opsecurity.listener.PlugManCommand;
import de.jatitv.opsecurity.objects.PlayerObject;
import de.jatitv.opsecurity.util.Metrics;
import de.jatitv.opsecurity.util.UpdateChecker;
import de.jatitv.opsecurity.util.send;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;
public final class Main extends JavaPlugin {
// Debug Settings
public static Boolean Bstats = true;
public static String Prefix = "§8[§2OP§4Security§8]";
public static List<String> Autor;
public static Integer SpigotID = 90739;
public static Integer BstatsID = 10858;
public static String Spigot = "https://spigotmc.org/resources/" + SpigotID;
public static String Discord = "http://dc.t2code.net";
// ---------------------------------------------
public static String Version;
public static Main plugin;
public static String update_version = null;
public static boolean minecraft1_8;
public static boolean minecraft1_9;
public static boolean minecraft1_10;
public static boolean minecraft1_11;
public static boolean minecraft1_12;
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
Logger logger = this.getLogger();
plugin = this;
Autor = plugin.getDescription().getAuthors();
Version = plugin.getDescription().getVersion();
minecraft1_8 = Bukkit.getServer().getClass().getPackage().getName().contains("1_8");
minecraft1_9 = Bukkit.getServer().getClass().getPackage().getName().contains("1_9");
minecraft1_10 = Bukkit.getServer().getClass().getPackage().getName().contains("1_10");
minecraft1_11 = Bukkit.getServer().getClass().getPackage().getName().contains("1_11");
minecraft1_12 = Bukkit.getServer().getClass().getPackage().getName().contains("1_12");
Load.onLoad(Prefix, Autor, Version, Spigot, Discord);
getCommand("opsecurity").setExecutor(new CmdExecuter());
Bukkit.getServer().getPluginManager().registerEvents(new Events(), this);
Bukkit.getServer().getPluginManager().registerEvents(new OPCommand(), this);
Bukkit.getServer().getPluginManager().registerEvents(new PlugManCommand(), this);
// Bukkit.getServer().getPluginManager().registerEvents(new LPCommand(), this);
if (Main.Bstats) {
int pluginId = BstatsID; // <-- Replace with the id of your plugin!
Metrics metrics = new Metrics(this, pluginId);
metrics.addCustomChart(new Metrics.SimplePie("updatecheckonjoin", () -> String.valueOf(SelectConfig.UpdateCheckOnJoin)));
} else {
new BukkitRunnable() {
@Override
public void run() {
Bukkit.getConsoleSender().sendMessage(Main.Prefix + "§4\n" + Main.Prefix + "§4Bstats is disabled!");
}
}.runTaskLater(Main.plugin, 200L);
}
UpdateChecker.onUpdateCheck();
UpdateChecker.onUpdateCheckTimer();
}
@Override
public void onDisable() {
// Plugin shutdown logic
}
}

View File

@ -0,0 +1,149 @@
package de.jatitv.opsecurity.system;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
public class NameHistory {
/**
* The URL from Mojang API that provides the JSON String in response.
*/
private static final String LOOKUP_URL = "https://api.mojang.com/user/profiles/%s/names";
/**
* The URL from Mojang API to resolve the UUID of a player from their name.
*/
private static final String GET_UUID_URL = "https://api.mojang.com/users/profiles/minecraft/%s?t=0";
private static final Gson JSON_PARSER = new Gson();
/**
* <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main thread!It blocks while attempting to get a response from Mojang servers!</h1>
*
* @param player The UUID of the player to be looked up.
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted.
* @throws IOException {@link #getPlayerPreviousNames(String)}
*/
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException {
return getPlayerPreviousNames(player.toString());
}
/**
* <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main thread! It blocks while attempting to get a response from Mojang servers!</h1>
* Alternative method accepting an 'OfflinePlayer' (and therefore 'Player') objects as parameter.
*
* @param player The OfflinePlayer object to obtain the UUID from.
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted.
* @throws IOException {@link #getPlayerPreviousNames(UUID)}
*/
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(OfflinePlayer player) throws IOException {
return getPlayerPreviousNames(player.getUniqueId());
}
/**
* <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main thread! It blocks while attempting to get a response from Mojang servers!</h1>
* Alternative method accepting an {@link OfflinePlayer} (and therefore {@link Player}) objects as parameter.
*
* @param uuid The UUID String to lookup
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted.
* @throws IOException
*/
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException {
if (uuid == null || uuid.isEmpty())
return null;
String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid)));
PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class);
return names;
}
/**
* If you don't have the UUID of a player, this method will resolve it for you.<br>
* The output of this method may be used directly with {@link #getPlayerPreviousNames(String)}.<br>
* <b>NOTE: as with the rest, this method opens a connection with a remote server, so running it synchronously will block the main thread which will lead to server lag.</b>
*
* @param name The name of the player to lookup.
* @return A String which represents the player's UUID. <b>Note: the uuid cannot be parsed to a UUID object directly, as it doesnt contain dashes. This feature will be implemented later</b>
* @throws IOException Inherited by {@link BufferedReader#readLine()}, {@link BufferedReader#close()}, {@link URL}, {@link HttpURLConnection#getInputStream()}
*/
public static String getPlayerUUID(String name) throws IOException {
String response = getRawJsonResponse(new URL(String.format(GET_UUID_URL, name)));
JsonObject o = JSON_PARSER.fromJson(response, JsonObject.class);
if (o == null)
return null;
return o.get("id") == null ? null : o.get("id").getAsString();
}
/**
* This is a helper method used to read the response of Mojang's API webservers.
*
* @param u the URL to connect to
* @return a String with the data read.
* @throws IOException Inherited by {@link BufferedReader#readLine()}, {@link BufferedReader#close()}, {@link URL}, {@link HttpURLConnection#getInputStream()}
*/
private static String getRawJsonResponse(URL u) throws IOException {
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setDoInput(true);
con.setConnectTimeout(2000);
con.setReadTimeout(2000);
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = in.readLine();
in.close();
return response;
}
/**
* This class represents the typical response expected by Mojang servers when requesting the name history of a player.
*/
public class PreviousPlayerNameEntry {
private String name;
@SerializedName("changedToAt")
private long changeTime;
/**
* Gets the player name of this entry.
*
* @return The name of the player.
*/
public String getPlayerName() {
return name;
}
/**
* Get the time of change of the name.
* <br><b>Note: This will return 0 if the name is the original (initial) name of the player! Make sure you check if it is 0 before handling!
* <br>Parsing 0 to a Date will result in the date "01/01/1970".</b>
*
* @return a timestamp in miliseconds that you can turn into a date or handle however you want :)
*/
public long getChangeTime() {
return changeTime;
}
/**
* Check if this name is the name used to register the account (the initial/original name)
*
* @return a boolean, true if it is the the very first name of the player, otherwise false.
*/
public boolean isPlayersInitialName() {
return getChangeTime() == 0;
}
@Override
public String toString() {
return "Name: " + name + " Date of change: " + new Date(changeTime).toString();
}
}
}

View File

@ -0,0 +1,16 @@
package de.jatitv.opsecurity.util;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class Cmd {
public static void console(String cmd) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),cmd);
}
public static void player(Player player, String cmd) {
player.chat("/" + cmd);
}
}

View File

@ -0,0 +1,840 @@
// This claas was created by JaTiTV
package 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 {
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,38 @@
package de.jatitv.opsecurity.util;
import de.jatitv.opsecurity.system.Main;
import java.util.ArrayList;
import java.util.List;
public class Replace {
private static String prefix = Main.Prefix;
public static String replace(String Text) {
return Text.replace("[prefix]", prefix).replace("&", "§").replace("[ue]", "ü")
.replace("[UE]", "Ü").replace("[oe]", "ö").replace("[OE]", "Ö")
.replace("[ae]", "ä").replace("[AE]", "Ä");
}
public static List<String> replace(List<String> Text) {
List<String> output = new ArrayList<>();
for (String input : Text) {
output.add(input.replace("[prefix]", prefix).replace("&", "§")
.replace("[ue]", "ü").replace("[UE]", "Ü").replace("[oe]", "ö")
.replace("[OE]", "Ö").replace("[ae]", "ä").replace("[AE]", "Ä"));
}
return output;
}
public static List replacePrice(List<String> Text, String price) {
List rp = new ArrayList();
for (String s : Text) {
rp.add(s.replace("[prefix]", prefix).replace("&", "§")
.replace("[ue]", "ü").replace("[UE]", "Ü").replace("[oe]", "ö")
.replace("[OE]", "Ö").replace("[ae]", "ä").replace("[AE]", "Ä")
.replace("[price]", String.valueOf(price)));
}
return rp;
}
}

View File

@ -0,0 +1,45 @@
package de.jatitv.opsecurity.util;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
public class TextBuilder {
private final String text;
private String hover;
private String click;
private ClickEvent.Action action;
public TextBuilder(String text) {
this.text = text;
}
public TextBuilder addHover(String hover) {
this.hover = hover;
return this;
}
public TextBuilder addClickEvent(ClickEvent.Action clickEventAction, String value) {
this.action = clickEventAction;
this.click = value;
return this;
}
public TextComponent build() {
TextComponent textComponent = new TextComponent();
textComponent.setText(this.text);
if(this.hover != null) {
textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(this.hover).create()));
}
if(this.click != null && (this.action != null)) {
textComponent.setClickEvent(new ClickEvent(action, this.click));
}
return textComponent;
}
public enum ClickEventType {
RUN_COMMAND, SUGGEST_COMMAND, OPEN_URL
}
}

View File

@ -0,0 +1,125 @@
// This claas was created by JaTiTV
package de.jatitv.opsecurity.util;
import de.jatitv.opsecurity.system.Main;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;
import java.util.function.Consumer;
public class UpdateChecker {
public static boolean cannotLookForUpdates;
public static void sendUpdateMsg(String Prefix, String foundVersion, String update_version) {
send.console("§4=========== " + Prefix + " §4===========");
send.console("§6A new version was found!");
send.console("§6Your version: §c" + foundVersion + " §7- §6Current version: §a" + update_version);
send.console("§6You can download it here: §e" + Main.Spigot);
send.console("§6You can find more information on Discord: §e" + Main.Discord);
send.console("§4=========== " + Prefix + " §4===========");
}
public static void sendUpdateMsg(String Prefix, String foundVersion, String update_version, Player player) {
TextComponent comp = new TextBuilder(Prefix + " §6A new version was found!")
.addHover("§6You can download it here: §e" + Main.Spigot).addClickEvent(ClickEvent.Action.OPEN_URL, Main.Spigot).build();
player.spigot().sendMessage(comp);
TextComponent comp1 = new TextBuilder(Prefix + " §c" + foundVersion + " §7-> §a" + update_version)
.addHover("§6You can download it here: §e" + Main.Spigot).addClickEvent(ClickEvent.Action.OPEN_URL, Main.Spigot).build();
player.spigot().sendMessage(comp1);
TextComponent comp2 = new TextBuilder(Prefix + " §6You can find more information on Discord.")
.addHover("§e" + Main.Discord).addClickEvent(ClickEvent.Action.OPEN_URL, Main.Discord).build();
player.spigot().sendMessage(comp2);
}
public static void onUpdateCheckTimer() {
int taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
public void run() {
(new UpdateChecker(Main.plugin, Main.SpigotID)).getVersion((update_version) -> {
String foundVersion = Main.plugin.getDescription().getVersion();
Main.update_version = update_version;
if (!foundVersion.equalsIgnoreCase(update_version)) {
new BukkitRunnable() {
@Override
public void run() {
sendUpdateMsg(Main.Prefix, foundVersion, update_version);
}
}.runTaskLater(Main.plugin, 600L);
}
});
}
}, 0L, 20 * 60 * 60L);
}
public static void onUpdateCheck() {
(new UpdateChecker(Main.plugin, Main.SpigotID)).getVersion((update_version) -> {
String foundVersion = Main.plugin.getDescription().getVersion();
Main.update_version = update_version;
if (foundVersion.equalsIgnoreCase(update_version)) {
new BukkitRunnable() {
@Override
public void run() {
send.console(Main.Prefix + " §2No update found.");
}
}.runTaskLater(Main.plugin, 120L);
}
});
}
private JavaPlugin plugin;
private int resourceId;
public UpdateChecker(JavaPlugin plugin, int resourceId) {
this.plugin = plugin;
this.resourceId = resourceId;
}
public void getVersion(Consumer<String> consumer) {
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
try {
InputStream inputStream = (new URL("https://api.spigotmc.org/legacy/update.php?resource=" + this.resourceId)).openStream();
try {
Scanner scanner = new Scanner(inputStream);
try {
if (scanner.hasNext()) {
consumer.accept(scanner.next());
}
} catch (Throwable var8) {
try {
scanner.close();
} catch (Throwable var7) {
var8.addSuppressed(var7);
}
throw var8;
}
scanner.close();
} catch (Throwable var9) {
if (inputStream != null) {
try {
inputStream.close();
} catch (Throwable var6) {
var9.addSuppressed(var6);
}
}
throw var9;
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException var10) {
cannotLookForUpdates = true;
this.plugin.getLogger().severe(Main.Prefix + "§4 Cannot look for updates: §c" + var10.getMessage());
}
});
}
}

View File

@ -0,0 +1,53 @@
package de.jatitv.opsecurity.util;
import de.jatitv.opsecurity.system.Main;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.logging.Level;
public class send {
public static void console(String msg) {
Bukkit.getConsoleSender().sendMessage(msg);
}
public static void player(Player player, String msg) {
player.sendMessage(msg);
}
public static void sender(CommandSender sender, String msg) {
sender.sendMessage(msg);
}
public static void debug(Plugin plugin, String msg) {
// if (!new File(Main.getPath(), "config.yml").exists()) return;
if (plugin.getConfig().getBoolean("Plugin.Debug")) Bukkit.getConsoleSender().sendMessage(plugin.getDescription().getPrefix() + " §5DEBUG: §6" + msg);
}
public static void debugmsg(Plugin plugin, String msg) {
Bukkit.getConsoleSender().sendMessage(plugin.getDescription().getPrefix() + " §5DEBUG-MSG: §6" + msg);
}
public static void info(Plugin plugin, String msg) {
plugin.getLogger().log(Level.INFO, msg);
}
public static void warning(Plugin plugin, String msg) {
plugin.getLogger().log(Level.WARNING, msg);
}
public static void error(Plugin plugin, String msg) {
plugin.getLogger().log(Level.SEVERE, msg);
}
public static void convert(String oldConfig, String newConfig) {
send.console(Main.Prefix + " §5Convert: §4" + oldConfig + " §5--> §2" + newConfig);
}
public static void convert(String config, String oldConfig, String newConfig) {
send.console(Main.Prefix + " §5Convert: §e" + config + " §4" + oldConfig + " §5--> §2" + newConfig);
}
}

View File

@ -0,0 +1,32 @@
name: OPSecurity
version: 2.3.3.1
api-version: 1.13
load: STARTUP
main: de.jatitv.opsecurity.system.Main
prefix: OPSecurity
authors: [ JaTiTV ]
commands:
opsecurity:
aliases: [opsec]
permissions:
opsecurity.admin:
default: op
children:
opsecurity.notify: true
opsecurity.updatemsg: true
opsecurity.command.reload: true
opsecurity.command.info: true
opsecurity.command.help: true
opsecurity.notify:
description: Players with this permission get the update message when joining if an update is available
default: op
opsecurity.updatemsg:
default: op
opsecurity.command.reload:
default: op
opsecurity.command.info:
default: op
opsecurity.command.help:
default: op