Main.java 18 KB

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