Main.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package de.Linus122.TimeIsMoney;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.ObjectInputStream;
  8. import java.io.ObjectOutputStream;
  9. import java.io.PrintWriter;
  10. import java.lang.reflect.Field;
  11. import java.net.URL;
  12. import java.sql.Timestamp;
  13. import java.util.ArrayList;
  14. import java.util.Calendar;
  15. import java.util.Date;
  16. import java.util.HashMap;
  17. import java.util.Iterator;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.Random;
  21. import java.util.Set;
  22. import java.util.UUID;
  23. import com.earth2me.essentials.Essentials;
  24. import org.bukkit.Bukkit;
  25. import org.bukkit.Location;
  26. import org.bukkit.Server;
  27. import org.bukkit.command.Command;
  28. import org.bukkit.command.ConsoleCommandSender;
  29. import org.bukkit.command.PluginCommand;
  30. import org.bukkit.command.SimpleCommandMap;
  31. import org.bukkit.configuration.file.YamlConfiguration;
  32. import org.bukkit.entity.Player;
  33. import org.bukkit.plugin.Plugin;
  34. import org.bukkit.plugin.PluginManager;
  35. import org.bukkit.plugin.RegisteredServiceProvider;
  36. import org.bukkit.plugin.SimplePluginManager;
  37. import org.bukkit.plugin.java.JavaPlugin;
  38. import modules.atm.ATM;
  39. import net.milkbowl.vault.economy.Economy;
  40. public class Main extends JavaPlugin {
  41. public static Economy economy = null;
  42. public static Utils utils = null;
  43. public static int CFG_VERSION = 12;
  44. public static int PL_VERSION;
  45. public static YamlConfiguration finalconfig;
  46. public static List<String> disabledWorlds;
  47. public static HashMap<String, UUID> boundIPs = new HashMap<String, UUID>();
  48. List<Payout> payouts = new ArrayList<Payout>();
  49. HashMap<String, Double> payedMoney = new HashMap<String, Double>();
  50. HashMap<UUID, Integer> onlineSeconds = new HashMap<UUID, Integer>();
  51. HashMap<UUID, Location> lastLocation = new HashMap<UUID, Location>();
  52. String message;
  53. ConsoleCommandSender clogger = this.getServer().getConsoleSender();
  54. int currentDay = 0;
  55. boolean use18Features = true;
  56. @SuppressWarnings({"deprecation", "unchecked"})
  57. @Override
  58. public void onEnable() {
  59. PL_VERSION = Integer.parseInt(((Plugin) this).getDescription().getVersion());
  60. this.getCommand("timeismoney").setExecutor(new Cmd(this));
  61. currentDay = (new Date()).getDay();
  62. File config = new File("plugins/TimeIsMoney/config.yml");
  63. if (config.exists()) {
  64. YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);
  65. String old_config = "config_old " + cfg.getInt("configuration-version") + ".yml";
  66. if (cfg.contains("configuration-version")) {
  67. if (cfg.getInt("configuration-version") < CFG_VERSION) {
  68. clogger.sendMessage("[TimeIsMoney] �cYOU ARE USING AN OLD CONFIG-VERSION. The plugin CANT work with this.");
  69. clogger.sendMessage("[TimeIsMoney] �cI have created an new config for you. The old one is saved as config_old.yml.");
  70. config.renameTo(new File("plugins/TimeIsMoney/" + old_config));
  71. }
  72. }
  73. this.saveDefaultConfig();
  74. for (String key : cfg.getConfigurationSection("").getKeys(true)) {
  75. if (!this.getConfig().contains(key)) {
  76. this.getConfig().set(key, cfg.get(key));
  77. }
  78. }
  79. } else {
  80. this.saveDefaultConfig();
  81. }
  82. finalconfig = YamlConfiguration.loadConfiguration(config);
  83. disabledWorlds = getConfig().getStringList("disabled_in_worlds");
  84. if (getConfig().getBoolean("enable_atm")) new ATM(this);
  85. final int seconds = getConfig().getInt("give_money_every_second");
  86. Bukkit.getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
  87. public void run() {
  88. try {
  89. for (Player p : Bukkit.getOnlinePlayers()) {
  90. if (disabledWorlds.contains(p.getWorld().getName())) continue;
  91. if (!boundIPs.containsKey(p.getAddress().getHostName())) {
  92. boundIPs.put(p.getAddress().getHostName(), p.getUniqueId());
  93. }
  94. if (onlineSeconds.containsKey(p.getUniqueId())) {
  95. onlineSeconds.put(p.getUniqueId(), onlineSeconds.get(p.getUniqueId()) + 1);
  96. } else {
  97. onlineSeconds.put(p.getUniqueId(), 1);
  98. }
  99. if (onlineSeconds.get(p.getUniqueId()) > seconds) {
  100. pay(p);
  101. onlineSeconds.remove(p.getUniqueId());
  102. }
  103. }
  104. } catch (NullPointerException e) {
  105. //
  106. }
  107. }
  108. }, 20L, 20L);
  109. Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
  110. public void run() {
  111. if (currentDay != new Date().getDay()) { //Next day, clear payouts!
  112. log("Cleared all payouts");
  113. payedMoney.clear();
  114. currentDay = new Date().getDay();
  115. }
  116. }
  117. }, 20L * 60, 20L * 60 * 15);
  118. setupEconomy();
  119. message = finalconfig.getString("message");
  120. message = message.replace('&', '�');
  121. try {
  122. FileInputStream fis = new FileInputStream(new File("plugins/TimeIsMoney/payed_today.data"));
  123. ObjectInputStream ois = new ObjectInputStream(fis);
  124. payedMoney = (HashMap<String, Double>) ((HashMap<String, Double>) ois.readObject()).clone();
  125. ois.close();
  126. } catch (Exception e) {
  127. }
  128. loadPayouts();
  129. String packageName = this.getServer().getClass().getPackage().getName();
  130. // Get full package string of CraftServer.
  131. // org.bukkit.craftbukkit.version
  132. String Bukkitversion = packageName.substring(packageName.lastIndexOf('.') + 1);
  133. // Get the last element of the package
  134. try {
  135. final Class<?> clazz = Class.forName(Bukkitversion + ".NBTUtils");
  136. // Check if we have a NMSHandler class at that location.
  137. if (Utils.class.isAssignableFrom(clazz)) { // Make sure it actually implements NMS
  138. utils = (Utils) clazz.getConstructor().newInstance(); // Set our handler
  139. }
  140. } catch (final Exception e) {
  141. this.getLogger().severe("Actionbars are not supported on your spigot version, sorry.");
  142. use18Features = false;
  143. return;
  144. }
  145. if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) {
  146. clogger.sendMessage("Time is Money: Essentials found. Hook in it -> Will use Essentials's AFK feature if afk is enabled.");
  147. }
  148. new Metrics(this);
  149. clogger.sendMessage("�aTime is Money �2v" + PL_VERSION + " �astarted.");
  150. }
  151. @Override
  152. public void onDisable() {
  153. FileOutputStream fos;
  154. try {
  155. fos = new FileOutputStream(new File("plugins/TimeIsMoney/payed_today.data"));
  156. ObjectOutputStream oos = new ObjectOutputStream(fos);
  157. oos.writeObject(payedMoney);
  158. oos.close();
  159. } catch (Exception e) {
  160. }
  161. }
  162. public void reload() {
  163. //File config = new File("plugins/TimeIsMoney/config.yml");
  164. //finalconfig = YamlConfiguration.loadConfiguration(config);
  165. Bukkit.getPluginManager().disablePlugin(this);
  166. Bukkit.getPluginManager().enablePlugin(this);
  167. //this.onDisable();
  168. //this.onEnable();
  169. //loadPayouts();
  170. }
  171. public void loadPayouts() {
  172. try {
  173. payouts.clear();
  174. for (String key : finalconfig.getConfigurationSection("payouts").getKeys(false)) {
  175. Payout payout = new Payout();
  176. payout.max_payout_per_day = finalconfig.getDouble("payouts." + key + ".max_payout_per_day");
  177. payout.payout_amount = finalconfig.getDouble("payouts." + key + ".payout_amount");
  178. if (finalconfig.getString("payouts." + key + ".permission") != null) {
  179. payout.permission = finalconfig.getString("payouts." + key + ".permission");
  180. }
  181. if (finalconfig.getString("payouts." + key + ".commands") != null) {
  182. payout.commands = finalconfig.getStringList("payouts." + key + ".commands");
  183. }
  184. if (finalconfig.getString("payouts." + key + ".chance") != null) {
  185. payout.chance = finalconfig.getInt("payouts." + key + ".chance");
  186. }
  187. payouts.add(payout);
  188. }
  189. clogger.sendMessage("[TimeIsMoney] �aLoaded " + finalconfig.getConfigurationSection("payouts").getKeys(false).size() + " Payouts!");
  190. } catch (Exception e) {
  191. clogger.sendMessage("[TimeIsMoney] �aFailed to load Payouts! (May made a mistake in config.yml?)");
  192. }
  193. }
  194. boolean setupEconomy() {
  195. RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
  196. if (economyProvider != null) {
  197. economy = economyProvider.getProvider();
  198. }
  199. return (economy != null);
  200. }
  201. public Payout getPayOutForPlayer(Player p) {
  202. Payout finalpayout = null;
  203. if (!this.getConfig().getBoolean("choose-payout-by-chance")) {
  204. //by Permission
  205. for (Payout payout : payouts) {
  206. if (payout.permission == "") finalpayout = payout;
  207. if (p.hasPermission(payout.permission)) {
  208. finalpayout = payout;
  209. }
  210. }
  211. } else {
  212. //by Chance
  213. Random rnd = new Random();
  214. List<Payout> list = new ArrayList<Payout>();
  215. for (Payout payout : payouts) {
  216. for (int i = 0; i < payout.chance; i++) list.add(payout);
  217. }
  218. finalpayout = list.get(rnd.nextInt(list.size() - 1));
  219. }
  220. return finalpayout;
  221. }
  222. @SuppressWarnings("deprecation")
  223. public void pay(Player p) {
  224. if (p == null) return;
  225. //REACHED MAX PAYOUT CHECK
  226. double payed = 0;
  227. if (payedMoney.containsKey(p.getName())) {
  228. payed = payedMoney.get(p.getName());
  229. }
  230. Payout payout = getPayOutForPlayer(p);
  231. if (payout == null) return;
  232. if (payout.max_payout_per_day != -1) {
  233. if (payed >= payout.max_payout_per_day) { //Reached max payout
  234. if (finalconfig.getBoolean("display-messages-in-chat")) {
  235. sendMessage(p, finalconfig.getString("message_payoutlimit_reached"));
  236. }
  237. if (finalconfig.getBoolean("display-messages-in-actionbar") && use18Features) {
  238. sendActionbar(p, finalconfig.getString("message_payoutlimit_reached_actionbar"));
  239. }
  240. return;
  241. }
  242. }
  243. if (!finalconfig.getBoolean("allow-multiple-accounts")) {
  244. if (boundIPs.containsKey(p.getAddress().getHostName())) {
  245. if (!boundIPs.get(p.getAddress().getHostName()).equals(p.getUniqueId())) {
  246. sendMessage(p, finalconfig.getString("message_multiple_ips"));
  247. return;
  248. }
  249. }
  250. }
  251. //AFK CHECK
  252. if (!finalconfig.getBoolean("afk_payout") && !p.hasPermission("tim.afkbypass")) {
  253. //ESENTIALS_AFK_FEATURE
  254. if (Bukkit.getServer().getPluginManager().isPluginEnabled("Essentials")) {
  255. Essentials essentials = (com.earth2me.essentials.Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
  256. if (essentials.getUser(p).isAfk()) {
  257. //AFK
  258. if (finalconfig.getBoolean("display-messages-in-chat")) {
  259. sendMessage(p, finalconfig.getString("message_afk"));
  260. }
  261. if (finalconfig.getBoolean("display-messages-in-actionbar") && use18Features) {
  262. sendActionbar(p, finalconfig.getString("message_afk_actionbar"));
  263. }
  264. return;
  265. }
  266. } else
  267. //PLUGIN_AFK_FEATURE
  268. if (lastLocation.containsKey(p.getUniqueId())) { //AntiAFK
  269. if (lastLocation.get(p.getUniqueId()).getX() == p.getLocation().getX() && lastLocation.get(p.getUniqueId()).getY() == p.getLocation().getY() && lastLocation.get(p.getUniqueId()).getZ() == p.getLocation().getZ() || lastLocation.get(p.getUniqueId()).getYaw() == p.getLocation().getYaw()) {
  270. //AFK
  271. if (finalconfig.getBoolean("display-messages-in-chat")) {
  272. sendMessage(p, finalconfig.getString("message_afk"));
  273. }
  274. if (finalconfig.getBoolean("display-messages-in-actionbar") && use18Features) {
  275. sendActionbar(p, finalconfig.getString("message_afk_actionbar"));
  276. }
  277. return;
  278. }
  279. }
  280. }
  281. //DEPOSIT
  282. if (finalconfig.getBoolean("store-money-in-bank")) {
  283. ATM.depositBank(p, payout.payout_amount);
  284. } else {
  285. double before = 0;
  286. if (economy.hasAccount(p)) {
  287. before = economy.getBalance(p);
  288. }
  289. economy.depositPlayer(p, payout.payout_amount);
  290. log(p.getName() + ": Deposited: " + payout.payout_amount + " Balance-before: " + before + " Balance-now: " + economy.getBalance(p));
  291. }
  292. if (finalconfig.getBoolean("display-messages-in-chat")) {
  293. sendMessage(p, message.replace("%money%", economy.format(payout.payout_amount)));
  294. }
  295. if (finalconfig.getBoolean("display-messages-in-actionbar") && use18Features) {
  296. sendActionbar(p, message.replace("%money%", economy.format(payout.payout_amount)));
  297. }
  298. for (String cmd : payout.commands) {
  299. dispatchCommandSync(cmd.replace("/", "").replaceAll("%player%", p.getName()));
  300. }
  301. //ADD PAYED MONEY
  302. if (payedMoney.containsKey(p.getName())) {
  303. payedMoney.put(p.getName(), payedMoney.get(p.getName()) + payout.payout_amount);
  304. } else {
  305. payedMoney.put(p.getName(), payout.payout_amount);
  306. }
  307. lastLocation.put(p.getUniqueId(), p.getLocation());
  308. }
  309. public void dispatchCommandSync(final String cmd) {
  310. final Server server = this.getServer();
  311. this.getServer().getScheduler().runTask(this, new Runnable() {
  312. public void run() {
  313. server.dispatchCommand(server.getConsoleSender(), cmd);
  314. }
  315. });
  316. }
  317. @SuppressWarnings("deprecation")
  318. public void log(String msg) {
  319. if (!this.getConfig().getBoolean("debug-log")) {
  320. return;
  321. }
  322. Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
  323. File file = new File("plugins/TimeIsMoney/log.txt");
  324. try {
  325. if (!file.exists()) {
  326. file.createNewFile();
  327. }
  328. FileReader pr = new FileReader(file);
  329. int number = 0;
  330. StringBuffer text = new StringBuffer();
  331. while ((number = pr.read()) != -1) {
  332. text.append((char) number);
  333. }
  334. text.append(currentTimestamp.toGMTString() + ":" + msg + "\n");
  335. PrintWriter pw = new PrintWriter(file);
  336. pw.print(text);
  337. pw.close();
  338. } catch (IOException e) {
  339. e.printStackTrace();
  340. }
  341. }
  342. public void sendMessage(Player p, String msg) {
  343. if (msg == null) return;
  344. if (msg.length() == 0) return;
  345. p.sendMessage(msg.replace('&', '�'));
  346. }
  347. public void sendActionbar(final Player p, final String msg) {
  348. if (msg.length() == 0) return;
  349. int times = finalconfig.getInt("display-messages-in-actionbar-time");
  350. if (times == 1) {
  351. if (utils != null) {
  352. utils.sendActionBarMessage(p, msg);
  353. }
  354. } else if (times > 1) {
  355. if (utils != null) {
  356. utils.sendActionBarMessage(p, msg);
  357. }
  358. times--;
  359. for (int i = 0; i < times; i++) {
  360. Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
  361. public void run() {
  362. utils.sendActionBarMessage(p, msg.replace('&', '�'));
  363. }
  364. }, 20L * i);
  365. }
  366. }
  367. }
  368. private boolean unloadPlugin(String pluginName)
  369. throws Exception {
  370. PluginManager manager = getServer().getPluginManager();
  371. SimplePluginManager spmanager = (SimplePluginManager) manager;
  372. if (spmanager != null) {
  373. Field pluginsField = spmanager.getClass().getDeclaredField("plugins");
  374. pluginsField.setAccessible(true);
  375. List<Plugin> plugins = (List) pluginsField.get(spmanager);
  376. Field lookupNamesField = spmanager.getClass().getDeclaredField("lookupNames");
  377. lookupNamesField.setAccessible(true);
  378. Map<String, Plugin> lookupNames = (Map) lookupNamesField.get(spmanager);
  379. Field commandMapField = spmanager.getClass().getDeclaredField("commandMap");
  380. commandMapField.setAccessible(true);
  381. SimpleCommandMap commandMap = (SimpleCommandMap) commandMapField.get(spmanager);
  382. Field knownCommandsField = null;
  383. Map<String, Command> knownCommands = null;
  384. if (commandMap != null) {
  385. knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
  386. knownCommandsField.setAccessible(true);
  387. knownCommands = (Map) knownCommandsField.get(commandMap);
  388. }
  389. Plugin plugin;
  390. Iterator<Map.Entry<String, Command>> it;
  391. for (Plugin plugin1 : manager.getPlugins()) {
  392. if (plugin1.getDescription().getName().equalsIgnoreCase(pluginName)) {
  393. manager.disablePlugin(plugin1);
  394. if ((plugins != null) && (plugins.contains(plugin1))) {
  395. plugins.remove(plugin1);
  396. }
  397. if ((lookupNames != null) && (lookupNames.containsKey(pluginName))) {
  398. lookupNames.remove(pluginName);
  399. }
  400. if (commandMap != null) {
  401. for (it = knownCommands.entrySet().iterator(); it.hasNext(); ) {
  402. Map.Entry<String, Command> entry = (Map.Entry) it.next();
  403. if ((entry.getValue() instanceof PluginCommand)) {
  404. PluginCommand command = (PluginCommand) entry.getValue();
  405. if (command.getPlugin() == plugin1) {
  406. command.unregister(commandMap);
  407. it.remove();
  408. }
  409. }
  410. }
  411. }
  412. }
  413. }
  414. } else {
  415. return true;
  416. }
  417. return true;
  418. }
  419. private boolean loadPlugin(String pluginName) {
  420. try {
  421. PluginManager manager = getServer().getPluginManager();
  422. Plugin plugin = manager.loadPlugin(new File("plugins", pluginName + ".jar"));
  423. if (plugin == null) {
  424. return false;
  425. }
  426. plugin.onLoad();
  427. manager.enablePlugin(plugin);
  428. } catch (Exception e) {
  429. return false;
  430. }
  431. return true;
  432. }
  433. private boolean reloadPlugin(String pluginName)
  434. throws Exception {
  435. boolean unload = unloadPlugin(pluginName);
  436. boolean load = loadPlugin(pluginName);
  437. if ((unload) && (load)) {
  438. } else {
  439. return false;
  440. }
  441. return true;
  442. }
  443. }