Main.java 17 KB

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