Essentials/Essentials/src/main/java/com/earth2me/essentials/Trade.java

403 lines
16 KiB
Java
Raw Normal View History

package com.earth2me.essentials;
2011-12-06 17:42:55 +01:00
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
2015-04-15 06:06:16 +02:00
import net.ess3.api.IEssentials;
import net.ess3.api.IUser;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Location;
import org.bukkit.entity.Item;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
2013-05-05 05:13:17 +02:00
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
2011-06-13 15:05:31 +02:00
import java.util.Map;
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
2015-04-15 06:06:16 +02:00
import static com.earth2me.essentials.I18n.tl;
2015-04-15 06:06:16 +02:00
public class Trade {
2020-10-03 19:46:05 +02:00
private static FileWriter fw = null;
2015-04-15 06:06:16 +02:00
private final transient String command;
private final transient Trade fallbackTrade;
private final transient BigDecimal money;
private final transient ItemStack itemStack;
private final transient Integer exp;
private final transient IEssentials ess;
public Trade(final String command, final IEssentials ess) {
this(command, null, null, null, null, ess);
}
public Trade(final String command, final Trade fallback, final IEssentials ess) {
this(command, fallback, null, null, null, ess);
}
@Deprecated
public Trade(final double money, final com.earth2me.essentials.IEssentials ess) {
this(null, null, BigDecimal.valueOf(money), null, null, (IEssentials) ess);
}
public Trade(final BigDecimal money, final IEssentials ess) {
this(null, null, money, null, null, ess);
}
public Trade(final ItemStack items, final IEssentials ess) {
this(null, null, null, items, null, ess);
}
public Trade(final int exp, final IEssentials ess) {
this(null, null, null, null, exp, ess);
}
private Trade(final String command, final Trade fallback, final BigDecimal money, final ItemStack item, final Integer exp, final IEssentials ess) {
this.command = command;
this.fallbackTrade = fallback;
this.money = money;
this.itemStack = item;
this.exp = exp;
this.ess = ess;
}
public static void log(final String type, final String subtype, final String event, final String sender, final Trade charge, final String receiver, final Trade pay, final Location loc, final BigDecimal endBalance, final IEssentials ess) {
2020-10-03 19:46:05 +02:00
//isEcoLogUpdateEnabled() - This refers to log entries with no location, ie API updates #EasterEgg
//isEcoLogEnabled() - This refers to log entries with with location, ie /pay /sell and eco signs.
if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) || (loc != null && !ess.getSettings().isEcoLogEnabled())) {
return;
}
if (fw == null) {
try {
fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true);
} catch (final IOException ex) {
Essentials.getWrappedLogger().log(Level.SEVERE, null, ex);
2020-10-03 19:46:05 +02:00
}
}
final StringBuilder sb = new StringBuilder();
sb.append(type).append(",").append(subtype).append(",").append(event).append(",\"");
sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date()));
sb.append("\",\"");
if (sender != null) {
sb.append(sender);
}
sb.append("\",");
if (charge == null) {
sb.append("\"\",\"\",\"\"");
} else {
if (charge.getItemStack() != null) {
sb.append(charge.getItemStack().getAmount()).append(",");
sb.append(charge.getItemStack().getType()).append(",");
if (VersionUtil.PRE_FLATTENING) {
sb.append(charge.getItemStack().getDurability());
}
2020-10-03 19:46:05 +02:00
}
if (charge.getMoney() != null) {
sb.append(charge.getMoney()).append(",");
sb.append("money").append(",");
sb.append(ess.getSettings().getCurrencySymbol());
}
if (charge.getExperience() != null) {
sb.append(charge.getExperience()).append(",");
sb.append("exp").append(",");
sb.append("\"\"");
}
}
sb.append(",\"");
if (receiver != null) {
sb.append(receiver);
}
sb.append("\",");
if (pay == null) {
sb.append("\"\",\"\",\"\"");
} else {
if (pay.getItemStack() != null) {
sb.append(pay.getItemStack().getAmount()).append(",");
sb.append(pay.getItemStack().getType()).append(",");
if (VersionUtil.PRE_FLATTENING) {
sb.append(pay.getItemStack().getDurability());
}
2020-10-03 19:46:05 +02:00
}
if (pay.getMoney() != null) {
sb.append(pay.getMoney()).append(",");
sb.append("money").append(",");
sb.append(ess.getSettings().getCurrencySymbol());
}
if (pay.getExperience() != null) {
sb.append(pay.getExperience()).append(",");
sb.append("exp").append(",");
sb.append("\"\"");
}
}
if (loc == null) {
sb.append(",\"\",\"\",\"\",\"\"");
} else {
sb.append(",\"");
sb.append(loc.getWorld().getName()).append("\",");
sb.append(loc.getBlockX()).append(",");
sb.append(loc.getBlockY()).append(",");
sb.append(loc.getBlockZ()).append(",");
}
if (endBalance == null) {
sb.append(",");
} else {
sb.append(endBalance);
sb.append(",");
}
2020-10-03 19:46:05 +02:00
sb.append("\n");
try {
fw.write(sb.toString());
fw.flush();
} catch (final IOException ex) {
Essentials.getWrappedLogger().log(Level.SEVERE, null, ex);
2020-10-03 19:46:05 +02:00
}
}
public static void closeLog() {
if (fw != null) {
try {
fw.close();
} catch (final IOException ex) {
Essentials.getWrappedLogger().log(Level.SEVERE, null, ex);
2020-10-03 19:46:05 +02:00
}
fw = null;
}
}
2015-04-15 06:06:16 +02:00
public void isAffordableFor(final IUser user) throws ChargeException {
2020-10-03 19:46:05 +02:00
final CompletableFuture<Boolean> future = new CompletableFuture<>();
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
isAffordableFor(user, future);
if (future.isCompletedExceptionally()) {
try {
future.get();
2020-10-03 19:46:05 +02:00
} catch (final InterruptedException e) { //If this happens, we have bigger problems...
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
e.printStackTrace();
2020-10-03 19:46:05 +02:00
} catch (final ExecutionException e) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
throw (ChargeException) e.getCause();
}
}
}
2020-10-03 19:46:05 +02:00
public void isAffordableFor(final IUser user, final CompletableFuture<Boolean> future) {
2015-04-15 06:06:16 +02:00
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge.");
}
if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))));
return;
2015-04-15 06:06:16 +02:00
}
if (getItemStack() != null && !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack()))));
return;
2015-04-15 06:06:16 +02:00
}
2020-10-03 19:46:05 +02:00
final BigDecimal money;
2015-04-15 06:06:16 +02:00
if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess))));
return;
2015-04-15 06:06:16 +02:00
}
if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("notEnoughExperience")));
2015-04-15 06:06:16 +02:00
}
}
public boolean pay(final IUser user) throws MaxMoneyException {
return pay(user, OverflowType.ABORT) == null;
}
public Map<Integer, ItemStack> pay(final IUser user, final OverflowType type) throws MaxMoneyException {
if (getMoney() != null && getMoney().signum() > 0) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying user " + user.getName() + " via trade " + getMoney().toPlainString());
}
user.giveMoney(getMoney());
}
if (getItemStack() != null) {
// This stores the would be overflow
2020-10-03 19:46:05 +02:00
final Map<Integer, ItemStack> overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack());
2015-04-15 06:06:16 +02:00
if (overFlow != null) {
switch (type) {
case ABORT:
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "abort paying " + user.getName() + " itemstack " + getItemStack().toString() + " due to lack of inventory space ");
}
return overFlow;
case RETURN:
// Pay the user the items, and return overflow
final Map<Integer, ItemStack> returnStack = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack());
user.getBase().updateInventory();
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " with overflow " + returnStack.get(0).toString());
}
return returnStack;
case DROP:
// Pay the users the items directly, and drop the rest, will always return no overflow.
final Map<Integer, ItemStack> leftOver = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack());
final Location loc = user.getBase().getLocation();
2020-10-03 19:46:05 +02:00
for (final ItemStack loStack : leftOver.values()) {
2015-04-15 06:06:16 +02:00
final int maxStackSize = loStack.getType().getMaxStackSize();
final int stacks = loStack.getAmount() / maxStackSize;
final int leftover = loStack.getAmount() % maxStackSize;
final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
for (int i = 0; i < stacks; i++) {
final ItemStack stack = loStack.clone();
stack.setAmount(maxStackSize);
itemStacks[i] = loc.getWorld().dropItem(loc, stack);
}
if (leftover > 0) {
final ItemStack stack = loStack.clone();
stack.setAmount(leftover);
itemStacks[stacks] = loc.getWorld().dropItem(loc, stack);
}
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " and dropping overflow " + leftOver.get(0).toString());
}
2020-10-03 19:46:05 +02:00
break;
2015-04-15 06:06:16 +02:00
}
} else if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " itemstack " + getItemStack().toString());
}
user.getBase().updateInventory();
}
if (getExperience() != null) {
SetExpFix.setTotalExperience(user.getBase(), SetExpFix.getTotalExperience(user.getBase()) + getExperience());
}
return null;
}
public void charge(final IUser user) throws ChargeException {
2020-10-03 19:46:05 +02:00
final CompletableFuture<Boolean> future = new CompletableFuture<>();
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
charge(user, future);
if (future.isCompletedExceptionally()) {
try {
future.get();
2020-10-03 19:46:05 +02:00
} catch (final InterruptedException e) { //If this happens, we have bigger problems...
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
e.printStackTrace();
2020-10-03 19:46:05 +02:00
} catch (final ExecutionException e) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
throw (ChargeException) e.getCause();
}
}
}
2020-10-03 19:46:05 +02:00
public void charge(final IUser user, final CompletableFuture<Boolean> future) {
2015-04-15 06:06:16 +02:00
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "attempting to charge user " + user.getName());
}
if (getMoney() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString());
}
if (!user.canAfford(getMoney()) && getMoney().signum() > 0) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))));
return;
2015-04-15 06:06:16 +02:00
}
user.takeMoney(getMoney());
}
if (getItemStack() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString());
}
if (!user.getBase().getInventory().containsAtLeast(getItemStack(), getItemStack().getAmount())) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))));
return;
2015-04-15 06:06:16 +02:00
}
user.getBase().getInventory().removeItem(getItemStack());
user.getBase().updateInventory();
}
if (command != null) {
final BigDecimal cost = getCommandCost(user);
if (!user.canAfford(cost) && cost.signum() > 0) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess))));
return;
2015-04-15 06:06:16 +02:00
}
user.takeMoney(cost);
}
if (getExperience() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " exp " + getExperience());
}
final int experience = SetExpFix.getTotalExperience(user.getBase());
if (experience < getExperience() && getExperience() > 0) {
Reduce sync loads for teleporting (#3102) This PR reduces the number of sync loads occurring on any teleport caused by essentials. Fixes #2861 Fixes #2287 Fixes #3274 Fixes #3201 Fixes #2120 Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border. ----------------------------------------- * Reduce sync teleporting loads * Avoid argument re-assigning * Remove async teleports when unnecessary * Make exceptions cleaner * Async all the things Made an async version of every method with fallbacks for deprecated methods. * Remove old now fallback method * Migrate everything to the new async teleport API * Update ITeleport javadocs * Fix invoking via async context * Fix /jail using deprecated method * Fix jail join handler using deprecated method * Rename all teleport classes to indicate async * Remove deprecated methods * Add (and deprecate) old teleport api * Revert TimedTeleport.java * Reduce Diff * Add legacy sendToJail method * Reduce Diff Further * Use getNewExceptionFuture in Commandtpo * Use getNewExceptionFuture everywhere * Fix even more usages * Revert LocationUtil.java * Fix issue causing unsafe locations to not work properly * Add deprecated notice in IUser implementation * Use CompletableFuture#completeExceptionally for exceptions * Use Essentials' logger in EssentialsCommand#showError * Return implementation rather than interface * Avoid possible deadlocks with entity ejections * Nuke some sync loads with homes Took 7 hours and 2 PRs to paper but it's here! * Fix ABI and make the codestyle worse * Make the codestyle worse because muh diff * Further ruin the codestyle * Fix error messages not showing in TimedTeleports * Improve messages around beds for /home * Fix #3274 Allow unsafe locations for different worlds + spectator mode * Fix fly safety operators
2020-06-24 10:52:25 +02:00
future.completeExceptionally(new ChargeException(tl("notEnoughExperience")));
return;
2015-04-15 06:06:16 +02:00
}
SetExpFix.setTotalExperience(user.getBase(), experience - getExperience());
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charge user " + user.getName() + " completed");
}
}
public BigDecimal getMoney() {
return money;
}
public ItemStack getItemStack() {
return itemStack;
}
public Integer getExperience() {
return exp;
}
public TradeType getType() {
if (getExperience() != null) {
return TradeType.EXP;
}
if (getItemStack() != null) {
return TradeType.ITEM;
}
return TradeType.MONEY;
}
public BigDecimal getCommandCost(final IUser user) {
BigDecimal cost = BigDecimal.ZERO;
if (command != null && !command.isEmpty()) {
cost = ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command);
if (cost.signum() == 0 && fallbackTrade != null) {
cost = fallbackTrade.getCommandCost(user);
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "calculated command (" + command + ") cost for " + user.getName() + " as " + cost);
}
}
if (cost.signum() != 0 && (user.isAuthorized("essentials.nocommandcost.all") || user.isAuthorized("essentials.nocommandcost." + command))) {
return BigDecimal.ZERO;
}
return cost;
}
2020-10-03 19:46:05 +02:00
public enum TradeType {
MONEY,
EXP,
ITEM
2015-04-15 06:06:16 +02:00
}
2020-10-03 19:46:05 +02:00
public enum OverflowType {
ABORT,
DROP,
RETURN
2015-04-15 06:06:16 +02:00
}
}