Main.java 20 KB

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