Main.java 19 KB

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