Main.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. package de.Linus122.TimeIsMoney;
  2. import static de.Linus122.TimeIsMoney.tools.Utils.CC;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.PrintWriter;
  9. import java.sql.Timestamp;
  10. import java.util.ArrayList;
  11. import java.util.Calendar;
  12. import java.util.Date;
  13. import java.util.HashMap;
  14. import java.util.HashSet;
  15. import java.util.List;
  16. import java.util.Random;
  17. import java.util.Set;
  18. import java.util.UUID;
  19. import java.util.stream.Collectors;
  20. import org.bukkit.Bukkit;
  21. import org.bukkit.Location;
  22. import org.bukkit.Server;
  23. import org.bukkit.command.ConsoleCommandSender;
  24. import org.bukkit.configuration.file.FileConfiguration;
  25. import org.bukkit.configuration.file.YamlConfiguration;
  26. import org.bukkit.entity.Player;
  27. import org.bukkit.plugin.RegisteredServiceProvider;
  28. import org.bukkit.plugin.java.JavaPlugin;
  29. import org.bukkit.scheduler.BukkitTask;
  30. import com.earth2me.essentials.Essentials;
  31. import net.md_5.bungee.api.ChatMessageType;
  32. import net.md_5.bungee.api.chat.TextComponent;
  33. import net.milkbowl.vault.economy.EconomyResponse;
  34. import net.milkbowl.vault.economy.EconomyResponse.ResponseType;
  35. import xyz.spaceio.spacegui.GUIProvider;
  36. import xyz.spaceio.spacegui.SpaceGUI;
  37. /**
  38. * The main class for TimeIsMoney
  39. *
  40. * @author Linus122
  41. * @since 1.9.6.1
  42. */
  43. public class Main extends JavaPlugin {
  44. /**
  45. * The economy being used by vault.
  46. */
  47. static net.milkbowl.vault.economy.Economy economy = null;
  48. /**
  49. * The config version number.
  50. */
  51. private static final int CFG_VERSION = 12;
  52. /**
  53. * The TimeIsMoney version.
  54. */
  55. static String PL_VERSION;
  56. /**
  57. * The TimeIsMoney config.
  58. */
  59. static FileConfiguration finalconfig;
  60. /**
  61. * The list of worlds where the payout feature will be disabled.
  62. */
  63. private static List<String> disabledWorlds;
  64. /**
  65. * The payouts listed in the config.
  66. */
  67. private final List<Payout> payouts = new ArrayList<>();
  68. /**
  69. * Players that have already reached the payout limit for today
  70. */
  71. private Set<UUID> payoutLimitReached = new HashSet<>();
  72. /**
  73. * The time online in seconds of each player by UUID.
  74. */
  75. private final HashMap<UUID, Integer> onlineSeconds = new HashMap<>();
  76. /**
  77. * The last location of each player by UUID.
  78. */
  79. private final HashMap<UUID, Location> lastLocation = new HashMap<>();
  80. /**
  81. * The console logger.
  82. */
  83. private final ConsoleCommandSender clogger = this.getServer().getConsoleSender();
  84. /**
  85. * Main task for keeping track of player's online time
  86. */
  87. private BukkitTask playtimeWatcherTask;
  88. /**
  89. * {@inheritDoc}
  90. */
  91. @SuppressWarnings({"deprecation"})
  92. @Override
  93. public void onEnable() {
  94. this.getCommand("timeismoney").setExecutor(new Cmd(this));
  95. PL_VERSION = this.getDescription().getVersion();
  96. GUIProvider.registerPlugin(this);
  97. //this.reloadConfig();
  98. File config = new File("plugins/TimeIsMoney/config.yml");
  99. if (config.exists()) {
  100. YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);
  101. String old_config = "config_old " + cfg.getInt("configuration-version") + ".yml";
  102. if (cfg.contains("configuration-version")) {
  103. if (cfg.getInt("configuration-version") < CFG_VERSION) {
  104. clogger.sendMessage(CC("[TimeIsMoney] &cYOU ARE USING AN OLD CONFIG-VERSION. The plugin CANT work with this."));
  105. clogger.sendMessage(CC("[TimeIsMoney] &cI have created an new config for you. The old one is saved as config_old.yml."));
  106. config.renameTo(new File("plugins/TimeIsMoney/" + old_config));
  107. }
  108. }
  109. this.saveDefaultConfig();
  110. for (String key : cfg.getConfigurationSection("").getKeys(true)) {
  111. if (!this.getConfig().contains(key)) {
  112. this.getConfig().set(key, cfg.get(key));
  113. }
  114. }
  115. } else {
  116. this.saveDefaultConfig();
  117. }
  118. finalconfig = this.getConfig();
  119. disabledWorlds = getConfig().getStringList("disabled_in_worlds");
  120. if (getConfig().getBoolean("enable_atm")) new ATM(this);
  121. startPlaytimeWatcher();
  122. // Placeholder API
  123. if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
  124. new NamePlaceholder(this).register();
  125. }
  126. Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
  127. if (PluginData.getLastRefreshDay() != new Date().getDay() && PluginData.getPayedMoney().size() > 0) { //Next day, clear payouts!
  128. log("Cleared all payouts for last day");
  129. PluginData.getPayedMoney().clear();
  130. PluginData.setLastRefreshDay(new Date().getDay());
  131. }
  132. }, 20L * 60, 20L * 60 * 15);
  133. setupEconomy();
  134. PluginData.loadData();
  135. loadPayouts();
  136. if (Bukkit.getPluginManager().isPluginEnabled("Essentials") && this.getConfig().getBoolean("afk_use_essentials")) {
  137. clogger.sendMessage("Time is Money: Essentials found. Hook in it -> Will use Essentials's AFK feature if afk is enabled.");
  138. }
  139. new Metrics(this);
  140. clogger.sendMessage(CC("&aTime is Money &2v" + PL_VERSION + " &astarted."));
  141. }
  142. public void startPlaytimeWatcher() {
  143. playtimeWatcherTask = Bukkit.getScheduler().runTaskTimer(this, () -> {
  144. try {
  145. for (Player p : Bukkit.getOnlinePlayers()) {
  146. if (disabledWorlds.contains(p.getWorld().getName())) continue;
  147. if (onlineSeconds.containsKey(p.getUniqueId())) {
  148. onlineSeconds.put(p.getUniqueId(), onlineSeconds.get(p.getUniqueId()) + 1);
  149. } else {
  150. onlineSeconds.put(p.getUniqueId(), 1);
  151. }
  152. if (onlineSeconds.get(p.getUniqueId()) >= getConfig().getInt("give_money_every_second")) {
  153. pay(p);
  154. onlineSeconds.remove(p.getUniqueId());
  155. }
  156. }
  157. } catch (NullPointerException ignored) {
  158. }
  159. }, 20L, 20L);
  160. }
  161. /**
  162. * {@inheritDoc}
  163. */
  164. @Override
  165. public void onDisable() {
  166. playtimeWatcherTask.cancel();
  167. PluginData.saveData();
  168. }
  169. /**
  170. * Reloads TimeIsMoney.
  171. */
  172. void reload() {
  173. this.reloadConfig();
  174. finalconfig = this.getConfig();
  175. if (getConfig().getBoolean("enable_atm")) new ATM(this);
  176. loadPayouts();
  177. }
  178. /**
  179. * Loads the payouts.
  180. */
  181. private void loadPayouts() {
  182. try {
  183. payouts.clear();
  184. for (String key : finalconfig.getConfigurationSection("payouts").getKeys(false)) {
  185. Payout payout = new Payout();
  186. payout.max_payout_per_day = finalconfig.getDouble("payouts." + key + ".max_payout_per_day");
  187. payout.payout_amount = finalconfig.getDouble("payouts." + key + ".payout_amount");
  188. if (finalconfig.isSet("payouts." + key + ".permission")) {
  189. payout.permission = finalconfig.getString("payouts." + key + ".permission");
  190. }
  191. if (finalconfig.isSet("payouts." + key + ".commands")) {
  192. payout.commands = finalconfig.getStringList("payouts." + key + ".commands");
  193. }
  194. if (finalconfig.isSet("payouts." + key + ".commands_if_afk")) {
  195. payout.commands_if_afk = finalconfig.getStringList("payouts." + key + ".commands_if_afk");
  196. }
  197. if (finalconfig.isSet("payouts." + key + ".chance")) {
  198. payout.chance = finalconfig.getInt("payouts." + key + ".chance");
  199. }
  200. payouts.add(payout);
  201. }
  202. clogger.sendMessage(CC("[TimeIsMoney] &aLoaded " + finalconfig.getConfigurationSection("payouts").getKeys(false).size() + " Payouts!"));
  203. } catch (Exception e) {
  204. clogger.sendMessage(CC("[TimeIsMoney] &aFailed to load Payouts! (May made a mistake in config.yml?)"));
  205. }
  206. }
  207. /**
  208. * Sets up the vault economy.
  209. *
  210. * @return True if the economy was set up, false otherwise.
  211. */
  212. private boolean setupEconomy() {
  213. RegisteredServiceProvider<net.milkbowl.vault.economy.Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
  214. if (economyProvider != null) {
  215. economy = economyProvider.getProvider();
  216. }
  217. return economy != null;
  218. }
  219. /**
  220. * Gets a list of applicable payouts for a player. Only returns one payout when using chance.
  221. *
  222. * @param player The player to get the payouts of.
  223. * @return A list of payouts
  224. */
  225. private List<Payout> getApplicablePayoutsForPlayer(Player player){
  226. if (!this.getConfig().getBoolean("choose-payout-by-chance")) {
  227. // Choose applicable payouts by permission
  228. return payouts.stream().filter(payout -> player.hasPermission(payout.permission) || payout.permission.length() == 0).collect(Collectors.toList());
  229. }else {
  230. // Get a random payout
  231. Random rnd = new Random();
  232. List<Payout> list = new ArrayList<>();
  233. for (Payout payout : payouts) {
  234. for (int i = 0; i < payout.chance; i++) list.add(payout);
  235. }
  236. List<Payout> returnlist = new ArrayList<>();
  237. returnlist.add(list.get(rnd.nextInt(list.size() - 1)));
  238. return returnlist;
  239. }
  240. }
  241. /**
  242. * Pays the specified player.
  243. *
  244. * @param p The player to pay.
  245. */
  246. private void pay(Player p) {
  247. if (p == null) return;
  248. //REACHED MAX PAYOUT CHECK
  249. double payed = 0;
  250. if (PluginData.getPayedMoney().containsKey(p.getName())) {
  251. payed = PluginData.getPayedMoney().get(p.getName());
  252. }
  253. List<Payout> applicablePayouts = this.getApplicablePayoutsForPlayer(p);
  254. if (applicablePayouts.size() == 0) {
  255. return;
  256. }
  257. Payout payout = new Payout();
  258. if(this.getConfig().getBoolean("merge-payouts")) {
  259. // Mering multiple payouts to one
  260. for (Payout payout_ : applicablePayouts) {
  261. payout.commands.addAll(payout_.commands);
  262. payout.commands_if_afk.addAll(payout_.commands_if_afk);
  263. payout.payout_amount += payout_.payout_amount;
  264. payout.max_payout_per_day += payout_.max_payout_per_day;
  265. }
  266. }else {
  267. payout = applicablePayouts.get(applicablePayouts.size() - 1);
  268. }
  269. if (payout.max_payout_per_day != -1) {
  270. if (payed >= payout.max_payout_per_day) { //Reached max payout
  271. if(finalconfig.getBoolean("display-payout-limit-reached-message-once") && payoutLimitReached.contains(p.getUniqueId())) {
  272. return;
  273. }
  274. if (finalconfig.getBoolean("display-messages-in-chat")) {
  275. sendMessage(p, finalconfig.getString("message_payoutlimit_reached"));
  276. }
  277. if (finalconfig.getBoolean("display-messages-in-actionbar")) {
  278. sendActionbar(p, finalconfig.getString("message_payoutlimit_reached_actionbar"));
  279. }
  280. if(finalconfig.getBoolean("display-payout-limit-reached-message-once"))
  281. payoutLimitReached.add(p.getUniqueId());
  282. return;
  283. }
  284. }
  285. if (!finalconfig.getBoolean("allow-multiple-accounts") && !p.hasPermission("tim.multipleaccountsbypass")) {
  286. int same_address_count = (int) Bukkit.getOnlinePlayers().stream().filter(player -> player.getAddress().getHostString().equals(p.getAddress().getHostString())).count();
  287. if (same_address_count > finalconfig.getInt("max-multiple-accounts")) {
  288. sendMessage(p, finalconfig.getString("message_multiple_ips"));
  289. return;
  290. }
  291. }
  292. //AFK CHECK
  293. boolean afk = false;
  294. double afkPercent = 0.0D;
  295. if (!p.hasPermission("tim.afkbypass")) {
  296. //ESENTIALS_AFK_FEATURE
  297. if (Bukkit.getServer().getPluginManager().isPluginEnabled("Essentials") && this.getConfig().getBoolean("afk_use_essentials")) {
  298. Essentials essentials = (com.earth2me.essentials.Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
  299. if (essentials.getUser(p).isAfk()) {
  300. afk = true;
  301. }
  302. } else {
  303. //PLUGIN_AFK_FEATURE
  304. if (lastLocation.containsKey(p.getUniqueId())) { //AntiAFK
  305. if (lastLocation.get(p.getUniqueId()).getX() == p.getLocation().getX() && lastLocation.get(p.getUniqueId()).getY() == p.getLocation().getY() && lastLocation.get(p.getUniqueId()).getZ() == p.getLocation().getZ() || lastLocation.get(p.getUniqueId()).getYaw() == p.getLocation().getYaw()) {
  306. afk = true;
  307. }
  308. }
  309. }
  310. if (afk) {
  311. if (!finalconfig.getBoolean("afk_payout")) { // Payout is disabled
  312. if (finalconfig.getBoolean("display-messages-in-chat")) {
  313. sendMessage(p, finalconfig.getString("message_afk"));
  314. }
  315. if (finalconfig.getBoolean("display-messages-in-actionbar")) {
  316. sendActionbar(p, finalconfig.getString("message_afk_actionbar"));
  317. }
  318. return;
  319. } else { // Payout is enabled
  320. if (!finalconfig.isSet("afk_payout_percent")) {
  321. afkPercent = 100; // Payout % isn't set (older config), so assume 100% as before
  322. } else {
  323. afkPercent = finalconfig.getDouble("afk_payout_percent");
  324. }
  325. }
  326. }
  327. }
  328. //DEPOSIT
  329. double payout_amt = afk ? payout.payout_amount * (afkPercent / 100) : payout.payout_amount;
  330. // Take money from bank
  331. if (finalconfig.getString("bank-account").length() > 0) {
  332. EconomyResponse response = economy.bankWithdraw(finalconfig.getString("bank-account"), payout_amt);
  333. if(response.type == ResponseType.FAILURE) {
  334. System.out.println("§cFailed to take money from bank account: " + finalconfig.getString("bank-account") + " amount " + payout_amt);
  335. return;
  336. }
  337. }
  338. if (finalconfig.getBoolean("store-money-in-bank")) {
  339. ATM.depositBank(p, payout_amt);
  340. } else {
  341. double before = 0;
  342. if (economy.hasAccount(p)) {
  343. before = economy.getBalance(p);
  344. }
  345. economy.depositPlayer(p, payout_amt);
  346. log(p.getName() + ": Deposited: " + payout_amt + " Balance-before: " + before + " Balance-now: " + economy.getBalance(p));
  347. }
  348. if (!afk) {
  349. if (finalconfig.getBoolean("display-messages-in-chat")) {
  350. sendMessage(p, CC(finalconfig.getString("message")).replace("%money%", economy.format(payout_amt)));
  351. }
  352. if (finalconfig.getBoolean("display-messages-in-actionbar")) {
  353. sendActionbar(p, CC(finalconfig.getString("message_actionbar")).replace("%money%", economy.format(payout_amt)));
  354. }
  355. for (String cmd : payout.commands) {
  356. dispatchCommandSync(cmd.replace("/", "").replaceAll("%player%", p.getName()));
  357. }
  358. } else {
  359. if (finalconfig.getBoolean("display-messages-in-chat") && finalconfig.isSet("message_afk_payout")) {
  360. sendMessage(p, CC(finalconfig.getString("message_afk_payout").replace("%money%", economy.format(payout_amt)).replace("%percent%", "" + afkPercent)));
  361. }
  362. if (finalconfig.getBoolean("display-messages-in-actionbar") && finalconfig.isSet("message_afk_actionbar_payout")) {
  363. sendActionbar(p, CC(finalconfig.getString("message_afk_actionbar_payout").replace("%money%", economy.format(payout_amt)).replace("%percent%", "" + afkPercent)));
  364. }
  365. for (String cmd : payout.commands_if_afk) {
  366. dispatchCommandSync(cmd.replace("/", "").replaceAll("%player%", p.getName()));
  367. }
  368. }
  369. //ADD PAYED MONEY
  370. if (PluginData.getPayedMoney().containsKey(p.getName())) {
  371. PluginData.getPayedMoney().put(p.getName(), PluginData.getPayedMoney().get(p.getName()) + payout_amt);
  372. } else {
  373. PluginData.getPayedMoney().put(p.getName(), payout_amt);
  374. }
  375. lastLocation.put(p.getUniqueId(), p.getLocation());
  376. // clear payout limit reached message
  377. if(finalconfig.getBoolean("display-payout-limit-reached-message-once"))
  378. payoutLimitReached.remove(p.getUniqueId());
  379. }
  380. /**
  381. * Dispatches a command as sync.
  382. *
  383. * @param cmd The command to dispatch sync.
  384. */
  385. private void dispatchCommandSync(final String cmd) {
  386. final Server server = this.getServer();
  387. this.getServer().getScheduler().runTask(this, () -> server.dispatchCommand(server.getConsoleSender(), cmd));
  388. }
  389. /**
  390. * Logs debug information if enabled in the config.
  391. *
  392. * @param msg The debug message to log.
  393. */
  394. @SuppressWarnings("deprecation")
  395. private void log(String msg) {
  396. if (!this.getConfig().getBoolean("debug-log")) {
  397. return;
  398. }
  399. Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
  400. File file = new File("plugins/TimeIsMoney/log.txt");
  401. try {
  402. if (!file.exists()) {
  403. file.createNewFile();
  404. }
  405. FileReader pr = new FileReader(file);
  406. int number;
  407. StringBuffer text = new StringBuffer();
  408. while ((number = pr.read()) != -1) {
  409. text.append((char) number);
  410. }
  411. text.append(currentTimestamp.toGMTString()).append(":").append(msg).append("\n");
  412. PrintWriter pw = new PrintWriter(file);
  413. pw.print(text);
  414. pw.close();
  415. } catch (IOException e) {
  416. e.printStackTrace();
  417. }
  418. }
  419. /**
  420. * Sends a chat message that supports color codes to the specified player.
  421. *
  422. * @param p The player to send the chat message to.
  423. * @param msg The message the chat should give the player.
  424. */
  425. private void sendMessage(Player p, String msg) {
  426. if (msg == null) return;
  427. if (msg.length() == 0) return;
  428. p.sendMessage(CC(msg));
  429. }
  430. /**
  431. * Sends an actionbar message to the specified player.
  432. *
  433. * @param player The player to send the actionbar message to.
  434. * @param message The message the actionbar should give to the player.
  435. */
  436. private void sendActionbar(final Player player, final String message) {
  437. if (message.length() == 0) return;
  438. int times = finalconfig.getInt("display-messages-in-actionbar-time");
  439. if (times == 1) {
  440. sendSingleActionbarMessage(player, CC(message));
  441. } else if (times > 1) {
  442. sendSingleActionbarMessage(player, CC(message));
  443. times--;
  444. for (int i = 0; i < times; i++) {
  445. Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> sendSingleActionbarMessage(player, CC(message)), 20L * i);
  446. }
  447. }
  448. }
  449. private void sendSingleActionbarMessage(final Player player, final String message) {
  450. String packageName = this.getServer().getClass().getPackage().getName();
  451. int version = Integer.parseInt(packageName.substring(packageName.lastIndexOf('.') + 1).split("_")[1]);
  452. if(version == 8 || version == 9) {
  453. // 1_8 -> 1_9
  454. sendActionbarReflect(player, message);
  455. return;
  456. } else if (version < 8) {
  457. // no action bar support
  458. return;
  459. }
  460. player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message));
  461. }
  462. private void sendActionbarReflect(final Player player, final String message) {
  463. String packageName = this.getServer().getClass().getPackage().getName();
  464. String version = packageName.substring(packageName.lastIndexOf('.') + 1);
  465. try {
  466. Object ichatbasecomponent = Class.forName("net.minecraft.server." + version + ".IChatBaseComponent$ChatSerializer").getDeclaredMethod("a", String.class).invoke(null, "{\"text\": \"" + CC(message) + "\"}");
  467. Object packet = Class.forName("net.minecraft.server." + version + ".PacketPlayOutChat").getConstructor(Class.forName("net.minecraft.server." + version + ".IChatBaseComponent"), byte.class).newInstance(ichatbasecomponent, (byte) 2);
  468. Object craftPlayer = Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftPlayer").cast(player);
  469. Object nmsPlayer = Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftPlayer").getMethod("getHandle").invoke(craftPlayer);
  470. Object pCon = Class.forName("net.minecraft.server." + version + ".EntityPlayer").getField("playerConnection").get(nmsPlayer);
  471. Class.forName("net.minecraft.server." + version + ".PlayerConnection").getMethod("sendPacket", Class.forName("net.minecraft.server." + version + ".Packet")).invoke(pCon, packet);
  472. } catch (Exception e) {
  473. // TODO Auto-generated catch block
  474. e.printStackTrace();
  475. }
  476. }
  477. }