Browse Source

fixed bugs

linus 7 years ago
parent
commit
82e387fdc8

+ 11 - 0
README.md

@@ -0,0 +1,11 @@
+# TimeIsMoney
+
+
+[![Build Status](https://travis-ci.org/mastercake10/TimeIsMoney.svg?branch=master)](https://travis-ci.org/mastercake10/TimeIsMoney)
+
+TimeIsMoney for Minecraft 1.7 - 1.10.2
+
+Contributing:
+
+feel free to contribute on this project.
+Pull this project if you have suggestions or if you fixed a bug, this would be awesome.

+ 74 - 0
TimeIsMoney2/src/config.yml

@@ -0,0 +1,74 @@
+configuration-version: 12
+
+auto-update: true
+debug-log: false
+
+# You can disable the plugin's payout feature in certain worlds
+disabled_in_worlds:
+- "creative_world"
+
+# You can define if the player gets a payout whether player is afk or not.
+# the permission tim.afkbypass would avoid this for certain user or groups.
+afk_payout: false
+display-messages-in-chat: true
+display-messages-in-actionbar: true
+display-messages-in-actionbar-time: 10
+give_money_every_second: 600
+store-money-in-bank: false
+
+# Payouts will be delivered by "chance" instead "permission".
+choose-payout-by-chance: false
+
+# You can add as many payouts you want. You only can choose between "permission"
+# and "change", not both.
+payouts:
+  1:
+    payout_amount: 50
+    max_payout_per_day: 1000
+    # chance: 10
+    permission:
+  2:
+    payout_amount: 100
+    max_payout_per_day: 10000
+    commands:
+      - /give %player% diamond 1
+    # chance: 90
+    # You can use any permission name you want. e.g. myserver.donor
+    permission: tim.vip
+
+# Translations
+message: "&aYou earned &c%money% &afor 10 minutes online time!"
+message_payoutlimit_reached: "&cYou have reached the payout limit today. You earned 0$"
+message_afk: "&cYou havn't earned money because you were afk!"
+message_actionbar: "&aYou earned &c%money% &afor 10 minutes online time!"
+message_payoutlimit_reached_actionbar: "&cYou have reached the payout limit today. You got 0$"
+message_afk_actionbar: "&cYou havn't earned money because you were afk!"
+message_atm_noperms: "&cYou don't have the permission to use ATM's!"
+message_atm_nomoneyinbank: "&cYou don't have enough money in bank!"
+message_atm_nomoney: "&cYou don't have enough money!"
+
+# ATM -> Place down a sign with [atm] on the first line to use it!
+atm_title: "&cATM"
+atm_withdraw: "&cWithdraw"
+atm_deposit: "&cDeposit"
+atm_balance: "&cBank balance:"
+
+# You can seperate the ATM balances for different worlds by group them. Just set group-atms to true and write atm_groups as described below.
+# Note: Existing bank accounts will be removed when enabling this feature. 
+group-atms: false
+# Example groups for seperating all worlds:
+#atm_groups:
+#  group1:
+#  - world
+#  group2:
+#  - world_nether
+#  group3:
+#   - world_the_end
+# Example groups for seperating skyblock worlds and survival worlds:
+#atm_groups:
+#  group1:
+#  - ASkyblock_world
+#  - Askyblock_spawn
+#  group2:
+#  - survival_world
+#  - farm_world

+ 23 - 0
TimeIsMoney2/src/de/Linus122/TimeIsMoney/Cmd.java

@@ -0,0 +1,23 @@
+package de.Linus122.TimeIsMoney;
+
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandExecutor;
+import org.bukkit.command.CommandSender;
+
+public class Cmd implements CommandExecutor {
+	Main main;
+	public Cmd(Main main) {
+		this.main = main;
+	}
+
+	@Override
+	public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] arg3) {
+		if(cs.hasPermission("tim.reload")){
+			main.reload();
+			cs.sendMessage("§aTime is Money §cv" + main.PL_VERSION + " §areloaded!");
+			
+		}
+		return true;
+	}
+
+}

+ 521 - 0
TimeIsMoney2/src/de/Linus122/TimeIsMoney/Main.java

@@ -0,0 +1,521 @@
+package de.Linus122.TimeIsMoney;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.PrintWriter;
+import java.lang.reflect.Field;
+import java.net.URL;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandSender;
+import org.bukkit.command.ConsoleCommandSender;
+import org.bukkit.command.PluginCommand;
+import org.bukkit.command.SimpleCommandMap;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.InvalidDescriptionException;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.PluginManager;
+import org.bukkit.plugin.RegisteredServiceProvider;
+import org.bukkit.plugin.SimplePluginManager;
+import org.bukkit.plugin.java.JavaPlugin;
+
+import modules.atm.ATM;
+import net.milkbowl.vault.economy.Economy;
+import webapi.VersionChecker;
+
+public class Main extends JavaPlugin{
+	
+	List<Payout> payouts = new ArrayList<Payout>();
+	HashMap<String, Double> payedMoney = new HashMap<String, Double>();
+	
+	HashMap<Player, Integer> onlineSeconds = new HashMap<Player, Integer>();
+	
+	HashMap<Player, Location> lastLocation = new HashMap<Player, Location>();
+	
+	public static Economy economy = null;
+	public static Utils utils = null;
+	String message;
+	
+	ConsoleCommandSender clogger = this.getServer().getConsoleSender();
+	
+	public static int CFG_VERSION = 12;
+	public static int PL_VERSION;
+
+	int currentDay = 0;
+	
+	public static YamlConfiguration finalconfig;
+	
+	boolean use18Features = true;
+	
+	public static List<String> disabledWorlds;
+	
+	@SuppressWarnings({ "deprecation", "unchecked" })
+	@Override
+	public void onEnable(){
+		PL_VERSION = Integer.parseInt(((Plugin)this).getDescription().getVersion());
+		this.getCommand("timeismoney").setExecutor(new Cmd(this));
+		
+		currentDay = (new Date()).getDay();
+	
+		File config = new File("plugins/TimeIsMoney/config.yml");
+		if(config.exists()){
+			YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);	
+			String old_config = "config_old " + cfg.getInt("configuration-version") + ".yml";
+			if(cfg.contains("configuration-version")){
+				if(cfg.getInt("configuration-version") < CFG_VERSION){
+					clogger.sendMessage("[TimeIsMoney] §cYOU ARE USING AN OLD CONFIG-VERSION. The plugin CANT work with this.");
+					clogger.sendMessage("[TimeIsMoney] §cI have created an new config for you. The old one is saved as config_old.yml.");
+					config.renameTo(new File("plugins/TimeIsMoney/" + old_config));
+				}
+			}
+			this.saveDefaultConfig();
+			for(String key : cfg.getConfigurationSection("").getKeys(true)){
+				if(!this.getConfig().contains(key)){
+					this.getConfig().set(key, cfg.get(key));
+				}
+			}
+		}else{
+			this.saveDefaultConfig();
+		}
+		
+		new ATM(this);
+		
+		finalconfig = YamlConfiguration.loadConfiguration(config);
+		disabledWorlds = getConfig().getStringList("disabled_in_worlds");
+		final int seconds = getConfig().getInt("give_money_every_second");
+		Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
+			public void run(){
+				for(Player p : Bukkit.getOnlinePlayers()){
+					if(disabledWorlds.contains(p.getWorld().getName())) continue;
+					if(onlineSeconds.containsKey(p)){
+						
+						onlineSeconds.put(p, onlineSeconds.get(p) + 1);
+					}else{
+						onlineSeconds.put(p, 1);
+					}
+					if(onlineSeconds.get(p) > seconds){
+						pay(p);
+						onlineSeconds.remove(p);
+					}
+				}
+			}
+		}, 20L, 20L);
+		Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
+			public void run(){
+				if(currentDay != new Date().getDay()){ //Next day, clear payouts!
+					log("Cleared all payouts");
+					payedMoney.clear();
+					currentDay = new Date().getDay();
+				}
+			}
+		}, 20L * 60, 20L * 60 * 15);
+		setupEconomy();
+		
+		message = finalconfig.getString("message");
+		message = message.replace('&', '§');
+
+		try{
+		    FileInputStream fis = new FileInputStream(new File("plugins/TimeIsMoney/payed_today.data"));
+		    ObjectInputStream ois = new ObjectInputStream(fis);
+		    payedMoney = (HashMap<String, Double>) ((HashMap<String, Double>) ois.readObject()).clone();
+
+		    ois.close();	
+		}catch(Exception e){
+			
+		}
+		
+		loadPayouts();
+		if(this.getConfig().getBoolean("auto-update")){
+
+			Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, new Runnable(){
+				public void run(){
+					if(Main.PL_VERSION < VersionChecker.getVersion()){
+						clogger.sendMessage("[TimeIsMoney] §cYou are using an old version, I will update this plugin for you.");
+						//Update
+						URL loc = Bukkit.getPluginManager().getPlugin("TimeIsMoney").getClass().getProtectionDomain().getCodeSource().getLocation();
+						Bukkit.getUpdateFolderFile().mkdir();
+						File file = new File(Bukkit.getUpdateFolderFile().getPath() + "/" + loc.getFile().split("/")[loc.getFile().split("/").length - 1]);
+						
+						try {
+							VersionChecker.download(file);
+						} catch (IOException e) {
+							// TODO Auto-generated catch block
+							e.printStackTrace();
+						}
+						clogger.sendMessage("[TimeIsMoney] §aSuccess! Downloaded v" + VersionChecker.getVersion());
+						try {
+							reloadPlugin("TimeIsMoney");
+						} catch (Exception e) {
+							// TODO Auto-generated catch block
+							e.printStackTrace();
+						}
+					}
+				}
+			},0L, 20L * 60 * 20);
+		}
+		
+		
+		 String packageName = this.getServer().getClass().getPackage().getName();
+        // Get full package string of CraftServer.
+        // org.bukkit.craftbukkit.version
+        String Bukkitversion = packageName.substring(packageName.lastIndexOf('.') + 1);
+        // Get the last element of the package
+        try {
+            final Class<?> clazz = Class.forName(Bukkitversion + ".NBTUtils");
+            // Check if we have a NMSHandler class at that location.
+            if (Utils.class.isAssignableFrom(clazz)) { // Make sure it actually implements NMS
+                utils = (Utils) clazz.getConstructor().newInstance(); // Set our handler
+     
+            }
+            
+        } catch (final Exception e) {
+            this.getLogger().severe("Actionbars are not supported on your spigot version, sorry.");
+            use18Features = false;
+            return;
+        }
+
+		if(Bukkit.getPluginManager().isPluginEnabled("Essentials")){
+			clogger.sendMessage("Time is Money: Essentials found. Hook in it -> Will use Essentials's AFK feature if afk is enabled.");
+		}
+		clogger.sendMessage("§aTime is Money §2v" + PL_VERSION + " started.");
+	}
+	@Override
+	public void onDisable(){
+	    FileOutputStream fos;
+	    try {
+	    	fos = new FileOutputStream(new File("plugins/TimeIsMoney/payed_today.data"));
+	        ObjectOutputStream oos = new ObjectOutputStream(fos);
+	        oos.writeObject(payedMoney);
+	        oos.close();
+	    }catch(Exception e){
+	    	
+	    }
+	}
+	public void reload(){
+		//File config = new File("plugins/TimeIsMoney/config.yml");
+		//finalconfig = YamlConfiguration.loadConfiguration(config);
+		Bukkit.getPluginManager().disablePlugin(this);
+		Bukkit.getPluginManager().enablePlugin(this);
+		//this.onDisable();
+		//this.onEnable();
+		//loadPayouts();
+	}
+	public void loadPayouts(){
+		try{
+			payouts.clear();
+			for(String key : finalconfig.getConfigurationSection("payouts").getKeys(false)){
+				Payout payout = new Payout();
+				payout.max_payout_per_day = finalconfig.getDouble("payouts." + key + ".max_payout_per_day");
+				payout.payout_amount = finalconfig.getDouble("payouts." + key + ".payout_amount");
+				if(finalconfig.getString("payouts." + key + ".permission") != null){
+					payout.permission = finalconfig.getString("payouts." + key + ".permission");	
+				}
+				if(finalconfig.getString("payouts." + key + ".commands") != null){
+					payout.commands = finalconfig.getStringList("payouts." + key + ".commands");
+				}
+				
+				if(finalconfig.getString("payouts." + key + ".chance") != null){
+					payout.chance = finalconfig.getInt("payouts." + key + ".chance");
+				}
+				payouts.add(payout);
+			}
+			clogger.sendMessage("[TimeIsMoney] §aLoaded " + finalconfig.getConfigurationSection("payouts").getKeys(false).size() + " Payouts!");
+		}catch(Exception e){
+			clogger.sendMessage("[TimeIsMoney] §aFailed to load Payouts! (May made a mistake in config.yml?)");
+		}
+	}
+    boolean setupEconomy()
+    {
+        RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
+        if (economyProvider != null) {
+            economy = economyProvider.getProvider();
+        }
+
+        return (economy != null);
+    }
+    public Payout getPayOutForPlayer(Player p){
+    	Payout finalpayout = null;
+    	if(!this.getConfig().getBoolean("choose-payout-by-chance")){
+    		//by Permission
+    		for(Payout payout: payouts){
+    			if(payout.permission == "") finalpayout = payout;
+    			if(p.hasPermission(payout.permission)){
+    				finalpayout = payout;
+    			}
+    		}	
+    	}else{
+    		//by Chance
+    		Random rnd = new Random();
+    		List<Payout> list = new ArrayList<Payout>();
+    		for(Payout payout: payouts){
+    			for(int i = 0; i < payout.chance; i++) list.add(payout);
+    		}
+    		finalpayout = list.get(rnd.nextInt(list.size() - 1));
+    	}
+    	return finalpayout;
+    }
+	@SuppressWarnings("deprecation")
+	public void pay(Player p){
+		if(p == null) return;
+		
+		//REACHED MAX PAYOUT CHECK
+		double payed = 0;
+		if(payedMoney.containsKey(p.getName())){
+			payed = payedMoney.get(p.getName());
+		}
+		Payout payout = getPayOutForPlayer(p);
+		if(payout == null) return;
+		if(payout.max_payout_per_day != -1){
+			if(payed >= payout.max_payout_per_day){ //Reached max payout
+				if(finalconfig.getBoolean("display-messages-in-chat")){
+					sendMessage(p, finalconfig.getString("message_payoutlimit_reached"));
+				}
+				if(finalconfig.getBoolean("display-messages-in-actionbar") && use18Features){
+					sendActionbar(p, finalconfig.getString("message_payoutlimit_reached_actionbar"));
+				}
+				return;
+			}	
+		}
+		
+		//AFK CHECK
+		if(!finalconfig.getBoolean("afk_payout") && !p.hasPermission("tim.afkbypass")){
+			//ESENTIALS_AFK_FEATURE
+			if(Bukkit.getServer().getPluginManager().isPluginEnabled("Essentials")){
+				com.earth2me.essentials.Essentials essentials = (com.earth2me.essentials.Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
+			    if(essentials.getUser(p).isAfk()){
+			    	//AFK
+					if(finalconfig.getBoolean("display-messages-in-chat")){
+						sendMessage(p, finalconfig.getString("message_afk"));	
+					}
+					if(finalconfig.getBoolean("display-messages-in-actionbar") && use18Features){
+						sendActionbar(p, finalconfig.getString("message_afk_actionbar"));
+					}
+					return;
+			    }
+			}else
+			//PLUGIN_AFK_FEATURE
+			if(lastLocation.containsKey(p)){ //AntiAFK
+				if(lastLocation.get(p).getX() == p.getLocation().getX() && lastLocation.get(p).getY() == p.getLocation().getY() && lastLocation.get(p).getZ() == p.getLocation().getZ() || lastLocation.get(p).getYaw() == p.getLocation().getYaw()){
+					//AFK
+					if(finalconfig.getBoolean("display-messages-in-chat")){
+						sendMessage(p, finalconfig.getString("message_afk"));	
+					}
+					if(finalconfig.getBoolean("display-messages-in-actionbar") && use18Features){
+						sendActionbar(p, finalconfig.getString("message_afk_actionbar"));
+					}
+					return;
+				}
+			}	
+		}
+		
+		//DEPOSIT
+		if(finalconfig.getBoolean("store-money-in-bank")){
+			ATM.depositBank(p, payout.payout_amount);
+		}else{
+			double before = 0;
+			if(economy.hasAccount(p)){
+				before = economy.getBalance(p);
+			}
+		
+			economy.depositPlayer(p, payout.payout_amount);
+			log(p.getName() + ": Deposited: " + payout.payout_amount + " Balance-before: " + before + " Balance-now: " + economy.getBalance(p));
+			
+		}
+		if(finalconfig.getBoolean("display-messages-in-chat")){
+			sendMessage(p, message.replace("%money%", economy.format(payout.payout_amount)));	
+		}
+		if(finalconfig.getBoolean("display-messages-in-actionbar") && use18Features){
+			sendActionbar(p, message.replace("%money%", economy.format(payout.payout_amount)));
+		}
+		for(String cmd : payout.commands){
+			this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd.replace("/", "").replaceAll("%player%", p.getName()));
+		}
+		
+		//ADD PAYED MONEY
+		if(payedMoney.containsKey(p.getName())){
+			payedMoney.put(p.getName(), payedMoney.get(p.getName()) + payout.payout_amount);
+		}else{
+			payedMoney.put(p.getName(), payout.payout_amount);
+		}
+		
+		lastLocation.put(p, p.getLocation());
+	
+	}
+	@SuppressWarnings("deprecation")
+	public void log(String msg){
+		if(!this.getConfig().getBoolean("debug-log")){
+			return;	
+		}
+		Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
+
+		File file = new File("plugins/TimeIsMoney/log.txt");
+			try {
+				if(!file.exists()){
+					file.createNewFile();
+				}
+				FileReader pr = new FileReader(file);
+				int number = 0;
+				StringBuffer text = new StringBuffer();
+				while((number = pr.read()) != -1){
+					
+					text.append((char) number);
+				}
+				text.append(currentTimestamp.toGMTString() + ":" + msg + "\n");
+				PrintWriter pw = new PrintWriter(file);
+				pw.print(text);
+				
+				pw.close();
+			} catch (IOException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+	}
+	public void sendMessage(Player p, String msg){
+		if(msg.length() == 0) return;
+		p.sendMessage(msg.replace('&', '§'));
+	}
+	public void sendActionbar(final Player p, final String msg){
+		if(msg.length() == 0) return;
+		int times = finalconfig.getInt("display-messages-in-actionbar-time");
+		if(times == 1){
+			if(utils != null){
+				utils.sendActionBarMessage(p, msg);	
+			}
+		}else if(times > 1){
+			if(utils != null){
+				utils.sendActionBarMessage(p, msg);	
+			}
+			times--;
+			for(int i = 0; i < times; i++){
+				Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
+					public void run(){
+						utils.sendActionBarMessage(p, msg.replace('&', '§'));
+					}
+				}, 20L * i);
+			}
+		}
+	}
+	private boolean unloadPlugin(String pluginName)
+		    throws Exception
+		  {
+		    PluginManager manager = getServer().getPluginManager();
+		    SimplePluginManager spmanager = (SimplePluginManager)manager;
+		    if (spmanager != null)
+		    {
+		      Field pluginsField = spmanager.getClass().getDeclaredField("plugins");
+		      pluginsField.setAccessible(true);
+		      List<Plugin> plugins = (List)pluginsField.get(spmanager);
+		      
+		      Field lookupNamesField = spmanager.getClass().getDeclaredField("lookupNames");
+		      lookupNamesField.setAccessible(true);
+		      Map<String, Plugin> lookupNames = (Map)lookupNamesField.get(spmanager);
+		      
+		      Field commandMapField = spmanager.getClass().getDeclaredField("commandMap");
+		      commandMapField.setAccessible(true);
+		      SimpleCommandMap commandMap = (SimpleCommandMap)commandMapField.get(spmanager);
+		      
+		      Field knownCommandsField = null;
+		      Map<String, Command> knownCommands = null;
+		      if (commandMap != null)
+		      {
+		        knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
+		        knownCommandsField.setAccessible(true);
+		        knownCommands = (Map)knownCommandsField.get(commandMap);
+		      }
+		      Plugin plugin;
+		      Iterator<Map.Entry<String, Command>> it;
+		      for (Plugin plugin1 : manager.getPlugins()) {
+		        if (plugin1.getDescription().getName().equalsIgnoreCase(pluginName))
+		        {
+		          manager.disablePlugin(plugin1);
+		          if ((plugins != null) && (plugins.contains(plugin1))) {
+		            plugins.remove(plugin1);
+		          }
+		          if ((lookupNames != null) && (lookupNames.containsKey(pluginName))) {
+		            lookupNames.remove(pluginName);
+		          }
+		          if (commandMap != null) {
+		            for (it = knownCommands.entrySet().iterator(); it.hasNext();)
+		            {
+		              Map.Entry<String, Command> entry = (Map.Entry)it.next();
+		              if ((entry.getValue() instanceof PluginCommand))
+		              {
+		                PluginCommand command = (PluginCommand)entry.getValue();
+		                if (command.getPlugin() == plugin1)
+		                {
+		                  command.unregister(commandMap);
+		                  it.remove();
+		                }
+		              }
+		            }
+		          }
+		        }
+		      }
+		    }
+		    else
+		    {
+
+		      return true;
+		    }
+
+
+		    return true;
+		  }
+		  
+		  private boolean loadPlugin(String pluginName)
+		  {
+		    try
+		    {
+		      PluginManager manager = getServer().getPluginManager();
+		      Plugin plugin = manager.loadPlugin(new File("plugins", pluginName + ".jar"));
+		      if (plugin == null)
+		      {
+		        return false;
+		      }
+		      plugin.onLoad();
+		      manager.enablePlugin(plugin);
+		    }
+		    catch (Exception e)
+		    {
+
+		      return false;
+		    }
+
+		    return true;
+		  }
+		  
+		  private boolean reloadPlugin(String pluginName)
+		    throws Exception
+		  {
+		    boolean unload = unloadPlugin(pluginName);
+		    boolean load = loadPlugin(pluginName);
+
+		    if ((unload) && (load))
+		    {
+
+		    }
+		    else
+		    {
+
+		      return false;
+		    }
+		    return true;
+		  }
+}

+ 12 - 0
TimeIsMoney2/src/de/Linus122/TimeIsMoney/Payout.java

@@ -0,0 +1,12 @@
+package de.Linus122.TimeIsMoney;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Payout {
+	double payout_amount = 0;
+	double max_payout_per_day = 0;
+	String permission = "";
+	int chance = 0;
+	List<String> commands = new ArrayList<String>();
+}

+ 7 - 0
TimeIsMoney2/src/de/Linus122/TimeIsMoney/Utils.java

@@ -0,0 +1,7 @@
+package de.Linus122.TimeIsMoney;
+
+import org.bukkit.entity.Player;
+
+public interface Utils {
+	public void sendActionBarMessage(Player p, String message);
+}

+ 361 - 0
TimeIsMoney2/src/modules/atm/ATM.java

@@ -0,0 +1,361 @@
+package modules.atm;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Material;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.block.Block;
+import org.bukkit.block.Sign;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandExecutor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.entity.Player;
+import org.bukkit.event.Event.Result;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.event.block.SignChangeEvent;
+import org.bukkit.event.inventory.InventoryClickEvent;
+import org.bukkit.event.inventory.InventoryDragEvent;
+import org.bukkit.event.inventory.InventoryMoveItemEvent;
+import org.bukkit.event.player.PlayerInteractEvent;
+import org.bukkit.inventory.Inventory;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.ItemMeta;
+import org.bukkit.plugin.Plugin;
+
+import de.Linus122.TimeIsMoney.Main;
+
+public class ATM implements Listener, CommandExecutor {
+	Plugin pl;
+	
+	public static YamlConfiguration cfg;
+	public static File fileBankAccounts = new File("plugins/TimeIsMoney/data.dat");
+	
+	public ATM(Main pl){
+		this.pl = pl;
+		pl.getServer().getPluginManager().registerEvents(this, pl);
+		pl.getCommand("atm").setExecutor(this);
+		if(!fileBankAccounts.exists()){
+			try {
+				fileBankAccounts.createNewFile();
+			} catch (IOException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}	
+		}
+		cfg = YamlConfiguration.loadConfiguration(fileBankAccounts);
+	}
+	public static void withdrawBank(Player p, double amount){
+		String bankString = getBankString(p);
+		if(!cfg.contains(bankString)) cfg.set(bankString, 0.0);
+		cfg.set(bankString, getBankBalance(p) - amount);
+		saveBanks();
+	}
+	public static void depositBank(Player p, double amount){
+		String bankString = getBankString(p);
+		if(!cfg.contains(bankString)) cfg.set(bankString, 0.0);
+		cfg.set(bankString, getBankBalance(p) + amount);
+		saveBanks();
+	}
+	public static boolean bankHas(Player p, double amount){
+		String bankString = getBankString(p);
+		if(!cfg.contains(bankString)) cfg.set(bankString, 0.0);
+		if(getBankBalance(p) >= amount){
+			return true;
+		}else{
+			return false;
+		}
+		
+	}
+	public static double getBankBalance(Player p){
+		String bankString = getBankString(p);
+		if(!cfg.contains(bankString)) cfg.set(bankString, 0.0);
+		return cfg.getDouble(bankString);
+	}
+	public static void saveBanks(){
+		try {
+			cfg.save(fileBankAccounts);
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+	}
+	//Converts old tim bank
+	public static void convertOldBank(Player p){
+		String bankString = getBankString(p);
+		if(Main.economy.hasAccount(bankString)){
+			if(Main.economy.getBalance(bankString) > 0){
+				p.sendMessage("§aSuccessfully converted your old TIM-Bank to new version!");
+				depositBank(p, Main.economy.getBalance(bankString));
+				Main.economy.withdrawPlayer(bankString, Main.economy.getBalance(bankString));	
+			}
+		}
+	}
+	private static String getBankString(Player p){
+		if(!Main.finalconfig.getBoolean("group-atms")){
+			return p.getName() + "_TimBANK";
+		}else{
+			for(String key : Main.finalconfig.getConfigurationSection("atm_groups").getKeys(false)){
+				List<String> list = Main.finalconfig.getStringList("atm_groups." + key);
+				if(list.contains(p.getWorld().getName())){
+					return p.getName() + "_TimBANK_" + key;
+				}
+			}
+		}
+		return p.getName() + "_TimBANK";
+		/*if(!Main.finalconfig.getBoolean("group-atms")){
+			return p.getName() + "_TimBANK";
+		}else{
+			for(String key : Main.finalconfig.getConfigurationSection("atm_groups").getKeys(false)){
+				List<String> list = Main.finalconfig.getStringList("atm_groups." + key);
+				if(list.contains(p.getWorld().getName())){
+					return p.getName() + "_TimBANK_" + key;
+				}
+			}
+		}
+		return p.getName() + "_TimBANK";*/
+	}
+	@EventHandler(priority = EventPriority.HIGHEST)
+	public void onInteract(PlayerInteractEvent e){
+		if(e.getClickedBlock() != null){
+			if(e.getClickedBlock().getType() == Material.WALL_SIGN || e.getClickedBlock().getType() == Material.SIGN || e.getClickedBlock().getType() == Material.SIGN_POST){
+				Sign sign = (Sign) e.getClickedBlock().getState();	
+				if(sign.getLine(0).equalsIgnoreCase("§cATM")){
+					if(!e.getPlayer().hasPermission("tim.atm.use")){
+						e.getPlayer().sendMessage(Main.finalconfig.getString("message_atm_noperms").replace('&', '§'));
+					}else{
+						this.openGUI(e.getPlayer());
+					}
+				}
+			}
+		}
+	}
+	@EventHandler
+	public void onMove(InventoryMoveItemEvent e){
+		if(e.getSource() == null) return;
+		if(e.getSource().getTitle() == null) return;
+		if(e.getSource().getTitle().equals(Main.finalconfig.getString("atm_title").replace('&', '§'))){
+			e.setCancelled(true);
+		}
+	}
+	@SuppressWarnings("deprecation")
+	@EventHandler
+	public void onClick(InventoryClickEvent e){
+		try{
+			if(e == null) return;
+			if(e.getInventory() == null) return;
+			if(e.getInventory().getTitle() == null) return;
+			if(e.getInventory().getTitle().equals(Main.finalconfig.getString("atm_title").replace('&', '§'))){
+				e.setResult(Result.DENY);
+				Player p = (Player) e.getWhoClicked();
+				//e.setCancelled(true);
+				if(e.getCurrentItem() != null){
+					if(e.getCurrentItem().getItemMeta().getDisplayName().split(" ")[0].equals(Main.finalconfig.getString("atm_withdraw").replace('&', '§'))){
+	
+						double amount = Double.parseDouble(e.getCurrentItem().getItemMeta().getLore().get(0));
+						
+						if(ATM.bankHas(p, amount)){
+							ATM.withdrawBank(p, amount);
+							Main.economy.depositPlayer(p, amount);
+							e.getWhoClicked().sendMessage(Main.finalconfig.getString("atm_withdraw").replace('&', '§') + " " + Main.economy.format(amount));
+						}else{
+							e.getWhoClicked().sendMessage(Main.finalconfig.getString("message_atm_nomoneyinbank").replace('&', '§'));
+						}
+					}else
+					if(e.getCurrentItem().getItemMeta().getDisplayName().split(" ")[0].equals(Main.finalconfig.getString("atm_deposit").replace('&', '§'))){
+						
+						double amount = Double.parseDouble(e.getCurrentItem().getItemMeta().getLore().get(0));
+						
+						if(Main.economy.has((Player) e.getWhoClicked(), amount)){
+							ATM.depositBank(p, amount);
+							Main.economy.withdrawPlayer((Player) e.getWhoClicked(), amount);
+							e.getWhoClicked().sendMessage(Main.finalconfig.getString("atm_deposit").replace('&', '§') + " " + Main.economy.format(amount));
+						}else{
+							e.getWhoClicked().sendMessage(Main.finalconfig.getString("message_atm_nomoney").replace('&', '§'));
+						}
+					}
+					ItemStack is = new ItemStack(Material.GOLD_NUGGET, 1);
+					ItemMeta im = is.getItemMeta();
+					im.setDisplayName("§cBank balance: " + ATM.getBankBalance(p));
+					is.setItemMeta(im);
+					e.getInventory().setItem(4, is);
+				}
+			}
+		}catch(Exception e2){
+			
+		}
+	}
+	private void openGUI(Player player) {
+		convertOldBank(player);
+		Inventory atm_gui = Bukkit.createInventory(null, 9, "§cATM");
+		
+		//
+		ItemStack is = new ItemStack(Material.GOLD_NUGGET, 1);
+		ItemMeta im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_balance").replace('&', '§') + " " + Main.economy.format(ATM.getBankBalance(player)));
+		is.setItemMeta(im);
+		atm_gui.setItem(4, is);
+		
+
+		//
+		is = new ItemStack(Material.CLAY_BRICK, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_withdraw").replace('&', '§') + " §a" + Main.economy.format(10));
+		List<String> lore = new ArrayList<String>();
+		lore.add("10");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(3, is);
+		
+		//
+		is = new ItemStack(Material.IRON_INGOT, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_withdraw").replace('&', '§') +  " §a" + Main.economy.format(100));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("100");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(2, is);
+		
+		//
+		is = new ItemStack(Material.GOLD_INGOT, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_withdraw").replace('&', '§') + " §a" + Main.economy.format(1000));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("1000");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(1, is);
+		
+		//
+		is = new ItemStack(Material.DIAMOND, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_withdraw").replace('&', '§') + " §a" + Main.economy.format(10000));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("10000");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(0, is);
+		
+		//DEPOSITE
+		//
+		is = new ItemStack(Material.CLAY_BRICK, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_deposit").replace('&', '§') + " §4" + Main.economy.format(10));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("10");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(5, is);
+		
+		//
+		is = new ItemStack(Material.IRON_INGOT, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_deposit").replace('&', '§') + " §4" + Main.economy.format(100));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("100");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(6, is);
+		
+		//
+		is = new ItemStack(Material.GOLD_INGOT, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_deposit").replace('&', '§') + " §4" + Main.economy.format(1000));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("1000");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(7, is);
+		
+		//
+		is = new ItemStack(Material.DIAMOND, 1);
+		im = is.getItemMeta();
+		im.setDisplayName(Main.finalconfig.getString("atm_deposit").replace('&', '§') + " §4" + Main.economy.format(10000));
+		lore.clear();
+		lore = new ArrayList<String>();
+		lore.add("10000");
+		im.setLore(lore);
+		is.setItemMeta(im);
+		atm_gui.setItem(8, is);
+		
+		player.openInventory(atm_gui);
+		
+	}
+	public static void changeMoney(Player p, double amount){
+		
+	}
+	@EventHandler
+	public void onItem2(InventoryDragEvent e){
+		if(e == null) return;
+		if(e.getInventory() == null) return;
+		if(e.getInventory().getTitle() == null) return;
+		if(e.getInventory().getTitle().equals(Main.finalconfig.getString("atm_title").replace('&', '§'))){
+			e.setResult(Result.DENY);
+		}
+	}
+	@EventHandler
+	public void onSign(final SignChangeEvent e){
+		final Block b = e.getBlock();
+		if(b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN || b.getType() == Material.SIGN_POST){
+			pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new Runnable(){
+				public void run(){
+					if(b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN || b.getType() == Material.SIGN_POST){
+						Sign sign = (Sign) e.getBlock().getState();
+						if(sign.getLine(0).equalsIgnoreCase("[atm]")){
+							if(!e.getPlayer().hasPermission("tim.atm.place")){
+								e.getPlayer().sendMessage("§cYou dont have permissions to build ATM's!");
+								sign.setLine(0, "");
+								return;
+							}else{
+								sign.setLine(0, "§cATM");
+								sign.update();
+								e.getPlayer().sendMessage("§2ATM created! (You can also write something in the Lins 2-4)");
+							}
+						}
+					}
+				}
+			}, 10L);
+		}
+	}
+
+	@Override
+	public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] args) {
+		if(args.length == 0){
+			if(cs.hasPermission("tim.use")){
+				openGUI((Player) cs);
+				return true;
+			}
+		}
+		if(cs.hasPermission("tim.admin")){
+			if(args.length > 0){
+				@SuppressWarnings("deprecation")
+				OfflinePlayer op = Bukkit.getOfflinePlayer(args[0]);
+				if(op == null){
+					cs.sendMessage("Player is offline");
+					return true;
+				}
+				if(op.isOnline()){
+					openGUI(op.getPlayer());
+					cs.sendMessage("opened!");
+				}
+			}else{
+				cs.sendMessage("/atm <player>");
+				return true;
+			}
+		}
+		return true;
+	}
+}

+ 17 - 0
TimeIsMoney2/src/plugin.yml

@@ -0,0 +1,17 @@
+name: TimeIsMoney
+depends: [Vault]
+soft-depends: [Essentials]
+author: Linus122
+main: de.Linus122.TimeIsMoney.Main
+version: 1944
+description: Gives money for online time
+commands:
+   timeismoney:
+      description: Reloads the Config
+      aliases: tim
+      usage: /<command>
+      permission: tim.reload
+   atm:
+      description: Opens the atm for other player
+      usage: /<command>
+      permission: tim.admin

+ 17 - 0
TimeIsMoney2/src/v1_10_R1/NBTUtils.java

@@ -0,0 +1,17 @@
+package v1_10_R1;
+
+import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+
+import de.Linus122.TimeIsMoney.Utils;
+import net.minecraft.server.v1_10_R1.IChatBaseComponent;
+import net.minecraft.server.v1_10_R1.PacketPlayOutChat;
+
+public class NBTUtils implements Utils{
+  public void sendActionBarMessage(Player p, String message)
+  {
+	    IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message.replace('&', '§') + "\"}");
+	    PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2);
+	    ((CraftPlayer)p).getHandle().playerConnection.sendPacket(bar);
+  }
+}

+ 17 - 0
TimeIsMoney2/src/v1_11_R1/NBTUtils.java

@@ -0,0 +1,17 @@
+package v1_11_R1;
+
+import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+
+import de.Linus122.TimeIsMoney.Utils;
+import net.minecraft.server.v1_11_R1.IChatBaseComponent;
+import net.minecraft.server.v1_11_R1.PacketPlayOutChat;
+
+public class NBTUtils implements Utils{
+  public void sendActionBarMessage(Player p, String message)
+  {
+	    IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message.replace('&', '§') + "\"}");
+	    PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2);
+	    ((CraftPlayer)p).getHandle().playerConnection.sendPacket(bar);
+  }
+}

+ 19 - 0
TimeIsMoney2/src/v1_8_R1/NBTUtils.java

@@ -0,0 +1,19 @@
+package v1_8_R1;
+
+import org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+
+import de.Linus122.TimeIsMoney.Utils;
+import net.minecraft.server.v1_8_R1.ChatSerializer;
+import net.minecraft.server.v1_8_R1.IChatBaseComponent;
+import net.minecraft.server.v1_8_R1.PacketPlayOutChat;
+
+public class NBTUtils implements Utils{
+  @Override
+  public void sendActionBarMessage(Player p, String message)
+  {
+	    IChatBaseComponent icbc = ChatSerializer.a("{\"text\": \"" + message.replace('&', '§') + "\"}");
+	    PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2);
+	    ((CraftPlayer)p).getHandle().playerConnection.sendPacket(bar);
+  }
+}

+ 18 - 0
TimeIsMoney2/src/v1_8_R2/NBTUtils.java

@@ -0,0 +1,18 @@
+package v1_8_R2;
+
+import org.bukkit.craftbukkit.v1_8_R2.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+
+import de.Linus122.TimeIsMoney.Utils;
+import net.minecraft.server.v1_8_R2.IChatBaseComponent;
+import net.minecraft.server.v1_8_R2.PacketPlayOutChat;
+
+public class NBTUtils implements Utils{
+  @Override
+  public void sendActionBarMessage(Player p, String message)
+  {
+	    IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message.replace('&', '§') + "\"}");
+	    PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2);
+	    ((CraftPlayer)p).getHandle().playerConnection.sendPacket(bar);
+  }
+}

+ 17 - 0
TimeIsMoney2/src/v1_8_R3/NBTUtils.java

@@ -0,0 +1,17 @@
+package v1_8_R3;
+
+import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+
+import de.Linus122.TimeIsMoney.Utils;
+import net.minecraft.server.v1_8_R3.IChatBaseComponent;
+import net.minecraft.server.v1_8_R3.PacketPlayOutChat;
+
+public class NBTUtils implements Utils{
+  public void sendActionBarMessage(Player p, String message)
+  {
+	    IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message.replace('&', '§') + "\"}");
+	    PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2);
+	    ((CraftPlayer)p).getHandle().playerConnection.sendPacket(bar);
+  }
+}

+ 17 - 0
TimeIsMoney2/src/v1_9_R1/NBTUtils.java

@@ -0,0 +1,17 @@
+package v1_9_R1;
+
+import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+
+import de.Linus122.TimeIsMoney.Utils;
+import net.minecraft.server.v1_9_R1.IChatBaseComponent;
+import net.minecraft.server.v1_9_R1.PacketPlayOutChat;
+
+public class NBTUtils implements Utils{
+  public void sendActionBarMessage(Player p, String message)
+  {
+	    IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message.replace('&', '§') + "\"}");
+	    PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2);
+	    ((CraftPlayer)p).getHandle().playerConnection.sendPacket(bar);
+  }
+}

+ 76 - 0
TimeIsMoney2/src/webapi/VersionChecker.java

@@ -0,0 +1,76 @@
+package webapi;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+
+import de.Linus122.TimeIsMoney.Main;
+
+public class VersionChecker {
+	public static String url_check_version = "http://avendria.de/tim/checkversion.php?version=";
+	public static String url_download = "http://avendria.de/tim/download.php";
+
+	public static int getVersion() {
+
+		try {
+			URLConnection con = new URL(url_check_version + Main.PL_VERSION).openConnection();
+			con.setRequestProperty("User-Agent",
+					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
+
+			return Integer.parseInt(get_content(con));
+
+		} catch (IOException e) {
+			return 0;
+		}
+
+	}
+
+	public static void download(File location) throws IOException {
+		URLConnection con = new URL(url_download).openConnection();
+		con.setRequestProperty("User-Agent",
+				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
+		InputStream in = con.getInputStream();
+		FileOutputStream fos = new FileOutputStream(location);
+		byte[] buf = new byte[512];
+		while (true) {
+			int len = in.read(buf);
+			if (len == -1) {
+				break;
+			}
+			fos.write(buf, 0, len);
+		}
+		in.close();
+		fos.flush();
+		fos.close();
+	}
+
+	public static String get_content(URLConnection con) {
+		String content = "";
+		if (con != null) {
+
+			try {
+
+				BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
+
+				String input;
+				while ((input = br.readLine()) != null) {
+					content += input;
+				}
+				br.close();
+
+			} catch (IOException e) {
+				
+			}
+
+		}
+		if(content.length() == 0){
+			return "0";
+		}
+		return content;
+	}
+}