1.2.0, fixes #1
This commit is contained in:
159
src/main/java/hu/ditservices/STPlugin.java
Normal file
159
src/main/java/hu/ditservices/STPlugin.java
Normal file
@ -0,0 +1,159 @@
|
||||
package hu.ditservices;
|
||||
|
||||
import hu.ditservices.handlers.DITTabCompleter;
|
||||
import hu.ditservices.handlers.SaveHandler;
|
||||
import hu.ditservices.handlers.TabHandler;
|
||||
import hu.ditservices.utils.*;
|
||||
import hu.ditservices.utils.Math;
|
||||
import org.bstats.bukkit.Metrics;
|
||||
import hu.ditservices.commands.DitCmd;
|
||||
import hu.ditservices.listeners.ChatEvents;
|
||||
import hu.ditservices.listeners.LogChat;
|
||||
import hu.ditservices.listeners.LogCommand;
|
||||
import hu.ditservices.listeners.LogConnect;
|
||||
import com.tchristofferson.configupdater.ConfigUpdater;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import com.jeff_media.updatechecker.UpdateCheckSource;
|
||||
import com.jeff_media.updatechecker.UpdateChecker;
|
||||
import com.jeff_media.updatechecker.UserAgentBuilder;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public final class STPlugin extends JavaPlugin implements CommandExecutor, Listener {
|
||||
private static STPlugin instance;
|
||||
private final Logger log = Bukkit.getLogger();
|
||||
|
||||
public FileConfiguration config = getConfig();
|
||||
|
||||
public long ServerStartTime;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
try {
|
||||
this.Init();
|
||||
} catch (Exception e) {
|
||||
this.log.warning("[SimplifyTools] - INITIALIZATION ERROR: "+e.getMessage());
|
||||
this.log.warning("[SimplifyTools] - Plugin disabled!");
|
||||
this.setEnabled(false);
|
||||
return;
|
||||
}
|
||||
//this.dplug = new DitPluginManager(this);
|
||||
this.log.info(this.getPrefix()+"Started running.");
|
||||
}
|
||||
|
||||
|
||||
private void Init() throws Exception {
|
||||
this.ServerStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
|
||||
if (Version.ServerVersion.isCurrentLower(Version.ServerVersion.v1_12_R1)){
|
||||
throw new Exception("The server version is not supported! Update to a version between 1.12 - 1.19.3 to run this plugin.");
|
||||
}
|
||||
if (this.Reload()){
|
||||
|
||||
|
||||
TabHandler tab = new TabHandler();
|
||||
PluginCommand ditCmd = this.getCommand("st");
|
||||
ditCmd.setExecutor(new DitCmd(this));
|
||||
ditCmd.setTabCompleter(new DITTabCompleter());
|
||||
|
||||
getServer().getPluginManager().registerEvents(this, this);
|
||||
getServer().getPluginManager().registerEvents(new LogChat(this), this);
|
||||
getServer().getPluginManager().registerEvents(new LogCommand(this), this);
|
||||
getServer().getPluginManager().registerEvents(new LogConnect(this), this);
|
||||
if (this.config.isSet("CustomAdvancement.enabled") && this.config.getBoolean("CustomAdvancement.enabled")){
|
||||
getServer().getPluginManager().registerEvents(new ChatEvents(this), this);
|
||||
this.log.info(this.getPrefix()+"Custom Advancement Messages enabled!");
|
||||
}
|
||||
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new TPS(), 0, 1);
|
||||
|
||||
if (this.config.getBoolean("Saving.enabled") && this.config.getInt("Saving.interval")>0){
|
||||
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new SaveHandler(), 0L, Math.convert(Math.Convert.SECONDS,Math.Convert.TICKS,instance.config.getInt("Saving.interval")));
|
||||
}
|
||||
|
||||
new UpdateChecker(this, UpdateCheckSource.GITHUB_RELEASE_TAG, "LabodiDavid/SimplifyTools")
|
||||
.setDownloadLink("https://github.com/LabodiDavid/SimplifyTools/releases")
|
||||
.setDonationLink("https://paypal.me/labodidavid")
|
||||
.setChangelogLink("https://github.com/LabodiDavid/SimplifyTools/blob/main/docs/ChangeLog.md")
|
||||
.setNotifyOpsOnJoin(true)
|
||||
.setNotifyByPermissionOnJoin("st.admin")
|
||||
.setUserAgent(new UserAgentBuilder().addPluginNameAndVersion())
|
||||
.checkEveryXHours(24)
|
||||
.checkNow();
|
||||
|
||||
Metrics metrics = new Metrics(this, 15108);
|
||||
}
|
||||
}
|
||||
public String getPrefix(){
|
||||
if (this.config.isSet("Prefix") && !Objects.requireNonNull(this.config.getString("Prefix")).isEmpty()){
|
||||
return ChatColor.translateAlternateColorCodes('&', this.config.getString("Prefix"));
|
||||
}else{
|
||||
return ChatColor.translateAlternateColorCodes('&',"&a[&fSimplify&7Tools&2] &4- &f");
|
||||
}
|
||||
}
|
||||
|
||||
public static STPlugin getInstance(){
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static String getUptime(){
|
||||
int uptime = (int)(System.currentTimeMillis() - instance.ServerStartTime)/1000;
|
||||
String returnText = "";
|
||||
|
||||
// Get remaining seconds from total minutes.
|
||||
int seconds = uptime % 60;
|
||||
// Convert to minutes, get remaining minutes from total hours.
|
||||
int minutes = (uptime / 60) % 60;
|
||||
// Convert to hours, get remaining hours from total days.
|
||||
int hours = (uptime / 3600) % 24;
|
||||
// Convert to days.
|
||||
int days = uptime / 86400;
|
||||
|
||||
if (days>1){
|
||||
returnText = returnText+ days+" days ";
|
||||
}
|
||||
if (hours>1){
|
||||
returnText = returnText+ hours+ " hours ";
|
||||
}
|
||||
if (minutes>1){
|
||||
returnText = returnText+ minutes+ " min ";
|
||||
}
|
||||
if (seconds>1){
|
||||
returnText = returnText+ seconds+ "s ";
|
||||
}
|
||||
|
||||
return returnText;
|
||||
|
||||
}
|
||||
|
||||
public boolean Reload(){
|
||||
File configFile = new File(getDataFolder(), "config.yml");
|
||||
|
||||
try {
|
||||
if (!configFile.exists()){
|
||||
this.saveDefaultConfig();
|
||||
}
|
||||
ConfigUpdater.update(this, "config.yml", configFile, Collections.emptyList());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
reloadConfig();
|
||||
this.config = getConfig();
|
||||
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public void onDisable() {
|
||||
System.out.println(this.getPrefix()+" stopped.");
|
||||
}
|
||||
}
|
123
src/main/java/hu/ditservices/commands/DitCmd.java
Normal file
123
src/main/java/hu/ditservices/commands/DitCmd.java
Normal file
@ -0,0 +1,123 @@
|
||||
package hu.ditservices.commands;
|
||||
|
||||
import hu.ditservices.utils.TPS;
|
||||
import hu.ditservices.STPlugin;
|
||||
import hu.ditservices.utils.Cooldown;
|
||||
import hu.ditservices.utils.Version;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class DitCmd implements CommandExecutor {
|
||||
private final String noArgMsg;
|
||||
private final STPlugin plugin;
|
||||
private final Cooldown cd;
|
||||
private final FileConfiguration config;
|
||||
|
||||
public DitCmd(final STPlugin instance){
|
||||
this.plugin = instance;
|
||||
this.noArgMsg = plugin.getPrefix()+ ChatColor.DARK_RED + "To list all SimplifyTools commands use the '/help SIMPLIFYTOOLS' command!";
|
||||
this.cd = new Cooldown(plugin);
|
||||
this.config = plugin.config;
|
||||
}
|
||||
|
||||
public boolean addToCoolDown(CommandSender sender){
|
||||
if (sender instanceof Player){
|
||||
Player p = (Player) sender;
|
||||
this.cd.Add(p);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (command.getName().equals("st")){
|
||||
|
||||
if (cd.Check(sender)){
|
||||
if (command.getName().equals("st") && args.length==0)
|
||||
{
|
||||
this.addToCoolDown(sender);
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Version: "+plugin.getDescription().getVersion());
|
||||
sender.sendMessage(this.noArgMsg);
|
||||
return true;
|
||||
}
|
||||
if (command.getName().equals("st") && args[0].contains("help"))
|
||||
{
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Version: "+plugin.getDescription().getVersion());
|
||||
sender.sendMessage(this.noArgMsg);
|
||||
return true;
|
||||
}
|
||||
if (command.getName().equals("st") && args[0].contains("settings"))
|
||||
{
|
||||
this.addToCoolDown(sender);
|
||||
sender.sendMessage(plugin.getPrefix()+ ChatColor.GREEN+" === Plugin Information === ");
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Plugin Version: "+plugin.getDescription().getVersion());
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Server Version: "+ Version.ServerVersion.getCurrent().toString());
|
||||
sender.sendMessage(ChatColor.GREEN+" -------- Features -------- ");
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Tab customization: "+(config.getBoolean("Tab.enabled") ? ChatColor.GREEN+"Enabled" : ChatColor.RED+"Disabled"));
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Custom Advancement Msg: "+(config.getBoolean("CustomAdvancement.enabled") ? ChatColor.GREEN+"Enabled" : ChatColor.RED+"Disabled"));
|
||||
sender.sendMessage(ChatColor.GREEN+" ========================== ");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (command.getName().equals("st") && args[0].contains("reload") && sender.hasPermission("st.reload")){
|
||||
|
||||
if(plugin.Reload()){
|
||||
this.addToCoolDown(sender);
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Successfully reload!");
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.RED+"Notice: Restart your server if the settings didn't applied.");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (command.getName().equals("st") && args[0].contains("tps") && sender.hasPermission("st.tps")){
|
||||
this.addToCoolDown(sender);
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Plugin Calculated TPS: "+TPS.getColor()+String.format("%.2f", TPS.getTPS()));
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
if (command.getName().equalsIgnoreCase("st") && args[0].contains("pmanager")){
|
||||
|
||||
if (sender.hasPermission("st.pmanager.unload") || sender.hasPermission("st.pmanager.load") || sender.hasPermission("st.pmanager")) {
|
||||
this.addToCoolDown(sender);
|
||||
if (args.length==1){
|
||||
sender.sendMessage(plugin.getPrefix()+ChatColor.DARK_RED+"Invalid arguments!");
|
||||
return true;
|
||||
}
|
||||
if (args[1].equalsIgnoreCase("load")) {
|
||||
//PluginCmd.handleLoad(sender,args);
|
||||
PluginCmd.LoadPlugin(sender,args);
|
||||
}
|
||||
if (args[1].equalsIgnoreCase("unload")) {
|
||||
//PluginCmd.handleUnload(sender,args);
|
||||
PluginCmd.UnloadPlugin(sender, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (command.getName().equalsIgnoreCase("st") && args[0].contains("save-all") && sender.hasPermission("st.save")){
|
||||
this.addToCoolDown(sender);
|
||||
return SaveCmd.Run(sender);
|
||||
}
|
||||
|
||||
if (command.getName().equalsIgnoreCase("st") && args[0].contains("ping") && sender.hasPermission("st.ping")){
|
||||
this.addToCoolDown(sender);
|
||||
return PingCmd.Run(sender);
|
||||
}
|
||||
if (command.getName().equalsIgnoreCase("st") && args[0].contains("stats") && sender.hasPermission("st.stats")){
|
||||
this.addToCoolDown(sender);
|
||||
return StatCmd.Run(sender);
|
||||
}
|
||||
}else{
|
||||
cd.CDText(sender);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
29
src/main/java/hu/ditservices/commands/PingCmd.java
Normal file
29
src/main/java/hu/ditservices/commands/PingCmd.java
Normal file
@ -0,0 +1,29 @@
|
||||
package hu.ditservices.commands;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import hu.ditservices.utils.Server;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class PingCmd {
|
||||
public static boolean Run(CommandSender sender) {
|
||||
STPlugin plugin = STPlugin.getInstance();
|
||||
if (sender instanceof Player) {
|
||||
Player player = (Player) sender;
|
||||
try {
|
||||
player.sendMessage(plugin.getPrefix() + "Your response time to the server: " + Server.getPlayerPing(player) + " ms");
|
||||
return true;
|
||||
} catch (IllegalArgumentException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
if (sender instanceof ConsoleCommandSender) {
|
||||
ConsoleCommandSender consoleCommandSender = (ConsoleCommandSender) sender;
|
||||
consoleCommandSender.sendMessage(plugin.getPrefix() + "For this command you have to be a player!");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
62
src/main/java/hu/ditservices/commands/PluginCmd.java
Normal file
62
src/main/java/hu/ditservices/commands/PluginCmd.java
Normal file
@ -0,0 +1,62 @@
|
||||
package hu.ditservices.commands;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import hu.ditservices.STPlugin;
|
||||
//import hu.ditservices.DitPluginManager;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
|
||||
public class PluginCmd {
|
||||
public static boolean LoadPlugin(CommandSender sender, String[] args){
|
||||
Plugin plugin = Bukkit.getPluginManager().getPlugin(args[2]);
|
||||
if (plugin == null) {
|
||||
sender.sendMessage(STPlugin.getInstance().getPrefix()+"Plugin not exist!");
|
||||
return false;
|
||||
}
|
||||
if (plugin.isEnabled()){
|
||||
sender.sendMessage(STPlugin.getInstance().getPrefix()+"Plugin "+plugin.getName()+" already enabled!");
|
||||
return true;
|
||||
}
|
||||
|
||||
Bukkit.getPluginManager().enablePlugin(plugin);
|
||||
sender.sendMessage(STPlugin.getInstance().getPrefix()+"Plugin "+plugin.getName()+" successfully enabled!");
|
||||
return true;
|
||||
}
|
||||
public static boolean UnloadPlugin(CommandSender sender, String[] args){
|
||||
Plugin plugin = Bukkit.getPluginManager().getPlugin(args[2]);
|
||||
if (plugin == null) {
|
||||
sender.sendMessage(STPlugin.getInstance().getPrefix()+"Plugin not exist!");
|
||||
return false;
|
||||
}
|
||||
if (!plugin.isEnabled()){
|
||||
sender.sendMessage(STPlugin.getInstance().getPrefix()+"Plugin "+plugin.getName()+" already disabled!");
|
||||
return true;
|
||||
}
|
||||
Bukkit.getPluginManager().disablePlugin(plugin);
|
||||
sender.sendMessage(STPlugin.getInstance().getPrefix()+"Plugin "+plugin.getName()+" successfully disabled!");
|
||||
return true;
|
||||
}
|
||||
|
||||
/*public static boolean handleLoad(CommandSender sender, String[] args){
|
||||
switch (DitPluginManager.load(args[2])){
|
||||
case 0: sender.sendMessage(DITSystem.getInstance().getPrefix()+" Plugin loaded."); return true;
|
||||
case 2: sender.sendMessage(DITSystem.getInstance().getPrefix()+"Missing dependency!"); return true;
|
||||
case -1: sender.sendMessage(DITSystem.getInstance().getPrefix()+"Invalid/ not exist plugin!"); return true;
|
||||
case 3: sender.sendMessage(DITSystem.getInstance().getPrefix()+"Invalid description!"); return true;
|
||||
case 5: sender.sendMessage(DITSystem.getInstance().getPrefix()+"This plugin is already running!"); return true;
|
||||
default: break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public static boolean handleUnload(CommandSender sender, String[] args){
|
||||
switch (DitPluginManager.unload(args[2])){
|
||||
case 0: sender.sendMessage(DITSystem.getInstance().getPrefix()+" Plugin disabled."); return true;
|
||||
case -1: sender.sendMessage(DITSystem.getInstance().getPrefix()+"This plugin is not exist."); return true;
|
||||
case 1: sender.sendMessage(DITSystem.getInstance().getPrefix()+"Plugin and their dependents disabled."); return true;
|
||||
case 5: sender.sendMessage(DITSystem.getInstance().getPrefix()+"This plugin is not loaded."); return true;
|
||||
default: break;
|
||||
}
|
||||
return false;
|
||||
}*/
|
||||
}
|
21
src/main/java/hu/ditservices/commands/SaveCmd.java
Normal file
21
src/main/java/hu/ditservices/commands/SaveCmd.java
Normal file
@ -0,0 +1,21 @@
|
||||
package hu.ditservices.commands;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class SaveCmd {
|
||||
public static boolean Run(CommandSender sender){
|
||||
STPlugin plugin = STPlugin.getInstance();
|
||||
String p = plugin.config.getString("Saving.broadcastMsgProgress").replace("{PREFIX}",plugin.getPrefix());
|
||||
String d = plugin.config.getString("Saving.broadcastMsgDone").replace("{PREFIX}",plugin.getPrefix());
|
||||
Bukkit.broadcast(p,"st.st");
|
||||
for(World w : Bukkit.getServer().getWorlds()){
|
||||
w.save();
|
||||
}
|
||||
Bukkit.savePlayers();
|
||||
Bukkit.broadcast(d,"st.st");
|
||||
return true;
|
||||
}
|
||||
}
|
23
src/main/java/hu/ditservices/commands/StatCmd.java
Normal file
23
src/main/java/hu/ditservices/commands/StatCmd.java
Normal file
@ -0,0 +1,23 @@
|
||||
package hu.ditservices.commands;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class StatCmd {
|
||||
public static boolean Run(CommandSender sender){
|
||||
Player player = (Player) sender;
|
||||
|
||||
player.sendMessage(STPlugin.getInstance().getPrefix()+ ChatColor.GREEN+" === Your statistics === ");
|
||||
player.sendMessage(ChatColor.AQUA+"Connects: "+(player.getStatistic(Statistic.LEAVE_GAME)+1));
|
||||
player.sendMessage(ChatColor.AQUA+"Deaths: "+player.getStatistic(Statistic.DEATHS));
|
||||
player.sendMessage(ChatColor.AQUA+"Mob kills: "+player.getStatistic(Statistic.MOB_KILLS));
|
||||
player.sendMessage(ChatColor.AQUA+"Player kills: "+player.getStatistic(Statistic.PLAYER_KILLS));
|
||||
player.sendMessage(ChatColor.AQUA+"Sleep count: "+player.getStatistic(Statistic.SLEEP_IN_BED));
|
||||
player.sendMessage(ChatColor.AQUA+"Enchant count: "+player.getStatistic(Statistic.ITEM_ENCHANTED));
|
||||
player.sendMessage(ChatColor.GREEN+" =================== ");
|
||||
return true;
|
||||
}
|
||||
}
|
83
src/main/java/hu/ditservices/handlers/DITTabCompleter.java
Normal file
83
src/main/java/hu/ditservices/handlers/DITTabCompleter.java
Normal file
@ -0,0 +1,83 @@
|
||||
package hu.ditservices.handlers;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
public class DITTabCompleter implements TabCompleter {
|
||||
|
||||
List<String> arguments = new ArrayList<String>();
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
|
||||
|
||||
if (command.getName().equals("st")) {
|
||||
|
||||
if (arguments.isEmpty()){
|
||||
String curr_cmd = "";
|
||||
for (Plugin plug : Bukkit.getPluginManager().getPlugins()) {
|
||||
List<Command> cmdList = PluginCommandYamlParser.parse(plug);
|
||||
for (int i = 0; i <= cmdList.size() - 1; i++) {
|
||||
if (cmdList.get(i).getLabel().contains("st ")) {
|
||||
curr_cmd =cmdList.get(i).getLabel();
|
||||
curr_cmd = curr_cmd.replace("st ","");
|
||||
arguments.add(curr_cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> idea = new ArrayList<>();
|
||||
List<String> result = new ArrayList<>();
|
||||
String curr_cmd = "";
|
||||
List<String> vizsg_list = new ArrayList<>();
|
||||
boolean vizsg_2 = false;
|
||||
if (args.length == 1) {
|
||||
for (String a : arguments){
|
||||
if (a.toLowerCase().startsWith(args[0].toLowerCase())){
|
||||
result.add(a);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (args.length >= 2) {
|
||||
for (String a : arguments) {
|
||||
vizsg_2 = false;
|
||||
if (a.contains(" ")){
|
||||
vizsg_list = Arrays.asList(a.split(" "));
|
||||
vizsg_2 = true;
|
||||
}
|
||||
if (vizsg_2 && args.length ==2){ // length-1
|
||||
idea.add(vizsg_list.get(1));
|
||||
}
|
||||
if (vizsg_2&& args[1].startsWith(vizsg_list.get(1))) {
|
||||
idea.add(vizsg_list.get(1));
|
||||
}
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase("pmanager")&& args[1].equalsIgnoreCase("unload") || args[1].equalsIgnoreCase("load")) {
|
||||
if (args.length == 3) {
|
||||
result.clear();
|
||||
PluginManager pm = Bukkit.getServer().getPluginManager();
|
||||
for (Plugin pl : pm.getPlugins()) {
|
||||
if (pl.getName().toLowerCase().startsWith(args[2].toLowerCase()) && args[1].equalsIgnoreCase("unload")) {
|
||||
result.add(pl.getName());
|
||||
}
|
||||
if (!pl.isEnabled()){
|
||||
if (pl.getName().toLowerCase().startsWith(args[2].toLowerCase()) && args[1].equalsIgnoreCase("load")) {
|
||||
result.add(pl.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return idea;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
185
src/main/java/hu/ditservices/handlers/DitPluginManager.java
Normal file
185
src/main/java/hu/ditservices/handlers/DitPluginManager.java
Normal file
@ -0,0 +1,185 @@
|
||||
package hu.ditservices.handlers;
|
||||
/*
|
||||
import hu.ditservices.DITSystem;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.SimpleCommandMap;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.plugin.*;
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
public class DitPluginManager {
|
||||
private static DITSystem plugin;
|
||||
public DitPluginManager(DITSystem instance){
|
||||
plugin = instance;
|
||||
}
|
||||
|
||||
public static int load(final String pluginName) {
|
||||
PluginManager pm = Bukkit.getServer().getPluginManager();
|
||||
boolean there = false;
|
||||
for (Plugin pl : pm.getPlugins()){
|
||||
if (pl.getName().toLowerCase().startsWith(pluginName)){
|
||||
there = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (there)
|
||||
{ return 1;} //plugin already exists
|
||||
else {
|
||||
String name = "";
|
||||
String path = plugin.getDataFolder().getParent();
|
||||
File folder = new File(path);
|
||||
ArrayList<File> files = new ArrayList<File>();
|
||||
File[] listOfFiles = folder.listFiles();
|
||||
for (File compare : listOfFiles) {
|
||||
if (compare.isFile()) {
|
||||
try {
|
||||
name = plugin.getPluginLoader().getPluginDescription(compare).getName();
|
||||
} catch (InvalidDescriptionException e) {
|
||||
plugin.getLogger().warning("[Loading Plugin] " + compare.getName() + " didn't match");
|
||||
}
|
||||
if (name.toLowerCase().startsWith(pluginName.toLowerCase())) {
|
||||
files.add(compare);
|
||||
try {
|
||||
Bukkit.getServer().getPluginManager().loadPlugin(compare);
|
||||
} catch (UnknownDependencyException e) {
|
||||
return 2; //missing dependent plugin
|
||||
} catch (InvalidPluginException e) {
|
||||
return -1; //not a plugin
|
||||
} catch (InvalidDescriptionException e) {
|
||||
return 3; //invalid description
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Plugin[] plugins = pm.getPlugins();
|
||||
for (Plugin pl : plugins) {
|
||||
for (File compare : files) {
|
||||
try {
|
||||
if (pl.getName().equalsIgnoreCase(plugin.getPluginLoader().getPluginDescription(compare).getName()))
|
||||
if (!pl.isEnabled()){
|
||||
pm.enablePlugin(pl);
|
||||
}else { return 5; }
|
||||
} catch (InvalidDescriptionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0; //success
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static int unload(String pluginName) {
|
||||
pluginName = pluginName.toLowerCase().trim();
|
||||
PluginManager manager = Bukkit.getServer().getPluginManager();
|
||||
SimplePluginManager spm = (SimplePluginManager) manager;
|
||||
SimpleCommandMap commandMap = null;
|
||||
List<Plugin> plugins = null;
|
||||
Map<String, Plugin> lookupNames = null;
|
||||
Map<String, Command> knownCommands = null;
|
||||
Map<Event, SortedSet<RegisteredListener>> listeners = null;
|
||||
boolean reloadlisteners = true;
|
||||
try {
|
||||
if (spm != null) {
|
||||
Field pluginsField = spm.getClass().getDeclaredField("plugins");
|
||||
pluginsField.setAccessible(true);
|
||||
plugins = (List<Plugin>) pluginsField.get(spm);
|
||||
|
||||
Field lookupNamesField = spm.getClass().getDeclaredField("lookupNames");
|
||||
lookupNamesField.setAccessible(true);
|
||||
lookupNames = (Map<String, Plugin>) lookupNamesField.get(spm);
|
||||
|
||||
try {
|
||||
Field listenersField = spm.getClass().getDeclaredField("listeners");
|
||||
listenersField.setAccessible(true);
|
||||
listeners = (Map<Event, SortedSet<RegisteredListener>>) listenersField.get(spm);
|
||||
} catch (Exception e) {
|
||||
reloadlisteners = false;
|
||||
}
|
||||
|
||||
Field commandMapField = spm.getClass().getDeclaredField("commandMap");
|
||||
commandMapField.setAccessible(true);
|
||||
commandMap = (SimpleCommandMap) commandMapField.get(spm);
|
||||
|
||||
Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
|
||||
knownCommandsField.setAccessible(true);
|
||||
knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
boolean in = false;
|
||||
|
||||
for (Plugin pl : Bukkit.getServer().getPluginManager().getPlugins()) {
|
||||
if (in)
|
||||
break;
|
||||
if (pl.getName().toLowerCase().startsWith(pluginName.toLowerCase())) {
|
||||
if (pl.isEnabled()) {
|
||||
manager.disablePlugin(pl);
|
||||
if (plugins != null && plugins.contains(pl))
|
||||
plugins.remove(pl);
|
||||
|
||||
if (lookupNames != null && lookupNames.containsKey(pl.getName())) {
|
||||
lookupNames.remove(pl.getName());
|
||||
}
|
||||
|
||||
if (listeners != null && reloadlisteners) {
|
||||
for (SortedSet<RegisteredListener> set : listeners.values()) {
|
||||
for (Iterator<RegisteredListener> it = set.iterator(); it.hasNext(); ) {
|
||||
RegisteredListener value = it.next();
|
||||
|
||||
if (value.getPlugin() == pl) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (commandMap != null) {
|
||||
|
||||
for (Iterator<Map.Entry<String, Command>> it = knownCommands.entrySet().iterator(); it.hasNext(); ) {
|
||||
Map.Entry<String, Command> entry = it.next();
|
||||
if (entry.getValue() instanceof PluginCommand) {
|
||||
PluginCommand c = (PluginCommand) entry.getValue();
|
||||
if (c.getPlugin() == pl) {
|
||||
c.unregister(commandMap);
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Plugin plu : Bukkit.getServer().getPluginManager().getPlugins()) {
|
||||
if (plu.getDescription().getDepend() != null) {
|
||||
for (String depend : plu.getDescription().getDepend()) {
|
||||
if (depend.equalsIgnoreCase(pl.getName())) {
|
||||
plugin.getLogger().info("[Unloading Plugin] " + plu.getName() + " must be disabled!");
|
||||
unload(plu.getName());
|
||||
return 1; //dependencies also disabled
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
in = true;
|
||||
} else { return 5; }
|
||||
}
|
||||
}
|
||||
if (!in) {
|
||||
plugin.getLogger().info("Not an existing plugin");
|
||||
return -1; //non-existent
|
||||
}
|
||||
System.gc();
|
||||
return 0; //success
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
*/
|
33
src/main/java/hu/ditservices/handlers/SaveHandler.java
Normal file
33
src/main/java/hu/ditservices/handlers/SaveHandler.java
Normal file
@ -0,0 +1,33 @@
|
||||
package hu.ditservices.handlers;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class SaveHandler implements Runnable{
|
||||
STPlugin plugin = STPlugin.getInstance();
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
String p = plugin.config.isSet("Saving.broadcastMsgProgress") ? plugin.config.getString("Saving.broadcastMsgProgress").replace("{PREFIX}",plugin.getPrefix()) : plugin.getPrefix()+"Auto save in progress..";
|
||||
String d = plugin.config.isSet("Saving.broadcastMsgDone") ? plugin.config.getString("Saving.broadcastMsgDone").replace("{PREFIX}",plugin.getPrefix()) : plugin.getPrefix()+"Auto save done.";
|
||||
if (Bukkit.getOnlinePlayers().size()>0){
|
||||
for (Player player : Bukkit.getOnlinePlayers()){
|
||||
player.sendMessage(p);
|
||||
}
|
||||
}
|
||||
plugin.getLogger().info(p);
|
||||
for(World w : Bukkit.getServer().getWorlds()){
|
||||
w.save();
|
||||
}
|
||||
Bukkit.savePlayers();
|
||||
if (Bukkit.getOnlinePlayers().size()>0){
|
||||
for (Player player : Bukkit.getOnlinePlayers()){
|
||||
player.sendMessage(d);
|
||||
}
|
||||
}
|
||||
plugin.getLogger().info(d);
|
||||
|
||||
}
|
||||
}
|
268
src/main/java/hu/ditservices/handlers/TabHandler.java
Normal file
268
src/main/java/hu/ditservices/handlers/TabHandler.java
Normal file
@ -0,0 +1,268 @@
|
||||
package hu.ditservices.handlers;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import hu.ditservices.utils.*;
|
||||
import hu.ditservices.utils.Math;
|
||||
import hu.ditservices.utils.reflection.ClazzContainer;
|
||||
import hu.ditservices.utils.reflection.Reflection;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TabHandler {
|
||||
public final List<String> headers = new ArrayList<>();
|
||||
public final List<String> footers = new ArrayList<>();
|
||||
|
||||
private Integer refreshRate;
|
||||
|
||||
private final STPlugin plugin;
|
||||
public List<String> headeranimList = new ArrayList<>();
|
||||
public List<String> footeranimList = new ArrayList<>();
|
||||
|
||||
private final ArrayList<String> formatArray = new ArrayList<>();
|
||||
public final List<Integer> DynamicHeaders = new ArrayList<>();
|
||||
public final List<Integer> DynamicFooters = new ArrayList<>();
|
||||
|
||||
private int count1 = 0; //headers
|
||||
private int count2 = 0; //footers
|
||||
private Object packet;
|
||||
|
||||
public TabHandler() throws Exception {
|
||||
|
||||
this.plugin = STPlugin.getInstance();
|
||||
if(this.init()){
|
||||
if (headers.isEmpty() && footers.isEmpty()){
|
||||
plugin.getLogger().warning(plugin.getPrefix()+"TAB customization disabled because empty customization config!");
|
||||
return;
|
||||
}
|
||||
this.updateTab();
|
||||
/*packet = plugin.getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_LIST_HEADER_FOOTER);
|
||||
boolean both = headers.size() > 0 && footers.size() > 0;
|
||||
boolean header = !both && headers.size() > 0;
|
||||
boolean footer = !both && footers.size() > 0;*/
|
||||
|
||||
//scheduleSyncRepeatingTask
|
||||
//Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new TabRunnable(this),20, Math.convert(Math.Convert.SECONDS,Math.Convert.TICKS,this.refreshRate));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean init() throws Exception {
|
||||
if (plugin.getConfig().getBoolean("Tab.enabled")){
|
||||
|
||||
int availProcessors = Server.getCpuCores();
|
||||
if (availProcessors < 3) {
|
||||
plugin.getLogger().warning("You're currently having " + availProcessors + " CPU processors, which is not enough to run a minecraft server with scheduled plugins including SimplifyTools.");
|
||||
plugin.getLogger().warning("You will be experiencing many lags during the server is running. Consider upgrading your CPU to at least reach 3 cores.");
|
||||
}
|
||||
|
||||
|
||||
if (plugin.getConfig().isSet("Tab.refreshRate")){
|
||||
this.refreshRate = plugin.getConfig().getInt("Tab.refreshRate");
|
||||
}else{
|
||||
this.refreshRate=1;
|
||||
}
|
||||
|
||||
//Getting the tab lines from the config
|
||||
headeranimList = plugin.getConfig().getStringList("Tab.headerAnimation");
|
||||
footeranimList = plugin.getConfig().getStringList("Tab.footerAnimation");
|
||||
|
||||
//Investigating lines where we need to run the formatting every tab refresh for example for the RAM usage.
|
||||
//Only storing those lines indexes.
|
||||
formatArray.add("{TOTALRAM}");
|
||||
formatArray.add("{FREERAM}");
|
||||
formatArray.add("{USEDRAM}");
|
||||
formatArray.add("{AVERAGEPING}");
|
||||
formatArray.add("{ONLINEPLAYERS}");
|
||||
formatArray.add("{MAXPLAYERS}");
|
||||
formatArray.add("{MOTD}");
|
||||
formatArray.add("{UPTIME}");
|
||||
formatArray.add("{TPS}");
|
||||
for (String f: formatArray){
|
||||
for (int i = 0; i<headeranimList.size(); i++){
|
||||
if (headeranimList.get(i).contains(f) && !DynamicHeaders.contains(i)){
|
||||
DynamicHeaders.add(i);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i<footeranimList.size(); i++){
|
||||
if (footeranimList.get(i).contains(f) && !DynamicFooters.contains(i)){
|
||||
DynamicFooters.add(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (String hanim : headeranimList){
|
||||
this.addHeaderFooter(true,hanim,false);
|
||||
}
|
||||
for (String fanim : footeranimList){
|
||||
this.addHeaderFooter(false,fanim,false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void updateTab(){
|
||||
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
|
||||
try {
|
||||
if (Bukkit.getOnlinePlayers().size()==0){
|
||||
return;
|
||||
}
|
||||
|
||||
if (count1 >= headers.size()) {
|
||||
count1 = 0;
|
||||
}
|
||||
if (count2 >= footers.size()) {
|
||||
count2 = 0;
|
||||
}
|
||||
//Re adding all lines where we replaced something like the RAM usage to every refresh
|
||||
//display current value. (We check those lines in the init())
|
||||
if (DynamicHeaders.size() > 0 && count1 < DynamicHeaders.size()) {
|
||||
if (DynamicHeaders.get(count1) == count1) {
|
||||
addHeaderFooter(true, headeranimList.get(count1), true, count1);
|
||||
}
|
||||
}
|
||||
if (DynamicFooters.size() > 0 && count2 < DynamicFooters.size()) {
|
||||
if (DynamicFooters.get(count2) == count2) {
|
||||
addHeaderFooter(false, footeranimList.get(count2), true, count2);
|
||||
}
|
||||
}
|
||||
/*
|
||||
if (both){
|
||||
plugin.getLogger().info("DEBUG: Sending both (header) JSON: "+WrappedChatComponent.fromHandle(headers.get(count1)).getJson());
|
||||
plugin.getLogger().info("DEBUG: Sending both (footer) JSON: "+WrappedChatComponent.fromHandle(footers.get(count2)).getJson());
|
||||
|
||||
packet.getChatComponents().write(0, WrappedChatComponent.fromHandle(headers.get(count1))).write(1,WrappedChatComponent.fromHandle(footers.get(count2)));
|
||||
}else{
|
||||
if (header){
|
||||
plugin.getLogger().info("DEBUG: Sending header JSON: "+WrappedChatComponent.fromHandle(headers.get(count1)).getJson());
|
||||
|
||||
packet.getChatComponents().write(0, WrappedChatComponent.fromHandle(headers.get(count1))).write(1,WrappedChatComponent.fromText("{\"text\":\"\"}"));
|
||||
}else{
|
||||
if (footer){
|
||||
plugin.getLogger().info("DEBUG: Sending footer JSON: "+WrappedChatComponent.fromHandle(footers.get(count2)).getJson());
|
||||
|
||||
packet.getChatComponents().write(0,WrappedChatComponent.fromText("{\"text\":\"\"}")).write(1,WrappedChatComponent.fromHandle(footers.get(count2)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Bukkit.getOnlinePlayers().size() > 0) {
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
plugin.getProtocolManager().sendServerPacket(player, packet);
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
if (Version.ServerVersion.isCurrentEqualOrLower(Version.ServerVersion.v1_12_R1)) {
|
||||
packet = ClazzContainer.buildPacketPlayOutPlayerListHeaderFooter(headers.get(count1),footers.get(count2));
|
||||
for (Player player : Bukkit.getOnlinePlayers()){
|
||||
Reflection.sendPacket(player,packet);
|
||||
}
|
||||
}else{
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
player.setPlayerListHeaderFooter(headers.get(count1),footers.get(count2));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (headers.size() > 1) {
|
||||
count1++;
|
||||
}
|
||||
if (footers.size() > 1) {
|
||||
count2++;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
},0,Math.convert(Math.Convert.SECONDS,Math.Convert.TICKS,this.refreshRate));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Manages the adding of the tab line and the final formatting of the text.
|
||||
* @param header If true the text will be added to the header, otherwise to the footer.
|
||||
* @param text The formatted tab line text.
|
||||
* @param dynamic If the text contains a replace which need to run every tab refresh then it's true.
|
||||
* @param index Index of the 'dynamic' line. This is an overloading so there we need the index[0] element.
|
||||
*/
|
||||
private void addHeaderFooter(boolean header,String text,boolean dynamic,int... index) throws Exception {
|
||||
try {
|
||||
//JsonObject json = new JsonObject();
|
||||
//json.addProperty("text",format(text));
|
||||
String Json = "{\"text\": \""+format(text)+"\"}";
|
||||
//String Json = format(text);
|
||||
//Json = Json.trim();
|
||||
//plugin.getLogger().info("JSON!: "+Json);
|
||||
Object tabText = Reflection.asChatSerializer(Json);
|
||||
|
||||
//plugin.getLogger().info("DEBUG: Adding JSON: "+Json);
|
||||
if (header){
|
||||
if (dynamic){
|
||||
|
||||
headers.set(index[0], Reflection.getChatSerializerString(tabText));
|
||||
//headers.set(index[0],Json);
|
||||
}else {
|
||||
//headers.add(Json);
|
||||
headers.add(Reflection.getChatSerializerString(tabText));
|
||||
}
|
||||
}else{
|
||||
if (dynamic){
|
||||
//footers.set(index[0],Json);
|
||||
footers.set(index[0], Reflection.getChatSerializerString(tabText));
|
||||
}else {
|
||||
//footers.add(Json);
|
||||
footers.add(Reflection.getChatSerializerString(tabText));
|
||||
}
|
||||
}
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Replaces the msg values to their represents and recognizes MC color codes.
|
||||
* @param msg The text.
|
||||
* @return Replaced text with recognized MC color codes.
|
||||
*/
|
||||
private String format(String msg){
|
||||
if (msg.contains("{TOTALRAM}")){
|
||||
msg = msg.replace("{TOTALRAM}",String.valueOf(Server.getRAM(Server.RAM.TOTAL)));
|
||||
}
|
||||
if (msg.contains("{FREERAM}")){
|
||||
msg = msg.replace("{FREERAM}",String.valueOf(Server.getRAM(Server.RAM.FREE)));
|
||||
}
|
||||
if (msg.contains("{USEDRAM}")){
|
||||
msg = msg.replace("{USEDRAM}",String.valueOf(Server.getRAM(Server.RAM.USED)));
|
||||
}
|
||||
if (msg.contains("{AVERAGEPING}")){
|
||||
msg = msg.replace("{AVERAGEPING}",String.valueOf(Server.getAveragePing()));
|
||||
}
|
||||
if (msg.contains("{ONLINEPLAYERS}")){
|
||||
msg = msg.replace("{ONLINEPLAYERS}",String.valueOf(plugin.getServer().getOnlinePlayers().size()));
|
||||
}
|
||||
if (msg.contains("{MAXPLAYERS}")){
|
||||
msg = msg.replace("{MAXPLAYERS}",String.valueOf(plugin.getServer().getMaxPlayers()));
|
||||
}
|
||||
if (msg.contains("{UPTIME}")){
|
||||
msg = msg.replace("{UPTIME}", STPlugin.getUptime());
|
||||
}
|
||||
if (msg.contains("{MOTD}")){
|
||||
msg = msg.replace("{MOTD}", plugin.getServer().getMotd()); //LegacyComponentSerializer.legacyAmpersand().serialize(plugin.getServer().motd().asComponent())
|
||||
}
|
||||
if (msg.contains("{TPS}")){
|
||||
msg = msg.replace("{TPS}",String.format("%.2f", TPS.getTPS()));
|
||||
}
|
||||
return ChatColor.translateAlternateColorCodes('&',msg);
|
||||
}
|
||||
}
|
33
src/main/java/hu/ditservices/listeners/ChatEvents.java
Normal file
33
src/main/java/hu/ditservices/listeners/ChatEvents.java
Normal file
@ -0,0 +1,33 @@
|
||||
package hu.ditservices.listeners;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerAdvancementDoneEvent;
|
||||
import hu.ditservices.utils.AdvancementHelper;
|
||||
|
||||
public class ChatEvents implements Listener {
|
||||
private STPlugin plugin;
|
||||
private FileConfiguration config;
|
||||
public ChatEvents(STPlugin instance){
|
||||
this.plugin = instance;
|
||||
this.config = plugin.config;
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onAdvance(PlayerAdvancementDoneEvent e){
|
||||
if (config.isSet("CustomAdvancement.enabled") && config.getBoolean("CustomAdvancement.enabled")){
|
||||
AdvancementHelper helper = new AdvancementHelper(this.config);
|
||||
if(helper.check(e.getAdvancement().getKey().getKey())) {
|
||||
final Player player = e.getPlayer();
|
||||
String title = helper.find(e.getAdvancement().getKey().getKey());
|
||||
Bukkit.broadcastMessage(plugin.getPrefix()+ChatColor.translateAlternateColorCodes('&', helper.getText(player.getName(),title)));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
29
src/main/java/hu/ditservices/listeners/LogChat.java
Normal file
29
src/main/java/hu/ditservices/listeners/LogChat.java
Normal file
@ -0,0 +1,29 @@
|
||||
package hu.ditservices.listeners;
|
||||
|
||||
import hu.ditservices.utils.Logger;
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent;
|
||||
|
||||
public class LogChat implements Listener {
|
||||
STPlugin plugin;
|
||||
FileConfiguration config;
|
||||
public LogChat(STPlugin instance){
|
||||
this.plugin = instance;
|
||||
this.config = plugin.config;
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onChat(AsyncPlayerChatEvent event){
|
||||
if (config.getBoolean("Log.Chat")) {
|
||||
Player player = event.getPlayer();
|
||||
String format = config.isSet("Log.FormatChat") ? config.getString("Log.FormatChat") : "[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME}: {MSG}";
|
||||
String LogMsg = format.replace("{DATE}", Logger.getDate()).replace("{TIME}", Logger.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{MSG}",event.getMessage()).replace("{ACTION}","[CHAT]");
|
||||
Logger.logLine(ChatColor.stripColor(LogMsg));
|
||||
}
|
||||
}
|
||||
}
|
30
src/main/java/hu/ditservices/listeners/LogCommand.java
Normal file
30
src/main/java/hu/ditservices/listeners/LogCommand.java
Normal file
@ -0,0 +1,30 @@
|
||||
package hu.ditservices.listeners;
|
||||
|
||||
import hu.ditservices.utils.Logger;
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
|
||||
public class LogCommand implements Listener {
|
||||
STPlugin plugin;
|
||||
FileConfiguration config;
|
||||
public LogCommand(STPlugin instance){
|
||||
|
||||
this.plugin = instance;
|
||||
this.config = plugin.config;
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onCommand(PlayerCommandPreprocessEvent event){
|
||||
if (config.getBoolean("Log.Command")) {
|
||||
Player player = event.getPlayer();
|
||||
String format = config.isSet("Log.FormatCommand") ? config.getString("Log.FormatCommand") : "[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME}: {COMMAND}";
|
||||
String LogMsg = format.replace("{DATE}", Logger.getDate()).replace("{TIME}", Logger.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{COMMAND}",event.getMessage()).replace("{ACTION}","[COMMAND]");
|
||||
Logger.logLine(ChatColor.stripColor(LogMsg));
|
||||
}
|
||||
}
|
||||
}
|
68
src/main/java/hu/ditservices/listeners/LogConnect.java
Normal file
68
src/main/java/hu/ditservices/listeners/LogConnect.java
Normal file
@ -0,0 +1,68 @@
|
||||
package hu.ditservices.listeners;
|
||||
|
||||
import hu.ditservices.utils.Logger;
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class LogConnect implements Listener {
|
||||
STPlugin plugin;
|
||||
private String JoinMsg;
|
||||
private String LeaveMsg;
|
||||
FileConfiguration config;
|
||||
public LogConnect(STPlugin instance){
|
||||
this.plugin = instance;
|
||||
this.config = plugin.config;
|
||||
if (config.getBoolean("CustomMsg.enabled")){
|
||||
this.JoinMsg = this.config.isSet("CustomMsg.connect") ? this.config.getString("CustomMsg.connect") : "{PREFIX}{NAME} &aconnected to the server.";
|
||||
this.LeaveMsg = this.config.isSet("CustomMsg.connect") ? this.config.getString("CustomMsg.disconnect") : "{PREFIX}{NAME} leaved the game.";
|
||||
}
|
||||
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if (config.getBoolean("CustomMsg.enabled")){
|
||||
event.setJoinMessage(null);
|
||||
String emsg = this.JoinMsg;
|
||||
emsg=emsg.replace("{NAME}",player.getName());
|
||||
emsg=emsg.replace("{PREFIX}",plugin.getPrefix());
|
||||
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&',emsg));
|
||||
}
|
||||
|
||||
if (config.getBoolean("Log.Connect")) {
|
||||
String format = config.isSet("Log.FormatConnect") ? config.getString("Log.FormatConnect") : "[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME} UUID: {UUID}";
|
||||
String LogMsg = format.replace("{DATE}", Logger.getDate()).replace("{TIME}", Logger.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{UUID}",player.getUniqueId().toString()).replace("{ACTION}","[CONNECT]");
|
||||
Logger.logLine(ChatColor.stripColor(LogMsg));
|
||||
}
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerQuit(PlayerQuitEvent event){
|
||||
Player player = event.getPlayer();
|
||||
if (config.getBoolean("CustomMsg.enabled")){
|
||||
event.setQuitMessage(null);
|
||||
String emsg = this.LeaveMsg;
|
||||
emsg=emsg.replace("{NAME}",player.getName());
|
||||
emsg=emsg.replace("{PREFIX}",plugin.getPrefix());
|
||||
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&',emsg));
|
||||
}
|
||||
if (config.getBoolean("Log.Connect")) {
|
||||
String format = config.isSet("Log.FormatConnect") ? config.getString("Log.FormatConnect") : "[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME} UUID: {UUID}";
|
||||
String LogMsg = format.replace("{DATE}", Logger.getDate()).replace("{TIME}", Logger.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{UUID}",player.getUniqueId().toString()).replace("{ACTION}","[DISCONNECT]");
|
||||
Logger.logLine(ChatColor.stripColor(LogMsg));
|
||||
}
|
||||
if (config.getBoolean("Saving.enabled")){
|
||||
if(config.getBoolean("Saving.onDisconnect")){
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "st save-all");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
178
src/main/java/hu/ditservices/utils/AdvancementHelper.java
Normal file
178
src/main/java/hu/ditservices/utils/AdvancementHelper.java
Normal file
@ -0,0 +1,178 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.GameRule;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
public class AdvancementHelper {
|
||||
private final STPlugin plugin = STPlugin.getInstance();
|
||||
private final FileConfiguration config;
|
||||
|
||||
private boolean initialized = false;
|
||||
|
||||
public AdvancementHelper(FileConfiguration c){
|
||||
this.config = c;
|
||||
this.initialize();
|
||||
}
|
||||
private Integer type;
|
||||
|
||||
public String[][] normal = {
|
||||
{"story/mine_stone", "Stone Age"},
|
||||
{"story/upgrade_tools", "Getting an Upgrade"},
|
||||
{"story/smelt_iron", "Acquire Hardware"},
|
||||
{"story/obtain_armor", "Suit Up"},
|
||||
{"story/lava_bucket", "Hot Stuff"},
|
||||
{"story/iron_tools", "Isn't It Iron Pick"},
|
||||
{"story/deflect_arrow", "Not Today, Thank You"},
|
||||
{"story/form_obsidian", "Ice Bucket Challenge"},
|
||||
{"story/mine_diamond", "Diamonds!"},
|
||||
{"story/enter_the_nether", "We Need to Go Deeper"},
|
||||
{"story/shiny_gear", "Cover Me With Diamonds"},
|
||||
{"story/enchant_item", "Enchanter"},
|
||||
{"story/follow_ender_eye", "Eye Spy"},
|
||||
{"story/enter_the_end", "The End?"},
|
||||
{"nether/find_fortress", "A Terrible Fortress"},
|
||||
{"nether/get_wither_skull", "Spooky Scary Skeleton"},
|
||||
{"nether/obtain_blaze_rod", "Into Fire"},
|
||||
{"nether/summon_wither", "Withering Heights"},
|
||||
{"nether/brew_potion", "Local Brewery"},
|
||||
{"nether/create_beacon", "Bring Home the Beacon"},
|
||||
{"nether/find_bastion", "Those Were the Days"},
|
||||
{"nether/obtain_ancient_debris", "Hidden in the Depths"},
|
||||
{"nether/obtain_crying_obsidian", "Who is Cutting Onions?"},
|
||||
{"nether/distract_piglin", "Oh Shiny"},
|
||||
{"nether/ride_strider", "This Boat Has Legs"},
|
||||
{"nether/loot_bastion", "War Pigs"},
|
||||
{"nether/use_lodestone", "Country Lode, Take Me Home"},
|
||||
{"nether/charge_respawn_anchor", "Not Quite \"Nine\" Lives"},
|
||||
{"end/kill_dragon", "Free the End"},
|
||||
{"end/enter_end_gateway", "Remote Getaway"},
|
||||
{"end/find_end_city", "The City at the End of the Game"},
|
||||
{"adventure/voluntary_exile", "Voluntary Exile"},
|
||||
{"adventure/kill_a_mob", "Monster Hunter"},
|
||||
{"adventure/trade", "What a Deal!"},
|
||||
{"adventure/honey_block_slide", "Sticky Situation"},
|
||||
{"adventure/ol_betsy", "Ol' Betsy"},
|
||||
{"adventure/sleep_in_bed", "Sweet Dreams"},
|
||||
{"adventure/throw_trident", "A Throwaway Joke"},
|
||||
{"adventure/shoot_arrow", "Take Aim"},
|
||||
{"adventure/whos_the_pillager_now", "Who's the Pillager Now?"},
|
||||
{"adventure/very_very_frightening", "Very Very Frightening"},
|
||||
{"husbandry/safely_harvest_honey", "Bee Our Guest"},
|
||||
{"husbandry/breed_an_animal", "The Parrots and the Bats"},
|
||||
{"husbandry/tame_an_animal", "Best Friends Forever"},
|
||||
{"husbandry/fishy_business", "Fishy Business"},
|
||||
{"husbandry/silk_touch_nest", "Total Beelocation"},
|
||||
{"husbandry/plant_seed", "A Seedy Place"},
|
||||
{"husbandry/tactical_fishing", "Tactical Fishing"}
|
||||
};
|
||||
public String[][] goal = {
|
||||
{"story/cure_zombie_villager", "Zombie Doctor"},
|
||||
{"nether/create_full_beacon", "Beaconator"},
|
||||
{"end/dragon_egg", "The Next Generation"},
|
||||
{"end/respawn_dragon", "The End... Again..."},
|
||||
{"end/dragon_breath", "You Need a Mint"},
|
||||
{"end/elytra", "Sky's the Limit"},
|
||||
{"adventure/totem_of_undying", "Postmortal"},
|
||||
{"adventure/summon_iron_golem", "Hired Help"}
|
||||
};
|
||||
public String[][] challenge = {
|
||||
{"nether/return_to_sender", "Return to Sender"},
|
||||
{"nether/fast_travel", "Subspace Bubble"},
|
||||
{"nether/uneasy_alliance", "Uneasy Alliance"},
|
||||
{"nether/all_potions", "A Furious Cocktail"},
|
||||
{"nether/all_effects", "How Did We Get Here?"},
|
||||
{"nether/netherite_armor", "Cover Me in Debris"},
|
||||
{"nether/explore_nether", "Hot Tourist Destinations"},
|
||||
{"end/levitate", "Great View From Up Here"},
|
||||
{"adventure/hero_of_the_village", "Hero of the Village"},
|
||||
{"adventure/kill_all_mobs", "Monsters Hunted"},
|
||||
{"adventure/two_birds_one_arrow", "Two Birds, One Arrow"},
|
||||
{"adventure/arbalistic", "Arbalistic"},
|
||||
{"adventure/adventuring_time", "Adventuring Time"},
|
||||
{"adventure/sniper_duel", "Sniper Duel"},
|
||||
{"adventure/bullseye", "Bullseye"},
|
||||
{"husbandry/bred_all_animals", "Two by Two"},
|
||||
{"husbandry/complete_catalogue", "A Complete Catalogue"},
|
||||
{"husbandry/balanced_diet", "A Balanced Diet"},
|
||||
{"husbandry/break_diamond_hoe", "Serious Dedication"},
|
||||
{"husbandry/obtain_netherite_hoe", "Serious Dedication"},
|
||||
};
|
||||
public String[] out_type = new String[3];
|
||||
|
||||
private void initialize(){
|
||||
|
||||
if (config.isSet("CustomAdvancement.formats.advancement")) {
|
||||
out_type[0] = config.getString("CustomAdvancement.formats.advancement");
|
||||
}
|
||||
if (config.isSet("CustomAdvancement.formats.goal")) {
|
||||
out_type[1] = config.getString("CustomAdvancement.formats.goal");
|
||||
}
|
||||
if (config.isSet("CustomAdvancement.formats.challenge")) {
|
||||
out_type[2] = config.getString("CustomAdvancement.formats.challenge");
|
||||
}
|
||||
String disablemsg = plugin.getPrefix()+"Disabling vanilla advancement messages for ";
|
||||
List<World> worlds = this.plugin.getServer().getWorlds();
|
||||
Method setRuleMethod, getRuleMethod;
|
||||
try {
|
||||
for (World w : worlds) {
|
||||
if (Version.ServerVersion.isCurrentEqualOrLower(Version.ServerVersion.v1_12_R1)){
|
||||
getRuleMethod = w.getClass().getDeclaredMethod("getGameRuleValue", String.class);
|
||||
if (getRuleMethod.invoke(w,"announceAdvancements")=="true"){
|
||||
setRuleMethod = w.getClass().getDeclaredMethod("setGameRuleValue", String.class, String.class);
|
||||
setRuleMethod.invoke(w,"announceAdvancements", "false");
|
||||
this.plugin.getLogger().info(disablemsg + w.getName());
|
||||
}
|
||||
}else{
|
||||
getRuleMethod = w.getClass().getDeclaredMethod("getGameRuleValue", GameRule.class);
|
||||
if ((boolean)getRuleMethod.invoke(w,GameRule.ANNOUNCE_ADVANCEMENTS)){
|
||||
setRuleMethod = w.getClass().getDeclaredMethod("setGameRule", GameRule.class, Object.class);
|
||||
setRuleMethod.invoke(w,GameRule.ANNOUNCE_ADVANCEMENTS,false);
|
||||
this.plugin.getLogger().info(disablemsg + w.getName());
|
||||
}
|
||||
|
||||
}
|
||||
//w.setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false);
|
||||
}
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public String getText(String PlayerName,String title){
|
||||
String rtrn = this.out_type[this.type];
|
||||
rtrn = rtrn.replace("{NAME}", PlayerName).replace("{ADV}", title);
|
||||
|
||||
return rtrn;
|
||||
}
|
||||
public String find(String ad) {
|
||||
for (int i = 0; i < normal.length; i++)
|
||||
if (ad.equals(normal[i][0])) {
|
||||
type = 0;
|
||||
return normal[i][1];
|
||||
}
|
||||
for (int i = 0; i < goal.length; i++)
|
||||
if (ad.equals(goal[i][0])) {
|
||||
type = 1;
|
||||
return goal[i][1];
|
||||
}
|
||||
for (int i = 0; i < challenge.length; i++)
|
||||
if (ad.equals(challenge[i][0])) {
|
||||
type = 2;
|
||||
return challenge[i][1];
|
||||
}
|
||||
return ad;
|
||||
}
|
||||
|
||||
public boolean check(String adv) {
|
||||
if(adv.contains("root") || adv.contains("recipes"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
66
src/main/java/hu/ditservices/utils/Cooldown.java
Normal file
66
src/main/java/hu/ditservices/utils/Cooldown.java
Normal file
@ -0,0 +1,66 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
import hu.ditservices.STPlugin;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class Cooldown {
|
||||
STPlugin plugin;
|
||||
FileConfiguration config;
|
||||
|
||||
Map<String, Long> cooldowns = new HashMap<>();
|
||||
private int delay = 2; //seconds
|
||||
public long time_left;
|
||||
|
||||
public Cooldown(STPlugin instance){
|
||||
this.plugin = instance;
|
||||
this.config = plugin.config;
|
||||
if (config.isSet("Cooldown.seconds")){
|
||||
int cd = this.delay;
|
||||
if (cd!=config.getInt("Cooldown.seconds")){
|
||||
this.delay = config.getInt("Cooldown.seconds");
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if the command sender has a cooldown in time.
|
||||
* @param sender The CommandSender object.
|
||||
*/
|
||||
public boolean Check(CommandSender sender){
|
||||
if (sender instanceof Player){
|
||||
Player player = (Player) sender;
|
||||
if (config.getBoolean("Cooldown.enabled")) {
|
||||
if (this.cooldowns.containsKey(player.getName())) {
|
||||
if (this.cooldowns.get(player.getName()) > System.currentTimeMillis()) {
|
||||
this.time_left = (this.cooldowns.get(player.getName()) - System.currentTimeMillis()) / 1000;
|
||||
return this.time_left == 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public void Add(Player player){
|
||||
if (config.getBoolean("Cooldown.enabled")) {
|
||||
if (this.cooldowns.containsKey(player.getName())) {
|
||||
this.cooldowns.remove(player.getName());
|
||||
}
|
||||
this.cooldowns.put(player.getName(), System.currentTimeMillis() + (this.delay * 1000L));
|
||||
}
|
||||
}
|
||||
public void CDText(CommandSender sender){
|
||||
String msg = config.getString("Cooldown.Msg");
|
||||
msg = msg.replace("{PREFIX}", plugin.getPrefix());
|
||||
msg = msg.replace("{SECONDS}",String.valueOf(this.time_left));
|
||||
sender.sendMessage(ChatColor.translateAlternateColorCodes('&',msg));
|
||||
}
|
||||
|
||||
}
|
70
src/main/java/hu/ditservices/utils/Logger.java
Normal file
70
src/main/java/hu/ditservices/utils/Logger.java
Normal file
@ -0,0 +1,70 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public class Logger implements Listener {
|
||||
public static String Location = "plugins/SimplifyTools/logs/";
|
||||
|
||||
/**
|
||||
* Gets the current date in yyyy-MM-dd format.
|
||||
*/
|
||||
public static String getDate() {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
return sdf.format(cal.getTime());
|
||||
}
|
||||
/**
|
||||
* Gets the current time in HH:mm:ss format.
|
||||
*/
|
||||
public static String getTime() {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
|
||||
return sdf.format(cal.getTime());
|
||||
}
|
||||
/**
|
||||
* Logs a line in the today's log file.
|
||||
* @param text The text to log.
|
||||
*/
|
||||
public static void logLine(String text){
|
||||
String fileName = Logger.getDate()+".txt";
|
||||
|
||||
File file = new File(Logger.Location+fileName);
|
||||
if (!file.exists()){ createFile(); }
|
||||
|
||||
try {
|
||||
BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
|
||||
writer.write(text);
|
||||
writer.newLine();
|
||||
writer.close();
|
||||
|
||||
} catch (Exception e){ e.printStackTrace(); }
|
||||
}
|
||||
|
||||
|
||||
private static void createFile(){
|
||||
String fileName = getDate() + ".txt";
|
||||
File directory = new File(Logger.Location);
|
||||
if(!directory.exists()){
|
||||
directory.mkdirs();
|
||||
}
|
||||
|
||||
File file = new File(Logger.Location + fileName);
|
||||
if( !file.exists() ){
|
||||
try {
|
||||
file.createNewFile();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
21
src/main/java/hu/ditservices/utils/Math.java
Normal file
21
src/main/java/hu/ditservices/utils/Math.java
Normal file
@ -0,0 +1,21 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class Math {
|
||||
public enum Convert {
|
||||
TICKS,SECONDS,MINUTES,HOURS
|
||||
}
|
||||
/**
|
||||
* Converting time measurement units from one to another.
|
||||
* @param from The unit FROM you want to convert. Math.Convert
|
||||
* @param to The unit TO you want to convert. Math.Convert
|
||||
* @param value An integer which you want to convert.
|
||||
*/
|
||||
public static long convert(Convert from, Convert to, int value){
|
||||
if (from== Convert.SECONDS && to==Convert.TICKS){
|
||||
return value*20L;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
75
src/main/java/hu/ditservices/utils/Server.java
Normal file
75
src/main/java/hu/ditservices/utils/Server.java
Normal file
@ -0,0 +1,75 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import java.lang.Math;
|
||||
|
||||
public class Server {
|
||||
|
||||
|
||||
public enum RAM {
|
||||
FREE,USED,TOTAL
|
||||
}
|
||||
/**
|
||||
* Get RAM usage statistics of the MC server.
|
||||
* @param t The RAM usage type you want to get. Server.RAM enum. It could be FREE,TOTAL,USED
|
||||
*/
|
||||
public static long getRAM(Server.RAM t) {
|
||||
long mb = 1048576L;
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
if (t == RAM.FREE){
|
||||
return runtime.freeMemory() / mb;
|
||||
}
|
||||
if (t == RAM.TOTAL){
|
||||
return runtime.totalMemory() / mb;
|
||||
}
|
||||
if (t == RAM.USED){
|
||||
return (runtime.totalMemory() - runtime.freeMemory()) / mb;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
/**
|
||||
* Get the CPU cores of the MC server.
|
||||
*/
|
||||
public static int getCpuCores(){
|
||||
return Runtime.getRuntime().availableProcessors();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get a player's ping.
|
||||
* @param player The player object.
|
||||
* @return Returns the player's ping in integer.
|
||||
*/
|
||||
public static int getPlayerPing(Player player){
|
||||
try {
|
||||
if (Version.ServerVersion.isCurrentLower(Version.ServerVersion.v1_16_R1)){
|
||||
Object entityPlayer = player.getClass().getMethod("getHandle").invoke(player);
|
||||
return (int) entityPlayer.getClass().getField("ping").get(entityPlayer);
|
||||
}
|
||||
return player.getPing();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get an average of the currently online player's ping.
|
||||
*/
|
||||
public static int getAveragePing(){
|
||||
int sum = 0;
|
||||
int avg = 0;
|
||||
int onlineplayers = 0;
|
||||
if (Bukkit.getOnlinePlayers().size() !=0){
|
||||
onlineplayers =Bukkit.getOnlinePlayers().size();
|
||||
for (Player player : Bukkit.getOnlinePlayers()){
|
||||
sum += Server.getPlayerPing(player);
|
||||
}
|
||||
avg = Math.floorDiv(sum,onlineplayers);
|
||||
|
||||
}
|
||||
return avg;
|
||||
|
||||
}
|
||||
}
|
61
src/main/java/hu/ditservices/utils/TPS.java
Normal file
61
src/main/java/hu/ditservices/utils/TPS.java
Normal file
@ -0,0 +1,61 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
public class TPS implements Runnable {
|
||||
|
||||
public static int TICK_COUNT = 0;
|
||||
public static long[] TICKS = new long[600];
|
||||
public static long LAST_TICK = 0L;
|
||||
|
||||
|
||||
|
||||
public static double getTPS() {
|
||||
return getTPS(100);
|
||||
}
|
||||
|
||||
public static ChatColor getColor(double... tps){
|
||||
double s = TPS.getTPS();
|
||||
if (tps.length>0){
|
||||
s = tps[0];
|
||||
}
|
||||
|
||||
if (s == 18.0) {
|
||||
return ChatColor.GREEN;
|
||||
} else if (s >= 15.0) {
|
||||
return ChatColor.YELLOW;
|
||||
} else {
|
||||
return ChatColor.RED;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static double getTPS(int ticks) {
|
||||
try {
|
||||
if (TICK_COUNT < ticks) {
|
||||
return 20.0D;
|
||||
}
|
||||
int target = (TICK_COUNT - 1 - ticks) % TICKS.length;
|
||||
long elapsed = System.currentTimeMillis() - TICKS[target];
|
||||
|
||||
return ticks / (elapsed / 1000.0D);
|
||||
} catch (Exception ignored){
|
||||
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static long getElapsed(int tickID) {
|
||||
if (TICK_COUNT - tickID >= TICKS.length) {
|
||||
}
|
||||
|
||||
long time = TICKS[(tickID % TICKS.length)];
|
||||
return System.currentTimeMillis() - time;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
TICKS[(TICK_COUNT % TICKS.length)] = System.currentTimeMillis();
|
||||
|
||||
TICK_COUNT += 1;
|
||||
}
|
||||
}
|
100
src/main/java/hu/ditservices/utils/Version.java
Normal file
100
src/main/java/hu/ditservices/utils/Version.java
Normal file
@ -0,0 +1,100 @@
|
||||
package hu.ditservices.utils;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class Version {
|
||||
public enum ServerVersion {
|
||||
v1_8_R1,
|
||||
v1_8_R2,
|
||||
v1_8_R3,
|
||||
v1_9_R1,
|
||||
v1_9_R2,
|
||||
v1_10_R1,
|
||||
v1_11_R1,
|
||||
v1_12_R1,
|
||||
v1_13_R1,
|
||||
v1_13_R2,
|
||||
v1_14_R1,
|
||||
v1_14_R2,
|
||||
v1_15_R1,
|
||||
v1_15_R2,
|
||||
v1_16_R1,
|
||||
v1_16_R2,
|
||||
v1_16_R3,
|
||||
v1_17_R1,
|
||||
v1_17_R2,
|
||||
v1_18_R1,
|
||||
v1_18_R2,
|
||||
v1_19_R1,
|
||||
v1_19_R2;
|
||||
|
||||
private int value;
|
||||
|
||||
private static String[] arrayVersion;
|
||||
private static ServerVersion current;
|
||||
|
||||
ServerVersion() {
|
||||
value = Integer.valueOf(getNumberEscapeSequence().matcher(name()).replaceAll(""));
|
||||
}
|
||||
|
||||
public static ServerVersion getCurrent() {
|
||||
if (current != null)
|
||||
return current;
|
||||
|
||||
String[] v = getArrayVersion();
|
||||
String vv = v[v.length - 1];
|
||||
for (ServerVersion one : values()) {
|
||||
if (one.name().equalsIgnoreCase(vv)) {
|
||||
current = one;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (current == null) {
|
||||
current = ServerVersion.v1_16_R3;
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
public static String[] getArrayVersion() {
|
||||
if (arrayVersion == null) {
|
||||
arrayVersion = org.bukkit.Bukkit.getServer().getClass().getPackage().getName().split("\\.");
|
||||
}
|
||||
|
||||
return arrayVersion;
|
||||
}
|
||||
|
||||
public static boolean isCurrentEqualOrHigher(ServerVersion v) {
|
||||
return getCurrent().value >= v.value;
|
||||
}
|
||||
|
||||
public static boolean isCurrentHigher(ServerVersion v) {
|
||||
return getCurrent().value > v.value;
|
||||
}
|
||||
|
||||
public static boolean isCurrentLower(ServerVersion v) {
|
||||
return getCurrent().value < v.value;
|
||||
}
|
||||
|
||||
public static boolean isCurrentEqualOrLower(ServerVersion v) {
|
||||
return getCurrent().value <= v.value;
|
||||
}
|
||||
|
||||
public static boolean isCurrentEqual(ServerVersion v) {
|
||||
return getCurrent().value == v.value;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern COMMA_SPACE_SEPARATED_PATTERN = Pattern.compile(", ");
|
||||
private static final Pattern NUMBER_ESCAPE_SEQUENCE = Pattern.compile("[^\\d]");
|
||||
|
||||
public static Pattern getCommaSpaceSeparatedPattern() {
|
||||
return COMMA_SPACE_SEPARATED_PATTERN;
|
||||
}
|
||||
|
||||
public static Pattern getNumberEscapeSequence() {
|
||||
return NUMBER_ESCAPE_SEQUENCE;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package hu.ditservices.utils.reflection;
|
||||
|
||||
import hu.ditservices.utils.Version;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public final class ClazzContainer {
|
||||
private static Class<?> packet, ChatComponentTextClass, CraftPlayerClass, IChatBaseComponentClass, PacketPlayOutPlayerListHeaderFooterClass;
|
||||
private static Object ChatComponentText, IChatBaseComponent;
|
||||
|
||||
static {
|
||||
try {
|
||||
IChatBaseComponentClass = classByName("net.minecraft.network.chat", "IChatBaseComponent");
|
||||
packet = classByName("net.minecraft.network.protocol", "Packet");
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public ClazzContainer(){
|
||||
|
||||
}
|
||||
|
||||
public static Class<?> classByName(String newPackageName, String name) throws ClassNotFoundException {
|
||||
if (Version.ServerVersion.isCurrentLower(Version.ServerVersion.v1_17_R1) || newPackageName == null) {
|
||||
newPackageName = "net.minecraft.server." + Version.ServerVersion.getArrayVersion()[3];
|
||||
}
|
||||
|
||||
return Class.forName(newPackageName + "." + name);
|
||||
}
|
||||
|
||||
public static Object buildChatComponentText(String text) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||
Constructor<?> constructor;
|
||||
if (Version.ServerVersion.isCurrentEqualOrHigher(Version.ServerVersion.v1_17_R1)){
|
||||
if (ChatComponentTextClass == null){
|
||||
ChatComponentTextClass = Reflection.getClass("net.minecraft.network.chat.ChatComponentText");
|
||||
}
|
||||
|
||||
constructor = ChatComponentTextClass.getConstructor(String.class);
|
||||
return constructor.newInstance(text);
|
||||
}else{
|
||||
if (ChatComponentTextClass == null){
|
||||
ChatComponentTextClass = Reflection.getClass("net.minecraft.server.%v.ChatComponentText");
|
||||
}
|
||||
constructor = Reflection.getClass("net.minecraft.server.%v.ChatComponentText").getConstructor(String.class);
|
||||
return constructor.newInstance(text);
|
||||
}
|
||||
}
|
||||
|
||||
public static Object buildPacketPlayOutPlayerListHeaderFooter(Object header, Object footer) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||
Constructor<?> constructor;
|
||||
Field headerField;
|
||||
Field footerField;
|
||||
Object packet;
|
||||
if (Version.ServerVersion.isCurrentEqualOrHigher(Version.ServerVersion.v1_17_R1)){
|
||||
if (PacketPlayOutPlayerListHeaderFooterClass == null){
|
||||
PacketPlayOutPlayerListHeaderFooterClass = Reflection.getClass("net.minecraft.network.protocol.game.PacketPlayOutPlayerListHeaderFooter");
|
||||
}
|
||||
}else{
|
||||
if (PacketPlayOutPlayerListHeaderFooterClass == null){
|
||||
PacketPlayOutPlayerListHeaderFooterClass = Reflection.getClass("net.minecraft.server.%v.PacketPlayOutPlayerListHeaderFooter");
|
||||
}
|
||||
}
|
||||
if (Version.ServerVersion.isCurrentEqualOrLower(Version.ServerVersion.v1_12_R1)){
|
||||
constructor = PacketPlayOutPlayerListHeaderFooterClass.getConstructor();
|
||||
packet = constructor.newInstance();
|
||||
try {
|
||||
headerField = packet.getClass().getDeclaredField("a");
|
||||
headerField.setAccessible(true);
|
||||
headerField.set(packet, buildChatComponentText((String) header));
|
||||
footerField = packet.getClass().getDeclaredField("b");
|
||||
footerField.setAccessible(true);
|
||||
footerField.set(packet, buildChatComponentText((String) footer));
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}else{
|
||||
constructor = PacketPlayOutPlayerListHeaderFooterClass.getConstructor(IChatBaseComponentClass,IChatBaseComponentClass);
|
||||
packet = constructor.newInstance(header,footer);
|
||||
}
|
||||
return packet;
|
||||
}
|
||||
|
||||
|
||||
public static Class<?> getIChatBaseComponent() {
|
||||
return IChatBaseComponentClass;
|
||||
}
|
||||
public static Class<?> getPacket() {
|
||||
return packet;
|
||||
}
|
||||
}
|
122
src/main/java/hu/ditservices/utils/reflection/Reflection.java
Normal file
122
src/main/java/hu/ditservices/utils/reflection/Reflection.java
Normal file
@ -0,0 +1,122 @@
|
||||
package hu.ditservices.utils.reflection;
|
||||
|
||||
import hu.ditservices.utils.Version;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class Reflection {
|
||||
|
||||
private static Method playerHandleMethod, sendPacketMethod, chatSerializerMethodA,chatSerializerMethodgetString;
|
||||
private static Field playerConnectionField;
|
||||
private static Class<?> chatSerializer;
|
||||
|
||||
private Reflection(){}
|
||||
|
||||
|
||||
public static Class<?> getClass(String name) {
|
||||
try {
|
||||
return Class.forName(name.replace("%v",Version.ServerVersion.getCurrent().toString()));
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Class<?> getCraftClass(String className) throws ClassNotFoundException {
|
||||
return Class.forName("org.bukkit.craftbukkit." + Version.ServerVersion.getArrayVersion()[3] + "." + className);
|
||||
}
|
||||
|
||||
public static Object getPlayerHandle(Player player) throws Exception {
|
||||
if (playerHandleMethod == null) {
|
||||
playerHandleMethod = player.getClass().getDeclaredMethod("getHandle");
|
||||
}
|
||||
|
||||
return playerHandleMethod.invoke(player);
|
||||
}
|
||||
|
||||
public static void sendPacket(Player player, Object packet) {
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object playerHandle = getPlayerHandle(player);
|
||||
|
||||
if (playerConnectionField == null) {
|
||||
playerConnectionField = playerHandle.getClass().getDeclaredField(
|
||||
(Version.ServerVersion.isCurrentEqualOrHigher(Version.ServerVersion.v1_17_R1) ? "b" : "playerConnection"));
|
||||
}
|
||||
|
||||
Object playerConnection = playerConnectionField.get(playerHandle);
|
||||
|
||||
if (sendPacketMethod == null) {
|
||||
sendPacketMethod = playerConnection.getClass().getDeclaredMethod(
|
||||
Version.ServerVersion.isCurrentEqualOrHigher(Version.ServerVersion.v1_18_R1) ? "a" : "sendPacket",
|
||||
ClazzContainer.getPacket());
|
||||
}
|
||||
|
||||
sendPacketMethod.invoke(playerConnection, packet);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String getChatSerializerString(Object serializer) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
if (chatSerializerMethodgetString==null){
|
||||
if (Version.ServerVersion.isCurrentEqualOrLower(Version.ServerVersion.v1_12_R1)){
|
||||
chatSerializerMethodgetString = ClazzContainer.getIChatBaseComponent().getDeclaredMethod("getText");
|
||||
}else{
|
||||
chatSerializerMethodgetString = ClazzContainer.getIChatBaseComponent().getDeclaredMethod("getString");
|
||||
}
|
||||
}
|
||||
return (String) chatSerializerMethodgetString.invoke(serializer);
|
||||
//return (String) ClazzContainer.getIChatBaseComponent().cast(chatSerializerMethodgetString.invoke(serializer));
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static Object asChatSerializer(String json) throws Exception {
|
||||
try {
|
||||
if (Version.ServerVersion.isCurrentEqualOrHigher(Version.ServerVersion.v1_17_R1)){
|
||||
if (chatSerializer==null){
|
||||
chatSerializer = Class.forName("net.minecraft.network.chat.IChatBaseComponent$ChatSerializer");
|
||||
}
|
||||
|
||||
}else{
|
||||
if (chatSerializer==null){
|
||||
chatSerializer = Class.forName("net.minecraft.server." + Version.ServerVersion.getArrayVersion()[3] + ".IChatBaseComponent$ChatSerializer");
|
||||
}
|
||||
}
|
||||
if (chatSerializerMethodA == null) {
|
||||
chatSerializerMethodA = chatSerializer.getMethod("a", String.class);
|
||||
}
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
return chatSerializerMethodA.invoke(chatSerializer,json);
|
||||
//return ClazzContainer.getIChatBaseComponent().cast(chatSerializerMethodA.invoke(chatSerializer, json));
|
||||
}
|
||||
|
||||
/*public static Class<?> getNMSClassRegex(String nmsClass) {
|
||||
|
||||
String version = null;
|
||||
Pattern pat = Pattern.compile("net\\.minecraft\\.(?:server)?\\.(v(?:\\d_)+R\\d)");
|
||||
for (Package p : Package.getPackages()) {
|
||||
String name = p.getName();
|
||||
Matcher m = pat.matcher(name);
|
||||
if (m.matches()) version = m.group(1);
|
||||
}
|
||||
|
||||
if (version == null) return null;
|
||||
|
||||
try {
|
||||
return Class.forName(String.format(nmsClass, version));
|
||||
} catch (ClassNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}*/
|
||||
}
|
Reference in New Issue
Block a user