Main.java 19 KB

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