1.0.0 - First Release

This commit is contained in:
LabodiDavid 2021-08-01 22:08:28 +02:00
parent cd2495d396
commit 6322a444be
39 changed files with 2344 additions and 0 deletions

39
.classpath Normal file
View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="test" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="module" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

107
.gitignore vendored Normal file
View File

@ -0,0 +1,107 @@
# ---> Maven
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
# ---> Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# 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*
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

16
.idea/compiler.xml Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="SimplifyTools" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="SimplifyTools" target="1.8" />
</bytecodeTargetLevel>
</component>
</project>

7
.idea/discord.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DiscordProjectSettings">
<option name="show" value="PROJECT_FILES" />
<option name="description" value="" />
</component>
</project>

7
.idea/encodings.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

30
.idea/jarRepositories.xml Normal file
View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="spigot-repo" />
<option name="name" value="spigot-repo" />
<option name="url" value="https://hub.spigotmc.org/nexus/content/repositories/snapshots/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="sonatype" />
<option name="name" value="sonatype" />
<option name="url" value="https://oss.sonatype.org/content/groups/public/" />
</remote-repository>
</component>
</project>

16
.idea/misc.xml Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<list size="1">
<item index="0" class="java.lang.String" itemvalue="org.bukkit.event.EventHandler" />
</list>
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="16" project-jdk-type="JavaSDK" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/SimplifyTools.iml" filepath="$PROJECT_DIR$/SimplifyTools.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

23
.project Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>DITSystem</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,6 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

35
README.md Normal file
View File

@ -0,0 +1,35 @@
# SimplifyTools
### An 'All-in-one' helper plugin for Minecraft Spigot Servers.
| Build Status | ![ Build Status](https://ci.dit-services.tk/buildStatus/icon?job=DIT-System) |
|:-------------:|:-----------------------------------------------------------------------------------------------------------------:|
| MC Version | ![ MC Version](https://ci.dit-services.tk/job/SimplifyTools/badge/icon?subject=MC&status=1.16.5&color=darkblue) |
| Lines of code | ![ Lines of code](https://tokei.rs/b1/github/LabodiDavid/SimplifyTools?category=code) |
| Files | ![ Files](https://tokei.rs/b1/github/LabodiDavid/SimplifyTools?category=files) |
## Features
- **Tab Manager** - Allows you to specify colored texts, with animations on the tab window.
Also you can display the average ping, Server RAM statistics.
![Tab manager preview](https://ci.dit-services.tk/userContent/simplifytools/1.gif)
- **Automatic/command saving** - Allows you to schedule auto saving of the world/player data on your server, or you can initiate a save by a command.
- **Custom Connect/Disconnect messages** - Allows you to customize the message that is broadcasted when someone joins or leaves the server.
![Connect messages preview](https://ci.dit-services.tk/userContent/simplifytools/2.gif)
- **Plugin Manager** - Allows you to unload/load plugins without a server restart.
(Note: This may be removed in 1.17.x versions for security reasons)
- **Gameplay statistics** - You can check your gameplay statistics such as player/mob kills, etc.
(Note: The plugin just shows the stats not recording itself, so stats before installing this plugin are counted too.)
![Stats preview](https://ci.dit-services.tk/userContent/simplifytools/3.gif)
- **Custom Advancement Messages** - You can customize the advancement messages in three categories: advancement, goal, challenge.
(Note: The advancement names are currently only can be displayed in english. In future versions there will be a feature to translate to any languages.)
![Advancement Messages preview](https://ci.dit-services.tk/userContent/simplifytools/4.gif)
- **Logging** - A logger with fully customizable format for dis/connect, chat, commands actions.
### [Check the config file for more explanation and examples](https://github.com/LabodiDavid/SimplifyTools/blob/main/src/main/resources/config.yml)
### [Commands & Permissions](docs/cmd_perms.md)
### If you have an idea or bug report [Create an issue](https://github.com/LabodiDavid/SimplifyTools/issues/new/choose) or [Create a pull request](https://github.com/LabodiDavid/SimplifyTools/compare)
## Main goal
My main goal is to create a single plugin that has many features, so it's can replace so many plugins that i often use on my servers while lowering the plugins count.
## 3rd party libraries used by this plugin
### [Config-Updater by tchristofferson](https://github.com/tchristofferson/Config-Updater)

26
SimplifyTools.iml Normal file
View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>SPIGOT</platformType>
</autoDetectTypes>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot:1.16.5-R0.1-SNAPSHOT" level="project" />
</component>
</module>

4
docs/ChangeLog.md Normal file
View File

@ -0,0 +1,4 @@
## SimplifyTools Changelog
- 1.0.0 - First Release
- Notice: If the /st reload command not reloading the new settings, you need to restart your MC server.

16
docs/cmd_perms.md Normal file
View File

@ -0,0 +1,16 @@
## SimplifyTools Commands
You can use the following commands to use the features of SimplifyTools.
- **/st**: The main SimplifyTools command.<br />Requires `st.st`
- **/st help**: Displays all SimplifyTools related commands.<br />Requires `st.help`
- **/st ping**: Displays your ping to the current server.<br />Requires `st.ping`
- **/st stats**: Displays your gameplay statistics.<br />Requires `st.stats`
- **/st save-all**: Saves the players, worlds data on the server.<br />Requires `st.save`
- **/st pmanager** <LOAD/UNLOAD>: A built-in plugin manager.<br />Requires `st.pmanager.*`
- **/st pmanager load** <PLUGIN-NAME>: Plugin loading.<br />Requires `st.pmanager.load (can be inherited from st.pmanager.*)`
- **/st pmanager unload** <PLUGIN-NAME>: Plugin unload.<br />Requires `st.pmanager.unload (can be inherited from st.pmanager.*)`
- **/st reload**: Plugin settings reload.<br />Requires `st.reload`
<br />
## SimplifyTools Wildcard Permissions
- **st.*** - Wildcard permission for all commands, permissions for this plugin.
- **st.pmanager.*** - Wildcard permission for the plugin manager commands.
- **st.admin** - A wildcard permission for admins. This is used for notify when update available, also grants usage for `st.save` and `st.pmanager.*`

95
pom.xml Normal file
View File

@ -0,0 +1,95 @@
<?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>tk.ditservices</groupId>
<artifactId>SimplifyTools</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SimplifyTools</name>
<description>SimplifyTools - All-in-one helper plugin.</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<url>dit-services.tk</url>
<ciManagement>
<system>jenkins</system>
<url>https://ci.dit-services.tk/job/SimplifyTools/</url>
</ciManagement>
<issueManagement>
<system>GitHub</system>
<url>https://github.com/LabodiDavid/SimplifyTools/issues</url>
</issueManagement>
<licenses>
<license>
<name>The GNU General Public Licence version 3 (GPLv3)</name>
<url>https://www.gnu.org/licenses/gpl-3.0.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</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.1.0</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>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: DITSystem

View File

@ -0,0 +1,70 @@
package tk.ditservices;
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 DITLog 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 = DITLog.getDate()+".txt";
File file = new File(DITLog.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(DITLog.Location);
if(!directory.exists()){
directory.mkdirs();
}
File file = new File(DITLog.Location + fileName);
if( !file.exists() ){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,127 @@
package tk.ditservices;
import org.bukkit.scheduler.BukkitScheduler;
import tk.ditservices.commands.DitCmd;
import tk.ditservices.listeners.ChatEvents;
import tk.ditservices.listeners.LogChat;
import tk.ditservices.listeners.LogCommand;
import tk.ditservices.listeners.LogConnect;
import tk.ditservices.utils.ConfigUpdater;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.World;
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.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import tk.ditservices.utils.Math;
import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
public final class DITSystem extends JavaPlugin implements CommandExecutor, Listener {
private static DITSystem instance;
Logger log = Bukkit.getLogger();
private DitPluginManager dplug;
public TabManager tab;
public FileConfiguration config;
@Override
public void onEnable() {
saveDefaultConfig();
instance = this;
this.DIT_initialize();
this.tab = new TabManager(this,this.config);
this.dplug = new DitPluginManager(this);
System.out.println(this.getPrefix()+"Started running.");
}
private void DIT_initialize() {
if (this.Reload()){
initOptions();
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);
getServer().getPluginManager().registerEvents(new ChatEvents(this), this);
}
}
public String getPrefix(){
if (this.config.isSet("Prefix")){
return ChatColor.translateAlternateColorCodes('&', this.config.getString("Prefix"));
}else{
return ChatColor.translateAlternateColorCodes('&',"&a[&fSimplify&7Tools&2] &4- &f");
}
}
public static DITSystem getInstance(){
return instance;
}
public void initOptions(){
if (config.getBoolean("Saving.enabled") && config.getInt("Saving.interval")>0){
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(instance, new Runnable() {
@Override
public void run() {
String p = config.isSet("Saving.broadcastMsgProgress") ? config.getString("Saving.broadcastMsgProgress").replace("{PREFIX}",instance.getPrefix()) : instance.getPrefix()+"Auto save in progress..";
String d = config.isSet("Saving.broadcastMsgDone") ? config.getString("Saving.broadcastMsgDone").replace("{PREFIX}",instance.getPrefix()) : instance.getPrefix()+"Auto save done.";
Bukkit.broadcast(p,"st.st");
for(World w : Bukkit.getServer().getWorlds()){
w.save();
}
Bukkit.savePlayers();
Bukkit.broadcast(d,"st.st");
}
}, 0L, Math.convert(Math.Convert.SECONDS,Math.Convert.TICKS,instance.config.getInt("Saving.interval")));
}
if (this.config.isSet("CustomAdvancement.enabled")) {
if(config.getBoolean("CustomAdvancement.enabled")){
List<World> worlds = getServer().getWorlds();
for (World w : worlds) {
if(w.getGameRuleValue(GameRule.ANNOUNCE_ADVANCEMENTS)) {
w.setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false);
log.info(this.getPrefix()+"Disabling vanilla advancement messages for " + w.getName());
}
}
}
}
}
public boolean Reload(){
File configFile = new File(getDataFolder(), "config.yml");
try {
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.");
}
}

View File

@ -0,0 +1,88 @@
package tk.ditservices;
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 = "";
//String[] vizsg_args = new String[args.length+1];
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;
}
}

View File

@ -0,0 +1,183 @@
package tk.ditservices;
import tk.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;
}
/**
* Loads the requested plugin.
* @param pluginName Plugin name in string.
*/
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
}
}

View File

@ -0,0 +1,207 @@
package tk.ditservices;
import tk.ditservices.utils.Math;
import tk.ditservices.utils.Server;
import net.minecraft.server.v1_16_R3.ChatComponentText;
import net.minecraft.server.v1_16_R3.IChatBaseComponent;
import net.minecraft.server.v1_16_R3.PacketPlayOutPlayerListHeaderFooter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class TabManager {
private List<ChatComponentText> headers = new ArrayList<>();
private List<ChatComponentText> footers = new ArrayList<>();
private Integer refreshRate;
private DITSystem plugin;
private FileConfiguration config;
private List<String> headeranimList = new ArrayList<String>();
private List<String> footeranimList = new ArrayList<String>();
private ArrayList<String> formatArray = new ArrayList<>();
private List<Integer> DynamicHeaders = new ArrayList<>();
private List<Integer> DynamicFooters = new ArrayList<>();
private enum AddLine {
HEADER, FOOTER
}
public TabManager(DITSystem instance,FileConfiguration c){
this.plugin = instance;
this.config = c;
if(this.init()){
this.showTab();
}
}
public void showTab(){
if (headers.isEmpty() && footers.isEmpty()){
return;
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter();
int count1 = 0; //headers
int count2 = 0; //footers
@Override
public void run() {
try {
//Tab code
Field a = packet.getClass().getDeclaredField("header");
a.setAccessible(true);
Field b = packet.getClass().getDeclaredField("footer");
b.setAccessible(true);
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(AddLine.HEADER,headeranimList.get(count1),true,count1);
}
}
if (DynamicFooters.size()>0 && count2 < DynamicFooters.size()){
if (DynamicFooters.get(count2) == count2){
addHeaderFooter(AddLine.FOOTER,footeranimList.get(count2),true,count2);
}
}
a.set(packet, headers.get(count1));
b.set(packet,footers.get(count2));
if (Bukkit.getOnlinePlayers().size() !=0){
for (Player player : Bukkit.getOnlinePlayers()){
((CraftPlayer)player).getHandle().playerConnection.sendPacket(packet);
}
}
if (headers.size()>1){
count1++;
}
if (footers.size()>1){
count2++;
}
} catch (Exception e){
e.printStackTrace();
}
}
},10, Math.convert(Math.Convert.SECONDS,Math.Convert.TICKS,this.refreshRate));
}
private boolean init(){
if (config.getBoolean("Tab.enabled")){
if (config.isSet("Tab.refreshRate")){
this.refreshRate = config.getInt("Tab.refreshRate");
}else{
this.refreshRate=40;
}
//Getting the tab lines from the config
headeranimList = config.getStringList("Tab.headerAnimation");
footeranimList = config.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}");
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(AddLine.HEADER,hanim,false);
}
for (String fanim : footeranimList){
this.addHeaderFooter(AddLine.FOOTER,fanim,false);
}
return true;
}
return false;
}
/**
* Manages the adding of the tab line and the final formatting of the text.
* @param head_or_footer AddLine Enum value to choose where to add a tab line.
* @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.
*/
public void addHeaderFooter(AddLine head_or_footer,String text,boolean dynamic,int... index){
IChatBaseComponent tabText = IChatBaseComponent.ChatSerializer.a("{\"text\":\"" + format(text) +"\"}");
if (head_or_footer==AddLine.HEADER){
if (dynamic){
headers.set(index[0],new ChatComponentText(tabText.getString()));
}else {
headers.add(new ChatComponentText(tabText.getString()));
}
}else{
if (head_or_footer==AddLine.FOOTER){
if (dynamic){
footers.set(index[0],new ChatComponentText(tabText.getString()));
}else {
footers.add(new ChatComponentText(tabText.getString()));
}
}
}
}
/**
* 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()));
}
return ChatColor.translateAlternateColorCodes('&', msg);
}
}

View File

@ -0,0 +1,149 @@
package tk.ditservices.commands;
import org.bukkit.Bukkit;
import org.bukkit.World;
import tk.ditservices.DITSystem;
import tk.ditservices.utils.Cooldown;
import org.bukkit.ChatColor;
import org.bukkit.command.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
public class DitCmd implements CommandExecutor {
String noArgMsg;
DITSystem plugin;
Cooldown cd;
FileConfiguration config;
public DitCmd(DITSystem 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;
}
@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)
{
if (sender instanceof Player)
{
Player p = (Player) sender;
p.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Version: "+plugin.getDescription().getVersion());
p.sendMessage(this.noArgMsg);
cd.Add(p);
return true;
}else {
if (sender instanceof ConsoleCommandSender){
sender.sendMessage(this.noArgMsg);
return true;
}
}
}
if (command.getName().equals("st") && args[0].contains("help"))
{
if (sender instanceof Player)
{
Player p = (Player) sender;
cd.Add(p);
p.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Version: "+plugin.getDescription().getVersion());
p.sendMessage(this.noArgMsg);
return true;
}else{
if (sender instanceof ConsoleCommandSender) {
ConsoleCommandSender konzoladmin = (ConsoleCommandSender) sender;
konzoladmin.sendMessage(this.noArgMsg);
return true;
}
}
}
if (command.getName().equals("st") && args[0].contains("reload") && sender.hasPermission("st.reload")){
if(plugin.Reload()){
if (sender instanceof Player){
Player p = (Player) sender;
cd.Add(p);
}
sender.sendMessage(plugin.getPrefix()+ChatColor.GREEN+"Successfully reload!");
}
//sender.sendMessage(plugin.getPrefix()+ChatColor.RED+" Ezt a verziót a "+ChatColor.YELLOW+"'/reload confirm'"+ChatColor.RED+" parancssal tudod csak újratölteni!");
}
if (command.getName().equalsIgnoreCase("st") && args[0].contains("pmanager")){
if (sender.hasPermission("st.pmanager.unload") || sender.hasPermission("st.pmanager.load") || sender.hasPermission("st.pmanager")) {
if (sender instanceof Player){
Player p = (Player) sender;
cd.Add(p);
}
if (args.length==1){
String msg = plugin.getPrefix()+ChatColor.DARK_RED+"Invalid command!";
if (sender instanceof Player){
Player p = (Player) sender;
p.sendMessage(msg);
}else{
ConsoleCommandSender c = (ConsoleCommandSender) sender;
c.sendMessage(msg);
}
return true;
}
if (args[1].equalsIgnoreCase("load")) {
PluginCmd.handleLoad(sender,args);
}
if (args[1].equalsIgnoreCase("unload")) {
PluginCmd.handleUnload(sender,args);
}
}
}
if (command.getName().equalsIgnoreCase("st") && args[0].contains("save-all") && sender.hasPermission("st.save")){
if (sender instanceof Player){
Player p = (Player) sender;
cd.Add(p);
}
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;
}
if (command.getName().equalsIgnoreCase("st") && args[0].contains("ping") && sender.hasPermission("st.ping")){
if (sender instanceof Player){
Player p = (Player) sender;
cd.Add(p);
} return PingCmd.Run(sender);
}
if (command.getName().equalsIgnoreCase("st") && args[0].contains("stats") && sender.hasPermission("st.stats")){
if (sender instanceof Player){
Player p = (Player) sender;
cd.Add(p);
} return StatCmd.Run(sender);
}
}else{
cd.CDText(sender);
}
}
return true;
}
}

View File

@ -0,0 +1,32 @@
package tk.ditservices.commands;
import tk.ditservices.DITSystem;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
public class PingCmd {
public static boolean Run(CommandSender sender) {
DITSystem plugin = DITSystem.getInstance();
if (sender instanceof Player) {
Player player = (Player) sender;
try {
Object entityPlayer = player.getClass().getMethod("getHandle").invoke(player);
int ping = (int) entityPlayer.getClass().getField("ping").get(entityPlayer);
player.sendMessage(plugin.getPrefix() + "Your response time to the server: " + ping + " ms");
return true;
} catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | NoSuchFieldException | InvocationTargetException e) {
e.printStackTrace();
}
} else {
if (sender instanceof ConsoleCommandSender) {
ConsoleCommandSender konzoladmin = (ConsoleCommandSender) sender;
konzoladmin.sendMessage(plugin.getPrefix() + "For this command you have to be a player!");
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,30 @@
package tk.ditservices.commands;
import tk.ditservices.DITSystem;
import tk.ditservices.DitPluginManager;
import org.bukkit.command.CommandSender;
public class PluginCmd {
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;
}
}

View File

@ -0,0 +1,23 @@
package tk.ditservices.commands;
import tk.ditservices.DITSystem;
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(DITSystem.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;
}
}

View File

@ -0,0 +1,35 @@
package tk.ditservices.listeners;
import tk.ditservices.DITSystem;
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 tk.ditservices.utils.AdvancementHelper;
public class ChatEvents implements Listener {
private DITSystem plugin;
private FileConfiguration config;
public ChatEvents(DITSystem instance){
this.plugin = instance;
this.config = plugin.config;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onAdvance(PlayerAdvancementDoneEvent e){
if (config.isSet("CustomAdvancement.enabled")){
if (config.getBoolean("CustomAdvancement.enabled")){
AdvancementHelper helper = new AdvancementHelper(plugin,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)));
}
}
}
}
}

View File

@ -0,0 +1,29 @@
package tk.ditservices.listeners;
import tk.ditservices.DITLog;
import tk.ditservices.DITSystem;
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 {
DITSystem plugin;
FileConfiguration config;
public LogChat(DITSystem 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}",DITLog.getDate()).replace("{TIME}",DITLog.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{MSG}",event.getMessage()).replace("{ACTION}","[CHAT]");
DITLog.logLine(ChatColor.stripColor(LogMsg));
}
}
}

View File

@ -0,0 +1,30 @@
package tk.ditservices.listeners;
import tk.ditservices.DITLog;
import tk.ditservices.DITSystem;
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 {
DITSystem plugin;
FileConfiguration config;
public LogCommand(DITSystem 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}",DITLog.getDate()).replace("{TIME}",DITLog.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{COMMAND}",event.getMessage()).replace("{ACTION}","[COMMAND]");
DITLog.logLine(ChatColor.stripColor(LogMsg));
}
}
}

View File

@ -0,0 +1,68 @@
package tk.ditservices.listeners;
import tk.ditservices.DITLog;
import tk.ditservices.DITSystem;
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 {
DITSystem plugin;
private String JoinMsg;
private String LeaveMsg;
FileConfiguration config;
public LogConnect(DITSystem 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}",DITLog.getDate()).replace("{TIME}",DITLog.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{UUID}",player.getUniqueId().toString()).replace("{ACTION}","[CONNECT]");
DITLog.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}",DITLog.getDate()).replace("{TIME}",DITLog.getTime()).replace("{PLAYERNAME}",player.getDisplayName()).replace("{UUID}",player.getUniqueId().toString()).replace("{ACTION}","[DISCONNECT]");
DITLog.logLine(ChatColor.stripColor(LogMsg));
}
if (config.getBoolean("Saving.enabled")){
if(config.getBoolean("Saving.onDisconnect")){
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "st save-all");
}
}
}
}

View File

@ -0,0 +1,146 @@
package tk.ditservices.utils;
import tk.ditservices.DITLog;
import tk.ditservices.DITSystem;
import org.bukkit.configuration.file.FileConfiguration;
public class AdvancementHelper {
private DITSystem plugin;
private FileConfiguration config;
public AdvancementHelper(DITSystem instance, FileConfiguration c){
this.plugin = instance;
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");
}
}
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;
}
}

View File

@ -0,0 +1,320 @@
/**
* Github repo: https://github.com/tchristofferson/Config-Updater
*/
package tk.ditservices.utils;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
/**
* A class to update/add new sections/keys to your config while keeping your current values and keeping your comments
* Algorithm:
* Read the new file and scan for comments and ignored sections, if ignored section is found it is treated as a comment.
* Read and write each line of the new config, if the old config has value for the given key it writes that value in the new config.
* If a key has an attached comment above it, it is written first.
* @author tchristofferson
*/
public class ConfigUpdater {
/**
* Update a yaml file from a resource inside your plugin jar
* @param plugin You plugin
* @param resourceName The yaml file name to update from, typically config.yml
* @param toUpdate The yaml file to update
* @param ignoredSections List of sections to ignore and copy from the current config
* @throws IOException If an IOException occurs
*/
public static void update(Plugin plugin, String resourceName, File toUpdate, List<String> ignoredSections) throws IOException {
BufferedReader newReader = new BufferedReader(new InputStreamReader(plugin.getResource(resourceName), StandardCharsets.UTF_8));
List<String> newLines = newReader.lines().collect(Collectors.toList());
newReader.close();
FileConfiguration oldConfig = YamlConfiguration.loadConfiguration(toUpdate);
FileConfiguration newConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource(resourceName), StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toUpdate), StandardCharsets.UTF_8));
List<String> ignoredSectionsArrayList = new ArrayList<>(ignoredSections);
//ignoredSections can ONLY contain configurations sections
ignoredSectionsArrayList.removeIf(ignoredSection -> !newConfig.isConfigurationSection(ignoredSection));
Yaml yaml = new Yaml();
Map<String, String> comments = parseComments(newLines, ignoredSectionsArrayList, oldConfig, yaml);
write(newConfig, oldConfig, comments, ignoredSectionsArrayList, writer, yaml);
}
//Write method doing the work.
//It checks if key has a comment associated with it and writes comment then the key and value
private static void write(FileConfiguration newConfig, FileConfiguration oldConfig, Map<String, String> comments, List<String> ignoredSections, BufferedWriter writer, Yaml yaml) throws IOException {
outer: for (String key : newConfig.getKeys(true)) {
String[] keys = key.split("\\.");
String actualKey = keys[keys.length - 1];
String comment = comments.remove(key);
StringBuilder prefixBuilder = new StringBuilder();
int indents = keys.length - 1;
appendPrefixSpaces(prefixBuilder, indents);
String prefixSpaces = prefixBuilder.toString();
if (comment != null) {
writer.write(comment);//No \n character necessary, new line is automatically at end of comment
}
for (String ignoredSection : ignoredSections) {
if (key.startsWith(ignoredSection)) {
continue outer;
}
}
Object newObj = newConfig.get(key);
Object oldObj = oldConfig.get(key);
if (newObj instanceof ConfigurationSection && oldObj instanceof ConfigurationSection) {
//write the old section
writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) oldObj);
} else if (newObj instanceof ConfigurationSection) {
//write the new section, old value is no more
writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) newObj);
} else if (oldObj != null) {
//write the old object
write(oldObj, actualKey, prefixSpaces, yaml, writer);
} else {
//write new object
write(newObj, actualKey, prefixSpaces, yaml, writer);
}
}
String danglingComments = comments.get(null);
if (danglingComments != null) {
writer.write(danglingComments);
}
writer.close();
}
//Doesn't work with configuration sections, must be an actual object
//Auto checks if it is serializable and writes to file
private static void write(Object obj, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException {
if (obj instanceof ConfigurationSerializable) {
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(((ConfigurationSerializable) obj).serialize()));
} else if (obj instanceof String || obj instanceof Character) {
if (obj instanceof String) {
String s = (String) obj;
obj = s.replace("\n", "\\n");
}
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj));
} else if (obj instanceof List) {
writeList((List) obj, actualKey, prefixSpaces, yaml, writer);
} else {
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj));
}
}
//Writes a configuration section
private static void writeSection(BufferedWriter writer, String actualKey, String prefixSpaces, ConfigurationSection section) throws IOException {
if (section.getKeys(false).isEmpty()) {
writer.write(prefixSpaces + actualKey + ": {}");
} else {
writer.write(prefixSpaces + actualKey + ":");
}
writer.write("\n");
}
//Writes a list of any object
private static void writeList(List list, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException {
writer.write(getListAsString(list, actualKey, prefixSpaces, yaml));
}
private static String getListAsString(List list, String actualKey, String prefixSpaces, Yaml yaml) {
StringBuilder builder = new StringBuilder(prefixSpaces).append(actualKey).append(":");
if (list.isEmpty()) {
builder.append(" []\n");
return builder.toString();
}
builder.append("\n");
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if (o instanceof String || o instanceof Character) {
builder.append(prefixSpaces).append("- '").append(o).append("'");
} else if (o instanceof List) {
builder.append(prefixSpaces).append("- ").append(yaml.dump(o));
} else {
builder.append(prefixSpaces).append("- ").append(o);
}
if (i != list.size()) {
builder.append("\n");
}
}
return builder.toString();
}
//Key is the config key, value = comment and/or ignored sections
//Parses comments, blank lines, and ignored sections
private static Map<String, String> parseComments(List<String> lines, List<String> ignoredSections, FileConfiguration oldConfig, Yaml yaml) {
Map<String, String> comments = new HashMap<>();
StringBuilder builder = new StringBuilder();
StringBuilder keyBuilder = new StringBuilder();
int lastLineIndentCount = 0;
outer: for (String line : lines) {
if (line != null && line.trim().startsWith("-"))
continue;
if (line == null || line.trim().equals("") || line.trim().startsWith("#")) {
builder.append(line).append("\n");
} else {
lastLineIndentCount = setFullKey(keyBuilder, line, lastLineIndentCount);
for (String ignoredSection : ignoredSections) {
if (keyBuilder.toString().equals(ignoredSection)) {
Object value = oldConfig.get(keyBuilder.toString());
if (value instanceof ConfigurationSection)
appendSection(builder, (ConfigurationSection) value, new StringBuilder(getPrefixSpaces(lastLineIndentCount)), yaml);
continue outer;
}
}
if (keyBuilder.length() > 0) {
comments.put(keyBuilder.toString(), builder.toString());
builder.setLength(0);
}
}
}
if (builder.length() > 0) {
comments.put(null, builder.toString());
}
return comments;
}
private static void appendSection(StringBuilder builder, ConfigurationSection section, StringBuilder prefixSpaces, Yaml yaml) {
builder.append(prefixSpaces).append(getKeyFromFullKey(section.getCurrentPath())).append(":");
Set<String> keys = section.getKeys(false);
if (keys.isEmpty()) {
builder.append(" {}\n");
return;
}
builder.append("\n");
prefixSpaces.append(" ");
for (String key : keys) {
Object value = section.get(key);
String actualKey = getKeyFromFullKey(key);
if (value instanceof ConfigurationSection) {
appendSection(builder, (ConfigurationSection) value, prefixSpaces, yaml);
prefixSpaces.setLength(prefixSpaces.length() - 2);
} else if (value instanceof List) {
builder.append(getListAsString((List) value, actualKey, prefixSpaces.toString(), yaml));
} else {
builder.append(prefixSpaces.toString()).append(actualKey).append(": ").append(yaml.dump(value));
}
}
}
//Counts spaces in front of key and divides by 2 since 1 indent = 2 spaces
private static int countIndents(String s) {
int spaces = 0;
for (char c : s.toCharArray()) {
if (c == ' ') {
spaces += 1;
} else {
break;
}
}
return spaces / 2;
}
//Ex. keyBuilder = key1.key2.key3 --> key1.key2
private static void removeLastKey(StringBuilder keyBuilder) {
String temp = keyBuilder.toString();
String[] keys = temp.split("\\.");
if (keys.length == 1) {
keyBuilder.setLength(0);
return;
}
temp = temp.substring(0, temp.length() - keys[keys.length - 1].length() - 1);
keyBuilder.setLength(temp.length());
}
private static String getKeyFromFullKey(String fullKey) {
String[] keys = fullKey.split("\\.");
return keys[keys.length - 1];
}
//Updates the keyBuilder and returns configLines number of indents
private static int setFullKey(StringBuilder keyBuilder, String configLine, int lastLineIndentCount) {
int currentIndents = countIndents(configLine);
String key = configLine.trim().split(":")[0];
if (keyBuilder.length() == 0) {
keyBuilder.append(key);
} else if (currentIndents == lastLineIndentCount) {
//Replace the last part of the key with current key
removeLastKey(keyBuilder);
if (keyBuilder.length() > 0) {
keyBuilder.append(".");
}
keyBuilder.append(key);
} else if (currentIndents > lastLineIndentCount) {
//Append current key to the keyBuilder
keyBuilder.append(".").append(key);
} else {
int difference = lastLineIndentCount - currentIndents;
for (int i = 0; i < difference + 1; i++) {
removeLastKey(keyBuilder);
}
if (keyBuilder.length() > 0) {
keyBuilder.append(".");
}
keyBuilder.append(key);
}
return currentIndents;
}
private static String getPrefixSpaces(int indents) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < indents; i++) {
builder.append(" ");
}
return builder.toString();
}
private static void appendPrefixSpaces(StringBuilder builder, int indents) {
builder.append(getPrefixSpaces(indents));
}
}

View File

@ -0,0 +1,73 @@
package tk.ditservices.utils;
import tk.ditservices.DITSystem;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class Cooldown {
private int delay = 2; //seconds
DITSystem plugin;
Map<String, Long> cooldowns = new HashMap<>();
public long time_left;
FileConfiguration config;
public Cooldown(DITSystem 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;
if (this.time_left == 0) {
return true;
}
return false;
}
return true;
}
} else{
return true;
}
}
if (sender instanceof ConsoleCommandSender){
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));
}
}

View File

@ -0,0 +1,21 @@
package tk.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;
}
}

View File

@ -0,0 +1,65 @@
package tk.ditservices.utils;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import java.lang.Math;
import java.lang.reflect.InvocationTargetException;
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();
runtime.gc();
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 a player's ping.
* @param player The player object.
*/
public static int getPlayerPing(Player player){
try {
Object entityPlayer = player.getClass().getMethod("getHandle").invoke(player);
return (int) entityPlayer.getClass().getField("ping").get(entityPlayer);
} catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | NoSuchFieldException | InvocationTargetException 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;
}
}

View File

@ -0,0 +1,87 @@
# SimplifyTools
# Config file
#
# REMOVING SETTINGS MAY CAUSE ERRORS DO NOT DO THAT!!!
#
#
# ░██████╗██╗███╗░░░███╗██████╗░██╗░░░░░██╗███████╗██╗░░░██╗████████╗░█████╗░░█████╗░██╗░░░░░░██████╗
# ██╔════╝██║████╗░████║██╔══██╗██║░░░░░██║██╔════╝╚██╗░██╔╝╚══██╔══╝██╔══██╗██╔══██╗██║░░░░░██╔════╝
# ╚█████╗░██║██╔████╔██║██████╔╝██║░░░░░██║█████╗░░░╚████╔╝░░░░██║░░░██║░░██║██║░░██║██║░░░░░╚█████╗░
# ░╚═══██╗██║██║╚██╔╝██║██╔═══╝░██║░░░░░██║██╔══╝░░░░╚██╔╝░░░░░██║░░░██║░░██║██║░░██║██║░░░░░░╚═══██╗
# ██████╔╝██║██║░╚═╝░██║██║░░░░░███████╗██║██║░░░░░░░░██║░░░░░░██║░░░╚█████╔╝╚█████╔╝███████╗██████╔╝
# ╚═════╝░╚═╝╚═╝░░░░░╚═╝╚═╝░░░░░╚══════╝╚═╝╚═╝░░░░░░░░╚═╝░░░░░░╚═╝░░░░╚════╝░░╚════╝░╚══════╝╚═════╝░
#
# Logging options
# If you enable one of them, a txt file will be created every day automatically with the current date.
Log:
Chat: false #Chat messages
Connect: false #Connections, disconnects
Command: false #All command will be logged !for example private messaging, authme passwords!!
#You can customize the format for the three types.
# These values will be replaced like that: {DATE} = YYYY-MM-DD, {TIME} = HH:MM:SS, {ACTION} = [CHAT] or [COMMAND] etc..
# Example connect in the log: [2020-12-08] - 19:07:04 - [CONNECT] - PlayerName UUID: 01010101-1010-asd1-1212-404826345656
FormatChat: '[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME}: {MSG}'
FormatConnect: '[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME} UUID: {UUID}' # Note: The disconnect message will be based on this too.
FormatCommand: '[{DATE}] - {TIME} - {ACTION} - {PLAYERNAME}: {COMMAND}'
# Custom Advance Messages
# Replaces vanilla advancement broadcasting
CustomAdvancement:
enabled: false
formats:
# {NAME} represent the player's name.
# {ADV} represent the advancement name.
advancement: '&l&f{NAME}&r &bhas completed the &f[&a&n{ADV}&r&f]&b advancement!'
goal: '&l&f{NAME}&r&f]&b &bhas reached the &f[&a&n{ADV}&r&f]&b goal!'
challenge: '&l&f{NAME}&r &bcompleted the &f[&a&n{ADV}&r&f]&b challenge!'
# Tab Customization
#
# You can use Minecraft color, format codes with '&' in the texts.
# example: header: &cThis server is using SimplifyTools by &1SimplifyDave
# Note: Use \n to add a new line
# Note: The RAM values are in MB.
# {USEDRAM} {TOTALRAM} {FREERAM} {AVERAGEPING} {ONLINEPLAYERS} {MAXPLAYERS} represents their values.
# NOTICE: You will need a full MC server restart when you want to apply new settings here.
Tab:
enabled: false # If you want to enable customization on the tab
refreshRate: 2 # The refresh rate in SECONDS
headerAnimation: #If animation set to true, you can set the animations per line.
#If you don't want animations, just leave one line text here!
#- '&l&cThis is an example header text without animation\nAnd this is a new line!'
- '&cThis server is using SimplifyTools by &1SimplifyDave \nAverage ping: {AVERAGEPING} ms'
- '&bThis server is using SimplifyTools by &9SimplifyDave \nAverage ping: {AVERAGEPING} ms'
- '&b&lThis server is using SimplifyTools by &9SimplifyDave \nAverage ping: {AVERAGEPING} ms'
footerAnimation:
#If you don't want animations, just leave one line text here!
#- '&l&cThis is an example footer text without animation\n with multiple lines in one element!'
- '&l&4Server RAM Usage: {TOTALRAM}MB / {USEDRAM}MB\nOnline players: {MAXPLAYERS}/{ONLINEPLAYERS}'
- '&l&aServer RAM Usage: {TOTALRAM}MB / {USEDRAM}MB\nOnline players: {MAXPLAYERS}/{ONLINEPLAYERS}'
# Custom Connect/Disconnect messages
CustomMsg:
enabled: false
connect: '{PREFIX}{NAME} &aconnected to the server.'
disconnect: '{PREFIX}{NAME} leaved the game.'
# Auto Save options
# Saves Worlds/Users data to disk.
# Note: You can do a save like this with the /st save-all command.
# NOTICE: You will need a full MC server restart when you want to apply new settings here.
Saving:
enabled: true
onDisconnect: true # When a player disconnects
interval: 0 # Auto saving interval in SECONDS. If this set to zero it means disabled.
broadcastMsgProgress: '{PREFIX}Auto save in progress..'
broadcastMsgDone: '{PREFIX}Auto save done.'
# Cooldown options (only applicable for this plugin!)
Cooldown:
enabled: true
# The time must be passed between using this plugin commands.
seconds: 2 #The command cooldown in seconds
Msg: '{PREFIX} Please wait {SECONDS} seconds!' # The message when the user spamming a command
# Miscellaneous
Prefix: '&a[&fSimplify&7Tools&2] &4- &f'

View File

@ -0,0 +1,98 @@
name: SimplifyTools
version: ${project.version}
main: tk.ditservices.DITSystem
api-version: 1.13
prefix: SimplifyTools
load: POSTWORLD
description: SimplifyTools - An All-in-one helper plugin.
author: SimplifyDave
website: https://dit-services.tk
commands:
st:
description: The default command for the plugin.
usage: "/st"
permission: st.st
st help:
description: Displays all SimplifyTools related commands.
usage: "/st help"
permission: st.help
st ping:
description: Displays your ping to the current server.
usage: "/st ping"
permission: st.ping
st stats:
description: Displays your gameplay statistics.
usage: "/st stats"
permission: st.stats
st save-all:
description: Saves the players, worlds data on the server.
usage: "/st save-all"
permission: st.save
st pmanager:
description: A built-in plugin manager.
usage: "/st pmanager <LOAD/UNLOAD>"
permission: st.pmanager
st pmanager load:
description: Plugin loading.
usage: "/st pmanager load <PLUGIN-NAME>"
permission: st.pmanager.load
st pmanager unload:
description: Plugin unloading.
usage: "/st pmanager unload <PLUGIN-NAME>"
permission: st.pmanager.unload
st reload:
description: Plugin settings reload.
usage: "/st reload"
permission: st.reload
permissions:
st.help:
description: Enables the help command.
default: true
st.status:
description: Enables the status command.
default: true
st.ping:
description: Enables the ping command.
default: true
st.reload:
description: Enables the reload command.
default: op
st.pmanager.load:
description: Enables the plugin loading command.
default: op
st.pmanager.unload:
description: Enables the plugin disabling command.
default: op
st.st:
description: This is the default permission.
default: true
st.stats:
description: Enables the stats command.
default: true
st.save:
description: Enables the save-all command.
default: op
st.admin:
description: An admin permission for the maintenance commands and for update notifies.
default: op
children:
st.save: true
st.pmanager.*: true
st.*:
description: Wildcard permission for all commands.
default: op
children:
st.st: true
st.help: true
st.ping: true
st.status: true
st.save: true
st.stats: true
st.settings: true
st.pmanager.*:
description: The plugin manager commands.
default: op
children:
st.pmanager.load: true
st.pmanager.unload: true