ATM.java 17 KB

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