ATM.java 17 KB

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