ATM.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. package de.Linus122.TimeIsMoney;
  2. import static de.Linus122.TimeIsMoney.tools.Utils.CC;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.Comparator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Map.Entry;
  10. import java.util.TreeMap;
  11. import java.util.UUID;
  12. import org.bukkit.Bukkit;
  13. import org.bukkit.Material;
  14. import org.bukkit.OfflinePlayer;
  15. import org.bukkit.World;
  16. import org.bukkit.block.Block;
  17. import org.bukkit.block.Sign;
  18. import org.bukkit.command.Command;
  19. import org.bukkit.command.CommandExecutor;
  20. import org.bukkit.command.CommandSender;
  21. import org.bukkit.configuration.InvalidConfigurationException;
  22. import org.bukkit.configuration.file.FileConfiguration;
  23. import org.bukkit.configuration.file.YamlConfiguration;
  24. import org.bukkit.entity.Player;
  25. import org.bukkit.event.Event.Result;
  26. import org.bukkit.event.EventHandler;
  27. import org.bukkit.event.EventPriority;
  28. import org.bukkit.event.Listener;
  29. import org.bukkit.event.block.Action;
  30. import org.bukkit.event.block.SignChangeEvent;
  31. import org.bukkit.event.inventory.InventoryCloseEvent;
  32. import org.bukkit.event.inventory.InventoryDragEvent;
  33. import org.bukkit.event.inventory.InventoryMoveItemEvent;
  34. import org.bukkit.event.player.PlayerInteractEvent;
  35. import org.bukkit.inventory.Inventory;
  36. import org.bukkit.plugin.Plugin;
  37. import com.earth2me.essentials.api.Economy;
  38. import com.google.common.primitives.Doubles;
  39. import net.milkbowl.vault.economy.EconomyResponse;
  40. import net.milkbowl.vault.economy.EconomyResponse.ResponseType;
  41. import xyz.spaceio.spacegui.SpaceGUI;
  42. import xyz.spaceio.spacegui.helpers.StackBuilder;
  43. import xyz.spaceio.spaceitem.DecorationMaterial;
  44. import xyz.spaceio.spaceitem.SpaceItem;
  45. /**
  46. * ATM listener and command executor.
  47. *
  48. * @author Linus122
  49. * @since 1.9.6.1
  50. */
  51. public class ATM implements Listener, CommandExecutor {
  52. /**
  53. * The {@link Plugin}.
  54. */
  55. private final Plugin plugin;
  56. /**
  57. * The bank accounts {@link java.io.File} that stores all data.
  58. */
  59. private static final File bankAccountsFile = new File("plugins/TimeIsMoney/data.dat");
  60. /**
  61. * The bank accounts {@link org.bukkit.configuration.file.YamlConfiguration} to manage the {@link #bankAccountsFile}.
  62. */
  63. private static YamlConfiguration bankAccountsConfig;
  64. /**
  65. * The different amounts of money shown in the atm to withdraw and deposit (atm_worth_gradation).
  66. */
  67. private double[] worths = new double[4];
  68. private File guiFile = new File("plugins/TimeIsMoney/atm_gui.yml");
  69. private List<Inventory> openATMs = new ArrayList<Inventory>();
  70. private SpaceGUI gui;
  71. private Material[] mats = new Material[] {Material.getMaterial("CLAY_BRICK") == null ? Material.getMaterial("BRICK") : Material.getMaterial("CLAY_BRICK"), Material.IRON_INGOT, Material.GOLD_INGOT, Material.DIAMOND};
  72. /**
  73. * Creates a new atm instance with the {@link de.Linus122.TimeIsMoney.Main} class.
  74. *
  75. * @param plugin The {@link de.Linus122.TimeIsMoney.Main} class that implements {@link org.bukkit.plugin.java.JavaPlugin}.
  76. */
  77. public ATM(Main plugin) {
  78. this.plugin = plugin;
  79. plugin.getServer().getPluginManager().registerEvents(this, plugin);
  80. worths = Doubles.toArray(Main.finalconfig.getDoubleList("atm_worth_gradation"));
  81. gui = new SpaceGUI().title("§cATM").size(9*3).fillBackground(new SpaceItem().setStack(DecorationMaterial.GRAY_STAINED_GLASS_PANE.get()));
  82. FileConfiguration fileConfig = new YamlConfiguration();
  83. if(guiFile.exists()) {
  84. try {
  85. fileConfig.load(guiFile);
  86. gui = (SpaceGUI) fileConfig.get("atm");
  87. } catch (IOException | InvalidConfigurationException e1) {
  88. // TODO Auto-generated catch block
  89. e1.printStackTrace();
  90. }
  91. } else {
  92. gui.getOrCreateItem(new SpaceItem().setStack(new StackBuilder(Material.GOLD_NUGGET).setDisplayname(CC("&cBalance &a%s"))).setLabel("balance"), 4 + 9);
  93. for(int i = 0; i < 4; i++) {
  94. gui.getOrCreateItem(new SpaceItem().setStack(new StackBuilder(mats[i]).setDisplayname(CC("&cWithdraw &a%s"))).setLabel("witdraw-" + i), 3 - i + 9);
  95. }
  96. for(int i = 0; i < 4; i++) {
  97. gui.getOrCreateItem(new SpaceItem().setStack(new StackBuilder(mats[i]).setDisplayname(CC("&cDeposit &a%s"))).setLabel("deposit-" + i), 5 + i + 9);
  98. }
  99. }
  100. // balance item
  101. SpaceItem balanceItem = gui.getItemWithLabel("balance");
  102. if(balanceItem != null) {
  103. balanceItem.setFormat((p) ->
  104. Main.economy.format(ATM.getBankBalance(p))
  105. );
  106. }
  107. for(int i = 0; i < 4; i++) {
  108. final int index = i;
  109. SpaceItem item = gui.getItemWithLabel("witdraw-" + i);
  110. if(item == null) continue;
  111. item.addAction((p, action) -> {
  112. ATM.interactWithdraw(p, worths[index]);
  113. action.getView().update(balanceItem);
  114. })
  115. .setFormat((p) -> Main.economy.format(worths[index]));
  116. }
  117. for(int i = 0; i < 4; i++) {
  118. final int index = i;
  119. SpaceItem item = gui.getItemWithLabel("deposit-" + i);
  120. if(item == null) continue;
  121. item.addAction((p, action) -> {
  122. ATM.interactDeposit(p, worths[index]);
  123. action.getView().update(balanceItem);
  124. })
  125. .setFormat((p) -> Main.economy.format(worths[index]));
  126. }
  127. if(!fileConfig.contains("atm")) {
  128. try {
  129. fileConfig.set("atm", gui);
  130. fileConfig.save(guiFile);
  131. } catch (IOException e) {
  132. // TODO Auto-generated catch block
  133. e.printStackTrace();
  134. }
  135. }
  136. plugin.getCommand("atm").setExecutor(this);
  137. if (!bankAccountsFile.exists()) {
  138. try {
  139. bankAccountsFile.createNewFile();
  140. } catch (IOException e) {
  141. e.printStackTrace();
  142. }
  143. }
  144. bankAccountsConfig = YamlConfiguration.loadConfiguration(bankAccountsFile);
  145. }
  146. private static void interactWithdraw(Player p, double amount) {
  147. if (ATM.bankHas(p, amount)) {
  148. EconomyResponse response = Main.economy.depositPlayer(p, amount);
  149. if (response.type == ResponseType.SUCCESS) {
  150. ATM.withdrawBank(p, amount);
  151. p.sendMessage(String.format(CC(Main.finalconfig.getString("message_atm_withdrew")), Main.economy.format(amount)));
  152. }
  153. } else {
  154. p.sendMessage(CC(Main.finalconfig.getString("message_atm_nomoneyinbank")));
  155. }
  156. }
  157. private static void interactDeposit(Player p, double amount) {
  158. if (Main.economy.has(p, amount)) {
  159. ATM.depositBank(p, amount);
  160. Main.economy.withdrawPlayer(p, amount);
  161. p.sendMessage(String.format(CC(Main.finalconfig.getString("message_atm_deposited")), Main.economy.format(amount)));
  162. } else {
  163. p.sendMessage(CC(Main.finalconfig.getString("message_atm_nomoney")));
  164. }
  165. }
  166. /**
  167. * Withdraws the specified amount of money from the specified player's bank.
  168. *
  169. * @param player The player to withdraw money from.
  170. * @param amount The amount of money to withdraw.
  171. */
  172. private static void withdrawBank(Player player, double amount) {
  173. withdrawBank(player, player.getWorld(), amount);
  174. }
  175. private static void withdrawBank(OfflinePlayer offlinePlayer, World inWorld, double amount) {
  176. String bankString = getBankString(offlinePlayer, inWorld);
  177. if (!bankAccountsConfig.contains(bankString)) bankAccountsConfig.set(bankString, 0.0);
  178. bankAccountsConfig.set(bankString, getBankBalance(offlinePlayer, inWorld) - amount);
  179. saveBanks();
  180. }
  181. /**
  182. * Deposits the specified amount of money to the specified player's bank.
  183. *
  184. * @param player The player to deposit money to.
  185. * @param amount The amount of money to deposit.
  186. */
  187. public static void depositBank(Player player, double amount) {
  188. depositBank(player, player.getWorld(), amount);
  189. }
  190. public static void depositBank(OfflinePlayer offlinePlayer, World inWorld, double amount) {
  191. String bankString = getBankString(offlinePlayer, inWorld);
  192. if (!bankAccountsConfig.contains(bankString)) bankAccountsConfig.set(bankString, 0.0);
  193. bankAccountsConfig.set(bankString, getBankBalance(offlinePlayer, inWorld) + amount);
  194. saveBanks();
  195. }
  196. /**
  197. * Checks if the player has the specified amount of money in their bank.
  198. *
  199. * @param p The player to check the balance of.
  200. * @param amount The amount of money.
  201. * @return True if the player has the specified amount of money, false otherwise.
  202. */
  203. private static boolean bankHas(Player player, double amount) {
  204. return bankHas(player, player.getWorld(), amount);
  205. }
  206. private static boolean bankHas(OfflinePlayer offlinePlayer, World inWorld, double amount) {
  207. String bankString = getBankString(offlinePlayer, inWorld);
  208. if (!bankAccountsConfig.contains(bankString)) bankAccountsConfig.set(bankString, 0.0);
  209. return getBankBalance(offlinePlayer, inWorld) >= amount;
  210. }
  211. /**
  212. * Gets the balance of the specified player's bank (doesn't support groups).
  213. *
  214. * @param offlinePlayer The offline player to get the balance of.
  215. * @param inWorld The World. Only needs to be specified when working with grouped ATM's (world-wise)
  216. * @return The offline player's balance in the bank.
  217. */
  218. public static double getBankBalance(OfflinePlayer offlinePlayer, World inWorld) {
  219. String bankString = getBankString(offlinePlayer, inWorld);
  220. if (!bankAccountsConfig.contains(bankString)) bankAccountsConfig.set(bankString, 0.0);
  221. return bankAccountsConfig.getDouble(bankString);
  222. }
  223. /**
  224. * Gets the balance of the specified player's bank.
  225. *
  226. * @param player The player to get the balance of.
  227. * @return The player's balance in the bank.
  228. */
  229. public static double getBankBalance(Player player) {
  230. return getBankBalance(player, player.getWorld());
  231. }
  232. /**
  233. * Saves the banks.
  234. */
  235. private static void saveBanks() {
  236. try {
  237. bankAccountsConfig.save(bankAccountsFile);
  238. } catch (IOException e) {
  239. e.printStackTrace();
  240. }
  241. }
  242. /**
  243. * Gets the bank string for the specified player.
  244. * Converts old bank accounts (those saved using the user name) to new bank accounts using UUID's.
  245. *
  246. * @param player The player to get the bank string of.
  247. * @param inWorld The World. Only needs to be specified when working with grouped ATM's (world-wise)
  248. * @return The bank string of the specified player.
  249. */
  250. private static String getBankString(OfflinePlayer player, World inWorld) {
  251. String oldBank = getBankStringByPrefix(player.getName(), inWorld);
  252. if(bankAccountsConfig.contains(oldBank)) {
  253. double oldMoneyAmount = bankAccountsConfig.getDouble(oldBank);
  254. bankAccountsConfig.set(getBankStringByPrefix(player.getUniqueId().toString(), inWorld), oldMoneyAmount);
  255. bankAccountsConfig.set(oldBank, null);
  256. }
  257. return getBankStringByPrefix(player.getUniqueId().toString(), inWorld);
  258. }
  259. /**
  260. * Returns the bank string of a player that is used internally for storing the money on.
  261. *
  262. * @param prefix The prefix to work with
  263. * @param inWorld The World. Only needs to be specified when working with grouped ATM's (world-wise)
  264. * @return The bank string of the specified player.
  265. */
  266. private static String getBankStringByPrefix(String prefix, World inWorld) {
  267. if (!Main.finalconfig.getBoolean("group-atms")) {
  268. return prefix + "_TimBANK";
  269. } else {
  270. for (String key : Main.finalconfig.getConfigurationSection("atm_groups").getKeys(false)) {
  271. List<String> list = Main.finalconfig.getStringList("atm_groups." + key);
  272. if (list.contains(inWorld.getName())) {
  273. return inWorld.getName() + "_TimBANK_" + key;
  274. }
  275. }
  276. }
  277. return prefix + "_TimBANK";
  278. }
  279. @EventHandler(priority = EventPriority.NORMAL)
  280. public void onInteract(PlayerInteractEvent e) {
  281. if (e.getClickedBlock() != null) {
  282. if (e.getClickedBlock().getState() instanceof Sign) {
  283. Sign sign = (Sign) e.getClickedBlock().getState();
  284. if (sign.getLine(0).equalsIgnoreCase(CC(Main.finalconfig.getString("atm_sign_label")))) {
  285. if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
  286. e.setCancelled(true);
  287. if (!e.getPlayer().hasPermission("tim.atm.use")) {
  288. e.getPlayer().sendMessage(CC(Main.finalconfig.getString("message_atm_noperms")));
  289. } else {
  290. this.openGUI(e.getPlayer());
  291. }
  292. }
  293. }
  294. }
  295. }
  296. }
  297. @EventHandler
  298. public void onClose(InventoryCloseEvent e) {
  299. if (e.getInventory() != null)
  300. openATMs.remove(e.getInventory());
  301. }
  302. @EventHandler
  303. public void onMove(InventoryMoveItemEvent e) {
  304. if (e.getSource() == null || e.getSource().getViewers().size() == 0 || e.getSource().getViewers().get(0).getOpenInventory() == null) return;
  305. if (openATMs.contains(e.getSource().getViewers().get(0).getOpenInventory().getTopInventory())) {
  306. e.setCancelled(true);
  307. }
  308. }
  309. /**
  310. * Opens the atm gui for the specified player.
  311. *
  312. * @param player The player to open the atm gui for.
  313. */
  314. private void openGUI(Player player) {
  315. if(worths.length == 0) {
  316. player.sendMessage("§cError in config.yml: atm_worth_gradation is empty.");
  317. return;
  318. }
  319. gui.open(player);
  320. }
  321. @EventHandler
  322. public void onInventoryDrag(InventoryDragEvent e) {
  323. if (e == null || e.getInventory() == null) return;
  324. if (openATMs.contains(e.getView().getTopInventory())) {
  325. e.setResult(Result.DENY);
  326. }
  327. }
  328. @EventHandler
  329. public void onSignChange(final SignChangeEvent e) {
  330. final Block b = e.getBlock();
  331. if (b.getState() instanceof Sign) {
  332. plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
  333. if (b.getState() instanceof Sign) {
  334. Sign sign = (Sign) e.getBlock().getState();
  335. if (sign.getLine(0).equalsIgnoreCase("[ATM]")
  336. || sign.getLine(0).equalsIgnoreCase(Main.finalconfig.getString("atm_sign_label"))
  337. || sign.getLine(0).equalsIgnoreCase(CC(Main.finalconfig.getString("atm_sign_label")))) {
  338. if (!e.getPlayer().hasPermission("tim.atm.place")) {
  339. e.getPlayer().sendMessage(CC(Main.finalconfig.getString("message_atm_nopermbuild")));
  340. sign.setLine(0, "");
  341. e.setCancelled(true);
  342. b.setType(Material.AIR);
  343. } else {
  344. sign.setLine(0, CC(Main.finalconfig.getString("atm_sign_label")));
  345. sign.update();
  346. e.getPlayer().sendMessage(CC(Main.finalconfig.getString("message_atm_created")));
  347. }
  348. }
  349. }
  350. }, 10L);
  351. }
  352. }
  353. @Override
  354. public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] args) {
  355. if (args.length == 0) {
  356. if (!(cs instanceof Player)) {
  357. cs.sendMessage("Only players can use atms.");
  358. return true;
  359. }
  360. if (cs.hasPermission("tim.use")) {
  361. openGUI((Player) cs);
  362. return true;
  363. }
  364. }
  365. if (cs.hasPermission("tim.admin")) {
  366. if (args.length > 0) {
  367. switch (args[0]) {
  368. case "balance":
  369. if (args.length > 1) {
  370. cs.sendMessage(CC("&2ATM-Balance of&c " + args[1] + "&2: &c") + Economy.format(getBankBalance(Bukkit.getOfflinePlayer(args[1]), null)));
  371. } else {
  372. cs.sendMessage("/atm balance <player>");
  373. }
  374. break;
  375. case "balancetop":
  376. cs.sendMessage("§cTop Bank Accounts:");
  377. Map<String, Double> topBal = new TreeMap<String, Double>();
  378. for (String keyBankString : bankAccountsConfig.getKeys(false)) {
  379. double amount = bankAccountsConfig.getDouble(keyBankString);
  380. String formattedDisplayString = keyBankString.split("_")[0];
  381. if(formattedDisplayString.length() > 16) {
  382. // uuid
  383. formattedDisplayString = Bukkit.getOfflinePlayer(UUID.fromString(formattedDisplayString)).getName();
  384. }
  385. topBal.put(formattedDisplayString, amount);
  386. }
  387. topBal.entrySet().stream().
  388. sorted(Entry.comparingByValue(Comparator.reverseOrder())).limit(10).forEachOrdered(entry -> cs.sendMessage("§a" + entry.getKey() + "§2: " + Main.economy.format(entry.getValue())));
  389. break;
  390. case "take":
  391. if(args.length > 2) {
  392. OfflinePlayer playerToTake = Bukkit.getOfflinePlayer(args[1]);
  393. String inWorld = args.length > 3 ? args[3] : "world";
  394. if(playerToTake == null) {
  395. cs.sendMessage("§cThis player does not exists");
  396. return true;
  397. }
  398. try {
  399. double amount = Double.parseDouble(args[2]);
  400. double bal = ATM.getBankBalance(playerToTake, null);
  401. if(amount > bal) {
  402. cs.sendMessage("§cAmount to high! Player only has " + Economy.format(bal));
  403. return true;
  404. }
  405. ATM.withdrawBank(playerToTake, Bukkit.getWorld(inWorld), amount);
  406. cs.sendMessage("§aWithdrew §2" + Economy.format(amount) + ".");
  407. }catch(NumberFormatException e) {
  408. cs.sendMessage("§cPlease enter a valid decimal");
  409. }
  410. }else {
  411. cs.sendMessage("§c/tim take <player> <amount> [world]");
  412. }
  413. break;
  414. case "give":
  415. if(args.length > 2) {
  416. OfflinePlayer playerToGive = Bukkit.getOfflinePlayer(args[1]);
  417. String inWorld = args.length > 3 ? args[3] : "world";
  418. if(playerToGive == null) {
  419. cs.sendMessage("§cThis player does not exists");
  420. return true;
  421. }
  422. try {
  423. double amount = Double.parseDouble(args[2]);
  424. double bal = ATM.getBankBalance(playerToGive, null);
  425. ATM.depositBank(playerToGive, Bukkit.getWorld(inWorld), amount);
  426. cs.sendMessage("§aDeposited §2" + Economy.format(amount) + ".");
  427. }catch(NumberFormatException e) {
  428. cs.sendMessage("§cPlease enter a valid decimal");
  429. }
  430. }else {
  431. cs.sendMessage("§c/tim give <player> <amount> [world]");
  432. }
  433. break;
  434. default:
  435. @SuppressWarnings("deprecation")
  436. OfflinePlayer op = Bukkit.getOfflinePlayer(args[0]);
  437. if (op == null) {
  438. cs.sendMessage("Player is offline");
  439. return true;
  440. }
  441. if (op.isOnline()) {
  442. openGUI(op.getPlayer());
  443. cs.sendMessage("opened!");
  444. return true;
  445. }
  446. cs.sendMessage(CC("&c/atm <player> &a- opens atm for player"));
  447. cs.sendMessage(CC("&c/atm balance <player> &a- gets balance of player"));
  448. cs.sendMessage(CC("&c/atm balancetop - Shows the top 10 player atm balances"));
  449. cs.sendMessage(CC("&c/atm give <player> <amount> [world] &a- Deposits money into a players atm"));
  450. cs.sendMessage(CC("&c/atm take <player> <amount> [world] &a- Withdraws money from a players atm"));
  451. break;
  452. }
  453. }
  454. }
  455. return true;
  456. }
  457. }