ATM.java 17 KB

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