Chroma-Chat/.metadata/.plugins/org.eclipse.core.resources/.history/21/20cc239649a600151c15ab42d7919fee

356 lines
11 KiB
Text
Raw Normal View History

package tk.sznp.thebuttonautoflair;
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.java.JavaPlugin;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.json.JSONArray;
import org.json.JSONObject;
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.
// Fired when plugin is first enabled
@Override
public void onEnable() {
try {
System.out.println("Extracting necessary libraries...");
final File[] libs = new File[] { new File(getDataFolder(),
"htmlcleaner-2.16.jar") };
for (final File lib : libs) {
if (!lib.exists()) {
JarUtils.extractFromJar(lib.getName(),
lib.getAbsolutePath());
}
}
for (final File lib : libs) {
if (!lib.exists()) {
getLogger().warning(
"Failed to load plugin! Could not find lib: "
+ lib.getName());
Bukkit.getServer().getPluginManager().disablePlugin(this);
return;
}
addClassPath(JarUtils.getJarUrl(lib));
}
} catch (final Exception e) {
e.printStackTrace();
}
getServer().getPluginManager().registerEvents(new PlayerListener(),
this);
Commands comm = new Commands();
this.getCommand("u").setExecutor(comm);
this.getCommand("u").setUsage(
this.getCommand("u").getUsage().replace('&', '<27>'));
this.getCommand("nrp").setExecutor(comm);
this.getCommand("nrp").setUsage(
this.getCommand("nrp").getUsage().replace('&', '<27>'));
this.getCommand("ooc").setExecutor(comm);
this.getCommand("ooc").setUsage(
this.getCommand("ooc").getUsage().replace('&', '<27>'));
Instance = this; // 2015.08.08.
Console = this.getServer().getConsoleSender(); // 2015.08.12.
LoadFiles(false); // 2015.08.09.
Runnable r = new Runnable() {
public void run() {
ThreadMethod();
}
};
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 ThreadMethod() {
while (!stop) {
try {
String body = DownloadString("https://www.reddit.com/r/TheButtonMinecraft/comments/3d25do/autoflair_system_comment_your_minecraft_name_and/.json?limit=1000");
JSONArray json = new JSONArray(body).getJSONObject(1)
.getJSONObject("data").getJSONArray("children");
for (Object obj : json) {
JSONObject item = (JSONObject) obj;
String author = item.getJSONObject("data").getString(
"author");
String ign = item.getJSONObject("data").getString("body");
int start = ign.indexOf("IGN:") + "IGN:".length();
if (start == -1 + "IGN:".length()) // +length: 2015.08.10.
continue; // 2015.08.09.
int end = ign.indexOf(' ', start);
if (end == -1 || end == start)
end = ign.indexOf('\n', start); // 2015.07.15.
if (end == -1 || end == start)
ign = ign.substring(start);
else
ign = ign.substring(start, end);
ign = ign.trim();
MaybeOfflinePlayer mp = MaybeOfflinePlayer.GetFromName(ign);
if (mp == null)
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) {
// System.out.println("Error!\n" + e);
LastException = e; // 2015.08.09.
}
}
}
public void DownloadFlair(MaybeOfflinePlayer mp)
throws MalformedURLException, IOException {
String[] flairdata = DownloadString(
"http://karmadecay.com/thebutton-data.php?users=" + mp.UserName)
.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; // 2015.08.09.
public String DownloadString(String urlstr) throws MalformedURLException,
IOException {
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;
}
private void SetFlair(MaybeOfflinePlayer p, String text, String flairclass,
String username) {
p.UserName = username;
p.FlairState = FlairStates.Recognised;
switch (flairclass) {
case "press-1":
p.SetFlairColor(0xc);
break;
case "press-2":
p.SetFlairColor(0x6);
break;
case "press-3":
p.SetFlairColor(0xe);
break;
case "press-4":
p.SetFlairColor(0xa);
break;
case "press-5":
p.SetFlairColor(0x9);
break;
case "press-6":
p.SetFlairColor(0x5);
break;
case "no-press":
p.SetFlairColor(0x7);
break;
case "cheater":
p.SetFlairColor(0x5);
break;
case "cant-press":
p.FlairColor = 0xf;
break;
case "unknown":
if (text.equals("-1")) // If true, only non-presser/can't press; if
// false, any flair
{
try {
if (CheckForJoinDate(p)) {
p.FlairColor = 0x7;
p.FlairTime = "--";
} else {
p.FlairColor = 0xf;
p.FlairTime = "--";
}
} catch (Exception e) {
p.FlairState = FlairStates.Commented; // Flair unknown
p.FlairColor = 0;
e.printStackTrace();
}
} else {
p.FlairState = FlairStates.Commented; // Flair unknown
p.FlairColor = 0;
}
return;
default:
return;
}
if (text.equals("-1"))
text = "--";
p.FlairTime = text;
}
public static boolean CheckForJoinDate(MaybeOfflinePlayer mp)
throws Exception {
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);
return date.before(new Calendar.Builder()
.setTimeZone(TimeZone.getTimeZone("UTC")).setDate(2015, 4, 1)
.build().getTime());
}
public static void ConfirmUserMessage(MaybeOfflinePlayer mp) {
Player p = Bukkit.getPlayer(mp.UUID);
if (mp.FlairState.equals(FlairStates.Commented) && p != null)
if (mp.UserNames.size() > 1)
p.sendMessage("<22>9Multiple Reddit users commented your name. You can select with /u accept.<2E>r <20>6Type /u accept or /u ignore<72>r");
else
p.sendMessage("<22>9A Reddit user commented your name. Is that you?<3F>r <20>6Type /u accept or /u ignore<72>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) {
System.out
.println("The Button Minecraft plugin cleanup for reloading...");
MaybeOfflinePlayer.AllPlayers.clear();
AnnounceMessages.clear();
}
System.out.println("Loading files for The Button Minecraft plugin...");
try {
File file = new File("announcemessages.txt");
if (file.exists())
file.delete();
file = new File("flairsaccepted.txt");
if (file.exists())
file.delete();
file = new File("flairsignored.txt");
if (file.exists())
file.delete();
file = new File("thebuttonmc.yml");
if (file.exists()) {
YamlConfiguration yc = new YamlConfiguration();
yc.load(file);
MaybeOfflinePlayer.Load(yc);
PlayerListener.NotificationSound = yc
.getString("notificationsound");
PlayerListener.NotificationPitch = yc
.getDouble("notificationpitch");
AnnounceTime = yc.getInt("announcetime");
AnnounceMessages.addAll(yc.getStringList("announcements"));
}
System.out.println("The Button Minecraft plugin loaded files!");
} catch (IOException e) {
System.out.println("Error!\n" + e);
LastException = e;
} catch (InvalidConfigurationException e) {
System.out.println("Error!\n" + e);
LastException = e;
}
}
public static void SaveFiles() {
System.out.println("Saving files for The Button Minecraft plugin...");
try {
File file = new File("thebuttonmc.yml");
YamlConfiguration yc = new YamlConfiguration();
MaybeOfflinePlayer.Save(yc);
yc.set("notificationsound", PlayerListener.NotificationSound);
yc.set("notificationpitch", PlayerListener.NotificationPitch);
yc.set("announcetime", AnnounceTime);
yc.set("announcements", AnnounceMessages);
yc.save(file);
System.out.println("The Button Minecraft plugin saved files!");
} catch (IOException e) {
System.out.println("Error!\n" + e);
LastException = e;
}
}
private void addClassPath(final URL url) throws IOException {
final URLClassLoader sysloader = (URLClassLoader) ClassLoader
.getSystemClassLoader();
final Class<URLClassLoader> sysclass = URLClassLoader.class;
try {
final Method method = sysclass.getDeclaredMethod("addURL",
new Class[] { URL.class });
method.setAccessible(true);
method.invoke(sysloader, new Object[] { url });
} catch (final Throwable t) {
t.printStackTrace();
throw new IOException("Error adding " + url
+ " to system classloader");
}
}
}