Main.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package de.Linus122.TimeIsMoney;
  2. import static de.Linus122.TimeIsMoney.tools.Utils.CC;
  3. import java.io.File;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6. import java.io.PrintWriter;
  7. import java.lang.reflect.InvocationTargetException;
  8. import java.sql.Timestamp;
  9. import java.util.ArrayList;
  10. import java.util.Calendar;
  11. import java.util.Date;
  12. import java.util.HashMap;
  13. import java.util.HashSet;
  14. import java.util.List;
  15. import java.util.Random;
  16. import java.util.Set;
  17. import java.util.UUID;
  18. import java.util.stream.Collectors;
  19. import org.bukkit.Bukkit;
  20. import org.bukkit.Location;
  21. import org.bukkit.Server;
  22. import org.bukkit.command.ConsoleCommandSender;
  23. import org.bukkit.configuration.file.FileConfiguration;
  24. import org.bukkit.configuration.file.YamlConfiguration;
  25. import org.bukkit.entity.Player;
  26. import org.bukkit.plugin.RegisteredServiceProvider;
  27. import org.bukkit.plugin.java.JavaPlugin;
  28. import org.bukkit.scheduler.BukkitTask;
  29. import com.earth2me.essentials.Essentials;
  30. import de.Linus122.TimeIsMoney.tools.ActionBarUtils;
  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. /**
  36. * The main class for TimeIsMoney
  37. *
  38. * @author Linus122
  39. * @since 1.9.6.1
  40. */
  41. public class Main extends JavaPlugin {
  42. /**
  43. * The economy being used by vault.
  44. */
  45. static net.milkbowl.vault.economy.Economy economy = null;
  46. /**
  47. * The config version number.
  48. */
  49. private static final int CFG_VERSION = 12;
  50. /**
  51. * The TimeIsMoney version.
  52. */
  53. static String PL_VERSION;
  54. /**
  55. * The TimeIsMoney config.
  56. */
  57. static FileConfiguration finalconfig;
  58. /**
  59. * The list of worlds where the payout feature will be disabled.
  60. */
  61. private static List<String> disabledWorlds;
  62. /**
  63. * The payouts listed in the config.
  64. */
  65. private final List<Payout> payouts = new ArrayList<>();
  66. /**
  67. * Players that have already reached the payout limit for today
  68. */
  69. private Set<UUID> payoutLimitReached = new HashSet<>();
  70. /**
  71. * The time online in seconds of each player by UUID.
  72. */
  73. private final HashMap<UUID, Integer> onlineSeconds = new HashMap<>();
  74. /**
  75. * The last location of each player by UUID.
  76. */
  77. private final HashMap<UUID, Location> lastLocation = new HashMap<>();
  78. /**
  79. * The console logger.
  80. */
  81. private final ConsoleCommandSender clogger = this.getServer().getConsoleSender();
  82. /**
  83. * Main task for keeping track of player's online time
  84. */
  85. private BukkitTask playtimeWatcherTask;
  86. /**
  87. * {@inheritDoc}
  88. */
  89. @SuppressWarnings({"deprecation", "unchecked"})
  90. @Override
  91. public void onEnable() {
  92. this.getCommand("timeismoney").setExecutor(new Cmd(this));
  93. PL_VERSION = this.getDescription().getVersion();
  94. this.reloadConfig();
  95. File config = new File("plugins/TimeIsMoney/config.yml");
  96. if (config.exists()) {
  97. YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);
  98. String old_config = "config_old " + cfg.getInt("configuration-version") + ".yml";
  99. if (cfg.contains("configuration-version")) {
  100. if (cfg.getInt("configuration-version") < CFG_VERSION) {
  101. clogger.sendMessage(CC("[TimeIsMoney] &cYOU ARE USING AN OLD CONFIG-VERSION. The plugin CANT work with this."));
  102. clogger.sendMessage(CC("[TimeIsMoney] &cI have created an new config for you. The old one is saved as config_old.yml."));
  103. config.renameTo(new File("plugins/TimeIsMoney/" + old_config));
  104. }
  105. }
  106. this.saveDefaultConfig();
  107. for (String key : cfg.getConfigurationSection("").getKeys(true)) {
  108. if (!this.getConfig().contains(key)) {
  109. this.getConfig().set(key, cfg.get(key));
  110. }
  111. }
  112. } else {
  113. this.saveDefaultConfig();
  114. }
  115. finalconfig = this.getConfig();
  116. disabledWorlds = getConfig().getStringList("disabled_in_worlds");
  117. if (getConfig().getBoolean("enable_atm")) new ATM(this);
  118. startPlaytimeWatcher();
  119. // Placeholder API
  120. if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
  121. new NamePlaceholder(this).register();
  122. }
  123. Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
  124. if (PluginData.getLastRefreshDay() != new Date().getDay() && PluginData.getPayedMoney().size() > 0) { //Next day, clear payouts!
  125. log("Cleared all payouts for last day");
  126. PluginData.getPayedMoney().clear();
  127. PluginData.setLastRefreshDay(new Date().getDay());
  128. }
  129. }, 20L * 60, 20L * 60 * 15);
  130. setupEconomy();
  131. PluginData.loadData();
  132. loadPayouts();
  133. if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) {
  134. clogger.sendMessage("Time is Money: Essentials found. Hook in it -> Will use Essentials's AFK feature if afk is enabled.");
  135. }
  136. new Metrics(this);
  137. clogger.sendMessage(CC("&aTime is Money &2v" + PL_VERSION + " &astarted."));
  138. }
  139. public void startPlaytimeWatcher() {
  140. playtimeWatcherTask = Bukkit.getScheduler().runTaskTimer(this, () -> {
  141. try {
  142. for (Player p : Bukkit.getOnlinePlayers()) {
  143. if (disabledWorlds.contains(p.getWorld().getName())) continue;
  144. if (onlineSeconds.containsKey(p.getUniqueId())) {
  145. onlineSeconds.put(p.getUniqueId(), onlineSeconds.get(p.getUniqueId()) + 1);
  146. } else {
  147. onlineSeconds.put(p.getUniqueId(), 1);
  148. }
  149. if (onlineSeconds.get(p.getUniqueId()) >= getConfig().getInt("give_money_every_second")) {
  150. pay(p);
  151. onlineSeconds.remove(p.getUniqueId());
  152. }
  153. }
  154. } catch (NullPointerException ignored) {
  155. }
  156. }, 20L, 20L);
  157. }
  158. /**
  159. * {@inheritDoc}
  160. */
  161. @Override
  162. public void onDisable() {
  163. playtimeWatcherTask.cancel();
  164. PluginData.saveData();
  165. }
  166. /**
  167. * Reloads TimeIsMoney.
  168. */
  169. void reload() {
  170. this.reloadConfig();
  171. finalconfig = this.getConfig();
  172. loadPayouts();
  173. }
  174. /**
  175. * Loads the payouts.
  176. */
  177. private void loadPayouts() {
  178. try {
  179. payouts.clear();
  180. for (String key : finalconfig.getConfigurationSection("payouts").getKeys(false)) {
  181. Payout payout = new Payout();
  182. payout.max_payout_per_day = finalconfig.getDouble("payouts." + key + ".max_payout_per_day");
  183. payout.payout_amount = finalconfig.getDouble("payouts." + key + ".payout_amount");
  184. if (finalconfig.isSet("payouts." + key + ".permission")) {
  185. payout.permission = finalconfig.getString("payouts." + key + ".permission");
  186. }
  187. if (finalconfig.isSet("payouts." + key + ".commands")) {
  188. payout.commands = finalconfig.getStringList("payouts." + key + ".commands");
  189. }
  190. if (finalconfig.isSet("payouts." + key + ".commands_if_afk")) {
  191. payout.commands_if_afk = finalconfig.getStringList("payouts." + key + ".commands_if_afk");
  192. }
  193. if (finalconfig.isSet("payouts." + key + ".chance")) {
  194. payout.chance = finalconfig.getInt("payouts." + key + ".chance");
  195. }
  196. payouts.add(payout);
  197. }
  198. clogger.sendMessage(CC("[TimeIsMoney] &aLoaded " + finalconfig.getConfigurationSection("payouts").getKeys(false).size() + " Payouts!"));
  199. } catch (Exception e) {
  200. clogger.sendMessage(CC("[TimeIsMoney] &aFailed to load Payouts! (May made a mistake in config.yml?)"));
  201. }
  202. }
  203. /**
  204. * Sets up the vault economy.
  205. *
  206. * @return True if the economy was set up, false otherwise.
  207. */
  208. private boolean setupEconomy() {
  209. RegisteredServiceProvider<net.milkbowl.vault.economy.Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
  210. if (economyProvider != null) {
  211. economy = economyProvider.getProvider();
  212. }
  213. return economy != null;
  214. }
  215. /**
  216. * Gets a list of applicable payouts for a player. Only returns one payout when using chance.
  217. *
  218. * @param player The player to get the payouts of.
  219. * @return A list of payouts
  220. */
  221. private List<Payout> getApplicablePayoutsForPlayer(Player player){
  222. if (!this.getConfig().getBoolean("choose-payout-by-chance")) {
  223. // Choose applicable payouts by permission
  224. return payouts.stream().filter(payout -> player.hasPermission(payout.permission) || payout.permission.length() == 0).collect(Collectors.toList());
  225. }else {
  226. // Get a random payout
  227. Random rnd = new Random();
  228. List<Payout> list = new ArrayList<>();
  229. for (Payout payout : payouts) {
  230. for (int i = 0; i < payout.chance; i++) list.add(payout);
  231. }
  232. List<Payout> returnlist = new ArrayList<>();
  233. returnlist.add(list.get(rnd.nextInt(list.size() - 1)));
  234. return returnlist;
  235. }
  236. }
  237. /**
  238. * Pays the specified player.
  239. *
  240. * @param p The player to pay.
  241. */
  242. @SuppressWarnings("deprecation")
  243. private void pay(Player p) {
  244. if (p == null) return;
  245. //REACHED MAX PAYOUT CHECK
  246. double payed = 0;
  247. if (PluginData.getPayedMoney().containsKey(p.getName())) {
  248. payed = PluginData.getPayedMoney().get(p.getName());
  249. }
  250. List<Payout> applicablePayouts = this.getApplicablePayoutsForPlayer(p);
  251. if (applicablePayouts.size() == 0) {
  252. return;
  253. }
  254. Payout payout = new Payout();
  255. if(this.getConfig().getBoolean("merge-payouts")) {
  256. // Mering multiple payouts to one
  257. for (Payout payout_ : applicablePayouts) {
  258. payout.commands.addAll(payout_.commands);
  259. payout.commands_if_afk.addAll(payout_.commands_if_afk);
  260. payout.payout_amount += payout_.payout_amount;
  261. payout.max_payout_per_day += payout_.max_payout_per_day;
  262. }
  263. }else {
  264. payout = applicablePayouts.get(applicablePayouts.size() - 1);
  265. }
  266. if (payout.max_payout_per_day != -1) {
  267. if (payed >= payout.max_payout_per_day) { //Reached max payout
  268. if(finalconfig.getBoolean("display-payout-limit-reached-message-once") && payoutLimitReached.contains(p.getUniqueId())) {
  269. return;
  270. }
  271. if (finalconfig.getBoolean("display-messages-in-chat")) {
  272. sendMessage(p, finalconfig.getString("message_payoutlimit_reached"));
  273. }
  274. if (finalconfig.getBoolean("display-messages-in-actionbar")) {
  275. sendActionbar(p, finalconfig.getString("message_payoutlimit_reached_actionbar"));
  276. }
  277. if(finalconfig.getBoolean("display-payout-limit-reached-message-once"))
  278. payoutLimitReached.add(p.getUniqueId());
  279. return;
  280. }
  281. }
  282. if (!finalconfig.getBoolean("allow-multiple-accounts")) {
  283. int same_address_count = (int) Bukkit.getOnlinePlayers().stream().filter(player -> player.getAddress().getHostString().equals(p.getAddress().getHostString())).count();
  284. if (same_address_count > finalconfig.getInt("max-multiple-accounts")) {
  285. sendMessage(p, finalconfig.getString("message_multiple_ips"));
  286. return;
  287. }
  288. }
  289. //AFK CHECK
  290. boolean afk = false;
  291. double afkPercent = 0.0D;
  292. if (!p.hasPermission("tim.afkbypass")) {
  293. //ESENTIALS_AFK_FEATURE
  294. if (Bukkit.getServer().getPluginManager().isPluginEnabled("Essentials")) {
  295. Essentials essentials = (com.earth2me.essentials.Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
  296. if (essentials.getUser(p).isAfk()) {
  297. afk = true;
  298. }
  299. } else {
  300. //PLUGIN_AFK_FEATURE
  301. if (lastLocation.containsKey(p.getUniqueId())) { //AntiAFK
  302. 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()) {
  303. afk = true;
  304. }
  305. }
  306. }
  307. if (afk) {
  308. if (!finalconfig.getBoolean("afk_payout")) { // Payout is disabled
  309. if (finalconfig.getBoolean("display-messages-in-chat")) {
  310. sendMessage(p, finalconfig.getString("message_afk"));
  311. }
  312. if (finalconfig.getBoolean("display-messages-in-actionbar")) {
  313. sendActionbar(p, finalconfig.getString("message_afk_actionbar"));
  314. }
  315. return;
  316. } else { // Payout is enabled
  317. if (!finalconfig.isSet("afk_payout_percent")) {
  318. afkPercent = 100; // Payout % isn't set (older config), so assume 100% as before
  319. } else {
  320. afkPercent = finalconfig.getDouble("afk_payout_percent");
  321. }
  322. }
  323. }
  324. }
  325. //DEPOSIT
  326. double payout_amt = afk ? payout.payout_amount * (afkPercent / 100) : payout.payout_amount;
  327. // Take money from bank
  328. if (finalconfig.getString("bank-account").length() > 0) {
  329. EconomyResponse response = economy.bankWithdraw(finalconfig.getString("bank-account"), payout_amt);
  330. if(response.type == ResponseType.FAILURE) {
  331. System.out.println("§cFailed to take money from bank account: " + finalconfig.getString("bank-account") + " amount " + payout_amt);
  332. return;
  333. }
  334. }
  335. if (finalconfig.getBoolean("store-money-in-bank")) {
  336. ATM.depositBank(p, payout_amt);
  337. } else {
  338. double before = 0;
  339. if (economy.hasAccount(p)) {
  340. before = economy.getBalance(p);
  341. }
  342. economy.depositPlayer(p, payout_amt);
  343. log(p.getName() + ": Deposited: " + payout_amt + " Balance-before: " + before + " Balance-now: " + economy.getBalance(p));
  344. }
  345. if (!afk) {
  346. if (finalconfig.getBoolean("display-messages-in-chat")) {
  347. sendMessage(p, CC(finalconfig.getString("message")).replace("%money%", economy.format(payout_amt)));
  348. }
  349. if (finalconfig.getBoolean("display-messages-in-actionbar")) {
  350. sendActionbar(p, CC(finalconfig.getString("message_actionbar")).replace("%money%", economy.format(payout_amt)));
  351. }
  352. for (String cmd : payout.commands) {
  353. dispatchCommandSync(cmd.replace("/", "").replaceAll("%player%", p.getName()));
  354. }
  355. } else {
  356. if (finalconfig.getBoolean("display-messages-in-chat") && finalconfig.isSet("message_afk_payout")) {
  357. sendMessage(p, CC(finalconfig.getString("message_afk_payout").replace("%money%", economy.format(payout_amt)).replace("%percent%", "" + afkPercent)));
  358. }
  359. if (finalconfig.getBoolean("display-messages-in-actionbar") && finalconfig.isSet("message_afk_actionbar_payout")) {
  360. sendActionbar(p, CC(finalconfig.getString("message_afk_actionbar_payout").replace("%money%", economy.format(payout_amt)).replace("%percent%", "" + afkPercent)));
  361. }
  362. for (String cmd : payout.commands_if_afk) {
  363. dispatchCommandSync(cmd.replace("/", "").replaceAll("%player%", p.getName()));
  364. }
  365. }
  366. //ADD PAYED MONEY
  367. if (PluginData.getPayedMoney().containsKey(p.getName())) {
  368. PluginData.getPayedMoney().put(p.getName(), PluginData.getPayedMoney().get(p.getName()) + payout_amt);
  369. } else {
  370. PluginData.getPayedMoney().put(p.getName(), payout_amt);
  371. }
  372. lastLocation.put(p.getUniqueId(), p.getLocation());
  373. // clear payout limit reached message
  374. if(finalconfig.getBoolean("display-payout-limit-reached-message-once"))
  375. payoutLimitReached.remove(p.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 p 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 p, String msg) {
  423. if (msg == null) return;
  424. if (msg.length() == 0) return;
  425. p.sendMessage(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, CC(message));
  438. } else if (times > 1) {
  439. sendSingleActionbarMessage(player, CC(message));
  440. times--;
  441. for (int i = 0; i < times; i++) {
  442. Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> sendSingleActionbarMessage(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) {
  450. // 1_8_R*
  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. }