ATM.java 17 KB

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