Search in sources :

Example 1 with VanillaStack

use of com.almuradev.almura.shared.item.VanillaStack in project Almura by AlmuraDev.

the class ServerStoreManager method handleListSellingItems.

public void handleListSellingItems(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 selling 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<StoreSellingItemRecord, 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 StoreSellingItemRecord itemRecord = StoreQueries.createInsertSellingItem(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 selling 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) {
                    StoreSellingItemDataRecord dataRecord = null;
                    try {
                        dataRecord = StoreQueries.createInsertSellingItemData(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 selling item record '{}' for store '{}' but it failed. " + "Discarding changes...", player.getName(), itemRecord.getRecNo(), id);
                        StoreQueries.createDeleteSellingItem(itemRecord.getRecNo()).build(context).execute();
                    }
                }
                inserted.put(itemRecord, stack);
            }
            this.scheduler.createTaskBuilder().execute(() -> {
                for (final Map.Entry<StoreSellingItemRecord, VanillaStack> entry : inserted.entrySet()) {
                    final StoreSellingItemRecord record = entry.getKey();
                    final VanillaStack stack = entry.getValue();
                    final BasicSellingItem item = new BasicSellingItem(record.getRecNo(), record.getCreated().toInstant(), stack.getItem(), stack.getQuantity(), stack.getMetadata(), record.getPrice(), record.getIndex(), stack.getCompound());
                    store.getSellingItems().add(item);
                }
                this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, store.getSellingItems()));
            }).submit(this.container);
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    }).submit(this.container);
}
Also used : SQLException(java.sql.SQLException) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) BasicStore(com.almuradev.almura.feature.store.basic.BasicStore) DSLContext(org.jooq.DSLContext) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket) StoreSellingItemRecord(com.almuradev.generated.store.tables.records.StoreSellingItemRecord) BasicSellingItem(com.almuradev.almura.feature.store.basic.listing.BasicSellingItem) IOException(java.io.IOException) StoreSellingItemDataRecord(com.almuradev.generated.store.tables.records.StoreSellingItemDataRecord) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) BigDecimal(java.math.BigDecimal) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with VanillaStack

use of com.almuradev.almura.shared.item.VanillaStack in project Almura by AlmuraDev.

the class ServerExchangeManager method handleModifyListItems.

public void handleModifyListItems(final Player player, final String id, final List<InventoryAction> actions) {
    checkNotNull(player);
    checkNotNull(id);
    checkNotNull(actions);
    checkState(!actions.isEmpty());
    final Exchange axs = this.getExchange(id).orElse(null);
    if (axs == null) {
        this.logger.error("Player '{}' attempted to list items for exchange '{}' but the server has no knowledge of it. Syncing exchange " + "registry...", player.getName(), id);
        this.syncExchangeRegistryTo(player);
        return;
    }
    final UUID seller = player.getUniqueId();
    final EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
    final IItemHandler simulatedInventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
    // Inventory -> Listing
    final List<InventoryAction> toListingActions = actions.stream().filter(a -> a.getDirection() == InventoryAction.Direction.TO_LISTING).collect(Collectors.toList());
    final List<VanillaStack> toListingStacks = new ArrayList<>();
    final List<VanillaStack> unknownInventoryStacks = new ArrayList<>();
    final List<VanillaStack> leftoverToListingStacks = new ArrayList<>();
    for (InventoryAction toListingAction : toListingActions) {
        final VanillaStack stack = toListingAction.getStack();
        int amountLeft = stack.getQuantity();
        boolean matched = false;
        for (int j = 0; j < simulatedInventory.getSlots(); j++) {
            final ItemStack slotStack = simulatedInventory.getStackInSlot(j);
            if (ItemHandlerHelper.canItemStacksStack(slotStack, stack.asRealStack())) {
                amountLeft -= simulatedInventory.extractItem(j, amountLeft, false).getCount();
                matched = true;
            }
            if (amountLeft <= 0) {
                break;
            }
        }
        if (!matched) {
            unknownInventoryStacks.add(stack);
        } else {
            if (amountLeft > 0) {
                final VanillaStack copyStack = stack.copy();
                copyStack.setQuantity(amountLeft);
                leftoverToListingStacks.add(copyStack);
            }
            final VanillaStack copyStack = stack.copy();
            copyStack.setQuantity(stack.getQuantity() - amountLeft);
            if (copyStack.getQuantity() != 0) {
                toListingStacks.add(copyStack);
            }
        }
    }
    // Listing -> Inventory
    final List<InventoryAction> toInventoryActions = actions.stream().filter(a -> a.getDirection() == InventoryAction.Direction.TO_INVENTORY).collect(Collectors.toList());
    final List<VanillaStack> listingNotFoundStacks = new ArrayList<>();
    final List<ListItem> desyncToInventoryStacks = new ArrayList<>();
    final List<ListItem> toInventoryStacks = new ArrayList<>();
    final List<ListItem> partialToInventoryStacks = new ArrayList<>();
    final List<ListItem> currentListItems = axs.getListItemsFor(player.getUniqueId()).orElse(null);
    if (!toInventoryActions.isEmpty()) {
        if (currentListItems == null || currentListItems.isEmpty()) {
            this.logger.error("Player '{}' attempted to move listings back to the inventory for exchange '{}' but the server knows of no " + "listings for them. This could be a de-sync or an exploit. Printing stacks...", player.getName(), axs.getId());
            this.network.sendTo(player, new ClientboundListItemsResponsePacket(axs.getId(), null));
            this.printStacksToConsole(toInventoryActions.stream().map(InventoryAction::getStack).collect(Collectors.toList()));
        } else {
            for (final InventoryAction action : toInventoryActions) {
                final VanillaStack stack = action.getStack();
                ListItem found = null;
                for (final ListItem listItem : currentListItems) {
                    if (ItemHandlerHelper.canItemStacksStack(stack.asRealStack(), listItem.asRealStack())) {
                        found = listItem;
                        break;
                    }
                }
                // Unknown listing
                if (found == null) {
                    listingNotFoundStacks.add(stack);
                    continue;
                }
                ListItem toRemove = found.copy();
                // Listing quantity mismatch (tracking this to let the user know)
                if (found.getQuantity() < stack.getQuantity()) {
                    desyncToInventoryStacks.add(found);
                    toRemove.setQuantity(found.getQuantity());
                } else {
                    toRemove.setQuantity(stack.getQuantity());
                }
                final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(simulatedInventory, toRemove.asRealStack(), true);
                // Simulated a partial stack insertion
                if (!resultStack.isEmpty()) {
                    final ListItem copyStack = toRemove.copy();
                    copyStack.setQuantity(resultStack.getCount());
                    partialToInventoryStacks.add(copyStack);
                }
                final ListItem copyStack = toRemove.copy();
                copyStack.setQuantity(toRemove.getQuantity() - resultStack.getCount());
                toInventoryStacks.add(copyStack);
            }
        }
    }
    // This may seem quite weird but we need to clear out the listing items reference for this player across the board to await what the results
    // are from the database to ensure we're 1:1 in sync. Otherwise, the Exchange would keep selling..
    axs.putListItemsFor(seller, null);
    axs.putForSaleItemsFor(seller, null);
    Sponge.getServer().getOnlinePlayers().stream().filter(p -> p.getUniqueId() != seller).forEach(p -> this.network.sendTo(p, new ClientboundForSaleFilterRequestPacket(axs.getId())));
    this.scheduler.createTaskBuilder().async().execute(() -> {
        try (final DSLContext context = this.databaseManager.createContext(true)) {
            final Iterator<VanillaStack> listingIter = toListingStacks.iterator();
            int index = 0;
            // New listing
            while (listingIter.hasNext()) {
                final VanillaStack stack = listingIter.next();
                final ItemStack realStack = stack.asRealStack();
                ListItem found = null;
                if (currentListItems != null) {
                    found = currentListItems.stream().filter(item -> ItemHandlerHelper.canItemStacksStack(realStack, item.asRealStack())).findAny().orElse(null);
                }
                if (found == null) {
                    final AxsListItemRecord itemRecord = ExchangeQueries.createInsertListItem(axs.getId(), Instant.now(), seller, realStack.getItem(), stack.getQuantity(), realStack.getMetadata(), index).build(context).fetchOne();
                    if (itemRecord == null) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' submitted a new list item for exchange '{}' 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) {
                        continue;
                    }
                    final AxsListItemDataRecord dataRecord = ExchangeQueries.createInsertItemData(itemRecord.getRecNo(), compound).build(context).fetchOne();
                    if (dataRecord == null) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' submitted data for item record '{}' for exchange '{}' but it failed. " + "Discarding changes...", player.getName(), itemRecord.getRecNo(), id);
                        ExchangeQueries.createDeleteListItem(itemRecord.getRecNo()).build(context).execute();
                    }
                } else {
                    final int result = ExchangeQueries.createUpdateListItem(found.getRecord(), stack.getQuantity() + found.getQuantity(), index).build(context).execute();
                    if (result == 0) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' attempted to add quantity to list item '{}' for exchange '{}' but it failed. " + "Discarding changes...", player.getName(), found.getRecord(), id);
                        listingIter.remove();
                    }
                }
                index++;
            }
            for (final ListItem next : toInventoryStacks) {
                ListItem existingStack = null;
                for (final ListItem stack : currentListItems) {
                    if (next.getRecord() == stack.getRecord()) {
                        existingStack = stack;
                        break;
                    }
                }
                final int diff = existingStack.getQuantity() - next.getQuantity();
                if (diff == 0) {
                    final int result = ExchangeQueries.createUpdateListItemIsHidden(next.getRecord(), true).build(context).execute();
                    if (result == 0) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' attempted to remove list item '{}' for exchange '{}' but it failed. Discarding " + "changes...", player.getName(), next.getRecord(), id);
                    }
                // Update partial listings
                } else {
                    final int result = ExchangeQueries.createUpdateListItem(next.getRecord(), diff, next.getIndex()).build(context).execute();
                    if (result == 0) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' removed quantity from list item '{}' for exchange '{}' to the database but it " + "failed. Discarding changes...", player.getName(), next.getRecord(), id);
                    }
                }
            }
            final Results listItemResults = ExchangeQueries.createFetchListItemsAndDataFor(seller, false).build(context).keepStatement(false).fetchMany();
            final Results forSaleItemResults = ExchangeQueries.createFetchForSaleItemsFor(seller, false).build(context).keepStatement(false).fetchMany();
            this.scheduler.createTaskBuilder().execute(() -> {
                final Player sellerPlayer = Sponge.getServer().getPlayer(seller).orElse(null);
                if (sellerPlayer != null) {
                    final IItemHandler inventory = ((EntityPlayerMP) sellerPlayer).getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
                    // Add stacks from listings
                    for (final ListItem stack : toInventoryStacks) {
                        final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(inventory, stack.asRealStack(), false);
                        if (!resultStack.isEmpty()) {
                        // TODO Their inventory changed since simulation. Best case scenario we toss it on the ground
                        }
                    }
                } else {
                // TODO They went offline on us. It is a very rare off-case. Half tempted to print what they should have got and let
                // TODO an admin deal with it
                }
                final List<ListItem> listItems = new ArrayList<>();
                listItemResults.forEach(result -> listItems.addAll(this.parseListItemsFrom(result)));
                final List<ForSaleItem> forSaleItems = new ArrayList<>();
                forSaleItemResults.forEach(result -> forSaleItems.addAll(this.parseForSaleItemsFrom(listItems, result)));
                // TODO Build a notification that says...
                // TODO  - Stacks requested to go to a listing but inventory can't fulfill it
                // TODO  - Stacks requested to go to the inventory but listings aren't found
                // TODO  - Stacks requested to go to the inventory but the listing couldn't fulfill it so we took what we could
                axs.putListItemsFor(seller, listItems);
                axs.putForSaleItemsFor(seller, forSaleItems);
                if (sellerPlayer != null) {
                    this.network.sendTo(sellerPlayer, new ClientboundListItemsResponsePacket(axs.getId(), listItems));
                    this.network.sendTo(sellerPlayer, new ClientboundListItemsSaleStatusPacket(axs.getId(), forSaleItems, null));
                }
                Sponge.getServer().getOnlinePlayers().forEach(p -> this.network.sendTo(p, new ClientboundForSaleFilterRequestPacket(axs.getId())));
            }).submit(this.container);
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }).submit(this.container);
}
Also used : AxsListItemRecord(com.almuradev.generated.axs.tables.records.AxsListItemRecord) AxsListItemData(com.almuradev.generated.axs.tables.AxsListItemData) IItemHandler(net.minecraftforge.items.IItemHandler) FilterRegistry(com.almuradev.almura.shared.feature.filter.FilterRegistry) Results(org.jooq.Results) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) Item(net.minecraft.item.Item) Axs(com.almuradev.generated.axs.tables.Axs) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) DatabaseManager(com.almuradev.almura.shared.database.DatabaseManager) BigDecimal(java.math.BigDecimal) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) Map(java.util.Map) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) DSLContext(org.jooq.DSLContext) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ClientboundExchangeGuiResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeGuiResponsePacket) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) EconomyService(org.spongepowered.api.service.economy.EconomyService) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) Timestamp(java.sql.Timestamp) FeatureConstants(com.almuradev.almura.shared.feature.FeatureConstants) Sponge(org.spongepowered.api.Sponge) DatabaseQueue(com.almuradev.almura.shared.database.DatabaseQueue) ServiceManager(org.spongepowered.api.service.ServiceManager) NetworkConfig(com.almuradev.almura.shared.network.NetworkConfig) UUID(java.util.UUID) Result(org.jooq.Result) Instant(java.time.Instant) ClientboundExchangeRegistryPacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeRegistryPacket) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) ChannelBinding(org.spongepowered.api.network.ChannelBinding) List(java.util.List) Stream(java.util.stream.Stream) ExchangeQueries(com.almuradev.almura.feature.exchange.database.ExchangeQueries) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) ChannelId(org.spongepowered.api.network.ChannelId) IngameFeature(com.almuradev.almura.shared.feature.IngameFeature) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Almura(com.almuradev.almura.Almura) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) Getter(org.spongepowered.api.event.filter.Getter) GameStartingServerEvent(org.spongepowered.api.event.game.state.GameStartingServerEvent) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) ArrayList(java.util.ArrayList) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) Inject(javax.inject.Inject) AxsListItemDataRecord(com.almuradev.generated.axs.tables.records.AxsListItemDataRecord) ItemStack(net.minecraft.item.ItemStack) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Text(org.spongepowered.api.text.Text) AxsForSaleItemRecord(com.almuradev.generated.axs.tables.records.AxsForSaleItemRecord) GameState(org.spongepowered.api.GameState) CauseStackManager(org.spongepowered.api.event.CauseStackManager) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) ClientboundForSaleItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleItemsResponsePacket) Record(org.jooq.Record) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ClientboundTransactionCompletePacket(com.almuradev.almura.feature.exchange.network.ClientboundTransactionCompletePacket) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Scheduler(org.spongepowered.api.scheduler.Scheduler) ServerNotificationManager(com.almuradev.almura.feature.notification.ServerNotificationManager) EnumFacing(net.minecraft.util.EnumFacing) IOException(java.io.IOException) SerializationUtil(com.almuradev.almura.shared.util.SerializationUtil) Witness(com.almuradev.core.event.Witness) ForgeRegistries(net.minecraftforge.fml.common.registry.ForgeRegistries) ResourceLocation(net.minecraft.util.ResourceLocation) Listener(org.spongepowered.api.event.Listener) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Comparator(java.util.Comparator) ArrayList(java.util.ArrayList) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) AxsListItemRecord(com.almuradev.generated.axs.tables.records.AxsListItemRecord) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) Iterator(java.util.Iterator) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) UUID(java.util.UUID) Player(org.spongepowered.api.entity.living.player.Player) IItemHandler(net.minecraftforge.items.IItemHandler) DSLContext(org.jooq.DSLContext) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) Results(org.jooq.Results) AxsListItemDataRecord(com.almuradev.generated.axs.tables.records.AxsListItemDataRecord) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) ItemStack(net.minecraft.item.ItemStack)

Example 3 with VanillaStack

use of com.almuradev.almura.shared.item.VanillaStack in project Almura by AlmuraDev.

the class UIItemList method insertItem.

@Override
@Nonnull
public ItemStack insertItem(final int slot, @Nonnull final ItemStack stack, final boolean simulate) {
    if (simulate) {
        throw new UnsupportedOperationException("Simulation not supported!");
    }
    // Copy before changes because Vanilla
    final ItemStack diffStack = stack.copy();
    int amountUsed = 0;
    final ItemStack stackInSlot = this.getStackInSlot(slot);
    final int stackInSlotLimit = this.enforceStackLimit ? stackInSlot.getMaxStackSize() : this.maxSlotStackSize;
    if (ItemHandlerHelper.canItemStacksStack(stackInSlot, stack)) {
        final int toAdd = Math.min(Math.min(stackInSlotLimit, stack.getCount()), stackInSlotLimit - stackInSlot.getCount());
        amountUsed += toAdd;
        stackInSlot.grow(toAdd);
        this.markDirty();
    } else if (stackInSlot.isEmpty()) {
        final VanillaStack newStack = new BasicVanillaStack(stack);
        newStack.setQuantity(Math.min(stackInSlotLimit, stack.getCount()));
        this.addItem(slot, newStack);
        amountUsed += newStack.getQuantity();
    }
    diffStack.setCount(stack.getCount() - amountUsed);
    return diffStack;
}
Also used : ItemStack(net.minecraft.item.ItemStack) BasicVanillaStack(com.almuradev.almura.shared.item.BasicVanillaStack) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) BasicVanillaStack(com.almuradev.almura.shared.item.BasicVanillaStack) Nonnull(javax.annotation.Nonnull)

Example 4 with VanillaStack

use of com.almuradev.almura.shared.item.VanillaStack in project Almura by AlmuraDev.

the class ExchangeOfferScreen method construct.

@Override
public void construct() {
    this.guiscreenBackground = false;
    // Form
    final BasicForm form = new BasicForm(this, 400, 325, I18n.format("almura.feature.exchange.title.offer"));
    // Fixes issue overlapping draws from parent
    form.setZIndex(10);
    form.setBackgroundAlpha(255);
    // OK/Cancel buttons
    final UIButton buttonOk = new UIButtonBuilder(this).width(40).text(I18n.format("almura.button.ok")).x(1).anchor(Anchor.BOTTOM | Anchor.RIGHT).onClick(this::transact).build("button.ok");
    final UIButton buttonCancel = new UIButtonBuilder(this).width(40).text(I18n.format("almura.button.cancel")).x(getPaddedX(buttonOk, 2, Anchor.RIGHT)).anchor(Anchor.BOTTOM | Anchor.RIGHT).onClick(this::close).build("button.cancel");
    // Swap container
    final NonNullList<ItemStack> mainInventory = Minecraft.getMinecraft().player.inventory.mainInventory;
    final int totalItemsForSale = this.exchange.getForSaleItemsFor(Minecraft.getMinecraft().player.getUniqueID()).map(List::size).orElse(0);
    this.offerContainer = new UIExchangeOfferContainer(this, getPaddedWidth(form), getPaddedHeight(form) - 20, TextFormatting.WHITE + I18n.format("almura.feature.exchange.text.inventory"), TextFormatting.WHITE + I18n.format("almura.feature.exchange.text.unlisted_items"), mainInventory.size(), this.limit, totalItemsForSale);
    this.offerContainer.register(this);
    // Populate offer container
    final List<VanillaStack> inventoryOffers = new ArrayList<>();
    mainInventory.stream().filter(i -> !i.isEmpty() && i.getItem() != null).forEach(i -> inventoryOffers.add(new BasicVanillaStack(i)));
    this.offerContainer.setItems(this.pendingItems, BasicDualListContainer.SideType.RIGHT);
    this.offerContainer.setItems(inventoryOffers, BasicDualListContainer.SideType.LEFT);
    form.add(this.offerContainer, buttonOk, buttonCancel);
    addToScreen(form);
}
Also used : UIButton(net.malisis.core.client.gui.component.interaction.UIButton) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) ClientExchangeManager(com.almuradev.almura.feature.exchange.client.ClientExchangeManager) InventoryAction(com.almuradev.almura.feature.exchange.InventoryAction) TextFormatting(net.minecraft.util.text.TextFormatting) UIButtonBuilder(net.malisis.core.client.gui.component.interaction.button.builder.UIButtonBuilder) UIExchangeOfferContainer(com.almuradev.almura.feature.exchange.client.gui.component.UIExchangeOfferContainer) BasicVanillaStack(com.almuradev.almura.shared.item.BasicVanillaStack) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) BasicForm(net.malisis.core.client.gui.component.container.BasicForm) I18n(net.minecraft.client.resources.I18n) Inject(javax.inject.Inject) ItemStack(net.minecraft.item.ItemStack) List(java.util.List) Minecraft(net.minecraft.client.Minecraft) Side(net.minecraftforge.fml.relauncher.Side) Anchor(net.malisis.core.client.gui.Anchor) BasicDualListContainer(net.malisis.core.client.gui.component.container.BasicDualListContainer) Subscribe(com.google.common.eventbus.Subscribe) BasicScreen(net.malisis.core.client.gui.BasicScreen) NonNullList(net.minecraft.util.NonNullList) SideOnly(net.minecraftforge.fml.relauncher.SideOnly) Exchange(com.almuradev.almura.feature.exchange.Exchange) BasicForm(net.malisis.core.client.gui.component.container.BasicForm) UIButtonBuilder(net.malisis.core.client.gui.component.interaction.button.builder.UIButtonBuilder) UIExchangeOfferContainer(com.almuradev.almura.feature.exchange.client.gui.component.UIExchangeOfferContainer) UIButton(net.malisis.core.client.gui.component.interaction.UIButton) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack) BasicVanillaStack(com.almuradev.almura.shared.item.BasicVanillaStack) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) BasicVanillaStack(com.almuradev.almura.shared.item.BasicVanillaStack)

Example 5 with VanillaStack

use of com.almuradev.almura.shared.item.VanillaStack 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);
}
Also used : SQLException(java.sql.SQLException) BasicBuyingItem(com.almuradev.almura.feature.store.basic.listing.BasicBuyingItem) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) BasicStore(com.almuradev.almura.feature.store.basic.BasicStore) DSLContext(org.jooq.DSLContext) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket) IOException(java.io.IOException) StoreBuyingItemDataRecord(com.almuradev.generated.store.tables.records.StoreBuyingItemDataRecord) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) BigDecimal(java.math.BigDecimal) StoreBuyingItemRecord(com.almuradev.generated.store.tables.records.StoreBuyingItemRecord) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

VanillaStack (com.almuradev.almura.shared.item.VanillaStack)6 BigDecimal (java.math.BigDecimal)4 BasicVanillaStack (com.almuradev.almura.shared.item.BasicVanillaStack)3 IOException (java.io.IOException)3 SQLException (java.sql.SQLException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ItemStack (net.minecraft.item.ItemStack)3 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)3 DSLContext (org.jooq.DSLContext)3 BasicStore (com.almuradev.almura.feature.store.basic.BasicStore)2 ClientboundListItemsResponsePacket (com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 Inject (javax.inject.Inject)2 Almura (com.almuradev.almura.Almura)1 Exchange (com.almuradev.almura.feature.exchange.Exchange)1 InventoryAction (com.almuradev.almura.feature.exchange.InventoryAction)1 BasicExchange (com.almuradev.almura.feature.exchange.basic.BasicExchange)1