Advertisement
Jnk1296

IP-Check

Mar 31st, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 27.83 KB | None | 0 0
  1. package net.risenphoenix.jnk.ipcheck;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataInputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FilenameFilter;
  8. import java.io.InputStreamReader;
  9. import java.net.InetAddress;
  10. import java.util.ArrayList;
  11.  
  12. import org.bukkit.Bukkit;
  13. import org.bukkit.ChatColor;
  14. import org.bukkit.OfflinePlayer;
  15. import org.bukkit.command.Command;
  16. import org.bukkit.command.CommandSender;
  17. import org.bukkit.entity.Player;
  18. import org.bukkit.event.EventHandler;
  19. import org.bukkit.event.EventPriority;
  20. import org.bukkit.event.Listener;
  21. import org.bukkit.event.player.PlayerLoginEvent;
  22. import org.bukkit.event.player.PlayerLoginEvent.Result;
  23. import org.bukkit.plugin.java.JavaPlugin;
  24.  
  25. public class IPcheck extends JavaPlugin implements Listener{
  26.    
  27.     // IP-Check v1.1.0 by Jnk1296. Designed for checking for and banning multi-accounting players.
  28.    
  29.     public static final String plugName = "[IP-check] ";
  30.    
  31.     public static final String banListReadErr = "Error occurred while attempting to read banned-ips.txt!";
  32.     public static final String playerFileReadErr = "Error occurred while attempting to read player file!";
  33.     public static final String noPermErr = "You don't have permission to do that!";
  34.     public static final String numArgsErr = "Incorrect Number of Arguments.";
  35.     public static final String illArgsErr = "Illegal Argument(s) were passed into the command.";
  36.     public static final String noFind = "The player specified could not be found.";
  37.     public static final String defBanMsg = "Banned for Multi-accounting.";
  38.     public static final String noRecent = "You have not searched a player yet.";
  39.    
  40.     public static String recent = "";
  41.     public static String recentPlayer = "";
  42.    
  43.     public static File bannedIPs = new File("banned-ips.txt");
  44.     public static File playersDir = new File("plugins/Essentials/userdata");
  45.    
  46.     private static boolean foundIP = false;
  47.     private static boolean isBanned = false;
  48.     private static int playersFound = 0;
  49.    
  50.     @Override
  51.     public void onEnable() {
  52.         getServer().getPluginManager().registerEvents(this, this); // Register the Player Login Listener
  53.         Configuration.onLoad(); // Load the Configuration File
  54.     }
  55.    
  56.     @Override
  57.     public void onDisable() {
  58.         // Do Nothing
  59.     }
  60.    
  61.     @EventHandler (priority = EventPriority.MONITOR)
  62.     public void onPlayerJoin(PlayerLoginEvent e) {
  63.         if (Configuration.notifyLogin || Configuration.secureMode) { // Only perform this if either one of these options is enabled, else return immediately
  64.             Player player = e.getPlayer();
  65.             boolean shouldCheck = false;
  66.            
  67.             // Do not perform check on operators or players with the "ipcheck.getnotify permission.
  68.             if (!player.isOp() || player.hasPermission("ipcheck.getnotify")) {
  69.                
  70.                 // Construct the IP Address String
  71.                 String iNetAddress = getIP(e);
  72.                 getLogger().info(iNetAddress);
  73.                 StringBuilder ip = new StringBuilder();
  74.                 for (int i = 0; i < iNetAddress.length(); i++) {
  75.                     if ((iNetAddress.charAt(i) >= '0' && iNetAddress.charAt(i) <= '9') || iNetAddress.charAt(i) == '.') {
  76.                         ip.append(iNetAddress.charAt(i));
  77.                     } else if (iNetAddress.charAt(i) == ':') {
  78.                         break;
  79.                     }
  80.                 }
  81.                
  82.                 if (Configuration.secureMode) {
  83.                     shouldCheck = secureKick(secureCheck(ip.toString(), player.getName()), player.getName(), e);
  84.                 }
  85.                
  86.                 if (Configuration.notifyLogin && shouldCheck) {
  87.                     loginCheck(ip.toString(), e.getPlayer());
  88.                     return;
  89.                 }
  90.             }
  91.         }
  92.        
  93.         return;
  94.     }
  95.    
  96.     public static String getIP(PlayerLoginEvent e) {
  97.         InetAddress a = e.getAddress();
  98.         String ip = a.getHostAddress();
  99.        
  100.         return ip;
  101.     }
  102.    
  103.     @Override
  104.     public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
  105.         if (cmd.getName().equalsIgnoreCase("check")) {
  106.             try {
  107.                 if (args[0] != null) { 
  108.                     // Ban Command
  109.                     if (args[0].equalsIgnoreCase("ban")) {
  110.                         if (sender.hasPermission("ipcheck.ban") || sender.isOp()) {
  111.                             if (args.length == 2) {
  112.                                 //Command Instructions Here
  113.                                 if (args[1].charAt(0) >= '0'&& args[1].charAt(0) <= '9') { // Check that argument is a potential IP address
  114.                                     // Command Operation
  115.                                     report(banPlayers(checkPlayers(compareIP(args[1], getBannedList()), getPlayerFiles()), sender, args[1], true), sender, args[1], false);
  116.                                     recent = "";
  117.                                 } else {
  118.                                     sender.sendMessage(illArgsErr);
  119.                                 }
  120.                             } else {
  121.                                 sender.sendMessage(numArgsErr);
  122.                             }
  123.                         } else {
  124.                             sender.sendMessage(noPermErr);
  125.                         }
  126.                        
  127.                         return true;
  128.                        
  129.                     // Unban Command
  130.                     } else if (args[0].equalsIgnoreCase("unban")) {
  131.                         if (sender.hasPermission("ipcheck.unban") || sender.isOp()) {
  132.                             if (args.length == 2) {
  133.                                 //Command Instructions Here
  134.                                 if (args[1].charAt(0) >= '0'&& args[1].charAt(0) <= '9') { // Check that argument is a potential IP address
  135.                                     // Command Operation
  136.                                     report(banPlayers(checkPlayers(compareIP(args[1], getBannedList()), getPlayerFiles()), sender, args[1], false), sender, args[1], false);
  137.                                     recent = "";
  138.                                 } else {
  139.                                     sender.sendMessage(illArgsErr);
  140.                                 }
  141.                             } else {
  142.                                 sender.sendMessage(numArgsErr);
  143.                             }
  144.                         } else {
  145.                             sender.sendMessage(noPermErr);
  146.                         }
  147.                        
  148.                         return true;
  149.                        
  150.                     // Player Command
  151.                     } else if (args[0].equalsIgnoreCase("player")) {
  152.                         if (sender.hasPermission("ipcheck.player") || sender.isOp()) {
  153.                             if (args.length == 2) {
  154.                                 //Command Instructions Here
  155.                                 report(checkPlayers(compareIP(getPlayerInfo(args[1], getPlayerFiles()), getBannedList()), getPlayerFiles()), sender, recent, true);
  156.                             } else {
  157.                                 sender.sendMessage(numArgsErr);
  158.                             }
  159.                         } else {
  160.                             sender.sendMessage(noPermErr);
  161.                         }
  162.                        
  163.                         return true;
  164.                        
  165.                     // Banrecent Command
  166.                     } else if (args[0].equalsIgnoreCase("banrecent")) {
  167.                         if ((sender.hasPermission("ipcheck.recent") && sender.hasPermission("ipcheck.ban")) || sender.isOp()) {
  168.                             if (args.length == 1) {
  169.                                 //Command Instructions Here
  170.                                 if (!recent.equals("")) {
  171.                                     report(banPlayers(checkPlayers(compareIP(recent, getBannedList()), getPlayerFiles()), sender, recent, true), sender, recent, false);
  172.                                 } else {
  173.                                     sender.sendMessage(noRecent);
  174.                                 }
  175.                             } else {
  176.                                 sender.sendMessage(numArgsErr);
  177.                             }
  178.                         } else {
  179.                             sender.sendMessage(noPermErr);
  180.                         }
  181.                        
  182.                         return true;
  183.                        
  184.                     // Unbanrecent Command
  185.                     } else if (args[0].equalsIgnoreCase("unbanrecent")) {
  186.                         if ((sender.hasPermission("ipcheck.recent") && sender.hasPermission("ipcheck.unban")) || sender.isOp()) {
  187.                             if (args.length == 1) {
  188.                                 //Command Instructions Here
  189.                                 if (!recent.equals("")) {
  190.                                     report(banPlayers(checkPlayers(compareIP(recent, getBannedList()), getPlayerFiles()), sender, recent, false), sender, recent, false);
  191.                                 } else {
  192.                                     sender.sendMessage(noRecent);
  193.                                 }
  194.                             } else {
  195.                                 sender.sendMessage(numArgsErr);
  196.                             }
  197.                         } else {
  198.                             sender.sendMessage(noPermErr);
  199.                         }
  200.                        
  201.                         return true;
  202.                        
  203.                     // Exempt Command
  204.                     } else if (args[0].equalsIgnoreCase("exempt")) {
  205.                         if (sender.hasPermission("ipcheck.exempt") || sender.isOp()) {
  206.                             if (args.length == 3) {
  207.                                 //Command Instructions Here
  208.                                 if (args[1].equalsIgnoreCase("player")) {
  209.                                     Configuration.addExemption(1, args[2]);
  210.                                 } else if (args[1].equalsIgnoreCase("ip")) {
  211.                                     Configuration.addExemption(0, args[2]);
  212.                                 }
  213.                             } else {
  214.                                 sender.sendMessage(numArgsErr);
  215.                             }
  216.                         } else {
  217.                             sender.sendMessage(noPermErr);
  218.                         }
  219.                        
  220.                         return true;
  221.                        
  222.                     // Exempt-List Command
  223.                     } else if (args[0].equalsIgnoreCase("exempt-list")) {
  224.                         //TODO REQUIRES EXPLICIT PERMISSION SETUP
  225.                         if (args.length == 2) {
  226.                             //Command Instructions Here
  227.                             //TODO
  228.                         } else {
  229.                             sender.sendMessage(numArgsErr);
  230.                         }
  231.                        
  232.                         return true;
  233.                        
  234.                     // Toggle Command
  235.                     } else if (args[0].equalsIgnoreCase("toggle")) {
  236.                         if (sender.hasPermission("ipcheck.toggle") || sender.isOp()) {
  237.                             if (args.length == 2) {
  238.                                 //Command Instructions Here
  239.                                 //TODO
  240.                             } else {
  241.                                 sender.sendMessage(numArgsErr);
  242.                             }
  243.                         } else {
  244.                             sender.sendMessage(noPermErr);
  245.                         }
  246.                        
  247.                         return true;
  248.                    
  249.                     // All else
  250.                     } else if (args.length == 1) {
  251.                         //Command Instructions here
  252.                         if (args[0].charAt(0) >= '0'&& args[0].charAt(0) <= '9') {
  253.                             report(checkPlayers(compareIP(args[0], getBannedList()), getPlayerFiles()), sender, args[0], false);
  254.                             recent = "";
  255.                             return true;
  256.                         } else {
  257.                             sender.sendMessage(illArgsErr);
  258.                         }
  259.                     }
  260.                     return false;
  261.                 }
  262.             } catch (ArrayIndexOutOfBoundsException e) {
  263.                 sender.sendMessage(numArgsErr);
  264.             }
  265.         }
  266.            
  267.         return false;
  268.     }
  269.    
  270.     // Returns a File[] array of all player files found
  271.     public File[] getPlayerFiles() {
  272.         // Create a file array which holds all files found in the directory which have the extension *.yml
  273.         File[] playerFiles = playersDir.listFiles(new FilenameFilter() {
  274.             @Override
  275.             public boolean accept(File path, String name) {
  276.                 if (name.toLowerCase().endsWith(".yml") && !name.toLowerCase().startsWith("nation_") && !name.toLowerCase().startsWith("town_")) {
  277.                     return true;
  278.                 } else {
  279.                     return false;
  280.                 }
  281.             }
  282.         });
  283.        
  284.         return playerFiles;
  285.     }
  286.    
  287.     // Returns an ArrayList<String> of all banned IP addresses
  288.     public ArrayList<String> getBannedList() {
  289.         ArrayList<String> ips = new ArrayList<String>();
  290.        
  291.         try {
  292.             FileInputStream fstream = new FileInputStream(bannedIPs);
  293.             DataInputStream in = new DataInputStream(fstream);
  294.             BufferedReader br = new BufferedReader(new InputStreamReader(in));
  295.             String strLine;
  296.            
  297.             // Skip the first three lines of the file
  298.             for (int lineSkip = 0; lineSkip < 3; lineSkip++) br.readLine();
  299.            
  300.             while ((strLine = br.readLine()) != null) {
  301.                 char start = strLine.charAt(0);
  302.                 String ip = "";
  303.                 int charCount = 0;
  304.                
  305.                 if (start >= '0' && start <= '9') {
  306.                     while (strLine.charAt(charCount) != '|') {
  307.                         ip = ip + strLine.charAt(charCount);
  308.                         charCount++;
  309.                     }
  310.                    
  311.                     ips.add(ip);
  312.                 }
  313.             }
  314.            
  315.             br.close();
  316.         } catch (Exception e) {
  317.             // Console Output in the event we fail to read the configuration file.
  318.             getLogger().severe(banListReadErr);
  319.         }
  320.        
  321.         return ips;
  322.     }
  323.    
  324.     // Compares the IP given in the command to the IP list returned from getBannedList(), returns IP given
  325.     public String compareIP(String ip, ArrayList<String> bannedIPs) {
  326.         foundIP = false;
  327.        
  328.         if (ip.equals("no-find")) return ip;
  329.        
  330.         for (String s:bannedIPs) {
  331.             if (s.equals(ip)) {
  332.                 foundIP = true;
  333.                 break;
  334.             }
  335.         }
  336.        
  337.         return ip;
  338.     }
  339.    
  340.     // Checks the IP given against the IPs of all player files. and returns an ArrayList<String> of all player files that were found to match
  341.     public ArrayList<String> checkPlayers(String ip, File[] playerFiles) {
  342.         ArrayList<String> playersMatch = new ArrayList<String>();
  343.         playersFound = 0;
  344.        
  345.         for (int i = 0; i < playerFiles.length; i++) {
  346.             File path = new File(playersDir + "/" + playerFiles[i].getName());
  347.            
  348.             try {
  349.                 FileInputStream fstream = new FileInputStream(path);
  350.                 DataInputStream in = new DataInputStream(fstream);
  351.                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
  352.                 String strLine;
  353.                
  354.                 while ((strLine = br.readLine()) != null) {
  355.                     if (strLine.startsWith("ipAddress: ")) {
  356.                         String currentIP = strLine;
  357.                         currentIP = currentIP.replace("ipAddress: ", "");
  358.                        
  359.                         if (ip.equals(currentIP)) {
  360.                             playersFound++;
  361.                             playersMatch.add(playerFiles[i].getName());
  362.                         }
  363.                        
  364.                         break;
  365.                     }
  366.                 }
  367.                
  368.                 br.close();
  369.             } catch (Exception e) {
  370.                 // Console Output in the event we fail to read the configuration file.
  371.                 getLogger().severe(playerFileReadErr);
  372.             }
  373.         }
  374.        
  375.         return playersMatch;
  376.     }
  377.    
  378.     // Returns the report summary
  379.     public void report(ArrayList<String> players, CommandSender sender, String ip, boolean forPlayer) {
  380.         if (ip.equals("no-find")) {
  381.             sender.sendMessage(noFind);
  382.             return;
  383.         }
  384.        
  385.         StringBuilder sb = new StringBuilder();
  386.        
  387.         for(String s:players) {
  388.             s = s.replace(".yml", "");
  389.             sb.append(s + ", ");
  390.         }
  391.        
  392.         sender.sendMessage("");
  393.         sender.sendMessage(ChatColor.GOLD + "Total Accounts found for: " + ip + " ... " + playersFound);
  394.         sender.sendMessage(ChatColor.DARK_GRAY + "---------------------------------------------");
  395.         sender.sendMessage(ChatColor.LIGHT_PURPLE + "The following players connect with the above IP address: " + ChatColor.YELLOW + sb);
  396.         sender.sendMessage("");
  397.        
  398.         if (forPlayer) {
  399.             sender.sendMessage(ChatColor.LIGHT_PURPLE + "Player Searched for: " + ChatColor.YELLOW + recentPlayer);
  400.             if (isBanned) {
  401.                 sender.sendMessage(ChatColor.LIGHT_PURPLE + "Player Banned: " + ChatColor.RED + isBanned);
  402.             } else {
  403.                 sender.sendMessage(ChatColor.LIGHT_PURPLE + "Player Banned: " + ChatColor.GREEN + isBanned);
  404.             }
  405.             sender.sendMessage("");
  406.         }
  407.        
  408.         if (foundIP) {
  409.             sender.sendMessage(ChatColor.LIGHT_PURPLE + "IP Banned: " + ChatColor.RED + foundIP);
  410.         } else {
  411.             sender.sendMessage(ChatColor.LIGHT_PURPLE + "IP Banned: " + ChatColor.GREEN + foundIP);
  412.         }
  413.        
  414.         sender.sendMessage(ChatColor.DARK_GRAY + "---------------------------------------------");
  415.     }
  416.    
  417.     // Report for player login check
  418.     public void loginReport(String ip, Player player) {
  419.         //if (playersFound <= 1) {
  420.         //  return;
  421.         //}
  422.        
  423.         Player[] online = getServer().getOnlinePlayers();
  424.         Player curPlayer = player;
  425.         if ((curPlayer.hasPlayedBefore() && (playersFound - 1) > Configuration.notifyThreshold) || (!curPlayer.hasPlayedBefore() && playersFound > Configuration.notifyThreshold)) { // If number of accounts is greater than threshold
  426.             for(int i = 0; i < online.length; i++) {
  427.                 if (Configuration.detailNotify) { // If Detailed Notifications are enabled, display the detailed notification.
  428.                     if (online[i].hasPermission("ipcheck.getnotify") || online[i].isOp()) { // If player is an operator or has the ipcheck.getnotify permission
  429.                         online[i].sendMessage("");
  430.                         online[i].sendMessage(ChatColor.RED + "Background Report for: " + player.getDisplayName());
  431.                         online[i].sendMessage(ChatColor.DARK_GRAY + "------------------------");
  432.                         online[i].sendMessage(ChatColor.GREEN + "IP Address: " + ChatColor.LIGHT_PURPLE + ip);
  433.                        
  434.                         if (curPlayer.hasPlayedBefore()) {
  435.                             playersFound -= 1;
  436.                         }
  437.                            
  438.                         online[i].sendMessage(ChatColor.LIGHT_PURPLE + player.getDisplayName() + ChatColor.YELLOW + " was found to have " + ChatColor.LIGHT_PURPLE +  (playersFound) + ChatColor.YELLOW + // subtract one from playersfound to make up for Recursion
  439.                                 " possible alternative accounts. Perform command " + ChatColor.LIGHT_PURPLE + "'/check player " + player.getDisplayName() + "'" +
  440.                                 ChatColor.YELLOW + " for more information.");
  441.                         online[i].sendMessage(ChatColor.DARK_GRAY + "------------------------");
  442.                         online[i].sendMessage("");
  443.                     }
  444.                 } else if (!Configuration.detailNotify) { // If Detailed Notifications are disabled, display the simple notification.
  445.                     if (online[i].hasPermission("ipcheck.getnotify") || online[i].isOp()) { // If player is an operator or has the ipcheck.getnotify permission
  446.                         online[i].sendMessage(ChatColor.GOLD + plugName + ChatColor.RED + "Warning! " + ChatColor.LIGHT_PURPLE + player.getDisplayName() + ChatColor.RED + " may have multiple accounts!");
  447.                     }
  448.                 }
  449.             }
  450.         }
  451.     }
  452.     public ArrayList<String> banPlayers(ArrayList<String> players, CommandSender sender, String ip, boolean banning) {
  453.         // Ban or Unban IP Address
  454.         if (banning) {
  455.             Bukkit.banIP(ip);
  456.             sender.sendMessage("");
  457.             sender.sendMessage("Banned IP Address: " + ip);
  458.             sender.sendMessage("");
  459.             foundIP = true;
  460.         } else if (!banning) {
  461.             Bukkit.unbanIP(ip);
  462.             sender.sendMessage("");
  463.             sender.sendMessage("Unbanned IP Address: " + ip);
  464.             sender.sendMessage("");
  465.             foundIP = false;
  466.         }
  467.        
  468.         // Ban or Unban Players with corresponding IP Address
  469.         for(String s:players) {
  470.             s = s.replace(".yml", "");
  471.            
  472.             Bukkit.getOfflinePlayer(s).setBanned(banning);
  473.            
  474.             if (banning) {
  475.                 Player player = Bukkit.getPlayer(s);
  476.                
  477.                 if (player != null) {
  478.                     player.kickPlayer(defBanMsg);
  479.                 }
  480.                
  481.                 sender.sendMessage("Banned " + s);
  482.             } else if (!banning) {
  483.                 sender.sendMessage("Pardoned " + s);
  484.             }
  485.         }
  486.        
  487.         return players;
  488.     }
  489.    
  490.     // Returns the IP address of a player specified, also sets the banned status of the player (calls getBannedStatus())
  491.     public String getPlayerInfo(String player, File[] playerFiles) {
  492.         String ip = "";
  493.         File path = null;
  494.        
  495.         String lookFor = playersDir + "/" + player + ".yml";  // Set the expected player.yml path
  496.        
  497.         // Set Path if player was found
  498.         for (int i = 0; i < playerFiles.length; i++) {
  499.             if ((playersDir + "/" + playerFiles[i].getName()).equalsIgnoreCase(lookFor)) {
  500.                 path = new File(playersDir + "/" + playerFiles[i].getName());
  501.                 break;
  502.             }
  503.         }
  504.        
  505.         // If player was not found, return the "no-find" string for ip
  506.         if (path == null) {
  507.             ip = "no-find";
  508.             recent = ip;
  509.             return ip;
  510.         }
  511.        
  512.         // If the player was valid, then set recentPlayer
  513.         recentPlayer = player;
  514.        
  515.         // Set the banned status of the player
  516.         getBannedStatus(player);
  517.            
  518.         // If player was found, then load their configuration file and obtain the IP address from it
  519.         try {
  520.             FileInputStream fstream = new FileInputStream(path);
  521.             DataInputStream in = new DataInputStream(fstream);
  522.             BufferedReader br = new BufferedReader(new InputStreamReader(in));
  523.             String strLine;
  524.            
  525.             while ((strLine = br.readLine()) != null) {
  526.                 if (strLine.startsWith("ipAddress: ")) {
  527.                     strLine = strLine.replace("ipAddress: ", "");
  528.                     ip = strLine;
  529.                     recent = ip;
  530.                     break;
  531.                 }
  532.             }
  533.            
  534.             br.close();
  535.         } catch (Exception e) {
  536.             // Console Output in the event we fail to read the configuration file.
  537.             getLogger().severe(playerFileReadErr);
  538.         }
  539.        
  540.         // Return the IP address
  541.         return ip;
  542.     }
  543.    
  544.     // Get the banned status of a player
  545.     public static void getBannedStatus(String userName) {
  546.         isBanned = false;
  547.        
  548.         OfflinePlayer player = Bukkit.getOfflinePlayer(userName);
  549.         if (player.isBanned()) isBanned = true;
  550.     }
  551.    
  552.     // Method called when a player logs in (has played before)
  553.     public void loginCheck(String ip, Player player) {
  554.         checkPlayers(compareIP(ip, getBannedList()), getPlayerFiles());
  555.         loginReport(ip, player);
  556.     }
  557.    
  558.     public int secureCheck(String ip, String playerName) {
  559.         checkPlayers(compareIP(ip, getBannedList()), getPlayerFiles());
  560.        
  561.         return playersFound;
  562.     }
  563.    
  564.     public boolean secureKick(int accounts, String player, PlayerLoginEvent e) {
  565.         if (accounts > Configuration.secureThreshold && !Configuration.isExempt(player)) { // If the player was reported to have more than the secure-threshold # of accounts, then kick (if not exempt).
  566.             //Player kickPlayer = Bukkit.getPlayer(player);
  567.            
  568.             if (player != null) {
  569.                 e.setKickMessage(Configuration.secureKickMsg);
  570.                 e.setResult(Result.KICK_OTHER);
  571.                 return false;
  572.             }
  573.         }
  574.        
  575.         return true;
  576.     }
  577. }
  578.  
  579. // Configuration class
  580. package net.risenphoenix.jnk.ipcheck;
  581.  
  582. import java.io.BufferedReader;
  583. import java.io.DataInputStream;
  584. import java.io.File;
  585. import java.io.FileInputStream;
  586. import java.io.FileWriter;
  587. import java.io.IOException;
  588. import java.io.InputStreamReader;
  589. import java.sql.Date;
  590. import java.text.SimpleDateFormat;
  591. import java.util.ArrayList;
  592. import java.util.logging.Logger;
  593.  
  594. import org.bukkit.Bukkit;
  595.  
  596. public class Configuration {
  597.    
  598.     private static Logger logger = Bukkit.getLogger();
  599.    
  600.     // File paths
  601.     static File dir = new File("plugins/IP-config");
  602.     static File path = new File("plugins/IP-config/Config.ipc");
  603.    
  604.     private static String confWriteErr = "Failed to generate Configuration File!";
  605.     private static String confReadErr = "Failed to read Configuration File!";
  606.    
  607.     public static boolean secureMode = false;
  608.     public static boolean notifyLogin = true;
  609.     public static boolean detailNotify = false;
  610.    
  611.     public static int notifyThreshold = 1;
  612.     public static int secureThreshold = 1;
  613.    
  614.     public static String secureKickMsg = "Multiple Accounts Not Permitted.";
  615.     public static String banMessage = "Banned for Multi-Accounting.";
  616.    
  617.     private static String defaultConfig =
  618.             "# IPcheck Configuration / Exemption List\r\n" +
  619.             "# Last Modified: " + getTime() + "\r\n" +
  620.             "===============================\r\n" +
  621.             "Configuration Options\r\n" +
  622.             "===============================\r\n" +
  623.             "notify-on-login: true\r\n" +
  624.             "descriptive-notice: false\r\n" +
  625.             "min-account-notify-threshold: 1\r\n" +
  626.             "secure-mode: false\r\n" +
  627.             "secure-kick-threshold: 1\r\n" +
  628.             "secure-kick-message: 'Multiple Accounts Not Permitted.'\r\n" +
  629.             "ban-message: 'Banned for Multi-Accounting.'\r\n" +
  630.             "===============================\r\n" +
  631.             "Exemptions: IP\r\n" +
  632.             "===============================\r\n" +
  633.             "===============================\r\n" +
  634.             "Exemptions: Player_Name\r\n" +
  635.             "===============================\r\n" +
  636.             "===============================\r\n";
  637.  
  638.     public static void onLoad() {
  639.         defaultConfiguration(); // Generate Default Configuration if one does not exist.
  640.         parseConfigSettings(loadConfig()); // Load and parse configuration.
  641.     }
  642.    
  643.     public static String getTime() {
  644.         @SuppressWarnings("unused")
  645.         Date date = new Date(System.currentTimeMillis());
  646.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
  647.        
  648.         return sdf.toString();
  649.     }
  650.    
  651.     // Generate Default Configuration is one is needed.
  652.     public static void defaultConfiguration() {
  653.         FileWriter f = null;
  654.        
  655.         try {
  656.             // If VoteLinks folder does not exist, create it.
  657.             if (!dir.exists()) dir.mkdir();
  658.            
  659.             // If configuration file does not exist, create it.
  660.             if (!path.exists()) {
  661.                 f = new FileWriter(path, true);
  662.                
  663.                 f.write(defaultConfig);
  664.                 f.close();
  665.             }
  666.  
  667.         } catch (IOException e) {
  668.             // Console Output (in the event of an exception)
  669.             e.printStackTrace();
  670.             logger.info(confWriteErr);
  671.         }
  672.     }
  673.    
  674.     // Fetch Configuration File for Editing Purposes
  675.     public static ArrayList<String> getConfiguration() {
  676.         ArrayList<String> config = new ArrayList<String>();
  677.        
  678.         try {
  679.             FileInputStream fstream = new FileInputStream(path);
  680.             DataInputStream in = new DataInputStream(fstream);
  681.             BufferedReader br = new BufferedReader(new InputStreamReader(in));
  682.             String strLine;
  683.            
  684.             while ((strLine = br.readLine()) != null) {
  685.                 config.add(strLine);
  686.             }
  687.            
  688.             br.close();
  689.         } catch (Exception e) {
  690.             logger.info(confReadErr);
  691.         }
  692.        
  693.         return config;
  694.     }
  695.    
  696.     // Generate a Blank Configuration Document
  697.     public static void regenerateConfiguration() {
  698.         if (path.exists()) {
  699.             path.delete();
  700.         }
  701.        
  702.         defaultConfiguration();
  703.     }
  704.    
  705.     public static void addExemption(int exemptionType, String exemption) {
  706.         if (exemptionType == 0) { // IP Exemption
  707.             return;
  708.         } else if (exemptionType == 1) { // Player Exemption
  709.             writeConfiguration(addPlayerExemption(getConfiguration(), exemption));
  710.             loadConfig();
  711.         }
  712.        
  713.         logger.warning("Failed to add exemption.");
  714.     }
  715.    
  716.     // Add a Player Exemption to the configuration
  717.     public static ArrayList<String> addPlayerExemption(ArrayList<String> config, String player) {
  718.         ArrayList<String> newConfig = new ArrayList<String>();
  719.         String EOC = config.get(config.size() - 1);
  720.        
  721.         config.set(config.size() - 1, player);
  722.         config.add(EOC);
  723.        
  724.         for (String s:config) newConfig.add(s);
  725.        
  726.         return newConfig;
  727.     }
  728.    
  729.     // Write Modified Configuration to File
  730.     public static void writeConfiguration(ArrayList<String> newConfig) {
  731.         FileWriter f = null;
  732.        
  733.         try {
  734.             if (path.exists()) {
  735.                 path.delete();
  736.             }
  737.            
  738.             f = new FileWriter(path, true);
  739.            
  740.             for(String s:newConfig) {
  741.                 f.write(s + "\r\n");
  742.             }
  743.            
  744.             f.close();
  745.         } catch (Exception e) {
  746.             e.printStackTrace();
  747.             logger.severe(confWriteErr);
  748.         }
  749.     }
  750.    
  751.     // Load Configuration from File, returns the configuration as an ArrayList<String for parsing
  752.     public static ArrayList<String> loadConfig() {
  753.         ArrayList<String> config = new ArrayList<String>();
  754.        
  755.         try {
  756.             FileInputStream fstream = new FileInputStream(path);
  757.             DataInputStream in = new DataInputStream(fstream);
  758.             BufferedReader br = new BufferedReader(new InputStreamReader(in));
  759.             String strLine;
  760.            
  761.             while ((strLine = br.readLine()) != null) {
  762.                 config.add(strLine);
  763.             }
  764.            
  765.             br.close();
  766.         } catch (Exception e) {
  767.             logger.severe(confReadErr);
  768.         }
  769.        
  770.         return config;
  771.     }
  772.    
  773.     public static void parseConfigSettings(ArrayList<String> config) {
  774.         String modulus;
  775.        
  776.         for (String line:config) {
  777.             if (line.contains("notify-on-login: ")) {
  778.                 modulus = line.replace("notify-on-login: ", "");
  779.                 if (modulus.equalsIgnoreCase("true")) {
  780.                     notifyLogin = true;
  781.                 } else {
  782.                     notifyLogin = false;
  783.                 }
  784.             } else if (line.contains("descriptive-notice: ")) {
  785.                 modulus = line.replace("descriptive-notice: ", "");
  786.                 if (modulus.equalsIgnoreCase("true")) {
  787.                     detailNotify = true;
  788.                 } else {
  789.                     detailNotify = false;
  790.                 }
  791.             } else if (line.contains("min-account-notify-threshold: ")) {
  792.                 modulus = line.replace("min-account-notify-threshold: ", "");
  793.                 try {
  794.                     notifyThreshold = Integer.parseInt(modulus);
  795.                     if (notifyThreshold < 1) {
  796.                         logger.warning("Value of Configuration option 'min-account-notify-threshold' was lower than the minumum limit! 'min-account-notify-threshold' has been set to the default value (1).");
  797.                         notifyThreshold = 1;
  798.                     }
  799.                 } catch (NumberFormatException e) {
  800.                     logger.warning("Failed to parse Configuration option 'min-account-notify-threshold': was not valid integer.");
  801.                 }
  802.             } else if (line.contains("secure-mode: ")) {
  803.                 modulus = line.replace("secure-mode: ", "");
  804.                 if (modulus.equalsIgnoreCase("true")) {
  805.                     secureMode = true;
  806.                 } else {
  807.                     secureMode = false;
  808.                 }
  809.             } else if (line.contains("secure-kick-threshold: ")) {
  810.                 modulus = line.replace("secure-kick-threshold: ", "");
  811.                 try {
  812.                     secureThreshold = Integer.parseInt(modulus);
  813.                     if (secureThreshold < 1) {
  814.                         logger.warning("Value of Configuration option 'secure-kick-threshold' was lower than the minumum limit! 'secure-kick-threshold' has been set to the default value (1).");
  815.                         secureThreshold = 1;
  816.                     }
  817.                 } catch (NumberFormatException e) {
  818.                     logger.warning("Failed to parse Configuration option 'secure-kick-threshold': was not valid integer.");
  819.                 }
  820.             } else if (line.contains("secure-kick-message: ")) {
  821.                 modulus = line.replace("secure-kick-message: ", "");
  822.                 secureKickMsg = modulus;
  823.             } else if (line.contains("ban-message: ")) {
  824.                 modulus = line.replace("ban-message: ", "");
  825.                 banMessage = modulus;
  826.             }
  827.         }
  828.     }
  829.    
  830.     // Returns list of exempt players from Configuration File
  831.     public static ArrayList<String> getPlayerExemptList() {
  832.         ArrayList<String> exemptList = new ArrayList<String>();
  833.         ArrayList<String> config = loadConfig();
  834.         int line = 0;
  835.        
  836.         for (String s:config) {
  837.             if (s.equals("Exemptions: Player_Name")) {
  838.                 line+=2;
  839.                 break;
  840.             }
  841.            
  842.             line++;
  843.         }
  844.        
  845.         while (!config.get(line).contains("=")) {
  846.             exemptList.add(config.get(line));
  847.             line++;
  848.         }
  849.  
  850.         return exemptList;
  851.     }
  852.    
  853.     public static boolean isExempt(String player) {
  854.         ArrayList<String> list = getPlayerExemptList();
  855.        
  856.         for (String s:list) {
  857.             if (s.equalsIgnoreCase(player)) {
  858.                 return true;
  859.             }
  860.         }
  861.        
  862.         return false;
  863.     }
  864.  
  865. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement