use of com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket in project Almura by AlmuraDev.
the class ServerStoreManager method handleListBuyingItems.
public void handleListBuyingItems(final Player player, final String id, final List<ServerboundListItemsRequestPacket.ListCandidate> candidates) {
checkNotNull(player);
checkNotNull(id);
if (!player.hasPermission(Almura.ID + ".store.admin")) {
this.notificationManager.sendPopupNotification(player, Text.of(TextColors.RED, "Store"), Text.of("You do not have permission " + "to list items!"), 5);
return;
}
final Store store = this.getStore(id).orElse(null);
if (store == null) {
this.logger.error("Player '{}' attempted to list buying items for store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
this.syncStoreRegistryTo(player);
return;
}
this.scheduler.createTaskBuilder().async().execute(() -> {
try (final DSLContext context = this.databaseManager.createContext(true)) {
final Map<StoreBuyingItemRecord, VanillaStack> inserted = new HashMap<>();
for (final ServerboundListItemsRequestPacket.ListCandidate candidate : candidates) {
final VanillaStack stack = candidate.stack;
final int index = candidate.index;
final BigDecimal price = candidate.price;
final StoreBuyingItemRecord itemRecord = StoreQueries.createInsertBuyingItem(store.getId(), Instant.now(), stack.getItem(), stack.getQuantity(), stack.getMetadata(), index, price).build(context).fetchOne();
if (itemRecord == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the server console for more details!"));
this.logger.error("Player '{}' submitted a new buying item for store '{}' to the database but it failed. " + "Discarding changes and printing stack...", player.getName(), id);
this.printStacksToConsole(Lists.newArrayList(stack));
continue;
}
final NBTTagCompound compound = stack.getCompound();
if (compound != null) {
StoreBuyingItemDataRecord dataRecord = null;
try {
dataRecord = StoreQueries.createInsertBuyingItemData(itemRecord.getRecNo(), compound).build(context).fetchOne();
} catch (final IOException e) {
e.printStackTrace();
}
if (dataRecord == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the server console for more details!"));
this.logger.error("Player '{}' submitted data for buying item record '{}' for store '{}' but it failed. " + "Discarding changes...", player.getName(), itemRecord.getRecNo(), id);
StoreQueries.createDeleteBuyingItem(itemRecord.getRecNo()).build(context).execute();
}
}
inserted.put(itemRecord, stack);
}
this.scheduler.createTaskBuilder().execute(() -> {
for (final Map.Entry<StoreBuyingItemRecord, VanillaStack> entry : inserted.entrySet()) {
final StoreBuyingItemRecord record = entry.getKey();
final VanillaStack stack = entry.getValue();
final BasicBuyingItem item = new BasicBuyingItem(record.getRecNo(), record.getCreated().toInstant(), stack.getItem(), stack.getQuantity(), stack.getMetadata(), record.getPrice(), record.getIndex(), stack.getCompound());
store.getBuyingItems().add(item);
}
this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, store.getBuyingItems()));
}).submit(this.container);
} catch (final SQLException e) {
e.printStackTrace();
}
}).submit(this.container);
}
use of com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket in project Almura by AlmuraDev.
the class ServerStoreManager method handleSellingItemTransaction.
public void handleSellingItemTransaction(final Player player, final String id, final int recNo, final int quantity) {
checkNotNull(player);
checkNotNull(id);
checkState(recNo >= 0);
checkState(quantity >= 0);
final Store store = this.getStore(id).orElse(null);
if (store == null) {
this.logger.error("Player '{}' attempted to sell an item to store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
this.syncStoreRegistryTo(player);
return;
}
final EconomyService economyService = this.serviceManager.provide(EconomyService.class).orElse(null);
if (economyService == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell an to from store '{}' but the economy service no longer exists. This is a " + "critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final UniqueAccount account = economyService.getOrCreateAccount(player.getUniqueId()).orElse(null);
if (account == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell an item to store '{}' but the economy service returned no account for them. " + "This is a critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final List<SellingItem> sellingItems = store.getSellingItems();
if (sellingItems.isEmpty()) {
this.logger.error("Player '{}' attempted to sell an item to store '{}' but the server knows of no " + "selling items for it. This could be a de-sync or an exploit.", player.getName(), store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, sellingItems));
return;
}
final SellingItem found = sellingItems.stream().filter(v -> v.getRecord() == recNo).findAny().orElse(null);
if (found == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell item '{}' to store '{}' but the server knows of no knowledge of it. This could be a " + "de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, sellingItems));
return;
}
final boolean infinite = found.getQuantity() == FeatureConstants.UNLIMITED;
if (!infinite && found.getQuantity() < quantity) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("There is not enough quantity left to sell " + "your product!"));
return;
}
final BigDecimal price = found.getPrice();
final double total = price.doubleValue() * quantity;
final EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
final IItemHandler inventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
final SellingItem copyStack = found.copy();
copyStack.setQuantity(quantity);
int amountLeft = copyStack.getQuantity();
for (int j = 0; j < inventory.getSlots(); j++) {
final ItemStack slotStack = inventory.getStackInSlot(j);
if (ItemHandlerHelper.canItemStacksStack(slotStack, copyStack.asRealStack())) {
amountLeft -= inventory.extractItem(j, amountLeft, false).getCount();
}
if (amountLeft <= 0) {
break;
}
}
if (amountLeft != 0) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell item '{}' to store '{}' but they do not have enough inventory quantity. " + "This could be a de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
return;
}
this.scheduler.createTaskBuilder().async().execute(() -> {
try (final DSLContext context = this.databaseManager.createContext(true)) {
int result;
if (!infinite) {
result = StoreQueries.createUpdateSellingItem(found.getRecord(), found.getQuantity() - quantity, found.getIndex(), found.getPrice()).build(context).execute();
if (result == 0) {
// TODO It failed, message
return;
}
}
result = StoreQueries.createInsertSellingTransaction(Instant.now(), found.getRecord(), player.getUniqueId(), found.getPrice(), quantity).build(context).execute();
if (result == 0) {
// TODO It failed, message
StoreQueries.createUpdateSellingItem(found.getRecord(), found.getQuantity(), found.getIndex(), found.getPrice()).build(context).execute();
return;
}
final List<SellingItem> finalSellingItems = new ArrayList<>();
if (!infinite) {
final Results results = StoreQueries.createFetchSellingItemsAndDataFor(store.getId(), false).build(context).fetchMany();
results.forEach(r -> finalSellingItems.addAll(this.parseSellingItemsFrom(r)));
}
this.scheduler.createTaskBuilder().execute(() -> {
if (!infinite) {
store.putSellingItems(finalSellingItems);
}
// Pay the seller
try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
frame.pushCause(store);
account.deposit(economyService.getDefaultCurrency(), BigDecimal.valueOf(total), frame.getCurrentCause());
this.notificationManager.sendPopupNotification(player, Text.of(TextColors.GREEN, "Transaction Complete"), Text.of("Sold ", TextColors.AQUA, quantity, TextColors.WHITE, " x ", TextColors.YELLOW, found.asRealStack().getDisplayName(), TextColors.RESET, " for a total of ", TextColors.GOLD, "$", FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total)), 3);
}
if (!infinite) {
this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, store.getSellingItems()));
}
}).submit(this.container);
} catch (final SQLException e) {
e.printStackTrace();
}
}).submit(this.container);
}
use of com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket in project Almura by AlmuraDev.
the class ServerStoreManager method handleDelistSellingItems.
public void handleDelistSellingItems(final Player player, final String id, final List<Integer> recNos) {
checkNotNull(player);
checkNotNull(id);
checkNotNull(recNos);
checkState(!recNos.isEmpty());
if (!player.hasPermission(Almura.ID + ".store.admin")) {
this.notificationManager.sendPopupNotification(player, Text.of(TextColors.RED, "Store"), Text.of("You do not have permission " + "to unlist items!"), 5);
return;
}
final Store store = this.getStore(id).orElse(null);
if (store == null) {
this.logger.error("Player '{}' attempted to de-list selling items for store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
this.syncStoreRegistryTo(player);
return;
}
final List<SellingItem> sellingItems = store.getSellingItems();
if (sellingItems.isEmpty()) {
this.logger.error("Player '{}' attempted to de-list selling items for store '{}' but the server knows of no " + " buying items for it. This could be a de-sync or an exploit.", player.getName(), store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, sellingItems));
return;
}
final List<Integer> copyRecNos = Lists.newArrayList(recNos);
final Iterator<Integer> iter = copyRecNos.iterator();
while (iter.hasNext()) {
final Integer recNo = iter.next();
final SellingItem found = sellingItems.stream().filter(v -> v.getRecord() == recNo).findAny().orElse(null);
if (found == null) {
this.logger.error("Player '{}' attempted to de-list selling item '{}' for store '{}' but the server knows of no knowledge of it. " + "This could be a de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
iter.remove();
}
}
this.scheduler.createTaskBuilder().async().execute(() -> {
try (final DSLContext context = this.databaseManager.createContext(true)) {
final List<Query> toUpdate = new ArrayList<>();
for (final Integer recNo : recNos) {
toUpdate.add(StoreQueries.createUpdateSellingItemIsHidden(recNo, true).build(context));
}
context.batch(toUpdate).execute();
final Results results = StoreQueries.createFetchSellingItemsAndDataFor(store.getId(), false).build(context).fetchMany();
final List<SellingItem> finalSellingItems = new ArrayList<>();
results.forEach(result -> finalSellingItems.addAll(this.parseSellingItemsFrom(result)));
this.scheduler.createTaskBuilder().execute(() -> {
store.putSellingItems(finalSellingItems);
this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, finalSellingItems));
}).submit(this.container);
} catch (final SQLException e) {
e.printStackTrace();
}
}).submit(this.container);
}
use of com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket in project Almura by AlmuraDev.
the class ServerStoreManager method handleBuyingItemTransaction.
/**
* Transaction (Selling/Buying)
*/
public void handleBuyingItemTransaction(final Player player, final String id, final int recNo, final int quantity) {
checkNotNull(player);
checkNotNull(id);
checkState(recNo >= 0);
checkState(quantity >= 0);
final Store store = this.getStore(id).orElse(null);
if (store == null) {
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
this.syncStoreRegistryTo(player);
return;
}
final EconomyService economyService = this.serviceManager.provide(EconomyService.class).orElse(null);
if (economyService == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the economy service no longer exists. This is a " + "critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final UniqueAccount account = economyService.getOrCreateAccount(player.getUniqueId()).orElse(null);
if (account == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the economy service returned no account for them. " + "This is a critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final List<BuyingItem> buyingItems = store.getBuyingItems();
if (buyingItems.isEmpty()) {
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the server knows of no " + " buying items for it. This could be a de-sync or an exploit.", player.getName(), store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, buyingItems));
return;
}
final BuyingItem found = buyingItems.stream().filter(v -> v.getRecord() == recNo).findAny().orElse(null);
if (found == null) {
this.logger.error("Player '{}' attempted to buy item '{}' from store '{}' but the server knows of no knowledge of it. " + "This could be a de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, buyingItems));
return;
}
final boolean infinite = found.getQuantity() == FeatureConstants.UNLIMITED;
if (!infinite && found.getQuantity() < quantity) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("There is not enough quantity left to fulfill your order!"));
return;
}
final BigDecimal balance = account.getBalance(economyService.getDefaultCurrency());
final BigDecimal price = found.getPrice();
final double total = price.doubleValue() * quantity;
if (total > balance.doubleValue()) {
final String formattedTotal = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total);
final String formattedBalance = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(balance.doubleValue());
final String formattedDifference = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total - balance.doubleValue());
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("You attempted to purchase items totaling to ", TextColors.RED, formattedTotal, TextColors.RESET, " while you only have ", TextColors.GREEN, formattedBalance, TextColors.RESET, ".", Text.NEW_LINE, Text.NEW_LINE, "You need ", TextColors.LIGHT_PURPLE, formattedDifference, TextColors.RESET, " more!"));
return;
}
EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
final IItemHandler inventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
final BuyingItem copyStack = found.copy();
copyStack.setQuantity(quantity);
final ItemStack simulatedResultStack = ItemHandlerHelper.insertItemStacked(inventory, copyStack.asRealStack(), true);
if (!simulatedResultStack.isEmpty()) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("You lack sufficient inventory space to " + "purchase these item(s)!"));
return;
}
// Charge the buyer
try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
frame.pushCause(store);
account.withdraw(economyService.getDefaultCurrency(), BigDecimal.valueOf(total), frame.getCurrentCause());
this.notificationManager.sendPopupNotification(player, Text.of(TextColors.GREEN, "Transaction Complete"), Text.of("Purchased ", TextColors.AQUA, quantity, TextColors.WHITE, " x ", TextColors.YELLOW, found.asRealStack().getDisplayName(), TextColors.RESET, " for a total of ", TextColors.GOLD, "$", FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total)), 3);
}
this.scheduler.createTaskBuilder().async().execute(() -> {
try (final DSLContext context = this.databaseManager.createContext(true)) {
int result;
if (!infinite) {
result = StoreQueries.createUpdateBuyingItem(found.getRecord(), found.getQuantity() - quantity, found.getIndex(), found.getPrice()).build(context).execute();
if (result == 0) {
// TODO It failed, message
return;
}
}
result = StoreQueries.createInsertBuyingTransaction(Instant.now(), found.getRecord(), player.getUniqueId(), found.getPrice(), quantity).build(context).execute();
if (result == 0) {
// TODO It failed, message
StoreQueries.createUpdateBuyingItem(found.getRecord(), found.getQuantity(), found.getIndex(), found.getPrice()).build(context).execute();
return;
}
final List<BuyingItem> finalBuyingItems = new ArrayList<>();
if (!infinite) {
final Results results = StoreQueries.createFetchBuyingItemsAndDataFor(store.getId(), false).build(context).fetchMany();
results.forEach(r -> finalBuyingItems.addAll(this.parseBuyingItemsFor(r)));
}
this.scheduler.createTaskBuilder().execute(() -> {
if (!infinite) {
store.putBuyingItems(finalBuyingItems);
}
final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(inventory, copyStack.asRealStack(), false);
if (!resultStack.isEmpty()) {
// TODO Inventory changed awaiting DB and now we're full...could drop it on the ground? It is an off-case
}
if (!infinite) {
this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, store.getBuyingItems()));
}
}).submit(this.container);
} catch (final SQLException e) {
e.printStackTrace();
}
}).submit(this.container);
}
Aggregations