Chroma-Chat/src/buttondevteam/thebuttonmcchat/PluginMain.java

388 lines
13 KiB
Java
Raw Normal View History

2016-07-04 22:29:12 +00:00
package buttondevteam.thebuttonmcchat;
2016-06-22 22:08:39 +00:00
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.apache.commons.io.IOUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.Scoreboard;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.json.JSONArray;
import org.json.JSONObject;
import au.com.mineauz.minigames.mechanics.GameMechanics;
2016-07-04 22:29:12 +00:00
import buttondevteam.thebuttonmcchat.commands.CommandCaller;
2016-06-22 22:08:39 +00:00
import com.palmergames.bukkit.towny.Towny;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownyUniverse;
import java.io.*;
import java.lang.String;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.TimeZone;
public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
// A user, which flair isn't obtainable:
// https://www.reddit.com/r/thebutton/comments/31c32v/i_pressed_the_button_without_really_thinking/
public static PluginMain Instance;
public static ConsoleCommandSender Console; // 2015.08.12.
public static Scoreboard SB;
public final static String FlairThreadURL = "https://www.reddit.com/r/TheButtonMinecraft/comments/433ptk/autoflair_thread/";
public TownyUniverse TU;
public ArrayList<Town> Towns;
public ArrayList<Nation> Nations;
// Fired when plugin is first enabled
@Override
public void onEnable() {
try {
PluginMain.Instance.getLogger().info("Extracting necessary libraries...");
2016-07-17 00:26:53 +00:00
final File[] libs = new File[] { new File(getDataFolder(), "htmlcleaner-2.16.jar"),
2016-06-25 00:02:38 +00:00
new File(getDataFolder(), "reflections-0.9.10.jar"),
new File(getDataFolder(), "javassist-3.19.0-GA.jar") };
2016-06-22 22:08:39 +00:00
for (final File lib : libs) {
if (!lib.exists()) {
2016-07-17 00:26:53 +00:00
JarUtils.extractFromJar(lib.getName(), lib.getAbsolutePath());
2016-06-22 22:08:39 +00:00
}
}
for (final File lib : libs) {
if (!lib.exists()) {
2016-07-17 00:26:53 +00:00
getLogger().warning("Failed to load plugin! Could not find lib: " + lib.getName());
2016-06-22 22:08:39 +00:00
Bukkit.getServer().getPluginManager().disablePlugin(this);
return;
}
addClassPath(JarUtils.getJarUrl(lib));
}
} catch (final Exception e) {
e.printStackTrace();
}
2016-07-17 00:26:53 +00:00
getServer().getPluginManager().registerEvents(new PlayerListener(), this);
CommandCaller.RegisterChatCommands(this);
2016-06-22 22:08:39 +00:00
Instance = this;
Console = this.getServer().getConsoleSender();
LoadFiles(false);
2016-07-17 00:26:53 +00:00
SB = PluginMain.Instance.getServer().getScoreboardManager().getMainScoreboard(); // Main
// can
// be
// detected
// with
// @a[score_...]
2016-06-22 22:08:39 +00:00
if (SB.getObjective("town") == null)
SB.registerNewObjective("town", "dummy");
if (SB.getObjective("nation") == null)
SB.registerNewObjective("nation", "dummy");
if (SB.getObjective("admin") == null)
SB.registerNewObjective("admin", "dummy");
if (SB.getObjective("mod") == null)
SB.registerNewObjective("mod", "dummy");
2016-07-17 00:26:53 +00:00
TU = ((Towny) Bukkit.getPluginManager().getPlugin("Towny")).getTownyUniverse();
2016-06-22 22:08:39 +00:00
Towns = new ArrayList<Town>(TU.getTownsMap().values());
Nations = new ArrayList<Nation>(TU.getNationsMap().values());
setupChat();
setupEconomy();
setupPermissions();
GameMechanics.addGameMechanic(new CreativeGlobalMechanic());
Runnable r = new Runnable() {
public void run() {
FlairGetterThreadMethod();
2016-06-22 22:08:39 +00:00
}
};
Thread t = new Thread(r);
t.start();
r = new Runnable() {
public void run() {
AnnouncerThread.Run();
}
};
t = new Thread(r);
t.start();
}
public Boolean stop = false;
// Fired when plugin is disabled
@Override
public void onDisable() {
SaveFiles(); // 2015.08.09.
stop = true;
}
private void FlairGetterThreadMethod() {
2016-06-22 22:08:39 +00:00
while (!stop) {
try {
2016-07-17 00:26:53 +00:00
String body = DownloadString(FlairThreadURL + ".json?limit=1000");
JSONArray json = new JSONArray(body).getJSONObject(1).getJSONObject("data").getJSONArray("children");
2016-06-22 22:08:39 +00:00
for (Object obj : json) {
JSONObject item = (JSONObject) obj;
2016-07-17 00:26:53 +00:00
String author = item.getJSONObject("data").getString("author");
2016-06-22 22:08:39 +00:00
String ign = item.getJSONObject("data").getString("body");
int start = ign.indexOf("IGN:") + "IGN:".length();
if (start == -1 + "IGN:".length())
continue;
2016-06-22 22:08:39 +00:00
int end = ign.indexOf(' ', start);
if (end == -1 || end == start)
end = ign.indexOf('\n', start);
2016-06-22 22:08:39 +00:00
if (end == -1 || end == start)
ign = ign.substring(start);
else
ign = ign.substring(start, end);
ign = ign.trim();
2016-07-16 21:55:36 +00:00
ChatPlayer mp = ChatPlayer.GetFromName(ign);
2016-06-22 22:08:39 +00:00
if (mp == null)
continue;
if (!JoinedBefore(mp, 2015, 6, 5))
continue;
if (!mp.UserNames.contains(author))
mp.UserNames.add(author);
if (mp.FlairState.equals(FlairStates.NoComment)) {
mp.FlairState = FlairStates.Commented;
ConfirmUserMessage(mp);
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
} catch (Exception e) {
LastException = e;
2016-06-22 22:08:39 +00:00
}
}
}
2016-07-17 00:26:53 +00:00
public void DownloadFlair(ChatPlayer mp) throws MalformedURLException, IOException {
String[] flairdata = DownloadString("http://karmadecay.com/thebutton-data.php?users=" + mp.UserName)
2016-06-22 22:08:39 +00:00
.replace("\"", "").split(":");
String flair;
if (flairdata.length > 1)
flair = flairdata[1];
else
flair = "";
String flairclass;
if (flairdata.length > 2)
flairclass = flairdata[2];
else
flairclass = "unknown";
SetFlair(mp, flair, flairclass, mp.UserName);
}
public static Exception LastException;
2016-06-22 22:08:39 +00:00
2016-07-17 00:26:53 +00:00
public String DownloadString(String urlstr) throws MalformedURLException, IOException {
2016-06-22 22:08:39 +00:00
URL url = new URL(urlstr);
URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", "TheButtonAutoFlair");
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
in.close();
return body;
}
2016-07-17 00:26:53 +00:00
private void SetFlair(ChatPlayer p, String text, String flairclass, String username) {
2016-06-22 22:08:39 +00:00
p.UserName = username;
p.FlairState = FlairStates.Recognised;
switch (flairclass) {
case "cheater":
p.SetFlair(Short.parseShort(text), true);
2016-06-22 22:08:39 +00:00
return;
case "unknown":
if (text.equals("-1")) // If true, only non-presser/can't press; if
// false, any flair (but we can still detect
// can't press)
{
try {
if (CheckForJoinDate(p)) {
2016-07-16 21:55:36 +00:00
p.SetFlair(ChatPlayer.FlairTimeNonPresser);
2016-06-22 22:08:39 +00:00
} else {
2016-07-16 21:55:36 +00:00
p.SetFlair(ChatPlayer.FlairTimeCantPress);
2016-06-22 22:08:39 +00:00
}
} catch (Exception e) {
p.FlairState = FlairStates.Commented; // Flair unknown
2016-07-16 21:55:36 +00:00
p.SetFlair(ChatPlayer.FlairTimeNone);
2016-06-22 22:08:39 +00:00
e.printStackTrace();
}
} else {
try {
if (CheckForJoinDate(p)) {
p.FlairState = FlairStates.Commented; // Flair unknown
2016-07-16 21:55:36 +00:00
p.SetFlair(ChatPlayer.FlairTimeNone);
2016-06-22 22:08:39 +00:00
} else {
2016-07-16 21:55:36 +00:00
p.SetFlair(ChatPlayer.FlairTimeCantPress);
2016-06-22 22:08:39 +00:00
}
} catch (Exception e) {
p.FlairState = FlairStates.Commented; // Flair unknown
2016-07-16 21:55:36 +00:00
p.SetFlair(ChatPlayer.FlairTimeNone);
2016-06-22 22:08:39 +00:00
e.printStackTrace();
}
}
return;
default:
break;
}
p.SetFlair(Short.parseShort(text));
}
2016-07-17 00:26:53 +00:00
public static boolean CheckForJoinDate(ChatPlayer mp) throws Exception {
2016-06-22 22:08:39 +00:00
return JoinedBefore(mp, 2015, 4, 1);
}
2016-07-17 00:26:53 +00:00
public static boolean JoinedBefore(ChatPlayer mp, int year, int month, int day) throws Exception {
2016-06-22 22:08:39 +00:00
URL url = new URL("https://www.reddit.com/u/" + mp.UserName);
URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", "TheButtonAutoFlair");
InputStream in = con.getInputStream();
HtmlCleaner cleaner = new HtmlCleaner();
TagNode node = cleaner.clean(in);
node = node.getElementsByAttValue("class", "age", true, true)[0];
node = node.getElementsByName("time", false)[0];
String joindate = node.getAttributeByName("datetime");
SimpleDateFormat parserSDF = new SimpleDateFormat("yyyy-MM-dd");
joindate = joindate.split("T")[0];
Date date = parserSDF.parse(joindate);
2016-07-17 00:26:53 +00:00
return date.before(new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("UTC")).setDate(year, month, day)
.build().getTime());
2016-06-22 22:08:39 +00:00
}
2016-07-16 21:55:36 +00:00
public static void ConfirmUserMessage(ChatPlayer mp) {
2016-06-22 22:08:39 +00:00
Player p = Bukkit.getPlayer(mp.UUID);
if (mp.FlairState.equals(FlairStates.Commented) && p != null)
if (mp.UserNames.size() > 1)
2016-07-17 00:26:53 +00:00
p.sendMessage(
"§9Multiple Reddit users commented your name. You can select with /u accept.§r §6Type /u accept or /u ignore§r");
2016-06-22 22:08:39 +00:00
else
p.sendMessage("§9A Reddit user commented your name. Is that you?§r §6Type /u accept or /u ignore§r");
}
public static Collection<? extends Player> GetPlayers() {
return Instance.getServer().getOnlinePlayers();
}
public static ArrayList<String> AnnounceMessages = new ArrayList<>();
public static int AnnounceTime = 15 * 60 * 1000;
public static void LoadFiles(boolean reload) {
if (reload) {
PluginMain.Instance.getLogger().info("Cleanup for reloading...");
2016-07-17 00:26:53 +00:00
ChatPlayer.OnlinePlayers.clear();
2016-06-22 22:08:39 +00:00
AnnounceMessages.clear();
}
PluginMain.Instance.getLogger().info("Loading files...");
2016-06-22 22:08:39 +00:00
try {
2016-07-17 00:26:53 +00:00
File file = new File("thebuttonmc.yml"); // TODO
2016-06-22 22:08:39 +00:00
if (file.exists()) {
YamlConfiguration yc = new YamlConfiguration();
yc.load(file);
2016-07-17 00:26:53 +00:00
PlayerListener.NotificationSound = yc.getString("notificationsound");
PlayerListener.NotificationPitch = yc.getDouble("notificationpitch");
AnnounceTime = yc.getInt("announcetime"); // TODO: Move out to
// the core
2016-06-22 22:08:39 +00:00
AnnounceMessages.addAll(yc.getStringList("announcements"));
PlayerListener.AlphaDeaths = yc.getInt("alphadeaths");
}
PluginMain.Instance.getLogger().info("Loaded files!");
2016-06-22 22:08:39 +00:00
} catch (IOException e) {
PluginMain.Instance.getLogger().warning("Error!\n" + e);
2016-06-22 22:08:39 +00:00
LastException = e;
} catch (InvalidConfigurationException e) {
PluginMain.Instance.getLogger().warning("Error!\n" + e);
2016-06-22 22:08:39 +00:00
LastException = e;
}
}
public static void SaveFiles() {
PluginMain.Instance.getLogger().info("Saving files...");
2016-06-22 22:08:39 +00:00
try {
File file = new File("thebuttonmc.yml");
YamlConfiguration yc = new YamlConfiguration();
yc.set("notificationsound", PlayerListener.NotificationSound);
yc.set("notificationpitch", PlayerListener.NotificationPitch);
2016-07-17 00:26:53 +00:00
yc.set("announcetime", AnnounceTime); // TODO: Move out to the core
2016-06-22 22:08:39 +00:00
yc.set("announcements", AnnounceMessages);
yc.set("alphadeaths", PlayerListener.AlphaDeaths);
yc.save(file);
PluginMain.Instance.getLogger().info("Saved files!");
2016-06-22 22:08:39 +00:00
} catch (IOException e) {
PluginMain.Instance.getLogger().warning("Error!\n" + e);
2016-06-22 22:08:39 +00:00
LastException = e;
}
}
private void addClassPath(final URL url) throws IOException {
2016-07-17 00:26:53 +00:00
final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
2016-06-22 22:08:39 +00:00
final Class<URLClassLoader> sysclass = URLClassLoader.class;
try {
2016-07-17 00:26:53 +00:00
final Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
2016-06-22 22:08:39 +00:00
method.setAccessible(true);
method.invoke(sysloader, new Object[] { url });
} catch (final Throwable t) {
t.printStackTrace();
2016-07-17 00:26:53 +00:00
throw new IOException("Error adding " + url + " to system classloader");
2016-06-22 22:08:39 +00:00
}
}
public static Permission permission = null;
public static Economy economy = null;
public static Chat chat = null;
private boolean setupPermissions() {
2016-07-17 00:26:53 +00:00
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.permission.Permission.class);
2016-06-22 22:08:39 +00:00
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
}
return (permission != null);
}
private boolean setupChat() {
2016-07-17 00:26:53 +00:00
RegisteredServiceProvider<Chat> chatProvider = getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.chat.Chat.class);
2016-06-22 22:08:39 +00:00
if (chatProvider != null) {
chat = chatProvider.getProvider();
}
return (chat != null);
}
private boolean setupEconomy() {
2016-07-17 00:26:53 +00:00
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.economy.Economy.class);
2016-06-22 22:08:39 +00:00
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return (economy != null);
}
}