First public release of HubThat's code.

This commit is contained in:
BuildTools 2019-07-22 22:02:24 +02:00
commit 5526ca908d
22 changed files with 2454 additions and 0 deletions

21
.classpath Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry including="**/*.java" kind="src" output="target/classes" path="src">
<attributes>
<attribute name="optional" 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="lib" path="C:/Users/Lorenzo/Desktop/spigot/spigot-1.14.2.jar"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target/
/bin/

23
.project Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HubThat</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.m2e.core.maven2Nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,12 @@
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.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

92
config.yml Normal file
View File

@ -0,0 +1,92 @@
global:
ALREADY-TELEPORTING: '&cYou are already teleporting!'
# When anyone tries to do /spawn or /hub but is already teleporting.
move-detect: true
# Detects if a Player moves.
PREFIX: '&0[&6HT&0]'
# HubThat commands prefix.
FIRSTRUN: true
# Do not Modify!
VERSION: 8.0
# Do not Modify!
MOVED: '&cYou moved! Teleportation cancelled.'
# When anyone tries to move when teleporting.
set-gamemode-on-join: false
# Set players' gamemode when they join the server. Should work with Multiverse.
gamemode: 0
# Chose which game mode to set players in. ignored if set-gamemode-on-join is set to false.
# 0 = survival
# 1 = creative
# 2 = adventure
# 3 = spectator
tp-hub-on-join: true
# Teleport players to the Hub when they join.
tp-hub-on-respawn: false
# If true, players will be respawned at the Hub. If false, players will be respawned at their world's spawn. respawn-handler must be true.
respawn-handler: true
# If true, HubThat will handle respawns.
world-related-chat: false
# If true, chat will be available to players whose world have the same spawn.
hub:
delay: 5
# Teleport delay in seconds.
ONLY_PLAYERS: '&cOnly players can go to the hub!'
# When /hub has ran in console.
HUB_NOT_SET: '&cThe hub is not set.'
# When anyone tries to use /hub but the hub is not set.
DELAY_TEXT_WAIT: '&aWait&6 %sec% &asecond(s).'
# The waiting message.
TELEPORTED: '&aYou have been teleported to the hub.'
# When /hub is used succesfully.
NO_PERMISSIONS: '&cYou do not have permissions for this command.'
# When anyone hasn't permissions for the /hub command.
sethub:
ONLY_PLAYERS: '&cOnly players can set the hub!'
# When /sethub has ran in console.
SET_ERROR: '&cSomething went wrong when setting the hub.'
# When there is an error when setting the Hub.
HUB_SUCCESS_1: '&aHub set succesfully in world &6%world%&a.'
# When the hub has set succesfully.
NO_PERMISSIONS: '&cYou do not have permissions for this command.'
# When anyone hasn't permissions for the /sethub command.
spawn:
delay: 5
# Teleport delay in seconds.
outdated-spawn: '&cWARNING: This spawn is outdated. Update it by typing /setspawn.'
# When the spawn is made with a different/uncompatible version of HubThat.
ONLY_PLAYERS: '&cOnly players can go to the spawn!'
# When /spawn has ran in console.
NO_PERMISSIONS: '&cYou do not have permissions for this command.'
# When anyone hasn't permissions for the /spawn command.
SPAWN_NOT_SET: '&cThe spawn is not set.'
# When the spawn is not set.
DELAY_TEXT_WAIT: '&aWait&6 %sec% &asecond(s).'
# The waiting message.
TELEPORTED: '&aYou have been teleported to the spawn.'
# When /spawn is used succesfully.
setspawn:
ONLY_PLAYERS: '&cOnly players can set the spawn!'
# When /setspawn has ran in console.
SPAWN_SUCCESS_1: '&aSpawn set succesfully in world&6 %world%&a.'
# When the Spawn was set succesfully.
NO_PERMISSIONS: '&cYou do not have permissions for this command.'
# When anyone hasn't permissions for the /setspawn command.
SET_ERROR: '&cSomething went wrong when setting the spawn.'
# When there is an error when setting the Spawn.
worldtp:
ONLY_PLAYERS: '&cOnly players can teleport!'
# When /worldtp has ran in console.
NO_PERMISSIONS: '&cYou do not have permissions for this command.'
# When anyone hasn't permissions for the /worldtp command.
NEEDED_ARGS: '&cWrite the world''s name!'
# When the command has no args.
UNKNOWN_WORLD: '&cThat world does not exist!'
# When the world is not existing.
TELEPORTED: '&aYou have been teleported to&6 %world%&a!'
# When teleported succesfully in a world.
worldlist:
NO_PERMISSIONS: '&cYou do not have permissions for this command.'
# When anyone hasn't permissions for the /worldlist command.
updates:
update-notify: true
# Do you want to be warned when the plugin has an update? [RECCOMENDED: TRUE]

42
plugin.yml Normal file
View File

@ -0,0 +1,42 @@
name: HubThat
version: 8.0
author: mind_overflow
main: net.mindoverflow.hubthat.Main
commands:
hubthat:
description: Main Command for HubThat.
setspawn:
description: Set the spawn for a world at your location.
spawn:
description: Go to current world's Spawn
sethub:
description: Set the Hub of the Server.
hub:
description: Go to the Hub of the Server.
worldtp:
description: Go to a specific World.
worldlist:
description: List all the Worlds.
permissions:
hubthat.spawn:
default: true
hubthat.hub:
default: true
hubthat.setspawn:
default: op
hubthat.sethub:
default: op
hubthat.nospawndelay:
default: op
hubthat.nohubdelay:
default: op
hubthat.gotoworld:
default: op
hubthat.listworlds:
default: op
hubthat.updates:
default: op
hubthat.reloadconfig:
default: op

36
pom.xml Normal file
View File

@ -0,0 +1,36 @@
<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>HubThat</groupId>
<artifactId>HubThat</artifactId>
<name>HubThat</name>
<description>HubThat</description>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<version>8.0-RELEASE</version>
</project>

View File

@ -0,0 +1,52 @@
package net.mindoverflow.hubthat;
import org.bukkit.Bukkit;
public class BukkitVersionChecker {
public Main plugin;
public BukkitVersionChecker (Main plugin){
this.plugin = plugin;
}
public static int getFirstNum() {
String mcVersion = Bukkit.getVersion().substring(Bukkit.getVersion().indexOf("(")+1,Bukkit.getVersion().indexOf(")"));
String firstNum = mcVersion.substring(mcVersion.indexOf(" ")+1,mcVersion.indexOf("."));
return Integer.parseInt(firstNum);
}
public static int getSecondNum() {
String mcVersion = Bukkit.getVersion().substring(Bukkit.getVersion().indexOf("(")+1,Bukkit.getVersion().indexOf(")"));
String secondNum = mcVersion.substring(mcVersion.indexOf(".")+1, mcVersion.lastIndexOf("."));
return Integer.parseInt(secondNum);
}
public static boolean isLowerThan(int first, int second)
{
if (getFirstNum() == first) {
if (getSecondNum() < second) return true;
return false;
}
if (getFirstNum() < first) return true;
return false;
}
public static boolean isHigherThan(int first, int second)
{
if (getFirstNum() == first) {
if (getSecondNum() > second) return true;
return false;
}
if (getFirstNum() > first) return true;
return false;
}
public static boolean isVersion(int first, int second)
{
if (getFirstNum() == first && getSecondNum() == second) return true;
return false;
}
}

View File

@ -0,0 +1,60 @@
package net.mindoverflow.hubthat;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.md_5.bungee.api.ChatColor;
public class CommandGotoWorld implements CommandExecutor {
public Main plugin;
public CommandGotoWorld(Main plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args) {
if(CommandLabel.equalsIgnoreCase("worldtp")) {
if(!(sender instanceof Player)) {
String ONLY_PLAYERS = plugin.getConfig().getString("worldtp.ONLY_PLAYERS").replace("&", "<EFBFBD>");
sender.sendMessage(ONLY_PLAYERS);
return true;
}
Player player = (Player)sender;
if(sender.hasPermission(new permission().GotoWorld)) {
if(args.length == 0) {
String nargs = plugin.getConfig().getString("worldtp.NEEDED_ARGS").replace("&", "<EFBFBD>");
sender.sendMessage(nargs);
return true;
} else {
World ww = Bukkit.getWorld(args[0]);
if(Bukkit.getWorlds().contains(ww)) {
Location loc = new Location(ww, ww.getSpawnLocation().getX(), ww.getSpawnLocation().getY(), ww.getSpawnLocation().getZ());
player.teleport(loc);
String tported = plugin.getConfig().getString("worldtp.TELEPORTED").replace("%world%", args[0]).replace("&", "<EFBFBD>");
sender.sendMessage(tported);
return true;
} else {
String nworld = plugin.getConfig().getString("worldtp.UNKNOWN_WORLD").replace("&", "<EFBFBD>");
sender.sendMessage(nworld);
return true;
}
}
} else {
String noperm = plugin.getConfig().getString("worldtp.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
sender.sendMessage(PREFIX + ChatColor.RED + noperm);
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,110 @@
package net.mindoverflow.hubthat;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
public class CommandHub implements CommandExecutor, Listener {
YamlConfiguration s;
private Main plugin;
public CommandHub(Main plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args){
if(!(sender instanceof Player)) {
String onlyplayers = plugin.getConfig().getString("hub.ONLY_PLAYERS").replace("&", "<EFBFBD>");
sender.sendMessage(ChatColor.DARK_RED + onlyplayers);
return true;
}
final Player player = (Player) sender;
if(!Main.tporting.containsKey(player.getName())) {
Main.tporting.put(player.getName(), false);
}
if(CommandLabel.equalsIgnoreCase("hub")) {
if(sender.hasPermission(new permission().Hub)){
File hub = new File(plugin.getDataFolder() + File.separator + "hub.yml");
if(!hub.exists()){
String not_set = plugin.getConfig().getString("hub.HUB_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + not_set);
return true;
} if (!sender.hasPermission(new permission().HubDelayBypass)){
if(Main.tporting.get(player.getName())){
String ALREADY_TP = plugin.getConfig().getString("global.ALREADY-TELEPORTING").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ALREADY_TP);
return true;
} else {
Main.tporting.put(player.getName(), true);
}
Long hubdelay = plugin.getConfig().getLong("hub.delay") * 20;
String hubdelaytextwait = plugin.getConfig().getString("hub.DELAY_TEXT_WAIT").replace("%sec%", hubdelay / 20 + "").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + hubdelaytextwait);
s = YamlConfiguration.loadConfiguration(hub);
String world = s.getString("hub.world");
double x = s.getDouble("hub.x");
double y = s.getDouble("hub.y");
double z = s.getDouble("hub.z");
final double yaw = s.getDouble("hub.yaw");
final double pitch = s.getDouble("hub.pitch");
final Location loc = new Location(Bukkit.getWorld(world), x, y, z);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
if(Main.tporting.get(player.getName())){
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
player.teleport(loc);
String hubteleported = plugin.getConfig().getString("hub.TELEPORTED").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + hubteleported);
Main.tporting.put(player.getName(), false);
}
}
}, hubdelay);
} else if (sender.hasPermission(new permission().HubDelayBypass)){
s = YamlConfiguration.loadConfiguration(hub);
String world = s.getString("hub.world");
double x = this.s.getDouble("hub.x");
double y = this.s.getDouble("hub.y");
double z = this.s.getDouble("hub.z");
final double yaw = this.s.getDouble("hub.yaw");
final double pitch = this.s.getDouble("hub.pitch");
final Location loc = new Location(Bukkit.getWorld(world), x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
player.teleport(loc);
String hubteleported = plugin.getConfig().getString("hub.TELEPORTED").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + hubteleported);
}
}else{
String hubnoperm = plugin.getConfig().getString("hub.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + hubnoperm);
}
}
return false;
}
}

View File

@ -0,0 +1,43 @@
package net.mindoverflow.hubthat;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import net.md_5.bungee.api.ChatColor;
public class CommandListWorlds implements CommandExecutor {
public Main plugin;
public CommandListWorlds (Main plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args) {
if(CommandLabel.equalsIgnoreCase("worldlist")) {
if(sender.hasPermission(new permission().ListWorlds)) {
sender.sendMessage("<EFBFBD>3Worlds List:");
sender.sendMessage("<EFBFBD>7---------");
int wn = 0;
for (World ww : Bukkit.getWorlds()) {
++wn;
sender.sendMessage("<EFBFBD>3" + wn + "<EFBFBD>7: <20>6" + ww.getName() + "<EFBFBD>7, <20>8" + ww.getWorldType().toString().toLowerCase());
}
wn = 0;
sender.sendMessage("<EFBFBD>7---------");
return true;
} else {
String noperm = plugin.getConfig().getString("worldlist.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
sender.sendMessage(PREFIX + ChatColor.RED + noperm);
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,80 @@
package net.mindoverflow.hubthat;
import java.io.File;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
public class CommandSetHub implements CommandExecutor{
public Main plugin;
YamlConfiguration s;
public CommandSetHub(Main plugin){
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args){
if(!(sender instanceof Player)){
String ONLY_PLAYERS = plugin.getConfig().getString("sethub.ONLY_PLAYERS").replace("&", "<EFBFBD>");
sender.sendMessage(ChatColor.DARK_RED + ONLY_PLAYERS);
return true;
}
Player player = (Player) sender;
if(CommandLabel.equalsIgnoreCase("sethub"))
{if(sender.hasPermission(new permission().SetHub))
{
File hub = new File(plugin.getDataFolder() + File.separator + "hub.yml");
if(!hub.exists())
{try{
hub.createNewFile();
}catch(Exception e){
e.printStackTrace();
String SET_ERROR = plugin.getConfig().getString("sethub.SET_ERROR").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + SET_ERROR);
return true;
}
}
s = YamlConfiguration.loadConfiguration(hub);
s.set("hub.world", player.getLocation().getWorld().getName());
s.set("hub.x", player.getLocation().getX());
s.set("hub.y", player.getLocation().getY());
s.set("hub.z", player.getLocation().getZ());
s.set("hub.yaw", player.getLocation().getYaw());
s.set("hub.pitch", player.getLocation().getPitch());
try{
s.save(hub);
}catch (Exception e){
String SET_ERROR = plugin.getConfig().getString("sethub.SET_ERROR").replace("&", "<EFBFBD>");
player.sendMessage(ChatColor.RED + SET_ERROR);
return true;
}
String HUB_SUCCESS = plugin.getConfig().getString("sethub.HUB_SUCCESS_1").replace("%world%", player.getLocation().getWorld().getName()).replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + HUB_SUCCESS);
}else{
String NO_PERMISSIONS = plugin.getConfig().getString("sethub.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + NO_PERMISSIONS);
}
}
return false;
}
}

View File

@ -0,0 +1,158 @@
package net.mindoverflow.hubthat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
public class CommandSetSpawn implements CommandExecutor{
public Main plugin;
YamlConfiguration s;
public CommandSetSpawn(Main plugin){
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args){
if(!(sender instanceof Player)){
String ONLY_PLAYERS = plugin.getConfig().getString("setspawn.ONLY_PLAYERS").replace("&", "<EFBFBD>");
sender.sendMessage(ChatColor.DARK_RED + ONLY_PLAYERS);
return true;
}
Player player = (Player) sender;
if(CommandLabel.equalsIgnoreCase("setspawn")){
if(sender.hasPermission(new permission().SetSpawn)){
if(args.length == 0) {
File spawn = new File(plugin.getDataFolder() +File.separator + "spawn.yml");
if (!spawn.exists()) {
try {
spawn.createNewFile();
}
catch (Exception e)
{
e.printStackTrace();
String SET_ERROR = plugin.getConfig().getString("setspawn.SET_ERROR").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + SET_ERROR);
return true;
}
}
s = YamlConfiguration.loadConfiguration(spawn);
player.getWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
s.set("spawn.world." + player.getWorld().getName(), player.getWorld().getName());
s.set("spawn.x." + player.getWorld().getName(), player.getLocation().getX());
s.set("spawn.y." + player.getWorld().getName(), player.getLocation().getY());
s.set("spawn.z." + player.getWorld().getName(), player.getLocation().getZ());
s.set("spawn.yaw." + player.getWorld().getName(), Float.valueOf(player.getLocation().getYaw()));
s.set("spawn.pitch." + player.getWorld().getName(), Float.valueOf(player.getLocation().getPitch()));
s.set("spawn.version." + player.getWorld().getName(), Main.spawnversion);
File nome = new File(plugin.getDataFolder() +File.separator + "spawns" + File.separator + player.getWorld().getName());
File dir = new File(plugin.getDataFolder() +File.separator + "spawns");
if(!dir.exists())
{
dir.mkdir();
}
if (!nome.exists()) {
try {
nome.createNewFile();
} catch (IOException e) {
e.printStackTrace();
String SET_ERROR = plugin.getConfig().getString("setspawn.SET_ERROR").replace("&", "<EFBFBD>");
player.sendMessage(ChatColor.RED + SET_ERROR);
return true;
}
}
try {
s.save(spawn);
} catch (Exception e) {
String SET_ERROR = plugin.getConfig().getString("setspawn.SET_ERROR").replace("&", "<EFBFBD>");
player.sendMessage(ChatColor.RED + SET_ERROR);
return true;
}
player.getWorld().setSpawnLocation(player.getLocation().getBlockX(),
player.getLocation().getBlockY(), player.getLocation().getBlockZ());
String SPAWN_SUCCESS_1 = plugin.getConfig().getString("setspawn.SPAWN_SUCCESS_1").replace("%world%", player.getLocation().getWorld().getName()).replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + SPAWN_SUCCESS_1);
} else {
ArrayList<String> worlds = new ArrayList<String>();
for (World ww : Bukkit.getWorlds()) {
worlds.add(ww.getName());
}
if(worlds.contains(args[0])) {
File spawn = new File(plugin.getDataFolder() +File.separator + "spawn.yml");
if (!spawn.exists()) {
try {
spawn.createNewFile();
}
catch (Exception e)
{
e.printStackTrace();
String SET_ERROR = plugin.getConfig().getString("setspawn.SET_ERROR").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + SET_ERROR);
return true;
}
}
s = YamlConfiguration.loadConfiguration(spawn);
s.set("spawn.world." + args[0], player.getWorld().getName());
s.set("spawn.x." + args[0], player.getLocation().getX());
s.set("spawn.y." + args[0], player.getLocation().getY());
s.set("spawn.z." + args[0], player.getLocation().getZ());
s.set("spawn.yaw." + args[0], Float.valueOf(player.getLocation().getYaw()));
s.set("spawn.pitch." + args[0], Float.valueOf(player.getLocation().getPitch()));
s.set("spawn.version." + args[0], Main.spawnversion);
File nome = new File(plugin.getDataFolder() +File.separator + "spawns" + File.separator + args[0]);
if (!nome.exists()) {
try {
nome.createNewFile();
} catch (IOException e) {
e.printStackTrace();
String SET_ERROR = plugin.getConfig().getString("setspawn.SET_ERROR").replace("&", "<EFBFBD>");
player.sendMessage(ChatColor.RED + SET_ERROR);
return true;
}
}
try {
s.save(spawn);
} catch (Exception e) {
String SET_ERROR = plugin.getConfig().getString("setspawn.SET_ERROR").replace("&", "<EFBFBD>");
player.sendMessage(ChatColor.RED + SET_ERROR);
return true;
}
Bukkit.getWorld(args[0]).setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
String SPAWN_SUCCESS_1 = plugin.getConfig().getString("setspawn.SPAWN_SUCCESS_1").replace("%world%", args[0]).replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + SPAWN_SUCCESS_1);
}
worlds.clear();
}
}else{
String NO_PERMISSIONS = plugin.getConfig().getString("setspawn.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + NO_PERMISSIONS);
}
}
return false;
}
}

Binary file not shown.

View File

@ -0,0 +1,163 @@
package net.mindoverflow.hubthat;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
public class CommandSpawn implements CommandExecutor{
public static Main plugin;
@SuppressWarnings("static-access")
public CommandSpawn(Main plugin){
this.plugin = plugin;
}
YamlConfiguration s;
static int id = -1;
@Override
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args){
if(!(sender instanceof Player)){
String ONLY_PLAYERS = plugin.getConfig().getString("spawn.ONLY_PLAYERS").replace("&", "<EFBFBD>");
sender.sendMessage(ChatColor.DARK_RED + ONLY_PLAYERS);
return true;
}
File spawn = new File(plugin.getDataFolder() + File.separator + "spawn.yml");
final Player player = (Player) sender;
if (args.length == 1) {
if(Bukkit.getWorld(args[0]) == null) {
sender.sendMessage("<EFBFBD>cError! World does not exist or is not loaded.");
} else {
s = YamlConfiguration.loadConfiguration(spawn);
File nome = new File (plugin.getDataFolder() + File.separator + "spawns" + File.separator + args[0]);
if(!(nome.exists())){
String NOTSET = plugin.getConfig().getString("spawn.SPAWN_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + NOTSET);
} else if (nome.exists()){
final double yaw = s.getDouble("spawn.yaw." + args[0]);
final double pitch = s.getDouble("spawn.pitch." + args[0]);
World world = Bukkit.getWorld(s.getString("spawn.world." + args[0]));
double x = s.getDouble("spawn.x." + args[0]);
double y = s.getDouble("spawn.y." + args[0]);
double z = s.getDouble("spawn.z." + args[0]);
final Location loc = new Location(world, x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
player.teleport(loc);
String TELEPORTED = plugin.getConfig().getString("spawn.TELEPORTED");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + TELEPORTED.replace("&", "<EFBFBD>"));
}
}
} else {
if(!Main.tporting.containsKey(player.getName())) {
Main.tporting.put(player.getName(), false);
}
if(CommandLabel.equalsIgnoreCase("spawn")){
if(sender.hasPermission(new permission().Spawn)){
if(!spawn.exists()){
String SPAWN_NOT_SET = plugin.getConfig().getString("spawn.SPAWN_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + SPAWN_NOT_SET);
return true;
}
if(!sender.hasPermission(new permission().SpawnDelayBypass)){
s = YamlConfiguration.loadConfiguration(spawn);
File nome = new File (plugin.getDataFolder() + File.separator + "spawns" + File.separator + player.getWorld().getName());
if(!(nome.exists())){
String NOTSET = plugin.getConfig().getString("spawn.SPAWN_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + NOTSET);
} else if (nome.exists()){
Long spawndelay = plugin.getConfig().getLong("spawn.delay") * 20;
String DELAY_TEXT_WAIT = plugin.getConfig().getString("spawn.DELAY_TEXT_WAIT").replace("%sec%", spawndelay / 20 + "").replace("&", "<EFBFBD>");
if(Main.tporting.get(player.getName())){
String ALREADY_TP = plugin.getConfig().getString("global.ALREADY-TELEPORTING").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ALREADY_TP);
return true;
} else {
Main.tporting.put(player.getName(), true);
}
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + DELAY_TEXT_WAIT);
id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
if(Main.tporting.get(player.getName())){
final double yaw = s.getDouble("spawn.yaw." + player.getWorld().getName());
final double pitch = s.getDouble("spawn.pitch." + player.getWorld().getName());
World world = Bukkit.getWorld(s.getString("spawn.world." + player.getWorld().getName()));
double x = s.getDouble("spawn.x." + player.getWorld().getName());
double y = s.getDouble("spawn.y." + player.getWorld().getName());
double z = s.getDouble("spawn.z." + player.getWorld().getName());
final Location loc = new Location(world, x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
player.teleport(loc);
String TELEPORTED = plugin.getConfig().getString("spawn.TELEPORTED");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + TELEPORTED.replace("&", "<EFBFBD>"));
Main.tporting.put(player.getName(), false);
}
}
}, spawndelay);
}
} else if(sender.hasPermission(new permission().SpawnDelayBypass)){
s = YamlConfiguration.loadConfiguration(spawn);
File nome = new File (plugin.getDataFolder() + File.separator + "spawns" + File.separator + player.getWorld().getName());
if(!(nome.exists())){
String NOTSET = plugin.getConfig().getString("spawn.SPAWN_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + NOTSET);
} else if (nome.exists()){
final double yaw = s.getDouble("spawn.yaw." + player.getWorld().getName());
final double pitch = s.getDouble("spawn.pitch." + player.getWorld().getName());
World world = Bukkit.getWorld(s.getString("spawn.world." + player.getWorld().getName()));
double x = s.getDouble("spawn.x." + player.getWorld().getName());
double y = s.getDouble("spawn.y." + player.getWorld().getName());
double z = s.getDouble("spawn.z." + player.getWorld().getName());
final Location loc = new Location(world, x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
player.teleport(loc);
String TELEPORTED = plugin.getConfig().getString("spawn.TELEPORTED");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + TELEPORTED.replace("&", "<EFBFBD>"));
}
}
}else{
String NO_PERMISSIONS = plugin.getConfig().getString("spawn.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = plugin.getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + NO_PERMISSIONS);
}
}
}
return false;
}
public static void cancelSpawnTask() {
if(id != -1) {
plugin.getServer().getScheduler().cancelTask(id);
}
}
}

Binary file not shown.

View File

@ -0,0 +1,641 @@
package net.mindoverflow.hubthat;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener
{
public static HashMap <String, Boolean> tporting = new HashMap <String, Boolean> ();
public static HashMap <String, String> worldrespawn = new HashMap <String, String> ();
public static Main plugin;
public static double spawnversion = 2.5;
public static double version = 8.0;
public final Logger logger = Logger.getLogger("Minecraft");
public UpdateChecker UpdateChecker;
protected Logger log;
public File sharesFile = new File(getDataFolder() + File.separator + "shares.yml");
public FileConfiguration shares = (YamlConfiguration.loadConfiguration(sharesFile));
File pluginfolder = new File(getDataFolder() + "");
File config = new File(getDataFolder() + File.separator + "config.yml");
File spawnsfolder = new File(getDataFolder() + File.separator + "spawns");
File hubFile = new File(getDataFolder() + File.separator + "hub.yml");
File spawnFile = new File(getDataFolder() + File.separator + "spawn.yml");
YamlConfiguration spawnYaml = YamlConfiguration.loadConfiguration(spawnFile);
YamlConfiguration hubYaml = YamlConfiguration.loadConfiguration(hubFile);
@SuppressWarnings("static-access")
@Override
public void onEnable()
{
if (!pluginfolder.exists())
{
pluginfolder.mkdir();
}
if(!spawnsfolder.exists())
{
spawnsfolder.mkdir();
}
if(!config.exists())
{
saveDefaultConfig();
reloadConfig();
}
this.log = this.getLogger();
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new CommandHub(this), this);
CommandHub CommandHub = new CommandHub(this);
CommandSetHub CommandSetHub = new CommandSetHub(this);
CommandSetSpawn CommandSetSpawn = new CommandSetSpawn(this);
CommandSpawn CommandSpawn = new CommandSpawn(this);
CommandGotoWorld CommandGotoWorld = new CommandGotoWorld(this);
CommandListWorlds CommandListWorlds = new CommandListWorlds(this);
getCommand("hub").setExecutor(CommandHub);
getCommand("sethub").setExecutor(CommandSetHub);
getCommand("setspawn").setExecutor(CommandSetSpawn);
getCommand("spawn").setExecutor(CommandSpawn);
getCommand("worldtp").setExecutor(CommandGotoWorld);
getCommand("worldlist").setExecutor(CommandListWorlds);
if(this.getConfig().getBoolean("updates.update-notify"))
{
UpdateChecker = new UpdateChecker(this);
try
{
if(UpdateChecker.linksValid())
{
if(UpdateChecker.updateNeeded())
{
new UpdatesTimer(this).runTaskTimer(this, 0 * 20L, 5 * 60 * 20L);
log.info(ChatColor.GRAY + "A new version is out: " + ChatColor.GOLD + UpdateChecker.getVersion() + ChatColor.GRAY + "!");
log.info(ChatColor.GRAY + "Download: " + ChatColor.GOLD + UpdateChecker.getLink());
log.info(UpdateChecker.updateText());
try
{
if(UpdateChecker.linksValid())
{
if(UpdateChecker.warning() != "")
{
this.log.info(UpdateChecker.warning());
}
}
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
else
{
log.info(ChatColor.GRAY + "There's a " + ChatColor.RED + "Problem" + ChatColor.GRAY + " with the updates server.");
log.info(ChatColor.GRAY + "It may be in maintenance mode.");
log.info(ChatColor.GRAY + "Please check if there are new updates manually.");
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if (!this.getConfig().getBoolean("updates.update-notify"))
{
String PREFIX = getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
log.info(PREFIX + ChatColor.RED + "Update Checking Disabled!");
}
if(getConfig().getDouble("global.VERSION") < version)
{
getConfig().set("global.FIRSTRUN", false);
try
{
getConfig().save(config);
}
catch (IOException e)
{
e.printStackTrace();
}
reloadConfig();
}
if(getConfig().getDouble("global.VERSION") < 7.0)
{
getConfig().set("global.respawn-handler", true);
}
if(getConfig().getBoolean("global.FIRSTRUN") == false && getConfig().getDouble("global.VERSION") <= 4.1 || getConfig().getDouble("global.VERSION") == 6.0)
{
Bukkit.broadcastMessage(("&0[&6HT&0] &4WARNING: HUBTHAT CONFIGURATION UNCOMPATIBLE; DELETING!").replace("&", "<EFBFBD>"));
config.delete();
Bukkit.broadcastMessage(("&0[&6HT&0] &4WARNING: HUBTHAT CONFIGURATION DELETED; CREATING A NEW ONE!").replace("&", "<EFBFBD>"));
saveDefaultConfig();
getConfig().set("global.FIRSTRUN", false);
Bukkit.broadcastMessage(("&0[&6HT&0] &4WARNING: HUBTHAT CONFIGURATION CREATED; RELOADING CONFIG!").replace("&", "<EFBFBD>"));
reloadConfig();
}
if(getConfig().getDouble("global.VERSION") <= 6.5)
{
getConfig().set("global.tp-hub-on-join", true);
getConfig().set("global.tp-hub-on-respawn", false);
try
{
getConfig().save(config);
}
catch (IOException e)
{
e.printStackTrace();
}
}
if(getConfig().getDouble("global.VERSION") <= 7.3)
{
getConfig().set("global.set-gamemode-on-join", true);
getConfig().set("global.gamemode", 0);
getConfig().set("global.world-related-chat", true);
try
{
getConfig().save(config);
}
catch (IOException e)
{
e.printStackTrace();
}
}
if(getConfig().getDouble("global.VERSION") != version)
{
getConfig().set("global.VERSION", version);
try
{
getConfig().save(config);
}
catch (IOException e)
{
e.printStackTrace();
}
}
reloadConfig();
Metrics metrics = new Metrics(this);
metrics.addCustomChart(new Metrics.SimplePie("respawn-handler", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("global.respawn-handler");
}
}));
metrics.addCustomChart(new Metrics.SimplePie("world-related-chat", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("global.world-related-chat");
}
}));
metrics.addCustomChart(new Metrics.SimplePie("update-notify", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("updates.update-notify");
}
}));
metrics.addCustomChart(new Metrics.SimplePie("set-gamemode-on-join", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("global.set-gamemode-on-join");
}
}));
metrics.addCustomChart(new Metrics.SimplePie("tp-hub-on-join", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("global.tp-hub-on-join");
}
}));
metrics.addCustomChart(new Metrics.SimplePie("tp-hub-on-respawn", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("global.tp-hub-on-respawn");
}
}));
if(getConfig().getBoolean("global.set-gamemode-on-join"))
{
metrics.addCustomChart(new Metrics.SimplePie("join-gamemode", new java.util.concurrent.Callable<String>() {
@Override
public String call() throws Exception {
return getConfig().getString("global.gamemode");
}
}));
}
}
@SuppressWarnings("static-access")
@EventHandler
public void playerJoin(final PlayerJoinEvent e)
{
Player player = e.getPlayer();
tporting.put(player.getName(), false);
if(player.getName().equalsIgnoreCase("lol7344") || player.getName().equalsIgnoreCase("mind_overflow") || player.getUniqueId().equals(UUID.fromString("297a1dc8-c0a3-485a-ad21-8956c749f927")))
{
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
player.sendMessage(("&0[&6HT&0]<5D>7 This server is running <20>3HubThat&7 v.&3" + version + "&7!").replace("&", "<EFBFBD>"));
}
}, 1000);
}
if(hubFile.exists())
{
if(this.getConfig().getBoolean("global.tp-hub-on-join"))
{
String world = hubYaml.getString("hub.world");;
double x = hubYaml.getDouble("hub.x");
double y = hubYaml.getDouble("hub.y");
double z = hubYaml.getDouble("hub.z");
final double yaw = hubYaml.getDouble("hub.yaw");
final double pitch = hubYaml.getDouble("hub.pitch");
final Location loc = new Location(Bukkit.getWorld(world), x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
player.teleport(loc);
}
}
else
{
if(this.getConfig().getBoolean("global.tp-hub-on-join"))
{
String not_set = getConfig().getString("hub.HUB_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.RED + not_set);
}
}
if(this.getConfig().getBoolean("global.set-gamemode-on-join"))
{
int gamemode = this.getConfig().getInt("global.gamemode");
if(gamemode == 0)
{
setGamemode(player, GameMode.SURVIVAL);
} else if (gamemode == 1)
{
setGamemode(player, GameMode.CREATIVE);
} else if (gamemode == 2)
{
setGamemode(player, GameMode.ADVENTURE);
} else if (gamemode == 3)
{
if(BukkitVersionChecker.isHigherThan(1, 7))
{
setGamemode(player, GameMode.SPECTATOR);
} else {
player.sendMessage(ChatColor.RED + "Spectator mode was not available in Minecraft 1.7 and lower!");
}
} else
{
player.sendMessage(ChatColor.RED + "Invalid HubThat join gamemode! Please contact an admin or check config file.");
}
}
if(this.getConfig().getBoolean("updates.update-notify"))
{
if(player.isOp() || player.hasPermission(new permission().SeeUpdates))
{
if(UpdateChecker.linksValid())
{
if(UpdatesTimer.updateNeeded)
{
Timer timer = new Timer();
final String tversion = UpdatesTimer.tversion;
final String tlink = UpdatesTimer.tlink;
final String text = UpdatesTimer.text;
timer.schedule(new TimerTask()
{
public void run()
{
e.getPlayer().sendMessage(ChatColor.GRAY + "" + ChatColor.STRIKETHROUGH + "-----[" + ChatColor.RESET + "" + ChatColor.DARK_AQUA + " HubThat Updater " + ChatColor.GRAY + "" + ChatColor.STRIKETHROUGH + "]-----" + ChatColor.RESET);
e.getPlayer().sendMessage(ChatColor.GRAY + "A new version is out: " + ChatColor.GOLD + tversion + ChatColor.GRAY + "!");
e.getPlayer().sendMessage(ChatColor.GRAY + "Download: " + ChatColor.GOLD + tlink);
if(text != "") {e.getPlayer().sendMessage(text);}
}
}, 200);
}
}
else
{
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
e.getPlayer().sendMessage(ChatColor.GRAY + "" + ChatColor.STRIKETHROUGH + "-----[" + ChatColor.RESET + "" + ChatColor.DARK_AQUA + " HubThat Updater " + ChatColor.GRAY + "" + ChatColor.STRIKETHROUGH + "]-----" + ChatColor.RESET);
e.getPlayer().sendMessage(ChatColor.GRAY + "There's a " + ChatColor.RED + "Problem" + ChatColor.GRAY + " with the updates server.");
e.getPlayer().sendMessage(ChatColor.GRAY + "It may be in maintenance mode.");
e.getPlayer().sendMessage(ChatColor.GRAY + "Please check if the plugin is updated manually.");
e.getPlayer().sendMessage(ChatColor.GRAY + "Check console logs for details.");
}
}, 200);
}
}
}
if(e.getPlayer().isOp() || player.hasPermission(new permission().SeeUpdates))
{
final String warning = UpdatesTimer.warning;
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
if(warning != "") {e.getPlayer().sendMessage(warning);}
}
}, 300);
}
return;
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e)
{
final Player player = e.getPlayer();
if(tporting.containsKey(player.getName()))
{
tporting.remove(player.getName());
}
if(worldrespawn.containsKey(player.getName()))
{
worldrespawn.remove(player.getName());
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent e)
{
Player player = e.getPlayer();
if(!tporting.containsKey(player.getName()))
{
tporting.put(player.getName(), false);
}
if(tporting.get(player.getName()))
{
if(getConfig().getBoolean("global.move-detect"))
{
if(e.getFrom().getBlockX() != e.getTo().getBlockX() || e.getFrom().getBlockY() != e.getTo().getBlockY() || e.getFrom().getBlockZ() != e.getTo().getBlockZ())
{
String PREFIX = getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
String MOVED = this.getConfig().getString("global.MOVED");
player.sendMessage(PREFIX + MOVED.replace("&", "<EFBFBD>"));
tporting.put(player.getName(), false);
CommandSpawn.cancelSpawnTask();
}
}
}
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args){
if(!(sender instanceof Player))
{
if (command.getName().equalsIgnoreCase("hubthat"))
{
if(args.length == 1 && args[0].equalsIgnoreCase("reload"))
{
reloadConfig();
spawnYaml = YamlConfiguration.loadConfiguration(spawnFile);
if(this.getConfig().getBoolean("updates.update-notify"))
{
UpdateChecker = new UpdateChecker(this);
}
this.log.info(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "HubThat configuration reloaded!");
return true;
}
else if (args.length == 1 && args[0].equalsIgnoreCase("help"))
{
this.log.info(ChatColor.DARK_GRAY + "---------" + ChatColor.BLACK + "[" + ChatColor.GOLD + "HubThat Help Page" + ChatColor.BLACK + "]" + ChatColor.DARK_GRAY + "---------");
this.log.info(ChatColor.GOLD + "/hubthat" + ChatColor.GRAY + ": show HubThat info");
this.log.info(ChatColor.GOLD + "/hubthat help" + ChatColor.GRAY + ": show this page");
this.log.info(ChatColor.GOLD + "/hubthat reload" + ChatColor.GRAY + ": reload the config - " + ChatColor.DARK_GRAY + "hubthat.reloadconfig");
this.log.info(ChatColor.GOLD + "/hub" + ChatColor.GRAY + ": teleport to the Hub - " + ChatColor.DARK_GRAY + "hubthat.hub");
this.log.info(ChatColor.GOLD + "/spawn" + ChatColor.GRAY + ": teleport to current world's Spawn - " + ChatColor.DARK_GRAY + "hubthat.spawn");
this.log.info(ChatColor.GOLD + "/sethub" + ChatColor.GRAY + ": set server's Hub - " + ChatColor.DARK_GRAY + "hubthat.sethub");
this.log.info(ChatColor.GOLD + "/setspawn" + ChatColor.GRAY + ": set current world's Spawn - " + ChatColor.DARK_GRAY + "hubthat.setspawn");
this.log.info(ChatColor.GOLD + "/worldlist" + ChatColor.GRAY + ": list all the worlds - " + ChatColor.DARK_GRAY + "hubthat.listworlds");
this.log.info(ChatColor.GOLD + "/worldtp <world>" + ChatColor.GRAY + ": teleport to a world - " + ChatColor.DARK_GRAY + "hubthat.gotoworld");
return true;
}
else
{
this.log.info(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "HubThat Version " + ChatColor.GOLD + version + ChatColor.GRAY + " for SpigotMC/CraftBukkit " + ChatColor.GOLD + "1.7" + ChatColor.GRAY + "-" + ChatColor.GOLD + "1.14" + ChatColor.GRAY + ".");
this.log.info(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "Coded by " + ChatColor.GOLD + "lol7344" + ChatColor.GRAY + ", all rights reserved. (" + ChatColor.GOLD + "Copyright" + ChatColor.GRAY + ").");
this.log.info(" ");
this.log.info(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "Write " + ChatColor.GOLD + "/hubthat help " + ChatColor.GRAY + "to see plugin commands.");
return true;
}
}
}
Player player = (Player)sender;
if (command.getName().equalsIgnoreCase("hubthat"))
{
if(args.length == 1 && args[0].equalsIgnoreCase("reload"))
{
if(player.hasPermission(new permission().ReloadConfig))
{
reloadConfig();
sender.sendMessage(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "HubThat configuration reloaded!");
return true;
}
else
{
String hubnoperm = getConfig().getString("worldlist.NO_PERMISSIONS").replace("&", "<EFBFBD>");
String PREFIX = getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
sender.sendMessage(PREFIX + ChatColor.RED + hubnoperm);
}
}
else if (args.length == 1 && args[0].equalsIgnoreCase("help"))
{
sender.sendMessage(ChatColor.DARK_GRAY + "---------" + ChatColor.BLACK + "[" + ChatColor.GOLD + "HubThat Help Page" + ChatColor.BLACK + "]" + ChatColor.DARK_GRAY + "---------");
sender.sendMessage(ChatColor.GOLD + "/hubthat" + ChatColor.GRAY + ": show HubThat info");
sender.sendMessage(ChatColor.GOLD + "/hubthat help" + ChatColor.GRAY + ": show this page");
sender.sendMessage(ChatColor.GOLD + "/hubthat reload" + ChatColor.GRAY + ": reload the config - " + ChatColor.DARK_GRAY + "hubthat.reloadconfig");
sender.sendMessage(ChatColor.GOLD + "/hub" + ChatColor.GRAY + ": teleport to the Hub - " + ChatColor.DARK_GRAY + "hubthat.hub");
sender.sendMessage(ChatColor.GOLD + "/spawn" + ChatColor.DARK_GRAY + " <world>" + ChatColor.GRAY + ": teleport to current/another world's Spawn - " + ChatColor.DARK_GRAY + "hubthat.spawn");
sender.sendMessage(ChatColor.GOLD + "/sethub" + ChatColor.GRAY + ": set server's Hub - " + ChatColor.DARK_GRAY + "hubthat.sethub");
sender.sendMessage(ChatColor.GOLD + "/setspawn" + ChatColor.DARK_GRAY + " <world>" + ChatColor.GRAY + ": set current/another world's Spawn - " + ChatColor.DARK_GRAY + "hubthat.setspawn");
sender.sendMessage(ChatColor.GOLD + "/worldlist" + ChatColor.GRAY + ": list all the worlds - " + ChatColor.DARK_GRAY + "hubthat.listworlds");
sender.sendMessage(ChatColor.GOLD + "/worldtp <world>" + ChatColor.GRAY + ": teleport to a world - " + ChatColor.DARK_GRAY + "hubthat.gotoworld");
return true;
}
else
{
sender.sendMessage(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "HubThat Version " + ChatColor.GOLD + version + ChatColor.GRAY + " for SpigotMC/CraftBukkit " + ChatColor.GOLD + "1.7" + ChatColor.GRAY + "-" + ChatColor.GOLD + "1.14" + ChatColor.GRAY + ".");
sender.sendMessage(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "Coded by " + ChatColor.GOLD + "mind_overflow" + ChatColor.GRAY + ", all rights reserved. (" + ChatColor.GOLD + "Copyright" + ChatColor.GRAY + ").");
sender.sendMessage(" ");
sender.sendMessage(ChatColor.BLACK + "[" + ChatColor.GOLD + "HT" + ChatColor.BLACK + "] " + ChatColor.GRAY + "Write " + ChatColor.GOLD + "/hubthat help " + ChatColor.GRAY + "to see plugin commands.");
return true;
}
}
return false;
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e)
{
Player sender = e.getPlayer();
if(getConfig().getBoolean("global.world-related-chat"))
{
String senderWorldSpawn = spawnYaml.getString("spawn.world." + sender.getWorld().getName(), "unset");
for (Player receiver : Bukkit.getOnlinePlayers())
{
String receiverWorldSpawn = spawnYaml.getString("spawn.world." + receiver.getWorld().getName(), "unset");
if (!senderWorldSpawn.equalsIgnoreCase(receiverWorldSpawn))
{
e.getRecipients().remove(receiver);
}
}
}
}
@EventHandler
public void onPlayerRespawn(final PlayerRespawnEvent e)
{
final Player player = e.getPlayer();
if(worldrespawn.containsKey(player.getName()))
{
if(getConfig().getBoolean("global.respawn-handler"))
{
if(getConfig().getBoolean("global.tp-hub-on-respawn"))
{
File hub = new File(getDataFolder() + File.separator + "hub.yml");
if(hub.exists())
{
YamlConfiguration s = YamlConfiguration.loadConfiguration(hub);
final double yaw = s.getDouble("hub.yaw");
final double pitch = s.getDouble("hub.pitch");
World world = Bukkit.getWorld(s.getString("hub.world"));
double x = s.getDouble("hub.x");
double y = s.getDouble("hub.y");
double z = s.getDouble("hub.z");
final Location loc = new Location(world, x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
Bukkit.getScheduler().runTaskLater(this, new Runnable()
{
public void run()
{
player.teleport(loc);
worldrespawn.remove(player.getName());
}
}, 10);
}
else
{
String NOTSET = getConfig().getString("spawn.SPAWN_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + NOTSET);
worldrespawn.remove(player.getName());
}
}
else
{
File nome = new File (getDataFolder() + File.separator + "spawns" + File.separator + player.getWorld().getName());
if(!(nome.exists()))
{
String NOTSET = getConfig().getString("spawn.SPAWN_NOT_SET").replace("&", "<EFBFBD>");
String PREFIX = getConfig().getString("global.PREFIX").replace("&", "<EFBFBD>");
player.sendMessage(PREFIX + ChatColor.GREEN + NOTSET);
worldrespawn.remove(player.getName());
}
else if (nome.exists())
{
final double yaw = spawnYaml.getDouble("spawn.yaw." + player.getWorld().getName());
final double pitch = spawnYaml.getDouble("spawn.pitch." + player.getWorld().getName());
World world = Bukkit.getWorld(spawnYaml.getString("spawn.world." + player.getWorld().getName()));
double x = spawnYaml.getDouble("spawn.x." + player.getWorld().getName());
double y = spawnYaml.getDouble("spawn.y." + player.getWorld().getName());
double z = spawnYaml.getDouble("spawn.z." + player.getWorld().getName());
final Location loc = new Location(world, x, y, z);
loc.setYaw((float)yaw);
loc.setPitch((float)pitch);
Bukkit.getScheduler().runTaskLater(this, new Runnable()
{
public void run()
{
player.teleport(loc);
worldrespawn.remove(player.getName());
}
}, 10);
}
}
}
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent e)
{
if (worldrespawn.containsKey(e.getEntity().getName()))
{
worldrespawn.remove(e.getEntity().getName());
}
worldrespawn.put(e.getEntity().getName(), e.getEntity().getWorld().getName());
}
public void setGamemode(Player p, GameMode g)
{
p.setGameMode(g);
Bukkit.getScheduler().runTaskLater(this, new Runnable()
{
@Override
public void run() {
p.setGameMode(g);
//"This is sketchy, but needed because of how popular Multiverse is.
}
}, 15);
}
public void reloadConfig()
{
super.reloadConfig();
}
}

View File

@ -0,0 +1,731 @@
package net.mindoverflow.hubthat;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HttpsURLConnection;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
public class Metrics {
static {
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests = false;
// Should the sent data be logged?
private static boolean logSentData = false;
// Should the response text be logged?
private static boolean logResponseStatusText = false;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets its unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
//config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
//config.addDefault("logSentData", false);
// Should the response text be logged?
//config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"All data is anonymous and this has practically no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
//logFailedRequests = config.getBoolean("logFailedRequests", false);
//logSentData = config.getBoolean("logSentData", false);
//logResponseStatusText = config.getBoolean("logResponseStatusText", false);
logFailedRequests = false;
logSentData = false;
logResponseStatusText = false;
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.add("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
}
continue; // continue looping since we cannot do any other thing.
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JsonObject getRequestJsonObject() {
JsonObject chart = new JsonObject();
chart.addProperty("chartId", chartId);
try {
JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.add("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JsonObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.add(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(entry.getValue());
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
}

View File

@ -0,0 +1,118 @@
package net.mindoverflow.hubthat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class UpdateChecker {
public static Main plugin;
public static String version;
public static String link;
public UpdateChecker (Main plugin){
UpdateChecker.plugin = plugin;
}
public boolean linksValid() {
try{
HttpsURLConnection.setFollowRedirects(true);
HttpsURLConnection con = (HttpsURLConnection) new URL("https://mind-overflow.tk/").openConnection();
con.setConnectTimeout(3000);
con.setReadTimeout(3000);
con.setRequestMethod("HEAD");
if(con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
final URL url1 = new URL("https://mind-overflow.tk/htuv");
HttpsURLConnection huc1 = (HttpsURLConnection) url1.openConnection();
int responseCode1 = huc1.getResponseCode();
final URL url2 = new URL("https://mind-overflow.tk/htlnk");
HttpsURLConnection huc2 = (HttpsURLConnection) url2.openConnection();
int responseCode2 = huc2.getResponseCode();
if (responseCode1 == 200 && responseCode2 == 200) {
return true;
} else {
System.out.println("HubThat Updates Server codes: " + responseCode1 + "; " + responseCode2);
return false;
}
} else {
System.out.println("HubThat Updates Server is unreachable. Check your Internet Connection and Firewall.");
return false;
}
} catch(IOException e){
e.printStackTrace();
System.out.println("HubThat Updates Server is unreachable. Check your Internet Connection and Firewall.");
return false;
}
}
public static String updateText() throws IOException {
URL htexturl = new URL("https://mind-overflow.tk/htext");
HttpsURLConnection htextconnection = (HttpsURLConnection) htexturl.openConnection();
int responseCode = htextconnection.getResponseCode();
if (responseCode == 200) {
String htext = getStringFromUrl("https://mind-overflow.tk/htext");
return htext;
} else
{
return "";
}
}
public static String warning() throws IOException {
String htwarningboolean = getStringFromUrl("https://mind-overflow.tk/htwarningboolean");
String htwarningtext = getStringFromUrl("https://mind-overflow.tk/htwarning");
if (htwarningboolean.contains("true"))
{
return htwarningtext;
} else
{
return "";
}
}
public static boolean updateNeeded() throws MalformedURLException, IOException{
version = getStringFromUrl("https://mind-overflow.tk/htuv");
link = getStringFromUrl("https://mind-overflow.tk/htlnk");
if(!plugin.getDescription().getVersion().equals(version)){
return true;
}
return false;
}
public static String getVersion(){
return version;
}
public static String getLink(){
return link;
}
static String getStringFromUrl(String urlString)
{
try {
URL url = new URL(urlString);
HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
InputStream connectionStream = httpsConnection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(connectionStream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
String text = bufferedReader.readLine();
connectionStream.close();
return text;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}

View File

@ -0,0 +1,37 @@
package net.mindoverflow.hubthat;
import java.io.IOException;
import org.bukkit.scheduler.BukkitRunnable;
public class UpdatesTimer extends BukkitRunnable {
public Main plugin;
public UpdatesTimer(Main plugin) {
this.plugin = plugin;
}
public static String tlink;
public static String tversion;
public static String text;
public static boolean updateNeeded;
public static String warning;
@Override
public void run() {
if(plugin.getConfig().getBoolean("updates.update-notify")){
try {
updateNeeded = UpdateChecker.updateNeeded();
tversion = UpdateChecker.getVersion();
tlink = UpdateChecker.getLink();
text = UpdateChecker.updateText();
warning = UpdateChecker.warning();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,29 @@
package net.mindoverflow.hubthat;
import org.bukkit.permissions.Permission;
public class permission {
public Permission Spawn;
public Permission SetSpawn;
public Permission SetHub;
public Permission Hub;
public Permission HubDelayBypass;
public Permission SpawnDelayBypass;
public Permission GotoWorld;
public Permission ListWorlds;
public Permission SeeUpdates;
public Permission ReloadConfig;
public permission()
{
Spawn = new Permission ("hubthat.spawn");
SetSpawn = new Permission ("hubthat.setspawn");
SetHub = new Permission ("hubthat.sethub");
Hub = new Permission ("hubthat.hub");
SpawnDelayBypass = new Permission ("hubthat.nospawndelay");
HubDelayBypass = new Permission ("hubthat.nohubdelay");
GotoWorld = new Permission ("hubthat.gotoworld");
ListWorlds = new Permission ("hubthat.listworlds");
SeeUpdates = new Permission ("hubthat.updates");
ReloadConfig = new Permission ("hubthat.reloadconfig");
}
}