1
0
mirror of https://github.com/Zrips/Jobs.git synced 2025-02-18 05:11:32 +01:00

Block protection

This commit is contained in:
Zrips 2016-09-29 17:24:29 +03:00
parent 4fc68817f7
commit d5113847f0
22 changed files with 1819 additions and 973 deletions

View File

@ -30,6 +30,7 @@ import java.util.logging.Logger;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -38,6 +39,7 @@ import com.gamingmesh.jobs.Gui.GuiManager;
import com.gamingmesh.jobs.Signs.SignUtil; import com.gamingmesh.jobs.Signs.SignUtil;
import com.gamingmesh.jobs.api.JobsExpGainEvent; import com.gamingmesh.jobs.api.JobsExpGainEvent;
import com.gamingmesh.jobs.commands.JobsCommands; import com.gamingmesh.jobs.commands.JobsCommands;
import com.gamingmesh.jobs.config.BlockProtectionManager;
import com.gamingmesh.jobs.config.BossBarManager; import com.gamingmesh.jobs.config.BossBarManager;
import com.gamingmesh.jobs.config.ConfigManager; import com.gamingmesh.jobs.config.ConfigManager;
import com.gamingmesh.jobs.config.ExploreManager; import com.gamingmesh.jobs.config.ExploreManager;
@ -52,7 +54,10 @@ import com.gamingmesh.jobs.config.ShopManager;
import com.gamingmesh.jobs.config.TitleManager; import com.gamingmesh.jobs.config.TitleManager;
import com.gamingmesh.jobs.config.YmlMaker; import com.gamingmesh.jobs.config.YmlMaker;
import com.gamingmesh.jobs.container.ActionInfo; import com.gamingmesh.jobs.container.ActionInfo;
import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.BlockProtection;
import com.gamingmesh.jobs.container.BoostMultiplier; import com.gamingmesh.jobs.container.BoostMultiplier;
import com.gamingmesh.jobs.container.DBAction;
import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobInfo; import com.gamingmesh.jobs.container.JobInfo;
import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobProgression;
@ -71,7 +76,6 @@ import com.gamingmesh.jobs.listeners.McMMOlistener;
import com.gamingmesh.jobs.listeners.MythicMobsListener; import com.gamingmesh.jobs.listeners.MythicMobsListener;
import com.gamingmesh.jobs.listeners.PistonProtectionListener; import com.gamingmesh.jobs.listeners.PistonProtectionListener;
import com.gamingmesh.jobs.stuff.ActionBar; import com.gamingmesh.jobs.stuff.ActionBar;
import com.gamingmesh.jobs.stuff.Debug;
import com.gamingmesh.jobs.stuff.JobsClassLoader; import com.gamingmesh.jobs.stuff.JobsClassLoader;
import com.gamingmesh.jobs.stuff.Loging; import com.gamingmesh.jobs.stuff.Loging;
import com.gamingmesh.jobs.stuff.TabComplete; import com.gamingmesh.jobs.stuff.TabComplete;
@ -97,6 +101,7 @@ public class Jobs extends JavaPlugin {
private static BossBarManager BBManager; private static BossBarManager BBManager;
private static ShopManager shopManager; private static ShopManager shopManager;
private static Loging loging; private static Loging loging;
private static BlockProtectionManager BpManager = null;
private static PistonProtectionListener PistonProtectionListener = null; private static PistonProtectionListener PistonProtectionListener = null;
private static McMMOlistener McMMOlistener = null; private static McMMOlistener McMMOlistener = null;
@ -164,6 +169,14 @@ public class Jobs extends JavaPlugin {
return loging; return loging;
} }
public void setBpManager() {
BpManager = new BlockProtectionManager();
}
public static BlockProtectionManager getBpManager() {
return BpManager;
}
public static void setShopManager(Jobs plugin) { public static void setShopManager(Jobs plugin) {
shopManager = new ShopManager(plugin); shopManager = new ShopManager(plugin);
} }
@ -677,6 +690,7 @@ public class Jobs extends JavaPlugin {
setGCManager(); setGCManager();
setConfigManager(); setConfigManager();
setCommandManager(); setCommandManager();
setBpManager();
getCommand("jobs").setExecutor(cManager); getCommand("jobs").setExecutor(cManager);
this.getCommand("jobs").setTabCompleter(new TabComplete()); this.getCommand("jobs").setTabCompleter(new TabComplete());
@ -709,13 +723,14 @@ public class Jobs extends JavaPlugin {
scheduleManager.DateUpdater(); scheduleManager.DateUpdater();
dao.loadBlockProtection();
dao.loadExplore();
String message = ChatColor.translateAlternateColorCodes('&', "&e[Jobs] Plugin has been enabled succesfully."); String message = ChatColor.translateAlternateColorCodes('&', "&e[Jobs] Plugin has been enabled succesfully.");
ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
console.sendMessage(message); console.sendMessage(message);
lManager.reload(); lManager.reload();
dao.loadExplore();
cManager.fillCommands(); cManager.fillCommands();
} catch (Exception e) { } catch (Exception e) {
System.out.println("There was some issues when starting plugin. Please contact dev about this. Plugin will be disabled."); System.out.println("There was some issues when starting plugin. Please contact dev about this. Plugin will be disabled.");
@ -729,6 +744,7 @@ public class Jobs extends JavaPlugin {
GUIManager.CloseInventories(); GUIManager.CloseInventories();
shopManager.CloseInventories(); shopManager.CloseInventories();
dao.saveExplore(); dao.saveExplore();
dao.saveBlockProtection();
Jobs.shutdown(); Jobs.shutdown();
String message = ChatColor.translateAlternateColorCodes('&', "&e[Jobs] &2Plugin has been disabled succesfully."); String message = ChatColor.translateAlternateColorCodes('&', "&e[Jobs] &2Plugin has been disabled succesfully.");
ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
@ -744,6 +760,10 @@ public class Jobs extends JavaPlugin {
* @param multiplier - the payment/xp multiplier * @param multiplier - the payment/xp multiplier
*/ */
public static void action(JobsPlayer jPlayer, ActionInfo info, double multiplier) { public static void action(JobsPlayer jPlayer, ActionInfo info, double multiplier) {
action(jPlayer, info, multiplier, null);
}
public static void action(JobsPlayer jPlayer, ActionInfo info, double multiplier, Block block) {
if (jPlayer == null) if (jPlayer == null)
return; return;
@ -766,7 +786,6 @@ public class Jobs extends JavaPlugin {
if (income != 0D || points != 0D) { if (income != 0D || points != 0D) {
// jPlayer // jPlayer
BoostMultiplier FinalBoost = pManager.getFinalBonus(jPlayer, Jobs.getNoneJob()); BoostMultiplier FinalBoost = pManager.getFinalBonus(jPlayer, Jobs.getNoneJob());
// Calculate income // Calculate income
@ -806,9 +825,16 @@ public class Jobs extends JavaPlugin {
if (GconfigManager.PointStopMoney) if (GconfigManager.PointStopMoney)
amount = 0D; amount = 0D;
} }
if (!isBpOk(jPlayer, info, block))
return;
if (amount == 0D && pointAmount == 0D) if (amount == 0D && pointAmount == 0D)
return; return;
if (info.getType() == ActionType.BREAK && block != null)
Jobs.getBpManager().remove(block);
if (pointAmount != 0D) if (pointAmount != 0D)
jPlayer.setSaved(false); jPlayer.setSaved(false);
@ -930,6 +956,9 @@ public class Jobs extends JavaPlugin {
expAmount = 0D; expAmount = 0D;
} }
if (!isBpOk(jPlayer, info, block))
return;
if (amount == 0D && pointAmount == 0D && expAmount == 0D) if (amount == 0D && pointAmount == 0D && expAmount == 0D)
continue; continue;
@ -967,6 +996,55 @@ public class Jobs extends JavaPlugin {
} }
} }
private static boolean isBpOk(JobsPlayer jPlayer, ActionInfo info, Block block) {
if (block != null && Jobs.getGCManager().useBlockProtection) {
if (info.getType() == ActionType.BREAK) {
BlockProtection bp = Jobs.getBpManager().getBp(block.getLocation());
if (bp != null) {
Long time = bp.getTime();
if (time == -1)
return false;
Integer cd = Jobs.getBpManager().getBlockDelayTime(block);
if (time > System.currentTimeMillis() && bp.isPaid() && bp.getAction() != DBAction.DELETE) {
int sec = Math.round((time - System.currentTimeMillis()) / 1000);
Jobs.getActionBar().send(jPlayer.getPlayer(), Jobs.getLanguage().getMessage("message.blocktimer", "[time]", sec));
return false;
}
Jobs.getBpManager().add(block, cd);
if (cd == null) {
if (Jobs.getGCManager().useGlobalTimer) {
Jobs.getBpManager().add(block, System.currentTimeMillis() + (Jobs.getGCManager().globalblocktimer * 1000));
}
}
} else {
if (Jobs.getGCManager().useGlobalTimer) {
Jobs.getBpManager().add(block, System.currentTimeMillis() + (Jobs.getGCManager().globalblocktimer * 1000));
}
}
} else if (info.getType() == ActionType.PLACE) {
BlockProtection bp = Jobs.getBpManager().getBp(block.getLocation());
if (bp != null) {
Long time = bp.getTime();
if (time != -1) {
if (time > System.currentTimeMillis() && bp.isPaid() && bp.getAction() != DBAction.DELETE) {
int sec = Math.round((time - System.currentTimeMillis()) / 1000);
Jobs.getActionBar().send(jPlayer.getPlayer(), Jobs.getLanguage().getMessage("message.blocktimer", "[time]", sec));
return false;
}
} else if (bp.isPaid()) {
if (bp.getTime() == -1 && Jobs.getBpManager().getBlockDelayTime(block) != null && Jobs.getBpManager().getBlockDelayTime(block) == -1)
return false;
}
} else
Jobs.getBpManager().add(block, Jobs.getBpManager().getBlockDelayTime(block));
}
}
return true;
}
private static int getPlayerExperience(Player player) { private static int getPlayerExperience(Player player) {
int bukkitExp = (ExpToLevel(player.getLevel()) + Math.round(deltaLevelToExp(player.getLevel()) * player.getExp())); int bukkitExp = (ExpToLevel(player.getLevel()) + Math.round(deltaLevelToExp(player.getLevel()) * player.getExp()));
return bukkitExp; return bukkitExp;
@ -1016,23 +1094,24 @@ public class Jobs extends JavaPlugin {
// JobsPayment event // JobsPayment event
JobsExpGainEvent JobsExpGainEvent = new JobsExpGainEvent(payment.getOfflinePlayer(), job, payment.getExp()); JobsExpGainEvent JobsExpGainEvent = new JobsExpGainEvent(payment.getOfflinePlayer(), job, payment.getExp());
Bukkit.getServer().getPluginManager().callEvent(JobsExpGainEvent); Bukkit.getServer().getPluginManager().callEvent(JobsExpGainEvent);
double expAmount;
// If event is canceled, don't do anything // If event is canceled, don't do anything
if (JobsExpGainEvent.isCancelled()) if (JobsExpGainEvent.isCancelled())
expAmount = 0D; return;
else
expAmount = JobsExpGainEvent.getExp();
economy.pay(jPlayer, payment.getAmount(), payment.getPoints(), expAmount); isUnderMoneyLimit(jPlayer, payment.getAmount());
isUnderExpLimit(jPlayer, payment.getExp());
isUnderPointLimit(jPlayer, payment.getPoints());
economy.pay(jPlayer, payment.getAmount(), payment.getPoints(), payment.getExp());
JobProgression prog = jPlayer.getJobProgression(job); JobProgression prog = jPlayer.getJobProgression(job);
int oldLevel = prog.getLevel(); int oldLevel = prog.getLevel();
if (GconfigManager.LoggingUse) if (GconfigManager.LoggingUse)
loging.recordToLog(jPlayer, info, payment.getAmount(), expAmount); loging.recordToLog(jPlayer, info, payment.getAmount(), payment.getExp());
if (prog.addExperience(expAmount)) if (prog.addExperience(payment.getExp()))
pManager.performLevelUp(jPlayer, prog.getJob(), oldLevel); pManager.performLevelUp(jPlayer, prog.getJob(), oldLevel);
} }

View File

@ -48,7 +48,6 @@ import com.gamingmesh.jobs.dao.JobsDAO;
import com.gamingmesh.jobs.dao.JobsDAOData; import com.gamingmesh.jobs.dao.JobsDAOData;
import com.gamingmesh.jobs.economy.PointsData; import com.gamingmesh.jobs.economy.PointsData;
import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.ChatColor;
import com.gamingmesh.jobs.stuff.Debug;
import com.gamingmesh.jobs.stuff.PerformCommands; import com.gamingmesh.jobs.stuff.PerformCommands;
import com.gamingmesh.jobs.stuff.Perm; import com.gamingmesh.jobs.stuff.Perm;

View File

@ -0,0 +1,74 @@
package com.gamingmesh.jobs.commands.list;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.commands.Cmd;
import com.gamingmesh.jobs.commands.JobCommand;
import com.gamingmesh.jobs.container.BlockProtection;
import com.gamingmesh.jobs.container.DBAction;
public class bp implements Cmd {
@SuppressWarnings("deprecation")
@Override
@JobCommand(1900)
public boolean perform(Jobs plugin, final CommandSender sender, final String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(Jobs.getLanguage().getMessage("general.error.ingame"));
return false;
}
final Player player = (Player) sender;
Location loc = player.getLocation();
final List<Block> changedBlocks = new ArrayList<Block>();
for (int x = -10; x < 10; x++) {
for (int y = -10; y < 10; y++) {
for (int z = -10; z < 10; z++) {
Location l = loc.clone().add(x, y, z);
BlockProtection bp = Jobs.getBpManager().getBp(l);
if (bp != null) {
Long time = bp.getTime();
if (bp.getAction() == DBAction.DELETE)
continue;
if (time != -1 && time < System.currentTimeMillis()) {
Jobs.getBpManager().remove(l);
continue;
}
changedBlocks.add(l.getBlock());
if (time == -1)
player.sendBlockChange(l, Material.STAINED_GLASS, (byte) 15);
else
player.sendBlockChange(l, Material.STAINED_GLASS, (byte) 0);
}
}
}
}
if (changedBlocks.isEmpty())
sender.sendMessage(Jobs.getLanguage().getMessage("command.bp.output.notFound"));
else
sender.sendMessage(Jobs.getLanguage().getMessage("command.bp.output.found", "%amount%", changedBlocks.size()));
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
for (Block one : changedBlocks) {
player.sendBlockChange(one.getLocation(), one.getType(), one.getData());
}
}
}, 120L);
return true;
}
}

View File

@ -1,99 +1,93 @@
package com.gamingmesh.jobs.commands.list; package com.gamingmesh.jobs.commands.list;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.commands.Cmd; import com.gamingmesh.jobs.commands.Cmd;
import com.gamingmesh.jobs.commands.JobCommand; import com.gamingmesh.jobs.commands.JobCommand;
import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.JobsPlayer;
import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.ChatColor;
import com.gamingmesh.jobs.stuff.Debug; public class join implements Cmd {
public class join implements Cmd { @Override
@JobCommand(100)
@Override public boolean perform(Jobs plugin, final CommandSender sender, final String[] args) {
@JobCommand(100) if (!(sender instanceof Player)) {
public boolean perform(Jobs plugin, final CommandSender sender, final String[] args) { sender.sendMessage(Jobs.getLanguage().getMessage("general.error.ingame"));
if (!(sender instanceof Player)) { return false;
sender.sendMessage(Jobs.getLanguage().getMessage("general.error.ingame")); }
return false;
} if (args.length != 1 && args.length != 0) {
Jobs.getCommandManager().sendUsage(sender, "join");
if (args.length != 1 && args.length != 0) { return true;
Jobs.getCommandManager().sendUsage(sender, "join"); }
return true;
} if (args.length == 0) {
if (sender instanceof Player && Jobs.getGCManager().JobsGUIOpenOnJoin) {
if (args.length == 0) { Inventory inv = null;
if (sender instanceof Player && Jobs.getGCManager().JobsGUIOpenOnJoin) { try {
Inventory inv = null; inv = Jobs.getGUIManager().CreateJobsGUI((Player) sender);
try { } catch (Exception e) {
inv = Jobs.getGUIManager().CreateJobsGUI((Player) sender); ((Player) sender).closeInventory();
} catch (Exception e) { Jobs.getGUIManager().GuiList.remove(((Player) sender).getName());
((Player) sender).closeInventory(); return true;
Jobs.getGUIManager().GuiList.remove(((Player) sender).getName()); }
return true; if (inv == null)
} return true;
if (inv == null)
return true; ((Player) sender).openInventory(inv);
} else
((Player) sender).openInventory(inv); return false;
} else return true;
return false; }
return true;
} Player pSender = (Player) sender;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(pSender);
Player pSender = (Player) sender;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(pSender); String jobName = args[0];
Job job = Jobs.getJob(jobName);
String jobName = args[0]; if (job == null) {
Job job = Jobs.getJob(jobName); // job does not exist
if (job == null) { sender.sendMessage(ChatColor.RED + Jobs.getLanguage().getMessage("general.error.job"));
// job does not exist return true;
sender.sendMessage(ChatColor.RED + Jobs.getLanguage().getMessage("general.error.job")); }
return true;
} if (!Jobs.getCommandManager().hasJobPermission(pSender, job)) {
// you do not have permission to join the job
if (!Jobs.getCommandManager().hasJobPermission(pSender, job)) { sender.sendMessage(ChatColor.RED + Jobs.getLanguage().getMessage("general.error.permission"));
// you do not have permission to join the job return true;
sender.sendMessage(ChatColor.RED + Jobs.getLanguage().getMessage("general.error.permission")); }
return true;
} if (jPlayer.isInJob(job)) {
// already in job message
if (jPlayer.isInJob(job)) { String message = ChatColor.RED + Jobs.getLanguage().getMessage("command.join.error.alreadyin");
// already in job message message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.RED);
String message = ChatColor.RED + Jobs.getLanguage().getMessage("command.join.error.alreadyin"); sender.sendMessage(message);
message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.RED); return true;
sender.sendMessage(message); }
return true;
} if (job.getMaxSlots() != null && Jobs.getUsedSlots(job) >= job.getMaxSlots()) {
String message = ChatColor.RED + Jobs.getLanguage().getMessage("command.join.error.fullslots");
Debug.D("s"); message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.RED);
if (job.getMaxSlots() != null && Jobs.getUsedSlots(job) >= job.getMaxSlots()) { sender.sendMessage(message);
String message = ChatColor.RED + Jobs.getLanguage().getMessage("command.join.error.fullslots"); return true;
message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.RED); }
sender.sendMessage(message);
return true; int confMaxJobs = Jobs.getGCManager().getMaxJobs();
} short PlayerMaxJobs = (short) jPlayer.getJobProgression().size();
if (confMaxJobs > 0 && PlayerMaxJobs >= confMaxJobs && !Jobs.getPlayerManager().getJobsLimit(pSender, PlayerMaxJobs)) {
int confMaxJobs = Jobs.getGCManager().getMaxJobs(); sender.sendMessage(ChatColor.RED + Jobs.getLanguage().getMessage("command.join.error.maxjobs"));
short PlayerMaxJobs = (short) jPlayer.getJobProgression().size(); return true;
Debug.D(confMaxJobs > 0); }
Debug.D(PlayerMaxJobs >= confMaxJobs);
Debug.D(!Jobs.getPlayerManager().getJobsLimit(pSender, PlayerMaxJobs)); Jobs.getPlayerManager().joinJob(jPlayer, job);
if (confMaxJobs > 0 && PlayerMaxJobs >= confMaxJobs && !Jobs.getPlayerManager().getJobsLimit(pSender, PlayerMaxJobs)) {
sender.sendMessage(ChatColor.RED + Jobs.getLanguage().getMessage("command.join.error.maxjobs")); String message = Jobs.getLanguage().getMessage("command.join.success");
return true; message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.WHITE);
} sender.sendMessage(message);
return true;
Jobs.getPlayerManager().joinJob(jPlayer, job); }
}
String message = Jobs.getLanguage().getMessage("command.join.success");
message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.WHITE);
sender.sendMessage(message);
return true;
}
}

View File

@ -0,0 +1,195 @@
package com.gamingmesh.jobs.config;
import java.util.HashMap;
import java.util.Map.Entry;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.BlockProtection;
import com.gamingmesh.jobs.container.DBAction;
import com.gamingmesh.jobs.listeners.JobsPaymentListener;
public class BlockProtectionManager {
private HashMap<World, HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>>> map =
new HashMap<World, HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>>>();
public Long timer = 0L;
public HashMap<World, HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>>> getMap() {
return this.map;
}
public int getSize() {
int i = 0;
for (Entry<World, HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>>> worlds : map.entrySet()) {
for (Entry<String, HashMap<String, HashMap<Vector, BlockProtection>>> regions : worlds.getValue().entrySet()) {
for (Entry<String, HashMap<Vector, BlockProtection>> chunks : regions.getValue().entrySet()) {
i += chunks.getValue().size();
}
}
}
return i;
}
public void add(Block block, boolean paid) {
add(block, -1L, paid);
}
public void add(Block block) {
add(block, -1L, true);
}
public void add(Block block, Long time, boolean paid) {
add(block.getLocation(), time, paid);
}
public void add(Block block, Integer cd) {
add(block, cd, true);
}
public void add(Block block, Integer cd, boolean paid) {
if (cd == null)
return;
if (cd != -1)
add(block, System.currentTimeMillis() + (cd * 1000), paid);
else
add(block, paid);
}
public void add(Block block, Long time) {
add(block.getLocation(), time, true);
}
public void add(Location loc, Long time) {
add(loc, time, true);
}
public BlockProtection add(Location loc, Long time, boolean paid) {
Vector v = new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>> regions = map.get(loc.getWorld());
if (regions == null)
regions = new HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>>();
String region = locToRegion(loc);
HashMap<String, HashMap<Vector, BlockProtection>> chunks = regions.get(region);
if (chunks == null)
chunks = new HashMap<String, HashMap<Vector, BlockProtection>>();
String chunk = locToChunk(loc);
HashMap<Vector, BlockProtection> Bpm = chunks.get(chunk);
if (Bpm == null)
Bpm = new HashMap<Vector, BlockProtection>();
BlockProtection Bp = Bpm.get(v);
if (Bp == null)
Bp = new BlockProtection(DBAction.INSERT);
else
Bp.setAction(DBAction.UPDATE);
Bp.setPaid(paid);
Bp.setTime(time);
Bpm.put(v, Bp);
chunks.put(chunk, Bpm);
regions.put(region, chunks);
map.put(loc.getWorld(), regions);
return Bp;
}
public BlockProtection remove(Block block) {
return remove(block.getLocation());
}
public BlockProtection remove(Location loc) {
HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>> world = map.get(loc.getWorld());
if (world == null)
return null;
HashMap<String, HashMap<Vector, BlockProtection>> region = world.get(locToRegion(loc));
if (region == null)
return null;
HashMap<Vector, BlockProtection> chunk = region.get(locToChunk(loc));
if (chunk == null)
return null;
Vector v = new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
BlockProtection bp = chunk.get(v);
if (bp != null)
bp.setAction(DBAction.DELETE);
return bp;
}
public Long getTime(Block block) {
return getTime(block.getLocation());
}
public Long getTime(Location loc) {
BlockProtection Bp = getBp(loc);
if (Bp == null)
return null;
return Bp.getTime();
}
public BlockProtection getBp(Location loc) {
HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>> world = map.get(loc.getWorld());
if (world == null)
return null;
HashMap<String, HashMap<Vector, BlockProtection>> region = world.get(locToRegion(loc));
if (region == null)
return null;
HashMap<Vector, BlockProtection> chunk = region.get(locToChunk(loc));
if (chunk == null)
return null;
Vector v = new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
BlockProtection Bp = chunk.get(v);
if (Bp == null)
return null;
return Bp;
}
private static String locToChunk(Location loc) {
int x = (int) Math.floor(loc.getBlockX() / 16);
int z = (int) Math.floor(loc.getBlockZ() / 16);
return x + ":" + z;
}
private static String locToRegion(Location loc) {
int x = (int) Math.floor(loc.getBlockX() / 16);
int z = (int) Math.floor(loc.getBlockZ() / 16);
String reg = (int) Math.floor(x / 32) + ":" + (int) Math.floor(z / 32);
return reg;
}
@SuppressWarnings("deprecation")
public Integer getBlockDelayTime(Block block) {
return Jobs.getRestrictedBlockManager().restrictedBlocksTimer.get(block.getTypeId());
}
@SuppressWarnings("deprecation")
public boolean checkVegybreak(Block block, Player player) {
if (!Jobs.getRestrictedBlockManager().restrictedBlocksTimer.containsKey(block.getTypeId()))
return false;
if (CheckVegyTimer(block, Jobs.getRestrictedBlockManager().restrictedBlocksTimer.get(block.getTypeId()), player))
return true;
return false;
}
public boolean CheckVegyTimer(Block block, int time, Player player) {
long currentTime = System.currentTimeMillis();
if (!block.hasMetadata(JobsPaymentListener.VegyMetadata))
return false;
long BlockTime = block.getMetadata(JobsPaymentListener.VegyMetadata).get(0).asLong();
if (currentTime >= BlockTime + time * 1000) {
return false;
}
int sec = Math.round((((BlockTime + time * 1000) - currentTime)) / 1000);
Jobs.getActionBar().send(player, Jobs.getLanguage().getMessage("message.blocktimer", "[time]", sec));
return true;
}
}

View File

@ -90,14 +90,16 @@ public class GeneralConfigManager {
public boolean PayForRenaming, PayForEachCraft, SignsEnabled, public boolean PayForRenaming, PayForEachCraft, SignsEnabled,
SignsColorizeJobName, ShowToplistInScoreboard, useGlobalTimer, useCoreProtect, BlockPlaceUse, SignsColorizeJobName, ShowToplistInScoreboard, useGlobalTimer, useCoreProtect, BlockPlaceUse,
EnableAnounceMessage, useBlockPiston, useSilkTouchProtection, UseCustomNames, EnableAnounceMessage, useSilkTouchProtection, UseCustomNames,
UseJobsBrowse, PreventSlimeSplit, PreventMagmaCubeSplit, WaterBlockBreake; UseJobsBrowse, PreventSlimeSplit, PreventMagmaCubeSplit;
public int globalblocktimer, CowMilkingTimer, public int globalblocktimer, CowMilkingTimer,
CoreProtectInterval, BlockPlaceInterval, InfoUpdateInterval; CoreProtectInterval, BlockPlaceInterval, InfoUpdateInterval;
public Double payNearSpawnerMultiplier, VIPpayNearSpawnerMultiplier, TreeFellerMultiplier, gigaDrillMultiplier, superBreakerMultiplier, PetPay, VipPetPay; public Double payNearSpawnerMultiplier, VIPpayNearSpawnerMultiplier, TreeFellerMultiplier, gigaDrillMultiplier, superBreakerMultiplier, PetPay, VipPetPay;
public String localeString = "EN"; public String localeString = "EN";
public boolean useBlockProtection; public boolean useBlockProtection;
public boolean useBlockTimer; public int BlockProtectionDays;
public boolean useMinimumOveralPayment; public boolean useMinimumOveralPayment;
public boolean useMinimumOveralPoints; public boolean useMinimumOveralPoints;
public boolean useBreederFinder = false; public boolean useBreederFinder = false;
@ -112,8 +114,8 @@ public class GeneralConfigManager {
public double MinimumOveralPaymentLimit; public double MinimumOveralPaymentLimit;
public double MinimumOveralPointsLimit; public double MinimumOveralPointsLimit;
public HashMap <BoostType, Double> Boost = new HashMap <BoostType, Double>(); public HashMap<BoostType, Double> Boost = new HashMap<BoostType, Double>();
public double DynamicPaymentMaxPenalty; public double DynamicPaymentMaxPenalty;
public double DynamicPaymentMaxBonus; public double DynamicPaymentMaxBonus;
public double TaxesAmount; public double TaxesAmount;
@ -124,7 +126,7 @@ public class GeneralConfigManager {
public boolean UseTaxes; public boolean UseTaxes;
public boolean TransferToServerAccount; public boolean TransferToServerAccount;
public boolean TakeFromPlayersPayment; public boolean TakeFromPlayersPayment;
public int AutoJobJoinDelay; public int AutoJobJoinDelay;
public boolean AutoJobJoinUse; public boolean AutoJobJoinUse;
@ -146,6 +148,11 @@ public class GeneralConfigManager {
public HashMap<String, List<String>> commandArgs = new HashMap<String, List<String>>(); public HashMap<String, List<String>> commandArgs = new HashMap<String, List<String>>();
public boolean DBCleaningJobsUse;
public int DBCleaningJobsLvl;
public boolean DBCleaningUsersUse;
public int DBCleaningUsersDays;
public HashMap<String, List<String>> getCommandArgs() { public HashMap<String, List<String>> getCommandArgs() {
return commandArgs; return commandArgs;
} }
@ -313,6 +320,8 @@ public class GeneralConfigManager {
public synchronized void reload() { public synchronized void reload() {
// general settings // general settings
loadGeneralSettings(); loadGeneralSettings();
Jobs.getJobsDAO().cleanJobs();
Jobs.getJobsDAO().cleanUsers();
// Load locale // Load locale
Jobs.setLanguageManager(this.plugin); Jobs.setLanguageManager(this.plugin);
Jobs.getLanguageManager().load(); Jobs.getLanguageManager().load();
@ -419,7 +428,19 @@ public class GeneralConfigManager {
MultiServerCompatability = c.get("MultiServerCompatability", false); MultiServerCompatability = c.get("MultiServerCompatability", false);
if (MultiServerCompatability) if (MultiServerCompatability)
saveOnDisconnect = true; saveOnDisconnect = true;
c.getW().addComment("Optimizations.DBCleaning.Jobs.Use", "When set to true, jobs data base will be cleaned on each startup to avoid having not used jobs",
"keep in mind that this will only clean actual jobs, but not recorded players");
DBCleaningJobsUse = c.get("Optimizations.DBCleaning.Jobs.Use", false);
c.getW().addComment("Optimizations.DBCleaning.Jobs.Level", "Any one who has jobs level equal or less then set, hies job will be removed from data base");
DBCleaningJobsLvl = c.get("Optimizations.DBCleaning.Jobs.Level", 1);
c.getW().addComment("Optimizations.DBCleaning.Users.Use",
"When set to true, data base will be cleaned on each startup from user data to avoid having old player data");
DBCleaningUsersUse = c.get("Optimizations.DBCleaning.Users.Use", false);
c.getW().addComment("Optimizations.DBCleaning.Users.Days", "Any one who not playied for defined amount of days, will be removed from data base");
DBCleaningUsersDays = c.get("Optimizations.DBCleaning.Users.Days", 60);
c.getW().addComment("Optimizations.AutoJobJoin.Use", "Use or not auto join jobs feature", c.getW().addComment("Optimizations.AutoJobJoin.Use", "Use or not auto join jobs feature",
"If you are not using auto join feature, keep it disabled"); "If you are not using auto join feature, keep it disabled");
AutoJobJoinUse = c.get("Optimizations.AutoJobJoin.Use", false); AutoJobJoinUse = c.get("Optimizations.AutoJobJoin.Use", false);
@ -439,7 +460,7 @@ public class GeneralConfigManager {
"Only commands can be performed from disabled worlds with jobs.disabledworld.commands permission node"); "Only commands can be performed from disabled worlds with jobs.disabledworld.commands permission node");
DisabledWorldsUse = c.get("Optimizations.DisabledWorlds.Use", false); DisabledWorldsUse = c.get("Optimizations.DisabledWorlds.Use", false);
DisabledWorldsList = c.getStringList("Optimizations.DisabledWorlds.List", Arrays.asList(Bukkit.getWorlds().get(0).getName())); DisabledWorldsList = c.getStringList("Optimizations.DisabledWorlds.List", Arrays.asList(Bukkit.getWorlds().get(0).getName()));
// c.getW().addComment("Optimizations.Purge.Use", "By setting this to true, Jobs plugin will clean data base on startup from all jobs with level 1 and at 0 exp"); // c.getW().addComment("Optimizations.Purge.Use", "By setting this to true, Jobs plugin will clean data base on startup from all jobs with level 1 and at 0 exp");
// PurgeUse = c.get("Optimizations.Purge.Use", false); // PurgeUse = c.get("Optimizations.Purge.Use", false);
@ -666,27 +687,23 @@ public class GeneralConfigManager {
CowMilkingTimer = c.get("Economy.MilkingCow.Timer", 30) * 1000; CowMilkingTimer = c.get("Economy.MilkingCow.Timer", 30) * 1000;
c.getW().addComment("ExploitProtections.General.PlaceAndBreakProtection", c.getW().addComment("ExploitProtections.General.PlaceAndBreakProtection",
"Enable blocks protection, like ore, from exploiting by placing and destroying same block again and again.", "This works only until server restart", "Enable blocks protection, like ore, from exploiting by placing and destroying same block again and again.",
"Modify restrictedBlocks.yml for blocks you want to protect"); "Modify restrictedBlocks.yml for blocks you want to protect");
useBlockProtection = c.get("ExploitProtections.General.PlaceAndBreakProtection", true); useBlockProtection = c.get("ExploitProtections.General.PlaceAndBreakProtection", true);
c.getW().addComment("ExploitProtections.General.KeepDataFor",
"For how long in days to keep block protection data in data base", "This will clean block data which ones have -1 as cooldown value",
"Data base cleannup will be performed on each server startup");
BlockProtectionDays = c.get("ExploitProtections.General.KeepDataFor", 14);
c.getW().addComment("ExploitProtections.General.GlobalBlockTimer", "All blocks will be protected X sec after player places it on ground.");
useGlobalTimer = c.get("ExploitProtections.General.GlobalBlockTimer.use", true);
globalblocktimer = c.get("ExploitProtections.General.GlobalBlockTimer.timer", 3);
c.getW().addComment("ExploitProtections.General.SilkTouchProtection", "Enable silk touch protection.", c.getW().addComment("ExploitProtections.General.SilkTouchProtection", "Enable silk touch protection.",
"With this enabled players wont get paid for breaked blocks from restrictedblocks list with silk touch tool."); "With this enabled players wont get paid for breaked blocks from restrictedblocks list with silk touch tool.");
useSilkTouchProtection = c.get("ExploitProtections.General.SilkTouchProtection", false); useSilkTouchProtection = c.get("ExploitProtections.General.SilkTouchProtection", false);
c.getW().addComment("ExploitProtections.General.StopPistonBlockMove", "Enable piston moving blocks from restrictedblocks list.",
"If piston moves block then it will be like new block and BlockPlaceAndBreakProtection wont work properly",
"If you using core protect and its being logging piston block moving, then you can disable this");
useBlockPiston = c.get("ExploitProtections.General.StopPistonBlockMove", true);
c.getW().addComment("ExploitProtections.General.BlocksTimer", "Enable blocks timer protection.",
"Only enable if you want to protect block from beying broken to fast, useful for vegetables.", "Modify restrictedBlocks.yml for blocks you want to protect");
useBlockTimer = c.get("ExploitProtections.General.BlocksTimer", true);
c.getW().addComment("ExploitProtections.General.GlobalBlockTimer", "All blocks will be protected X sec after player places it on ground.");
useGlobalTimer = c.get("ExploitProtections.General.GlobalBlockTimer.use", false);
globalblocktimer = c.get("ExploitProtections.General.GlobalBlockTimer.timer", 30);
c.getW().addComment("ExploitProtections.General.PetPay", "Do you want to pay when players pet kills monster/player", "Can be exploited with mob farms", c.getW().addComment("ExploitProtections.General.PetPay", "Do you want to pay when players pet kills monster/player", "Can be exploited with mob farms",
"0.2 means 20% of original reward", "Optionaly you can give jobs.petpay permission node for specific players/ranks to get paid by VipPetPay multiplier"); "0.2 means 20% of original reward", "Optionaly you can give jobs.petpay permission node for specific players/ranks to get paid by VipPetPay multiplier");
PetPay = c.get("ExploitProtections.General.PetPay", 0.1); PetPay = c.get("ExploitProtections.General.PetPay", 0.1);
@ -712,11 +729,6 @@ public class GeneralConfigManager {
c.getW().addComment("ExploitProtections.Spawner.PreventMagmaCubeSplit", "Prevent magmacube spliting when they are from spawner"); c.getW().addComment("ExploitProtections.Spawner.PreventMagmaCubeSplit", "Prevent magmacube spliting when they are from spawner");
PreventMagmaCubeSplit = c.get("ExploitProtections.Spawner.PreventMagmaCubeSplit", true); PreventMagmaCubeSplit = c.get("ExploitProtections.Spawner.PreventMagmaCubeSplit", true);
c.getW().addComment("ExploitProtections.WaterBlockBreake",
"Prevent water braking placed blocks. Protection resets with server restart or after plants grows to next stage with bone powder or naturally",
"For strange reason works only 5 of 10 times, but this is completely enough to prevent exploiting");
WaterBlockBreake = c.get("ExploitProtections.WaterBlockBreake", true);
c.getW().addComment("use-breeder-finder", "Breeder finder.", c.getW().addComment("use-breeder-finder", "Breeder finder.",
"If you are not using breeding payment, you can disable this to save little resources. Really little."); "If you are not using breeding payment, you can disable this to save little resources. Really little.");
useBreederFinder = c.get("use-breeder-finder", true); useBreederFinder = c.get("use-breeder-finder", true);
@ -727,8 +739,8 @@ public class GeneralConfigManager {
"Use: jobs.boost.all.money or jobs.boost.all.exp or jobs.boost.all.points or jobs.boost.all.all to get boost for all jobs", "Use: jobs.boost.all.money or jobs.boost.all.exp or jobs.boost.all.points or jobs.boost.all.all to get boost for all jobs",
"1.25 means that player will get 25% more than others, you can set less than 1 to get less from anothers"); "1.25 means that player will get 25% more than others, you can set less than 1 to get less from anothers");
Boost.put(BoostType.EXP, c.get("boost.exp", 1.00)); Boost.put(BoostType.EXP, c.get("boost.exp", 1.00));
Boost.put(BoostType.MONEY, c.get("boost.money", 1.00)); Boost.put(BoostType.MONEY, c.get("boost.money", 1.00));
Boost.put(BoostType.POINTS, c.get("boost.points", 1.00)); Boost.put(BoostType.POINTS, c.get("boost.points", 1.00));
c.getW().addComment("old-job", "Old job save", "Players can leave job and return later with some level loss during that", c.getW().addComment("old-job", "Old job save", "Players can leave job and return later with some level loss during that",
"You can fix players level if hes job level is at max level"); "You can fix players level if hes job level is at max level");

View File

@ -9,7 +9,6 @@ import java.util.List;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.LocaleReader; import com.gamingmesh.jobs.container.LocaleReader;
import com.gamingmesh.jobs.stuff.Debug;
public class LanguageManager { public class LanguageManager {
private Jobs plugin; private Jobs plugin;
@ -25,8 +24,6 @@ public class LanguageManager {
*/ */
synchronized void load() { synchronized void load() {
long time = System.currentTimeMillis();
// Just copying default language files, except en, that one will be generated // Just copying default language files, except en, that one will be generated
List<String> languages = new ArrayList<String>(); List<String> languages = new ArrayList<String>();
languages.add("cs"); languages.add("cs");
@ -38,25 +35,18 @@ public class LanguageManager {
languages.add("ru"); languages.add("ru");
languages.add("tr"); languages.add("tr");
Debug.D(System.currentTimeMillis() - time);
for (String lang : languages) { for (String lang : languages) {
YmlMaker langFile = new YmlMaker(plugin, "locale" + File.separator + "messages_" + lang + ".yml"); YmlMaker langFile = new YmlMaker(plugin, "locale" + File.separator + "messages_" + lang + ".yml");
langFile.saveDefaultConfig(); langFile.saveDefaultConfig();
} }
Debug.D(System.currentTimeMillis() - time);
languages.add("en"); languages.add("en");
File customLocaleFile = new File(plugin.getDataFolder(), "locale" + File.separator + "messages_" + Jobs.getGCManager().localeString + ".yml"); File customLocaleFile = new File(plugin.getDataFolder(), "locale" + File.separator + "messages_" + Jobs.getGCManager().localeString + ".yml");
if (!customLocaleFile.exists() && !Jobs.getGCManager().localeString.equalsIgnoreCase("en")) if (!customLocaleFile.exists() && !Jobs.getGCManager().localeString.equalsIgnoreCase("en"))
languages.add(Jobs.getGCManager().localeString); languages.add(Jobs.getGCManager().localeString);
Debug.D(System.currentTimeMillis() - time);
for (String lang : languages) { for (String lang : languages) {
Debug.D(lang + " -> " + (System.currentTimeMillis() - time));
File f = new File(plugin.getDataFolder(), "locale" + File.separator + "messages_" + lang + ".yml"); File f = new File(plugin.getDataFolder(), "locale" + File.separator + "messages_" + lang + ".yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(f); YamlConfiguration config = YamlConfiguration.loadConfiguration(f);
CommentedYamlConfiguration writer = new CommentedYamlConfiguration(); CommentedYamlConfiguration writer = new CommentedYamlConfiguration();
@ -384,6 +374,11 @@ public class LanguageManager {
c.get("command.signupdate.help.args", "[jobname]"); c.get("command.signupdate.help.args", "[jobname]");
Jobs.getGCManager().commandArgs.put("signupdate", Arrays.asList("[jobname]")); Jobs.getGCManager().commandArgs.put("signupdate", Arrays.asList("[jobname]"));
c.get("command.bp.help.info", "Shows Block protection arround you in 10 block radius");
c.get("command.bp.help.args", "");
c.get("command.bp.output.found", "&eFound &6%amount% &eprotected blocks around you");
c.get("command.bp.output.notFound", "&eNo protected blocks found around you");
c.get("command.reload.help.info", "Reload configurations."); c.get("command.reload.help.info", "Reload configurations.");
c.get("command.toggle.help.info", "Toggles payment output on action bar or bossbar."); c.get("command.toggle.help.info", "Toggles payment output on action bar or bossbar.");
@ -453,7 +448,5 @@ public class LanguageManager {
e.printStackTrace(); e.printStackTrace();
} }
} }
Debug.D(System.currentTimeMillis() - time);
} }
} }

View File

@ -2,11 +2,11 @@ package com.gamingmesh.jobs.config;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Set;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
@ -15,9 +15,7 @@ import com.gamingmesh.jobs.stuff.ChatColor;
public class RestrictedBlockManager { public class RestrictedBlockManager {
public ArrayList<String> restrictedBlocks = new ArrayList<String>();
public HashMap<Integer, Integer> restrictedBlocksTimer = new HashMap<Integer, Integer>(); public HashMap<Integer, Integer> restrictedBlocksTimer = new HashMap<Integer, Integer>();
public ArrayList<Integer> restrictedPlaceBlocksTimer = new ArrayList<Integer>();
private Jobs plugin; private Jobs plugin;
@ -30,6 +28,7 @@ public class RestrictedBlockManager {
* *
* loads from Jobs/restrictedAreas.yml * loads from Jobs/restrictedAreas.yml
*/ */
@SuppressWarnings("deprecation")
public synchronized void load() { public synchronized void load() {
File f = new File(plugin.getDataFolder(), "restrictedBlocks.yml"); File f = new File(plugin.getDataFolder(), "restrictedBlocks.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(f); YamlConfiguration config = YamlConfiguration.loadConfiguration(f);
@ -39,110 +38,169 @@ public class RestrictedBlockManager {
config.options().copyDefaults(true); config.options().copyDefaults(true);
c.getW().addComment("restrictedblocks", "All block to be protected from place/break exploit.", "This will prevent piston moving all blocks in list", c.getW().addComment("blocksTimer", "Block protected by timer in sec",
"Dont count in vegetables or any single click break blocks"); "Category name can be any you like to be easily recognized",
restrictedBlocks.add("14"); "id can be actual block id (use /jobs blockinfo to get correct id) or use block name",
restrictedBlocks.add("15"); "By setting time to -1 will keep block protected until global cleanup, mainly used for structure blocks like diamond");
restrictedBlocks.add("16");
restrictedBlocks.add("21");
restrictedBlocks.add("48");
restrictedBlocks.add("56");
restrictedBlocks.add("73");
restrictedBlocks.add("74");
restrictedBlocks.add("129");
restrictedBlocks.add("153");
c.getC().addDefault("restrictedblocks", restrictedBlocks);
restrictedBlocks = (ArrayList<String>) c.getC().getStringList("restrictedblocks");
c.copySetting("restrictedblocks");
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + restrictedBlocks.size() + " restricted blocks!"); if (!c.getC().isConfigurationSection("blocksTimer")) {
c.getC().addDefault("blocksTimer.Sapling.id", 6);
c.getC().addDefault("blocksTimer.Sapling.cd", 60);
c.getC().addDefault("blocksTimer.leaves.id", 18);
c.getC().addDefault("blocksTimer.leaves.cd", 60);
c.getC().addDefault("blocksTimer.grass.id", "longgrass");
c.getC().addDefault("blocksTimer.grass.cd", 60);
c.getC().addDefault("blocksTimer.deadBush.id", 32);
c.getC().addDefault("blocksTimer.deadBush.cd", 60);
c.getW().addComment("blockstimer", "Block protected by timer in sec", c.getC().addDefault("blocksTimer.rail.id", 66);
"141-60 means that carrot can be harvested after 60 sec (remember to use id's from placed objects, not from your inventory)"); c.getC().addDefault("blocksTimer.rail.cd", 60);
ArrayList<String> ls = new ArrayList<String>(); c.getC().addDefault("blocksTimer.rail2.id", 27);
ls.addAll(Arrays.asList("2-60", c.getC().addDefault("blocksTimer.rail2.cd", 60);
"3-60", c.getC().addDefault("blocksTimer.rail3.id", 28);
"6-60", c.getC().addDefault("blocksTimer.rail3.cd", 60);
"12-60", c.getC().addDefault("blocksTimer.rail4.id", 157);
"18-60", c.getC().addDefault("blocksTimer.rail4.cd", 60);
"31-60",
"32-60",
"37-60",
"38-60",
"39-60",
"40-60",
"55-60",
"59-60",
"80-60",
"81-60",
"83-60",
"103-60",
"106-60",
"111-60",
"141-60",
"142-60",
"161-60",
"171-60",
"175-60"));
c.getC().addDefault("blockstimer", ls);
ls = (ArrayList<String>) c.getC().getStringList("blockstimer");
for (String one : ls) { c.getC().addDefault("blocksTimer.web.id", 30);
c.getC().addDefault("blocksTimer.web.cd", 60);
if (!one.contains("-")) c.getC().addDefault("blocksTimer.dandelion.id", 37);
continue; c.getC().addDefault("blocksTimer.dandelion.cd", 60);
c.getC().addDefault("blocksTimer.poppy.id", 38);
c.getC().addDefault("blocksTimer.poppy.cd", 60);
c.getC().addDefault("blocksTimer.flower.id", 175);
c.getC().addDefault("blocksTimer.flower.cd", 60);
c.getC().addDefault("blocksTimer.mushroom.id", 39);
c.getC().addDefault("blocksTimer.mushroom.cd", 60);
c.getC().addDefault("blocksTimer.mushroomRed.id", 40);
c.getC().addDefault("blocksTimer.mushroomRed.cd", 60);
int id = 0; c.getC().addDefault("blocksTimer.torch.id", 50);
int timer = 0; c.getC().addDefault("blocksTimer.torch.cd", 60);
c.getC().addDefault("blocksTimer.redTorch.id", 76);
c.getC().addDefault("blocksTimer.redTorch.cd", 60);
try { c.getC().addDefault("blocksTimer.lader.id", 65);
id = Integer.parseInt(one.split("-")[0]); c.getC().addDefault("blocksTimer.lader.cd", 5);
timer = Integer.parseInt(one.split("-")[1]); c.getC().addDefault("blocksTimer.carpet.id", 171);
} catch (NumberFormatException e) { c.getC().addDefault("blocksTimer.carpet.cd", 60);
continue;
} c.getC().addDefault("blocksTimer.button.id", 77);
restrictedBlocksTimer.put(id, timer); c.getC().addDefault("blocksTimer.button.cd", 5);
c.getC().addDefault("blocksTimer.button2.id", 143);
c.getC().addDefault("blocksTimer.button2.cd", 5);
c.getC().addDefault("blocksTimer.lever.id", 69);
c.getC().addDefault("blocksTimer.lever.cd", 60);
c.getC().addDefault("blocksTimer.snow.id", 78);
c.getC().addDefault("blocksTimer.snow.cd", 60);
c.getC().addDefault("blocksTimer.snow2.id", 80);
c.getC().addDefault("blocksTimer.snow2.cd", 60);
c.getC().addDefault("blocksTimer.hook.id", 131);
c.getC().addDefault("blocksTimer.hook.cd", 60);
c.getC().addDefault("blocksTimer.tripWire.id", 132);
c.getC().addDefault("blocksTimer.tripWire.cd", 60);
c.getC().addDefault("blocksTimer.redstone.id", 55);
c.getC().addDefault("blocksTimer.redstone.cd", 60);
c.getC().addDefault("blocksTimer.repeater.id", 93);
c.getC().addDefault("blocksTimer.repeater.cd", 60);
c.getC().addDefault("blocksTimer.comparator.id", 149);
c.getC().addDefault("blocksTimer.comparator.cd", 60);
c.getC().addDefault("blocksTimer.lily.id", 111);
c.getC().addDefault("blocksTimer.lily.cd", -1);
c.getC().addDefault("blocksTimer.vines.id", 106);
c.getC().addDefault("blocksTimer.vines.cd", -1);
c.getC().addDefault("blocksTimer.wheat.id", 59);
c.getC().addDefault("blocksTimer.wheat.cd", 5);
c.getC().addDefault("blocksTimer.sugarcane.id", 83);
c.getC().addDefault("blocksTimer.sugarcane.cd", -1);
c.getC().addDefault("blocksTimer.cactus.id", 81);
c.getC().addDefault("blocksTimer.cactus.cd", -1);
c.getC().addDefault("blocksTimer.beatroot.id", 207);
c.getC().addDefault("blocksTimer.beatroot.cd", 60);
c.getC().addDefault("blocksTimer.potato.id", 142);
c.getC().addDefault("blocksTimer.potato.cd", 60);
c.getC().addDefault("blocksTimer.carrot.id", 141);
c.getC().addDefault("blocksTimer.carrot.cd", 60);
c.getC().addDefault("blocksTimer.warts.id", 115);
c.getC().addDefault("blocksTimer.warts.cd", 60);
c.getC().addDefault("blocksTimer.pumpkin.id", 86);
c.getC().addDefault("blocksTimer.pumpkin.cd", -1);
c.getC().addDefault("blocksTimer.pumpkinstem.id", 104);
c.getC().addDefault("blocksTimer.pumpkinstem.cd", -1);
c.getC().addDefault("blocksTimer.melon.id", 103);
c.getC().addDefault("blocksTimer.melon.cd", -1);
c.getC().addDefault("blocksTimer.melonstem.id", 105);
c.getC().addDefault("blocksTimer.melonstem.cd", -1);
c.getC().addDefault("blocksTimer.goldore.id", "goldore");
c.getC().addDefault("blocksTimer.goldore.cd", -1);
c.getC().addDefault("blocksTimer.ironore.id", "ironore");
c.getC().addDefault("blocksTimer.ironore.cd", -1);
c.getC().addDefault("blocksTimer.coalore.id", "coalore");
c.getC().addDefault("blocksTimer.coalore.cd", -1);
c.getC().addDefault("blocksTimer.lapisore.id", "lapisore");
c.getC().addDefault("blocksTimer.lapisore.cd", -1);
c.getC().addDefault("blocksTimer.diamondore.id", "diamondore");
c.getC().addDefault("blocksTimer.diamondore.cd", -1);
c.getC().addDefault("blocksTimer.redstoneore.id", "redstoneore");
c.getC().addDefault("blocksTimer.redstoneore.cd", -1);
c.getC().addDefault("blocksTimer.emeraldore.id", "emeraldore");
c.getC().addDefault("blocksTimer.emeraldore.cd", -1);
c.getC().addDefault("blocksTimer.quartzore.id", "quartzore");
c.getC().addDefault("blocksTimer.quartzore.cd", -1);
} }
c.copySetting("blockstimer"); if (c.getC().isConfigurationSection("blocksTimer")) {
Set<String> lss = c.getC().getConfigurationSection("blocksTimer").getKeys(false);
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + restrictedBlocksTimer.size() + " restricted blocks timers!"); for (String one : lss) {
if (((c.getC().isString("blocksTimer." + one + ".id")) || (c.getC().isInt("blocksTimer." + one + ".id"))) && (c.getC().isInt("blocksTimer." + one
c.getW().addComment("PlacedBlockTimer", "Block place protected by timer in sec", "For this to work CoreProtect plugin should be installed"); + ".cd"))) {
restrictedPlaceBlocksTimer.add(2); Material mat = getMaterial(c.getC().getString("blocksTimer." + one + ".id"));
restrictedPlaceBlocksTimer.add(3); if ((mat == null) || (!mat.isBlock())) {
restrictedPlaceBlocksTimer.add(6); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[Jobs] Your defined (" + c.getC().getString(new StringBuilder("blocksTimer.").append(one)
restrictedPlaceBlocksTimer.add(12); .append(".id").toString()) + ") protected block id/name is not correct!");
restrictedPlaceBlocksTimer.add(18); } else {
restrictedPlaceBlocksTimer.add(31); this.restrictedBlocksTimer.put(mat.getId(), c.getC().getInt("blocksTimer." + one + ".cd"));
restrictedPlaceBlocksTimer.add(32); }
restrictedPlaceBlocksTimer.add(37); }
restrictedPlaceBlocksTimer.add(38); }
restrictedPlaceBlocksTimer.add(39); }
restrictedPlaceBlocksTimer.add(40); c.copySetting("blocksTimer");
restrictedPlaceBlocksTimer.add(55);
restrictedPlaceBlocksTimer.add(59);
restrictedPlaceBlocksTimer.add(80);
restrictedPlaceBlocksTimer.add(81);
restrictedPlaceBlocksTimer.add(83);
restrictedPlaceBlocksTimer.add(103);
restrictedPlaceBlocksTimer.add(106);
restrictedPlaceBlocksTimer.add(111);
restrictedPlaceBlocksTimer.add(141);
restrictedPlaceBlocksTimer.add(142);
restrictedPlaceBlocksTimer.add(161);
restrictedPlaceBlocksTimer.add(171);
restrictedPlaceBlocksTimer.add(175);
c.getC().addDefault("PlacedBlockTimer", restrictedPlaceBlocksTimer);
restrictedPlaceBlocksTimer = (ArrayList<Integer>) c.getC().getIntegerList("PlacedBlockTimer");
c.copySetting("PlacedBlockTimer");
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + restrictedPlaceBlocksTimer.size() + " restricted place blocks timers!");
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + this.restrictedBlocksTimer.size() + " protected blocks timers!");
try { try {
writer.save(f); writer.save(f);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@SuppressWarnings("deprecation")
private static Material getMaterial(String id) {
id = id.replace("_", "").replace(" ", "");
Material material = null;
for (Material one : Material.values()) {
if (one.name().replace("_", "").equalsIgnoreCase(id)) {
material = one;
break;
}
}
if (material == null) {
Integer matId = null;
try {
matId = Integer.valueOf(id);
} catch (NumberFormatException localNumberFormatException) {
}
if (matId != null) {
material = Material.getMaterial(matId);
}
}
return material;
}
} }

View File

@ -1,231 +1,229 @@
package com.gamingmesh.jobs.config; package com.gamingmesh.jobs.config;
import java.io.File; import java.io.File;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.Schedule; import com.gamingmesh.jobs.container.Schedule;
import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.ChatColor;
import com.gamingmesh.jobs.stuff.TimeManage; import com.gamingmesh.jobs.stuff.TimeManage;
public class ScheduleManager { public class ScheduleManager {
public int dateByInt = 0; public int dateByInt = 0;
private Jobs plugin; private Jobs plugin;
public ScheduleManager(Jobs plugin) { public ScheduleManager(Jobs plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
public int getDateByInt() { public int getDateByInt() {
return dateByInt; return dateByInt;
} }
public void setDateByInt(int time) { public void setDateByInt(int time) {
dateByInt = time; dateByInt = time;
} }
public void DateUpdater() { public void DateUpdater() {
if (dateByInt == 0) if (dateByInt == 0)
dateByInt = TimeManage.timeInInt(); dateByInt = TimeManage.timeInInt();
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
dateByInt = TimeManage.timeInInt(); dateByInt = TimeManage.timeInInt();
DateUpdater(); DateUpdater();
return; return;
} }
}, 60 * 20L); }, 60 * 20L);
} }
public boolean scheduler() { public boolean scheduler() {
if (Jobs.getGCManager().BoostSchedule.size() > 0 && Jobs.getGCManager().useGlobalBoostScheduler) { if (Jobs.getGCManager().BoostSchedule.size() > 0 && Jobs.getGCManager().useGlobalBoostScheduler) {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(); Date date = new Date();
String currenttime = dateFormat.format(date); String currenttime = dateFormat.format(date);
int Current = Integer.valueOf(currenttime.replace(":", "")).intValue(); int Current = Integer.valueOf(currenttime.replace(":", "")).intValue();
String CurrentDayName = GetWeekDay(); String CurrentDayName = GetWeekDay();
for (Schedule one : Jobs.getGCManager().BoostSchedule) { for (Schedule one : Jobs.getGCManager().BoostSchedule) {
int From = one.GetFrom(); int From = one.GetFrom();
int Until = one.GetUntil(); int Until = one.GetUntil();
List<String> days = one.GetDays(); List<String> days = one.GetDays();
if (one.isStarted() && one.getBroadcastInfoOn() < System.currentTimeMillis() && one.GetBroadcastInterval() > 0) { if (one.isStarted() && one.getBroadcastInfoOn() < System.currentTimeMillis() && one.GetBroadcastInterval() > 0) {
one.setBroadcastInfoOn(System.currentTimeMillis() + one.GetBroadcastInterval() * 60 * 1000); one.setBroadcastInfoOn(System.currentTimeMillis() + one.GetBroadcastInterval() * 60 * 1000);
for (String oneMsg : one.GetMessageToBroadcast()) { for (String oneMsg : one.GetMessageToBroadcast()) {
Bukkit.broadcastMessage(oneMsg); Bukkit.broadcastMessage(oneMsg);
} }
} }
if (((one.isNextDay() && (Current >= From && Current < one.GetUntil() || Current >= one.GetNextFrom() && Current < one.GetNextUntil()) && !one if (((one.isNextDay() && (Current >= From && Current < one.GetUntil() || Current >= one.GetNextFrom() && Current < one.GetNextUntil()) && !one
.isStarted()) || !one.isNextDay() && (Current >= From && Current < Until)) && (days.contains(CurrentDayName) || days.contains("all")) && !one .isStarted()) || !one.isNextDay() && (Current >= From && Current < Until)) && (days.contains(CurrentDayName) || days.contains("all")) && !one
.isStarted()) { .isStarted()) {
if (one.isBroadcastOnStart()) if (one.isBroadcastOnStart())
if (one.GetMessageOnStart().size() == 0) if (one.GetMessageOnStart().size() == 0)
Bukkit.broadcastMessage(Jobs.getLanguage().getMessage("message.boostStarted")); Bukkit.broadcastMessage(Jobs.getLanguage().getMessage("message.boostStarted"));
else else
for (String oneMsg : one.GetMessageOnStart()) { for (String oneMsg : one.GetMessageOnStart()) {
Bukkit.broadcastMessage(oneMsg); Bukkit.broadcastMessage(oneMsg);
} }
for (Job onejob : one.GetJobs()) { for (Job onejob : one.GetJobs()) {
onejob.setExpBoost(one.GetExpBoost()); onejob.setExpBoost(one.GetExpBoost());
onejob.setMoneyBoost(one.GetMoneyBoost()); onejob.setMoneyBoost(one.GetMoneyBoost());
} }
one.setBroadcastInfoOn(System.currentTimeMillis() + one.GetBroadcastInterval() * 60 * 1000); one.setBroadcastInfoOn(System.currentTimeMillis() + one.GetBroadcastInterval() * 60 * 1000);
one.setStarted(true); one.setStarted(true);
one.setStoped(false); one.setStoped(false);
break; break;
} else if (((one.isNextDay() && Current > one.GetNextUntil() && Current < one.GetFrom() && !one.isStoped()) || !one.isNextDay() && Current > Until } else if (((one.isNextDay() && Current > one.GetNextUntil() && Current < one.GetFrom() && !one.isStoped()) || !one.isNextDay() && Current > Until
&& ((days.contains(CurrentDayName)) || days.contains("all"))) && !one.isStoped()) { && ((days.contains(CurrentDayName)) || days.contains("all"))) && !one.isStoped()) {
if (one.isBroadcastOnStop()) if (one.isBroadcastOnStop())
if (one.GetMessageOnStop().size() == 0) if (one.GetMessageOnStop().size() == 0)
Bukkit.broadcastMessage(Jobs.getLanguage().getMessage("message.boostStoped")); Bukkit.broadcastMessage(Jobs.getLanguage().getMessage("message.boostStoped"));
else else
for (String oneMsg : one.GetMessageOnStop()) { for (String oneMsg : one.GetMessageOnStop()) {
Bukkit.broadcastMessage(oneMsg); Bukkit.broadcastMessage(oneMsg);
} }
for (Job onejob : one.GetJobs()) { for (Job onejob : one.GetJobs()) {
onejob.setExpBoost(1.0); onejob.setExpBoost(1.0);
onejob.setMoneyBoost(1.0); onejob.setMoneyBoost(1.0);
} }
one.setStoped(true); one.setStoped(true);
one.setStarted(false); one.setStarted(false);
} }
} }
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
scheduler(); scheduler();
return; return;
} }
}, 30 * 20L); }, 30 * 20L);
} }
return true; return true;
} }
public static String GetWeekDay() { public static String GetWeekDay() {
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
switch (dayOfWeek) { switch (dayOfWeek) {
case 2: case 2:
return "monday"; return "monday";
case 3: case 3:
return "tuesday"; return "tuesday";
case 4: case 4:
return "wednesday"; return "wednesday";
case 5: case 5:
return "thursday"; return "thursday";
case 6: case 6:
return "friday"; return "friday";
case 7: case 7:
return "saturday"; return "saturday";
case 1: case 1:
return "sunday"; return "sunday";
} }
return "all"; return "all";
} }
/** /**
* Method to load the scheduler configuration * Method to load the scheduler configuration
* *
* loads from Jobs/schedule.yml * loads from Jobs/schedule.yml
*/ */
public void load() { public void load() {
File f = new File(plugin.getDataFolder(), "schedule.yml"); File f = new File(plugin.getDataFolder(), "schedule.yml");
YamlConfiguration conf = YamlConfiguration.loadConfiguration(f); YamlConfiguration conf = YamlConfiguration.loadConfiguration(f);
conf.options().copyDefaults(true); conf.options().copyDefaults(true);
if (!conf.contains("Boost")) if (!conf.contains("Boost"))
return; return;
ArrayList<String> sections = new ArrayList<String>(conf.getConfigurationSection("Boost").getKeys(false)); ArrayList<String> sections = new ArrayList<String>(conf.getConfigurationSection("Boost").getKeys(false));
for (String OneSection : sections) { for (String OneSection : sections) {
ConfigurationSection path = conf.getConfigurationSection("Boost." + OneSection); ConfigurationSection path = conf.getConfigurationSection("Boost." + OneSection);
if (!path.contains("Enabled")) if (!path.contains("Enabled"))
continue; continue;
if (!conf.getConfigurationSection("Boost." + OneSection).getBoolean("Enabled")) if (!conf.getConfigurationSection("Boost." + OneSection).getBoolean("Enabled"))
continue; continue;
Schedule sched = new Schedule(); Schedule sched = new Schedule();
sched.setName(OneSection); sched.setName(OneSection);
if (!path.contains("From") || !path.getString("From").contains(":")) if (!path.contains("From") || !path.getString("From").contains(":"))
continue; continue;
if (!path.contains("Until") || !path.getString("Until").contains(":")) if (!path.contains("Until") || !path.getString("Until").contains(":"))
continue; continue;
if (!path.contains("Days") || !path.isList("Days")) if (!path.contains("Days") || !path.isList("Days"))
continue; continue;
if (!path.contains("Jobs") || !path.isList("Jobs")) if (!path.contains("Jobs") || !path.isList("Jobs"))
continue; continue;
if (!path.contains("Exp") || !path.isDouble("Exp")) if (!path.contains("Exp") || !path.isDouble("Exp"))
continue; continue;
if (!path.contains("Money") || !path.isDouble("Money")) if (!path.contains("Money") || !path.isDouble("Money"))
continue; continue;
sched.setDays(path.getStringList("Days")); sched.setDays(path.getStringList("Days"));
sched.setJobs(path.getStringList("Jobs")); sched.setJobs(path.getStringList("Jobs"));
sched.setFrom(Integer.valueOf(path.getString("From").replace(":", ""))); sched.setFrom(Integer.valueOf(path.getString("From").replace(":", "")));
sched.setUntil(Integer.valueOf(path.getString("Until").replace(":", ""))); sched.setUntil(Integer.valueOf(path.getString("Until").replace(":", "")));
if (path.contains("MessageOnStart") && path.isList("MessageOnStart")) if (path.contains("MessageOnStart") && path.isList("MessageOnStart"))
sched.setMessageOnStart(path.getStringList("MessageOnStart"), path.getString("From"), path.getString("Until")); sched.setMessageOnStart(path.getStringList("MessageOnStart"), path.getString("From"), path.getString("Until"));
if (path.contains("BroadcastOnStart")) if (path.contains("BroadcastOnStart"))
sched.setBroadcastOnStart(path.getBoolean("BroadcastOnStart")); sched.setBroadcastOnStart(path.getBoolean("BroadcastOnStart"));
if (path.contains("MessageOnStop") && path.isList("MessageOnStop")) if (path.contains("MessageOnStop") && path.isList("MessageOnStop"))
sched.setMessageOnStop(path.getStringList("MessageOnStop"), path.getString("From"), path.getString("Until")); sched.setMessageOnStop(path.getStringList("MessageOnStop"), path.getString("From"), path.getString("Until"));
if (path.contains("BroadcastOnStop")) if (path.contains("BroadcastOnStop"))
sched.setBroadcastOnStop(path.getBoolean("BroadcastOnStop")); sched.setBroadcastOnStop(path.getBoolean("BroadcastOnStop"));
if (path.contains("BroadcastInterval")) if (path.contains("BroadcastInterval"))
sched.setBroadcastInterval(path.getInt("BroadcastInterval")); sched.setBroadcastInterval(path.getInt("BroadcastInterval"));
if (path.contains("BroadcastMessage") && path.isList("BroadcastMessage")) if (path.contains("BroadcastMessage") && path.isList("BroadcastMessage"))
sched.setMessageToBroadcast(path.getStringList("BroadcastMessage"), path.getString("From"), path.getString("Until")); sched.setMessageToBroadcast(path.getStringList("BroadcastMessage"), path.getString("From"), path.getString("Until"));
sched.setExpBoost(path.getDouble("Exp")); sched.setExpBoost(path.getDouble("Exp"));
sched.setMoneyBoost(path.getDouble("Money")); sched.setMoneyBoost(path.getDouble("Money"));
Jobs.getGCManager().BoostSchedule.add(sched);
Jobs.getGCManager().BoostSchedule.add(sched); }
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + Jobs.getGCManager().BoostSchedule.size() + " schedulers!");
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + Jobs.getGCManager().BoostSchedule.size() + " schedulers!"); }
} }
}
}

View File

@ -0,0 +1,58 @@
package com.gamingmesh.jobs.container;
public class BlockProtection {
private int id;
private Long time;
private Long recorded;
private DBAction action = DBAction.INSERT;
private Boolean paid = true;
public BlockProtection() {
}
public BlockProtection(DBAction action) {
this.action = action;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
this.recorded = System.currentTimeMillis();
}
public DBAction getAction() {
return action;
}
public void setAction(DBAction action) {
this.action = action;
}
public Long getRecorded() {
return recorded;
}
public Boolean isPaid() {
return paid;
}
public void setPaid(Boolean paid) {
this.paid = paid;
}
public void setRecorded(Long recorded) {
this.recorded = recorded;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

View File

@ -0,0 +1,35 @@
/**
* Jobs Plugin for Bukkit
* Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gamingmesh.jobs.container;
public enum DBAction {
NONE("None"),
UPDATE("Update"),
INSERT("Insert"),
DELETE("Delete");
private String name;
private DBAction(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

View File

@ -122,8 +122,8 @@ public class Job {
this.PointBoost = Point; this.PointBoost = Point;
} }
public boolean same(Job job) { public boolean isSame(Job job) {
return this == job; return this.equals(job);
} }
public double getPointBoost() { public double getPointBoost() {

View File

@ -69,6 +69,8 @@ public class JobsPlayer {
// log // log
private List<Log> logList = new ArrayList<Log>(); private List<Log> logList = new ArrayList<Log>();
private Long seen;
public JobsPlayer(String userName, OfflinePlayer player) { public JobsPlayer(String userName, OfflinePlayer player) {
this.userName = userName; this.userName = userName;
this.OffPlayer = player; this.OffPlayer = player;
@ -296,7 +298,7 @@ public class JobsPlayer {
*/ */
public JobProgression getJobProgression(Job job) { public JobProgression getJobProgression(Job job) {
for (JobProgression prog : progression) { for (JobProgression prog : progression) {
if (prog.getJob().same(job)) if (prog.getJob().isSame(job))
return prog; return prog;
} }
return null; return null;
@ -461,7 +463,7 @@ public class JobsPlayer {
// synchronized (saveLock) { // synchronized (saveLock) {
if (!isInJob(newjob)) { if (!isInJob(newjob)) {
for (JobProgression prog : progression) { for (JobProgression prog : progression) {
if (!prog.getJob().same(oldjob)) if (!prog.getJob().isSame(oldjob))
continue; continue;
prog.setJob(newjob); prog.setJob(newjob);
@ -495,7 +497,7 @@ public class JobsPlayer {
*/ */
public boolean isInJob(Job job) { public boolean isInJob(Job job) {
for (JobProgression prog : progression) { for (JobProgression prog : progression) {
if (prog.getJob().same(job)) if (prog.getJob().isSame(job))
return true; return true;
} }
return false; return false;
@ -644,4 +646,12 @@ public class JobsPlayer {
public void setSaved(boolean value) { public void setSaved(boolean value) {
isSaved = value; isSaved = value;
} }
public Long getSeen() {
return seen;
}
public void setSeen(Long seen) {
this.seen = seen;
}
} }

View File

@ -1,20 +1,26 @@
package com.gamingmesh.jobs.container; package com.gamingmesh.jobs.container;
public class PlayerInfo { public class PlayerInfo {
int id; int id;
String name; String name;
private Long seen;
public PlayerInfo(String name, int id) {
this.name = name; public PlayerInfo(String name, int id, Long seen) {
this.id = id; this.name = name;
} this.id = id;
this.seen = seen;
public String getName() { }
return name;
} public String getName() {
return name;
public int getID() { }
return id;
} public int getID() {
} return id;
}
public Long getSeen() {
return seen;
}
}

View File

@ -30,12 +30,17 @@ import java.util.Map.Entry;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.BlockProtection;
import com.gamingmesh.jobs.container.Convert; import com.gamingmesh.jobs.container.Convert;
import com.gamingmesh.jobs.container.DBAction;
import com.gamingmesh.jobs.container.ExploreChunk; import com.gamingmesh.jobs.container.ExploreChunk;
import com.gamingmesh.jobs.container.ExploreRegion; import com.gamingmesh.jobs.container.ExploreRegion;
import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.Job;
@ -93,12 +98,17 @@ public abstract class JobsDAO {
// creating explore database // creating explore database
checkUpdate8(); checkUpdate8();
checkUpdate9(); checkUpdate9();
// creating block protection database
checkUpdate10();
if (version <= 10)
checkUpdate11();
} }
version = 9; version = 11;
updateSchemaVersion(version); updateSchemaVersion(version);
} finally { } finally {
} }
loadAllSavedJobs(); loadAllSavedJobs();
} }
@ -120,6 +130,10 @@ public abstract class JobsDAO {
protected abstract void checkUpdate9() throws SQLException; protected abstract void checkUpdate9() throws SQLException;
protected abstract void checkUpdate10() throws SQLException;
protected abstract void checkUpdate11() throws SQLException;
protected abstract boolean createDefaultLogBase(); protected abstract boolean createDefaultLogBase();
protected abstract boolean createDefaultArchiveBase(); protected abstract boolean createDefaultArchiveBase();
@ -191,6 +205,43 @@ public abstract class JobsDAO {
return new ArrayList<JobsDAOData>(); return new ArrayList<JobsDAOData>();
} }
public void cleanUsers() {
if (!Jobs.getGCManager().DBCleaningUsersUse)
return;
JobsConnection conn = getConnection();
if (conn == null)
return;
long mark = System.currentTimeMillis() - (Jobs.getGCManager().DBCleaningUsersDays * 24 * 60 * 60 * 1000);
PreparedStatement prest = null;
try {
prest = conn.prepareStatement("DELETE FROM `" + prefix + "users` WHERE `seen` < ?;");
prest.setLong(1, mark);
prest.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(prest);
}
}
public void cleanJobs() {
if (!Jobs.getGCManager().DBCleaningJobsUse)
return;
JobsConnection conn = getConnection();
if (conn == null)
return;
PreparedStatement prest = null;
try {
prest = conn.prepareStatement("DELETE FROM `" + prefix + "jobs` WHERE `level` <= ?;");
prest.setInt(1, Jobs.getGCManager().DBCleaningJobsLvl);
prest.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(prest);
}
}
private void loadAllSavedJobs() { private void loadAllSavedJobs() {
JobsConnection conn = getConnection(); JobsConnection conn = getConnection();
if (conn == null) if (conn == null)
@ -233,9 +284,10 @@ public abstract class JobsDAO {
return; return;
PreparedStatement prestt = null; PreparedStatement prestt = null;
try { try {
prestt = conn.prepareStatement("INSERT INTO `" + prefix + "users` (`player_uuid`, `username`) VALUES (?, ?);"); prestt = conn.prepareStatement("INSERT INTO `" + prefix + "users` (`player_uuid`, `username`, `seen`) VALUES (?, ?, ?);");
prestt.setString(1, uuid.toString()); prestt.setString(1, uuid.toString());
prestt.setString(2, playerName); prestt.setString(2, playerName);
prestt.setLong(3, System.currentTimeMillis());
prestt.executeUpdate(); prestt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@ -250,7 +302,7 @@ public abstract class JobsDAO {
res = prest.executeQuery(); res = prest.executeQuery();
res.next(); res.next();
int id = res.getInt("id"); int id = res.getInt("id");
Jobs.getPlayerManager().getPlayerMap().put(uuid.toString(), new PlayerInfo(playerName, id)); Jobs.getPlayerManager().getPlayerMap().put(uuid.toString(), new PlayerInfo(playerName, id, System.currentTimeMillis()));
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@ -462,13 +514,14 @@ public abstract class JobsDAO {
statement.executeUpdate("DELETE from `" + getPrefix() + "users`"); statement.executeUpdate("DELETE from `" + getPrefix() + "users`");
} }
insert = conns.prepareStatement("INSERT INTO `" + getPrefix() + "users` (`id`, `player_uuid`, `username`) VALUES (?, ?, ?);"); insert = conns.prepareStatement("INSERT INTO `" + getPrefix() + "users` (`id`, `player_uuid`, `username`, `seen`) VALUES (?, ?, ?, ?);");
conns.setAutoCommit(false); conns.setAutoCommit(false);
for (Entry<String, JobsPlayer> oneUser : Jobs.getPlayerManager().getPlayersCache().entrySet()) { for (Entry<String, JobsPlayer> oneUser : Jobs.getPlayerManager().getPlayersCache().entrySet()) {
insert.setInt(1, oneUser.getValue().getUserId()); insert.setInt(1, oneUser.getValue().getUserId());
insert.setString(2, oneUser.getValue().getPlayerUUID().toString()); insert.setString(2, oneUser.getValue().getPlayerUUID().toString());
insert.setString(3, oneUser.getValue().getUserName()); insert.setString(3, oneUser.getValue().getUserName());
insert.setLong(4, oneUser.getValue().getSeen());
insert.addBatch(); insert.addBatch();
} }
insert.executeBatch(); insert.executeBatch();
@ -686,7 +739,7 @@ public abstract class JobsDAO {
prest.setString(1, uuid.toString()); prest.setString(1, uuid.toString());
res = prest.executeQuery(); res = prest.executeQuery();
while (res.next()) { while (res.next()) {
pInfo = new PlayerInfo(res.getString("username"), res.getInt("id")); pInfo = new PlayerInfo(res.getString("username"), res.getInt("id"), res.getLong("seen"));
Jobs.getPlayerManager().getPlayerMap().put(res.getString("player_uuid"), pInfo); Jobs.getPlayerManager().getPlayerMap().put(res.getString("player_uuid"), pInfo);
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -709,7 +762,8 @@ public abstract class JobsDAO {
prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users`;"); prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users`;");
res = prest.executeQuery(); res = prest.executeQuery();
while (res.next()) { while (res.next()) {
Jobs.getPlayerManager().getPlayerMap().put(res.getString("player_uuid"), new PlayerInfo(res.getString("username"), res.getInt("id"))); Jobs.getPlayerManager().getPlayerMap().put(res.getString("player_uuid"), new PlayerInfo(res.getString("username"), res.getInt("id"), res.getLong(
"seen")));
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@ -728,8 +782,6 @@ public abstract class JobsDAO {
// synchronized (jPlayer.saveLock) { // synchronized (jPlayer.saveLock) {
jPlayer.progression.clear(); jPlayer.progression.clear();
for (JobsDAOData jobdata : list) { for (JobsDAOData jobdata : list) {
if (Jobs.getJob(jobdata.getJobName()) == null)
continue;
// add the job // add the job
Job job = Jobs.getJob(jobdata.getJobName()); Job job = Jobs.getJob(jobdata.getJobName());
if (job == null) if (job == null)
@ -761,7 +813,8 @@ public abstract class JobsDAO {
prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users`;"); prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users`;");
res = prest.executeQuery(); res = prest.executeQuery();
while (res.next()) { while (res.next()) {
Jobs.getPlayerManager().getPlayerMap().put(res.getString("player_uuid"), new PlayerInfo(res.getString("username"), res.getInt("id"))); Jobs.getPlayerManager().getPlayerMap().put(res.getString("player_uuid"), new PlayerInfo(res.getString("username"), res.getInt("id"), res.getLong(
"seen")));
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@ -818,6 +871,25 @@ public abstract class JobsDAO {
} finally { } finally {
close(prest); close(prest);
} }
updateSeen(player);
}
public void updateSeen(JobsPlayer player) {
JobsConnection conn = getConnection();
if (conn == null)
return;
PreparedStatement prest = null;
try {
prest = conn.prepareStatement("UPDATE `" + prefix
+ "users` SET `seen` = ? WHERE `id` = ?;");
prest.setLong(1, System.currentTimeMillis());
prest.setInt(2, player.getUserId());
prest.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(prest);
}
} }
public void savePoints(JobsPlayer player) { public void savePoints(JobsPlayer player) {
@ -919,6 +991,10 @@ public abstract class JobsDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
close(prest1);
close(prest2);
this.dropDataBase("log");
this.createDefaultLogBase();
} finally { } finally {
close(prest1); close(prest1);
close(prest2); close(prest2);
@ -955,6 +1031,189 @@ public abstract class JobsDAO {
} }
} }
/**
* Save block protection information
* @param jobBlockProtection - the information getting saved
*/
public void saveBlockProtection() {
JobsConnection conn = getConnection();
if (conn == null)
return;
PreparedStatement insert = null;
PreparedStatement update = null;
PreparedStatement delete = null;
try {
insert = conn.prepareStatement("INSERT INTO `" + prefix + "blocks` (`world`, `x`, `y`, `z`, `recorded`, `resets`) VALUES (?, ?, ?, ?, ?, ?);");
update = conn.prepareStatement("UPDATE `" + prefix + "blocks` SET `recorded` = ?, `resets` = ? WHERE `id` = ?;");
delete = conn.prepareStatement("DELETE from `" + getPrefix() + "blocks` WHERE `id` = ?;");
Jobs.getPluginLogger().info("Saving blocks");
conn.setAutoCommit(false);
int inserted = 0;
int updated = 0;
int deleted = 0;
Long current = System.currentTimeMillis();
Long mark = System.currentTimeMillis() - (Jobs.getGCManager().BlockProtectionDays * 24L * 60L * 60L * 1000L);
ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
for (Entry<World, HashMap<String, HashMap<String, HashMap<Vector, BlockProtection>>>> worlds : Jobs.getBpManager().getMap().entrySet()) {
for (Entry<String, HashMap<String, HashMap<Vector, BlockProtection>>> regions : worlds.getValue().entrySet()) {
for (Entry<String, HashMap<Vector, BlockProtection>> chunks : regions.getValue().entrySet()) {
for (Entry<Vector, BlockProtection> block : chunks.getValue().entrySet()) {
switch (block.getValue().getAction()) {
case DELETE:
delete.setInt(1, block.getValue().getId());
delete.addBatch();
deleted++;
if (deleted % 10000 == 0) {
delete.executeBatch();
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Removed " + deleted + " old block protection entries.");
console.sendMessage(message);
}
break;
case INSERT:
if (block.getValue().getTime() < current && block.getValue().getTime() != -1)
continue;
insert.setString(1, worlds.getKey().getName());
insert.setInt(2, block.getKey().getBlockX());
insert.setInt(3, block.getKey().getBlockY());
insert.setInt(4, block.getKey().getBlockZ());
insert.setLong(5, block.getValue().getRecorded());
insert.setLong(6, block.getValue().getTime());
insert.addBatch();
inserted++;
if (inserted % 10000 == 0) {
insert.executeBatch();
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Added " + inserted + " new block protection entries.");
console.sendMessage(message);
}
break;
case UPDATE:
if (block.getValue().getTime() < current && block.getValue().getTime() != -1)
continue;
update.setLong(1, block.getValue().getRecorded());
update.setLong(2, block.getValue().getTime());
update.setInt(3, block.getValue().getId());
update.addBatch();
updated++;
if (updated % 10000 == 0) {
update.executeBatch();
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Upadated " + updated + " old block protection entries.");
console.sendMessage(message);
}
break;
case NONE:
if (block.getValue().getTime() < current && block.getValue().getTime() != -1)
continue;
if (block.getValue().getTime() == -1 && block.getValue().getRecorded() > mark)
continue;
delete.setInt(1, block.getValue().getId());
delete.addBatch();
deleted++;
if (deleted % 10000 == 0) {
delete.executeBatch();
Jobs.getPluginLogger().info("[Jobs] Removed " + deleted + " old block protection entries.");
}
break;
default:
continue;
}
}
}
}
}
insert.executeBatch();
update.executeBatch();
delete.executeBatch();
conn.commit();
conn.setAutoCommit(true);
if (inserted > 0) {
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Added " + inserted + " new block protection entries.");
console.sendMessage(message);
}
if (updated > 0) {
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Updated " + updated + " with new block protection entries.");
console.sendMessage(message);
}
if (deleted > 0) {
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Deleted " + deleted + " old block protection entries.");
console.sendMessage(message);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(insert);
close(update);
close(delete);
}
}
/**
* Save block protection information
* @param jobBlockProtection - the information getting saved
*/
public void loadBlockProtection() {
JobsConnection conn = getConnection();
if (conn == null)
return;
PreparedStatement prest = null;
ResultSet res = null;
Jobs.getBpManager().timer = 0L;
try {
prest = conn.prepareStatement("SELECT * FROM `" + prefix + "blocks`;");
res = prest.executeQuery();
int i = 0;
int ii = 0;
while (res.next()) {
World world = Bukkit.getWorld(res.getString("world"));
if (world == null)
continue;
int id = res.getInt("id");
int x = res.getInt("x");
int y = res.getInt("y");
int z = res.getInt("z");
long resets = res.getLong("resets");
Location loc = new Location(world, x, y, z);
BlockProtection bp = Jobs.getBpManager().add(loc, resets, true);
bp.setId(id);
long t = System.currentTimeMillis();
bp.setRecorded(res.getLong("recorded"));
bp.setAction(DBAction.NONE);
i++;
ii++;
if (ii >= 100000) {
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] Loading (" + i +") BP");
Bukkit.getServer().getConsoleSender().sendMessage(message);
ii = 0;
}
Jobs.getBpManager().timer += System.currentTimeMillis() - t;
}
if (i > 0) {
String message = ChatColor.translateAlternateColorCodes('&', "&6[Jobs] loaded " + i + " block protection entries. " + Jobs.getBpManager().timer);
Bukkit.getServer().getConsoleSender().sendMessage(message);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(res);
close(prest);
}
}
/** /**
* Save player-explore information * Save player-explore information
* @param jobexplore - the information getting saved * @param jobexplore - the information getting saved

View File

@ -117,6 +117,7 @@ public class JobsDAOMySQL extends JobsDAO {
createDefaultPointsBase(); createDefaultPointsBase();
createDefaultExploreBase(); createDefaultExploreBase();
createDefaultUsersBase(); createDefaultUsersBase();
createDefaultBlockProtection();
} }
@Override @Override
@ -643,7 +644,7 @@ public class JobsDAOMySQL extends JobsDAO {
prestUsersT = conn.prepareStatement("SELECT * FROM " + getPrefix() + "users;"); prestUsersT = conn.prepareStatement("SELECT * FROM " + getPrefix() + "users;");
res4 = prestUsersT.executeQuery(); res4 = prestUsersT.executeQuery();
while (res4.next()) { while (res4.next()) {
tempPlayerMap.put(res4.getString("player_uuid"), new PlayerInfo(res4.getString("username"), res4.getInt("id"))); tempPlayerMap.put(res4.getString("player_uuid"), new PlayerInfo(res4.getString("username"), res4.getInt("id"), System.currentTimeMillis()));
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -710,6 +711,64 @@ public class JobsDAOMySQL extends JobsDAO {
} }
} }
@Override
protected synchronized void checkUpdate10() {
JobsConnection conn = getConnection();
if (conn == null) {
Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!");
return;
}
PreparedStatement prest = null;
ResultSet res = null;
int rows = 0;
try {
// Check for jobs table
prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;");
prest.setString(1, database);
prest.setString(2, getPrefix() + "blocks");
res = prest.executeQuery();
if (res.next()) {
rows = res.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(res);
close(prest);
}
if (rows == 0)
createDefaultBlockProtection();
}
@Override
protected synchronized void checkUpdate11() {
JobsConnection conn = getConnection();
if (conn == null) {
Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!");
return;
}
try {
executeSQL("ALTER TABLE `" + getPrefix() + "users` ADD COLUMN `seen` bigint;");
} catch (SQLException e) {
e.printStackTrace();
return;
} finally {
}
PreparedStatement prest = null;
try {
prest = conn.prepareStatement("UPDATE `" + getPrefix() + "users` SET `seen` = ?;");
prest.setLong(1, System.currentTimeMillis());
prest.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(prest);
}
}
private boolean createDefaultExploreBase() { private boolean createDefaultExploreBase() {
try { try {
executeSQL("CREATE TABLE `" + getPrefix() executeSQL("CREATE TABLE `" + getPrefix()
@ -765,7 +824,17 @@ public class JobsDAOMySQL extends JobsDAO {
private boolean createDefaultUsersBase() { private boolean createDefaultUsersBase() {
try { try {
executeSQL("CREATE TABLE `" + getPrefix() executeSQL("CREATE TABLE `" + getPrefix()
+ "users` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20));"); + "users` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `seen` bigint);");
} catch (SQLException e) {
return false;
}
return true;
}
private boolean createDefaultBlockProtection() {
try {
executeSQL("CREATE TABLE `" + getPrefix()
+ "blocks` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `world` varchar(36) NOT NULL, `x` int, `y` int, `z` int, `recorded` bigint, `resets` bigint);");
} catch (SQLException e) { } catch (SQLException e) {
return false; return false;
} }

View File

@ -22,10 +22,13 @@ import java.io.File;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.PlayerInfo; import com.gamingmesh.jobs.container.PlayerInfo;
@ -119,6 +122,7 @@ public class JobsDAOSQLite extends JobsDAO {
createDefaultPointsBase(); createDefaultPointsBase();
createDefaultExploreBase(); createDefaultExploreBase();
createDefaultUsersBase(); createDefaultUsersBase();
createDefaultBlockProtection();
} }
@Override @Override
@ -279,8 +283,6 @@ public class JobsDAOSQLite extends JobsDAO {
if (convertJobs) { if (convertJobs) {
Bukkit.getConsoleSender().sendMessage("convert jobs table from byte");
Jobs.getPluginLogger().info("Converting byte uuids to string. This could take a long time!!!"); Jobs.getPluginLogger().info("Converting byte uuids to string. This could take a long time!!!");
try { try {
executeSQL("CREATE TABLE `" + getPrefix() executeSQL("CREATE TABLE `" + getPrefix()
@ -583,7 +585,6 @@ public class JobsDAOSQLite extends JobsDAO {
prestJobs = conn.prepareStatement("SELECT * FROM " + getPrefix() + "jobs;"); prestJobs = conn.prepareStatement("SELECT * FROM " + getPrefix() + "jobs;");
res2 = prestJobs.executeQuery(); res2 = prestJobs.executeQuery();
while (res2.next()) { while (res2.next()) {
Bukkit.getConsoleSender().sendMessage(res2.getString("player_uuid") + " -> " + res2.getString("username"));
tempMap.put(res2.getString("player_uuid"), res2.getString("username")); tempMap.put(res2.getString("player_uuid"), res2.getString("username"));
} }
} finally { } finally {
@ -598,7 +599,6 @@ public class JobsDAOSQLite extends JobsDAO {
res3 = prestArchive.executeQuery(); res3 = prestArchive.executeQuery();
while (res3.next()) { while (res3.next()) {
tempMap.put(res3.getString("player_uuid"), res3.getString("username")); tempMap.put(res3.getString("player_uuid"), res3.getString("username"));
Bukkit.getConsoleSender().sendMessage(res3.getString("player_uuid") + " -> " + res3.getString("username"));
} }
} finally { } finally {
close(res3); close(res3);
@ -615,7 +615,6 @@ public class JobsDAOSQLite extends JobsDAO {
prestUsers = conn.prepareStatement("INSERT INTO `" + getPrefix() + "users` (`player_uuid`, `username`) VALUES (?, ?);"); prestUsers = conn.prepareStatement("INSERT INTO `" + getPrefix() + "users` (`player_uuid`, `username`) VALUES (?, ?);");
conn.setAutoCommit(false); conn.setAutoCommit(false);
for (Entry<String, String> users : tempMap.entrySet()) { for (Entry<String, String> users : tempMap.entrySet()) {
Bukkit.getConsoleSender().sendMessage(users.getKey() + " -----> " + users.getValue());
prestUsers.setString(1, users.getKey()); prestUsers.setString(1, users.getKey());
prestUsers.setString(2, users.getValue()); prestUsers.setString(2, users.getValue());
prestUsers.addBatch(); prestUsers.addBatch();
@ -635,7 +634,7 @@ public class JobsDAOSQLite extends JobsDAO {
prestUsers2 = conn.prepareStatement("SELECT * FROM " + getPrefix() + "users;"); prestUsers2 = conn.prepareStatement("SELECT * FROM " + getPrefix() + "users;");
res4 = prestUsers2.executeQuery(); res4 = prestUsers2.executeQuery();
while (res4.next()) { while (res4.next()) {
tempPlayerMap.put(res4.getString("player_uuid"), new PlayerInfo(res4.getString("username"), res4.getInt("id"))); tempPlayerMap.put(res4.getString("player_uuid"), new PlayerInfo(res4.getString("username"), res4.getInt("id"), System.currentTimeMillis()));
} }
} finally { } finally {
close(res4); close(res4);
@ -777,6 +776,99 @@ public class JobsDAOSQLite extends JobsDAO {
} }
@Override
protected synchronized void checkUpdate10() {
JobsConnection conn = getConnection();
if (conn == null) {
Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!");
return;
}
PreparedStatement prest = null;
ResultSet res = null;
int rows = 0;
try {
// Check for jobs table
prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;");
prest.setString(1, getPrefix() + "blocks");
res = prest.executeQuery();
if (res.next()) {
rows = res.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(res);
close(prest);
}
if (rows == 0)
createDefaultBlockProtection();
}
@Override
protected synchronized void checkUpdate11() {
JobsConnection conn = getConnection();
if (conn == null) {
Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!");
return;
}
try {
executeSQL("ALTER TABLE `" + getPrefix() + "users` ADD COLUMN `seen` bigint;");
} catch (SQLException e) {
e.printStackTrace();
return;
} finally {
}
PreparedStatement prest = null;
try {
prest = conn.prepareStatement("UPDATE `" + getPrefix() + "users` SET `seen` = ?;");
prest.setLong(1, System.currentTimeMillis());
prest.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(prest);
}
// HashMap<UUID, Long> map = new HashMap<UUID, Long>();
// Jobs.getPluginLogger().info("Updating player last seen value");
// for (OfflinePlayer one : Bukkit.getOfflinePlayers()) {
// map.put(one.getUniqueId(), one.getLastPlayed());
// }
//
// PreparedStatement prestJobsT = null;
// try {
// prestJobsT = conn.prepareStatement("UPDATE `" + getPrefix() + "users` SET `seen` = ? WHERE `player_uuid` = ?;");
// conn.setAutoCommit(false);
//
// int i = 0;
// int y = 0;
// for (Entry<UUID, Long> users : map.entrySet()) {
// prestJobsT.setLong(1, users.getValue());
// prestJobsT.setString(2, users.getKey().toString());
// prestJobsT.addBatch();
//
// i++;
// y++;
// if (i >= 1000) {
// Jobs.getPluginLogger().info("Updated " + y + "/" + map.size());
// i = 0;
// }
// }
// prestJobsT.executeBatch();
// conn.commit();
// conn.setAutoCommit(true);
// Jobs.getPluginLogger().info("Finished");
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// close(prestJobsT);
// }
}
private boolean createDefaultExploreBase() { private boolean createDefaultExploreBase() {
try { try {
executeSQL("CREATE TABLE `" + getPrefix() executeSQL("CREATE TABLE `" + getPrefix()
@ -800,7 +892,7 @@ public class JobsDAOSQLite extends JobsDAO {
private boolean createDefaultUsersBase() { private boolean createDefaultUsersBase() {
try { try {
executeSQL("CREATE TABLE `" + getPrefix() executeSQL("CREATE TABLE `" + getPrefix()
+ "users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20));"); + "users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `seen` bigint);");
} catch (SQLException e) { } catch (SQLException e) {
return false; return false;
} }
@ -839,6 +931,16 @@ public class JobsDAOSQLite extends JobsDAO {
return true; return true;
} }
private boolean createDefaultBlockProtection() {
try {
executeSQL("CREATE TABLE `" + getPrefix()
+ "blocks` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `world` varchar(36) NOT NULL, `x` int, `y` int, `z` int, `recorded` bigint, `resets` bigint);");
} catch (SQLException e) {
return false;
}
return true;
}
@Override @Override
protected boolean dropDataBase(String name) { protected boolean dropDataBase(String name) {
try { try {

View File

@ -29,7 +29,6 @@ import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
@ -40,7 +39,6 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent; import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;
@ -66,7 +64,6 @@ import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobLimitedItems; import com.gamingmesh.jobs.container.JobLimitedItems;
import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.JobsPlayer;
import com.gamingmesh.jobs.stuff.Debug;
public class JobsListener implements Listener { public class JobsListener implements Listener {
// hook to the main plugin // hook to the main plugin
@ -88,8 +85,6 @@ public class JobsListener implements Listener {
event.setCancelled(true); event.setCancelled(true);
Debug.D(event.getRawSlot());
int tsize = player.getOpenInventory().getTopInventory().getSize(); int tsize = player.getOpenInventory().getTopInventory().getSize();
if (event.getRawSlot() < 0 || event.getRawSlot() >= tsize) if (event.getRawSlot() < 0 || event.getRawSlot() >= tsize)
@ -492,38 +487,18 @@ public class JobsListener implements Listener {
pm.addPermission(new Permission("jobs.world." + world.getName().toLowerCase(), PermissionDefault.TRUE)); pm.addPermission(new Permission("jobs.world." + world.getName().toLowerCase(), PermissionDefault.TRUE));
} }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onWaterBlockBreak(BlockFromToEvent event) {
//disabling plugin in world
if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld()))
return;
if (!Jobs.getGCManager().WaterBlockBreake)
return;
if (event.getBlock().getType() == Material.STATIONARY_WATER && event.getToBlock().getType() != Material.AIR && event.getToBlock()
.getType() != Material.STATIONARY_WATER && event.getToBlock().getState().hasMetadata(
JobsPaymentListener.PlacedBlockMetadata)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onCropGrown(final BlockGrowEvent event) { public void onCropGrown(final BlockGrowEvent event) {
//disabling plugin in world //disabling plugin in world
if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld())) if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld()))
return; return;
if (!Jobs.getGCManager().WaterBlockBreake) Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
return; @Override
if (event.getBlock().getState().hasMetadata(JobsPaymentListener.PlacedBlockMetadata)) { public void run() {
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Jobs.getBpManager().remove(event.getBlock());
@Override return;
public void run() { }
event.getBlock().getState().removeMetadata(JobsPaymentListener.PlacedBlockMetadata, plugin); }, 1L);
return;
}
}, 1L);
}
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")

View File

@ -77,6 +77,7 @@ import com.gamingmesh.jobs.actions.ExploreActionInfo;
import com.gamingmesh.jobs.actions.ItemActionInfo; import com.gamingmesh.jobs.actions.ItemActionInfo;
import com.gamingmesh.jobs.api.JobsChunkChangeEvent; import com.gamingmesh.jobs.api.JobsChunkChangeEvent;
import com.gamingmesh.jobs.container.ActionType; import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.BlockProtection;
import com.gamingmesh.jobs.container.ExploreRespond; import com.gamingmesh.jobs.container.ExploreRespond;
import com.gamingmesh.jobs.container.FastPayment; import com.gamingmesh.jobs.container.FastPayment;
import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobProgression;
@ -254,17 +255,6 @@ public class JobsPaymentListener implements Listener {
if (block.getType() == Material.FURNACE && block.hasMetadata(this.furnaceOwnerMetadata)) if (block.getType() == Material.FURNACE && block.hasMetadata(this.furnaceOwnerMetadata))
block.removeMetadata(this.furnaceOwnerMetadata, this.plugin); block.removeMetadata(this.furnaceOwnerMetadata, this.plugin);
if (Jobs.getGCManager().useBlockProtection) {
if (block.getState().hasMetadata(BlockMetadata))
return;
if (Jobs.getPistonProtectionListener().CheckBlock(block))
block.getState().setMetadata(BlockMetadata, new FixedMetadataValue(this.plugin, true));
}
if (Jobs.getGCManager().useBlockTimer)
if (Jobs.getPistonProtectionListener().checkVegybreak(block, event.getPlayer()))
return;
// make sure plugin is enabled // make sure plugin is enabled
if (!this.plugin.isEnabled()) if (!this.plugin.isEnabled())
return; return;
@ -280,22 +270,6 @@ public class JobsPaymentListener implements Listener {
if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName()))
return; return;
// Global block timer
if (Jobs.getGCManager().useGlobalTimer && !Jobs.getRestrictedBlockManager().restrictedBlocksTimer.containsKey(block.getTypeId())) {
if (block.getState().hasMetadata(GlobalMetadata)) {
long currentTime = System.currentTimeMillis();
List<MetadataValue> meta = block.getState().getMetadata(GlobalMetadata);
if (meta.size() > 0) {
long BlockTime = meta.get(0).asLong();
if (currentTime < BlockTime + Jobs.getGCManager().globalblocktimer * 1000) {
int sec = Math.round((((BlockTime + Jobs.getGCManager().globalblocktimer * 1000) - currentTime)) / 1000);
Jobs.getActionBar().send(player, Jobs.getLanguage().getMessage("message.blocktimer", "[time]", sec));
return;
}
}
}
}
FastPayment fp = Jobs.FastPayment.get(player.getName()); FastPayment fp = Jobs.FastPayment.get(player.getName());
if (fp != null) { if (fp != null) {
if (fp.getTime() > System.currentTimeMillis()) { if (fp.getTime() > System.currentTimeMillis()) {
@ -316,18 +290,16 @@ public class JobsPaymentListener implements Listener {
// Protection for block break with silktouch // Protection for block break with silktouch
if (Jobs.getGCManager().useSilkTouchProtection && item != null) if (Jobs.getGCManager().useSilkTouchProtection && item != null)
if (Jobs.getPistonProtectionListener().CheckBlock(block)) for (Entry<Enchantment, Integer> one : item.getEnchantments().entrySet())
for (Entry<Enchantment, Integer> one : item.getEnchantments().entrySet()) if (one.getKey().getName().equalsIgnoreCase("SILK_TOUCH"))
if (one.getKey().getName().equalsIgnoreCase("SILK_TOUCH")) return;
return;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jPlayer == null) if (jPlayer == null)
return; return;
BlockActionInfo bInfo = new BlockActionInfo(block, ActionType.BREAK); BlockActionInfo bInfo = new BlockActionInfo(block, ActionType.BREAK);
Jobs.action(jPlayer, bInfo, multiplier, block);
Jobs.action(jPlayer, bInfo, multiplier);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@ -361,32 +333,16 @@ public class JobsPaymentListener implements Listener {
if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName()))
return; return;
// Block place/break protection
if (Jobs.getGCManager().useBlockProtection) { if (Jobs.getGCManager().useBlockProtection) {
if (block.getState().hasMetadata(BlockMetadata)) BlockProtection bp = Jobs.getBpManager().getBp(block.getLocation());
return; if (bp == null)
if (Jobs.getPistonProtectionListener().CheckBlock(block)) Jobs.getBpManager().add(block, Jobs.getBpManager().getBlockDelayTime(block), false);
block.getState().setMetadata(BlockMetadata, new FixedMetadataValue(this.plugin, true));
}
if (Jobs.getGCManager().WaterBlockBreake)
block.getState().setMetadata(PlacedBlockMetadata, new FixedMetadataValue(this.plugin, true));
if (Jobs.getGCManager().useBlockTimer)
if (Jobs.getPistonProtectionListener().CheckVegy(block)) {
long time = System.currentTimeMillis();
block.setMetadata(VegyMetadata, new FixedMetadataValue(this.plugin, time));
}
if (Jobs.getGCManager().useGlobalTimer) {
long time = System.currentTimeMillis();
block.setMetadata(GlobalMetadata, new FixedMetadataValue(this.plugin, time));
} }
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jPlayer == null) if (jPlayer == null)
return; return;
Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.PLACE), 0.0); Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.PLACE), 0.0, block);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)

View File

@ -1,131 +1,129 @@
package com.gamingmesh.jobs.listeners; package com.gamingmesh.jobs.listeners;
import java.util.HashMap; import java.util.HashMap;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.actions.ItemActionInfo; import com.gamingmesh.jobs.actions.ItemActionInfo;
import com.gamingmesh.jobs.container.ActionType; import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.JobsPlayer;
import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityActivateEvent; import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityActivateEvent;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityDeactivateEvent; import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityDeactivateEvent;
import com.gmail.nossr50.events.skills.repair.McMMOPlayerRepairCheckEvent; import com.gmail.nossr50.events.skills.repair.McMMOPlayerRepairCheckEvent;
public class McMMOlistener implements Listener { public class McMMOlistener implements Listener {
private Jobs plugin; private Jobs plugin;
public boolean mcMMOPresent = false; public boolean mcMMOPresent = false;
HashMap<String, HashMap<AbilityType, Long>> map = new HashMap<String, HashMap<AbilityType, Long>>(); HashMap<String, HashMap<AbilityType, Long>> map = new HashMap<String, HashMap<AbilityType, Long>>();
public McMMOlistener(Jobs plugin) { public McMMOlistener(Jobs plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@EventHandler @EventHandler
public void OnItemrepair(McMMOPlayerRepairCheckEvent event) { public void OnItemrepair(McMMOPlayerRepairCheckEvent event) {
//disabling plugin in world //disabling plugin in world
if (event.getPlayer() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getPlayer().getWorld())) if (event.getPlayer() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getPlayer().getWorld()))
return; return;
// make sure plugin is enabled // make sure plugin is enabled
if (!plugin.isEnabled()) if (!plugin.isEnabled())
return; return;
Player player = event.getPlayer(); Player player = event.getPlayer();
ItemStack resultStack = event.getRepairedObject(); ItemStack resultStack = event.getRepairedObject();
if (resultStack == null) if (resultStack == null)
return; return;
if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName()))
return; return;
// check if in creative // check if in creative
if (player.getGameMode().equals(GameMode.CREATIVE) && !Jobs.getGCManager().payInCreative()) if (player.getGameMode().equals(GameMode.CREATIVE) && !Jobs.getGCManager().payInCreative())
return; return;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR), 0.0); Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR), 0.0);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void OnAbilityOn(McMMOPlayerAbilityActivateEvent event) { public void OnAbilityOn(McMMOPlayerAbilityActivateEvent event) {
HashMap<AbilityType, Long> InfoMap = new HashMap<AbilityType, Long>(); HashMap<AbilityType, Long> InfoMap = new HashMap<AbilityType, Long>();
if (map.containsKey(event.getPlayer().getName())) if (map.containsKey(event.getPlayer().getName()))
InfoMap = map.get(event.getPlayer().getName()); InfoMap = map.get(event.getPlayer().getName());
InfoMap.put(event.getAbility(), System.currentTimeMillis() + (event.getAbility().getMaxLength() * 1000)); InfoMap.put(event.getAbility(), System.currentTimeMillis() + (event.getAbility().getMaxLength() * 1000));
map.put(event.getPlayer().getName(), InfoMap); map.put(event.getPlayer().getName(), InfoMap);
// Debug.D("rec 1 " + map.size() + " " + event.getPlayer().getName()); }
// Debug.D(map.containsKey(event.getPlayer().getName()));
} @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void OnAbilityOff(McMMOPlayerAbilityDeactivateEvent event) {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) if (map.containsKey(event.getPlayer().getName())) {
public void OnAbilityOff(McMMOPlayerAbilityDeactivateEvent event) { HashMap<AbilityType, Long> InfoMap = map.get(event.getPlayer().getName());
if (map.containsKey(event.getPlayer().getName())) { InfoMap.remove(event.getAbility());
HashMap<AbilityType, Long> InfoMap = map.get(event.getPlayer().getName()); if (InfoMap.isEmpty())
InfoMap.remove(event.getAbility()); map.remove(event.getPlayer().getName());
if (InfoMap.isEmpty()) }
map.remove(event.getPlayer().getName()); }
}
} public double getMultiplier(Player player) {
public double getMultiplier(Player player) { HashMap<AbilityType, Long> InfoMap = map.get(player.getName());
if (InfoMap == null)
HashMap<AbilityType, Long> InfoMap = map.get(player.getName()); return 1.0;
if (InfoMap == null)
return 1.0; Long t = InfoMap.get(AbilityType.TREE_FELLER);
if (t != null) {
Long t = InfoMap.get(AbilityType.TREE_FELLER); if (t < System.currentTimeMillis())
if (t != null) { return Jobs.getGCManager().TreeFellerMultiplier;
if (t < System.currentTimeMillis()) map.remove(AbilityType.TREE_FELLER);
return Jobs.getGCManager().TreeFellerMultiplier; }
map.remove(AbilityType.TREE_FELLER);
} t = InfoMap.get(AbilityType.GIGA_DRILL_BREAKER);
if (t != null) {
t = InfoMap.get(AbilityType.GIGA_DRILL_BREAKER); if (t < System.currentTimeMillis())
if (t != null) { return Jobs.getGCManager().gigaDrillMultiplier;
if (t < System.currentTimeMillis()) map.remove(AbilityType.GIGA_DRILL_BREAKER);
return Jobs.getGCManager().gigaDrillMultiplier; }
map.remove(AbilityType.GIGA_DRILL_BREAKER);
} t = InfoMap.get(AbilityType.SUPER_BREAKER);
if (t != null) {
t = InfoMap.get(AbilityType.SUPER_BREAKER); if (t < System.currentTimeMillis())
if (t != null) { return Jobs.getGCManager().superBreakerMultiplier;
if (t < System.currentTimeMillis()) map.remove(AbilityType.SUPER_BREAKER);
return Jobs.getGCManager().superBreakerMultiplier; }
map.remove(AbilityType.SUPER_BREAKER); return 1.0;
} }
return 1.0;
} public boolean CheckmcMMO() {
Plugin McMMO = Bukkit.getPluginManager().getPlugin("mcMMO");
public boolean CheckmcMMO() { if (McMMO != null) {
Plugin McMMO = Bukkit.getPluginManager().getPlugin("mcMMO"); try {
if (McMMO != null) { Class.forName("com.gmail.nossr50.api.AbilityAPI");
try { } catch (ClassNotFoundException e) {
Class.forName("com.gmail.nossr50.api.AbilityAPI"); // Disabling skill API check;
} catch (ClassNotFoundException e) { mcMMOPresent = false;
// Disabling skill API check; Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&',
mcMMOPresent = false; "&e[Jobs] &6mcMMO was found - &cBut your McMMO version is outdated, please update for full support."));
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', // Still enabling event listener for repair
"&e[Jobs] &6mcMMO was found - &cBut your McMMO version is outdated, please update for full support.")); return true;
// Still enabling event listener for repair }
return true; mcMMOPresent = true;
} Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', "&e[Jobs] &6mcMMO was found - Enabling capabilities."));
mcMMOPresent = true; return true;
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', "&e[Jobs] &6mcMMO was found - Enabling capabilities.")); }
return true; return false;
} }
return false; }
}
}

View File

@ -1,9 +1,8 @@
package com.gamingmesh.jobs.listeners; package com.gamingmesh.jobs.listeners;
import java.util.List; import org.bukkit.Location;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@ -21,94 +20,71 @@ public class PistonProtectionListener implements Listener {
this.plugin = plugin; this.plugin = plugin;
} }
@SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public boolean CheckBlock(Block block) {
for (String BlockId : Jobs.getRestrictedBlockManager().restrictedBlocks) {
if (BlockId.equalsIgnoreCase(String.valueOf(block.getTypeId()))) {
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
public boolean CheckPlaceBlock(Block block) {
for (int BlockId : Jobs.getRestrictedBlockManager().restrictedPlaceBlocksTimer) {
if (BlockId == block.getTypeId()) {
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
public boolean CheckVegy(Block block) {
if (!Jobs.getRestrictedBlockManager().restrictedBlocksTimer.containsKey(block.getTypeId()))
return false;
return true;
}
@SuppressWarnings("deprecation")
public boolean checkVegybreak(Block block, Player player) {
if (!Jobs.getRestrictedBlockManager().restrictedBlocksTimer.containsKey(block.getTypeId()))
return false;
if (CheckVegyTimer(block, Jobs.getRestrictedBlockManager().restrictedBlocksTimer.get(block.getTypeId()), player))
return true;
return false;
}
public boolean CheckVegyTimer(Block block, int time, Player player) {
long currentTime = System.currentTimeMillis();
if (!block.hasMetadata(JobsPaymentListener.VegyMetadata))
return false;
long BlockTime = block.getMetadata(JobsPaymentListener.VegyMetadata).get(0).asLong();
if (currentTime >= BlockTime + time * 1000) {
return false;
}
int sec = Math.round((((BlockTime + time * 1000) - currentTime)) / 1000);
Jobs.getActionBar().send(player, Jobs.getLanguage().getMessage("message.blocktimer", "[time]", sec));
return true;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void OnBlockMove(BlockPistonExtendEvent event) { public void OnBlockMove(BlockPistonExtendEvent event) {
//disabling plugin in world //disabling plugin in world
if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld())) if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld()))
return; return;
if (event.isCancelled()) if (event.isCancelled())
return; return;
if (!Jobs.getGCManager().useBlockPiston) if (!Jobs.getGCManager().useBlockProtection)
return; return;
List<Block> block = event.getBlocks(); BlockFace dir = event.getDirection();
for (Block OneBlock : block) {
if (CheckBlock(OneBlock)) { int x = dir.getModX();
event.setCancelled(true); int y = dir.getModY();
break; int z = dir.getModZ();
for (Block one : event.getBlocks()) {
Location oldLoc = one.getLocation();
Location newLoc = oldLoc.clone().add(x, y, z);
Long bp = Jobs.getBpManager().getTime(oldLoc);
if (bp != null) {
Jobs.getBpManager().add(newLoc, bp);
} else {
Integer cd = Jobs.getBpManager().getBlockDelayTime(one);
if (cd != null)
Jobs.getBpManager().add(newLoc, System.currentTimeMillis() + (cd * 1000));
else if (Jobs.getGCManager().useGlobalTimer)
Jobs.getBpManager().add(newLoc, System.currentTimeMillis() + (Jobs.getGCManager().globalblocktimer * 1000));
} }
} }
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void OnBlockRetractMove(BlockPistonRetractEvent event) { public void OnBlockRetractMove(BlockPistonRetractEvent event) {
//disabling plugin in world //disabling plugin in world
if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld())) if (event.getBlock() != null && !Jobs.getGCManager().canPerformActionInWorld(event.getBlock().getWorld()))
return; return;
if (event.isCancelled()) if (event.isCancelled())
return; return;
if (!Jobs.getGCManager().useBlockPiston) if (!Jobs.getGCManager().useBlockProtection)
return; return;
List<Block> block = Jobs.getNms().getPistonRetractBlocks(event); BlockFace dir = event.getDirection();
for (Block OneBlock : block) {
if (CheckBlock(OneBlock)) { int x = dir.getModX();
event.setCancelled(true); int y = dir.getModY();
break; int z = dir.getModZ();
for (Block one : Jobs.getNms().getPistonRetractBlocks(event)) {
Location oldLoc = one.getLocation();
Location newLoc = oldLoc.clone().add(x, y, z);
Long bp = Jobs.getBpManager().getTime(oldLoc);
if (bp != null) {
Jobs.getBpManager().add(newLoc, bp);
} else {
Integer cd = Jobs.getBpManager().getBlockDelayTime(one);
if (cd != null)
Jobs.getBpManager().add(newLoc, System.currentTimeMillis() + (cd * 1000));
else if (Jobs.getGCManager().useGlobalTimer)
Jobs.getBpManager().add(newLoc, System.currentTimeMillis() + (Jobs.getGCManager().globalblocktimer * 1000));
} }
} }
} }

View File

@ -1,169 +1,169 @@
name: Jobs name: Jobs
description: Jobs Plugin for the BukkitAPI description: Jobs Plugin for the BukkitAPI
main: com.gamingmesh.jobs.Jobs main: com.gamingmesh.jobs.Jobs
version: 3.5.7 version: 3.6.0
author: phrstbrn author: phrstbrn
depend: [Vault] depend: [Vault]
softdepend: [CoreProtect, MythicMobs, McMMO] softdepend: [CoreProtect, MythicMobs, McMMO]
commands: commands:
jobs: jobs:
description: Jobs description: Jobs
usage: /jobs usage: /jobs
permissions: permissions:
jobs.*: jobs.*:
description: Grants access to all Jobs commands description: Grants access to all Jobs commands
children: children:
jobs.admin: true jobs.admin: true
jobs.autojoin.*: jobs.autojoin.*:
default: false default: false
jobs.admin: jobs.admin:
description: Grants permissions as an admin description: Grants permissions as an admin
default: false default: false
children: children:
jobs.use: true jobs.use: true
jobs.command.*: true jobs.command.*: true
jobs.use: jobs.use:
description: Grants ability to use this plugin description: Grants ability to use this plugin
default: true default: true
jobs.command.*: jobs.command.*:
description: Grants player access to all commands description: Grants player access to all commands
default: false default: false
children: children:
jobs.command.browse: true jobs.command.browse: true
jobs.command.stats: true jobs.command.stats: true
jobs.command.admin.stats: true jobs.command.admin.stats: true
jobs.command.admin.archive: true jobs.command.admin.archive: true
jobs.command.archive: true jobs.command.archive: true
jobs.command.join: true jobs.command.join: true
jobs.command.leave: true jobs.command.leave: true
jobs.command.leaveall: true jobs.command.leaveall: true
jobs.command.info: true jobs.command.info: true
jobs.command.playerinfo: true jobs.command.playerinfo: true
jobs.command.fire: true jobs.command.fire: true
jobs.command.fireall: true jobs.command.fireall: true
jobs.command.employ: true jobs.command.employ: true
jobs.command.promote: true jobs.command.promote: true
jobs.command.demote: true jobs.command.demote: true
jobs.command.grantxp: true jobs.command.grantxp: true
jobs.command.removexp: true jobs.command.removexp: true
jobs.command.transfer: true jobs.command.transfer: true
jobs.command.reload: true jobs.command.reload: true
jobs.command.help: true jobs.command.help: true
jobs.command.top: true jobs.command.top: true
jobs.command.gtop: true jobs.command.gtop: true
jobs.command.toggle: true jobs.command.toggle: true
jobs.command.limit: true jobs.command.limit: true
jobs.command.give: true jobs.command.give: true
jobs.command.signs: true jobs.command.signs: true
jobs.command.fixnames: true jobs.command.fixnames: true
jobs.command.signupdate: true jobs.command.signupdate: true
jobs.command.moneyboost: true jobs.command.moneyboost: true
jobs.command.expboost: true jobs.command.expboost: true
jobs.command.browse: jobs.command.browse:
description: Grants access to the browse command description: Grants access to the browse command
default: true default: true
jobs.command.top: jobs.command.top:
description: Grants access to the top command description: Grants access to the top command
default: true default: true
jobs.command.gtop: jobs.command.gtop:
description: Grants access to the gtop command description: Grants access to the gtop command
default: true default: true
jobs.command.stats: jobs.command.stats:
description: Grants access to the stats command description: Grants access to the stats command
default: true default: true
jobs.command.archive: jobs.command.archive:
description: Grants access to the archive command description: Grants access to the archive command
default: true default: true
jobs.command.admin.archive: jobs.command.admin.archive:
description: Grants access to the archive command on other players description: Grants access to the archive command on other players
default: true default: true
jobs.command.admin.stats: jobs.command.admin.stats:
description: Grants access to the stats command on other players description: Grants access to the stats command on other players
default: true default: true
jobs.command.join: jobs.command.join:
description: Grants access to the join command description: Grants access to the join command
default: true default: true
jobs.command.leave: jobs.command.leave:
description: Grants access to the leave command description: Grants access to the leave command
default: true default: true
jobs.command.leaveall: jobs.command.leaveall:
description: Grants access to the leaveall command description: Grants access to the leaveall command
default: true default: true
jobs.command.info: jobs.command.info:
description: Grants access to the info command description: Grants access to the info command
default: true default: true
jobs.command.playerinfo: jobs.command.playerinfo:
description: Grants access to the playerinfo command description: Grants access to the playerinfo command
default: op default: op
jobs.command.fire: jobs.command.fire:
description: Grants access to the fire command description: Grants access to the fire command
default: op default: op
jobs.command.fireall: jobs.command.fireall:
description: Grants access to the fireall command description: Grants access to the fireall command
default: op default: op
jobs.command.employ: jobs.command.employ:
description: Grants access to the employ command description: Grants access to the employ command
default: op default: op
jobs.command.promote: jobs.command.promote:
description: Grants access to the promote command description: Grants access to the promote command
default: op default: op
jobs.command.demote: jobs.command.demote:
description: Grants access to the demote command description: Grants access to the demote command
default: op default: op
jobs.command.grantxp: jobs.command.grantxp:
description: Grants access to the grantxp command description: Grants access to the grantxp command
default: op default: op
jobs.command.removexp: jobs.command.removexp:
description: Grants access to the removexp command description: Grants access to the removexp command
default: op default: op
jobs.command.transfer: jobs.command.transfer:
description: Grants access to the transfer command description: Grants access to the transfer command
default: op default: op
jobs.command.reload: jobs.command.reload:
description: Grants access to the reload command description: Grants access to the reload command
default: op default: op
jobs.command.signupdate: jobs.command.signupdate:
description: Grants access to the reload command description: Grants access to the reload command
default: op default: op
jobs.command.give: jobs.command.give:
description: Grants access to the give command description: Grants access to the give command
default: op default: op
jobs.command.expboost: jobs.command.expboost:
description: Grants access to the expboost command description: Grants access to the expboost command
default: op default: op
jobs.command.moneyboost: jobs.command.moneyboost:
description: Grants access to the moneyboost command description: Grants access to the moneyboost command
default: op default: op
jobs.command.help: jobs.command.help:
description: Grants access to the help command description: Grants access to the help command
default: true default: true
jobs.command.toggle: jobs.command.toggle:
description: Grants access to the toggle command description: Grants access to the toggle command
default: true default: true
jobs.command.limit: jobs.command.limit:
description: Grants access to the limit command description: Grants access to the limit command
default: true default: true
jobs.command.fixnames: jobs.command.fixnames:
description: Grants access to the fixnames command description: Grants access to the fixnames command
default: true default: true
jobs.command.log: jobs.command.log:
description: Grants access to the log command description: Grants access to the log command
default: true default: true
jobs.command.shop: jobs.command.shop:
description: Grants access to the shop command description: Grants access to the shop command
default: true default: true
jobs.command.points: jobs.command.points:
description: Grants access to the points command description: Grants access to the points command
default: true default: true
jobs.command.log.others: jobs.command.log.others:
description: Grants access to the log command description: Grants access to the log command
default: op default: op
jobs.command.glog: jobs.command.glog:
description: Grants access to the glog command description: Grants access to the glog command
default: op default: op
jobs.command.bonus: jobs.command.bonus:
description: Grants access to the bonus command description: Grants access to the bonus command
default: true default: true
jobs.command.points: jobs.command.points:
description: Grants access to the points command description: Grants access to the points command
default: true default: true