Search in sources :

Example 1 with KitRedeemException

use of io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException in project Nucleus by NucleusPowered.

the class KitHandler method redeemKit.

public RedeemResult redeemKit(Kit kit, Player player, boolean performChecks, boolean isMustGetAll, boolean isFirstJoin) throws KitRedeemException {
    KitUserDataModule user = Nucleus.getNucleus().getUserDataManager().get(player.getUniqueId()).get().get(KitUserDataModule.class);
    Optional<Instant> oi = Util.getValueIgnoreCase(user.getKitLastUsedTime(), kit.getName());
    Instant now = Instant.now();
    if (performChecks) {
        // If the kit was used before...
        if (oi.isPresent()) {
            // if it's one time only and the user does not have an exemption...
            if (kit.isOneTime() && !player.hasPermission(cph.getPermissionWithSuffix("exempt.onetime"))) {
                throw new KitRedeemException("Already redeemed", KitRedeemException.Reason.ALREADY_REDEEMED);
            }
            // bypass it...
            if (!cph.testCooldownExempt(player) && kit.getCooldown().map(Duration::getSeconds).orElse(0L) > 0) {
                // ...and we haven't reached the cooldown point yet...
                Instant timeForNextUse = oi.get().plus(kit.getCooldown().get());
                if (timeForNextUse.isAfter(now)) {
                    throw new KitRedeemException.Cooldown("Cooldown not expired", Duration.between(now, timeForNextUse));
                }
            }
        }
    }
    // Kit pre redeem
    Cause cause = CauseStackHelper.createCause(player);
    NucleusKitEvent.Redeem.Pre preEvent = new KitEvent.PreRedeem(cause, oi.orElse(null), kit, player);
    if (Sponge.getEventManager().post(preEvent)) {
        throw new KitRedeemException.PreCancelled(preEvent.getCancelMessage().orElse(null));
    }
    List<Optional<ItemStackSnapshot>> slotList = Lists.newArrayList();
    Util.getStandardInventory(player).slots().forEach(x -> slotList.add(x.peek().map(ItemStack::createSnapshot)));
    InventoryTransactionResult inventoryTransactionResult = EMPTY_ITR;
    if (!kit.getStacks().isEmpty()) {
        inventoryTransactionResult = addToStandardInventory(player, kit.getStacks(), isProcessTokens);
        if (!isFirstJoin && !inventoryTransactionResult.getRejectedItems().isEmpty() && isMustGetAll) {
            Inventory inventory = Util.getStandardInventory(player);
            // Slots
            Iterator<Inventory> slot = inventory.slots().iterator();
            // Slots to restore
            slotList.forEach(x -> {
                Inventory i = slot.next();
                i.clear();
                x.ifPresent(y -> i.offer(y.createStack()));
            });
            // My friend was playing No Man's Sky, I almost wrote "No free slots in suit inventory".
            throw new KitRedeemException("No free slots in player inventory", KitRedeemException.Reason.NO_SPACE);
        }
    }
    // If something was consumed, consider a success.
    if (inventoryTransactionResult.getType() == InventoryTransactionResult.Type.SUCCESS) {
        kit.redeemKitCommands(player);
        // permissions or cooldowns change later
        if (performChecks) {
            user.addKitLastUsedTime(kit.getName(), now);
        }
        Sponge.getEventManager().post(new KitEvent.PostRedeem(cause, oi.orElse(null), kit, player));
        return new KitRedeemResult(inventoryTransactionResult.getRejectedItems(), slotList.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()));
    } else {
        // Failed.
        Sponge.getEventManager().post(new KitEvent.FailedRedeem(cause, oi.orElse(null), kit, player));
        throw new KitRedeemException("No items were redeemed", KitRedeemException.Reason.UNKNOWN);
    }
}
Also used : KitUserDataModule(io.github.nucleuspowered.nucleus.modules.kit.datamodules.KitUserDataModule) Optional(java.util.Optional) Instant(java.time.Instant) KitRedeemException(io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException) Cause(org.spongepowered.api.event.cause.Cause) NucleusKitEvent(io.github.nucleuspowered.nucleus.api.events.NucleusKitEvent) KitEvent(io.github.nucleuspowered.nucleus.modules.kit.events.KitEvent) ItemStack(org.spongepowered.api.item.inventory.ItemStack) InventoryTransactionResult(org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult) Inventory(org.spongepowered.api.item.inventory.Inventory)

Example 2 with KitRedeemException

use of io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException in project Nucleus by NucleusPowered.

the class KitListener method onPlayerJoin.

@Listener
public void onPlayerJoin(ClientConnectionEvent.Join event, @Root Player player) {
    loader.get(player).ifPresent(p -> {
        KitUserDataModule user = loader.get(player.getUniqueId()).get().get(KitUserDataModule.class);
        gds.getAutoRedeemable().stream().filter(k -> k.ignoresPermission() || (!this.isSepratePermissions && !player.hasPermission(PermissionRegistry.PERMISSIONS_PREFIX + "kits." + k.getName().toLowerCase()))).forEach(k -> {
            try {
                handler.redeemKit(k, player, true, this.mustGetAll);
            } catch (KitRedeemException e) {
            // player.sendMessage(e.getText());
            }
        });
    });
}
Also used : KitUserDataModule(io.github.nucleuspowered.nucleus.modules.kit.datamodules.KitUserDataModule) KitRedeemException(io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException) Getter(org.spongepowered.api.event.filter.Getter) Keys(org.spongepowered.api.data.key.Keys) ItemTypes(org.spongepowered.api.item.ItemTypes) Kit(io.github.nucleuspowered.nucleus.api.nucleusdata.Kit) Lists(com.google.common.collect.Lists) PermissionRegistry(io.github.nucleuspowered.nucleus.internal.PermissionRegistry) KitUserDataModule(io.github.nucleuspowered.nucleus.modules.kit.datamodules.KitUserDataModule) EntityTypes(org.spongepowered.api.entity.EntityTypes) Text(org.spongepowered.api.text.Text) ListenerBase(io.github.nucleuspowered.nucleus.internal.ListenerBase) Exclude(org.spongepowered.api.event.filter.type.Exclude) KitHandler(io.github.nucleuspowered.nucleus.modules.kit.handlers.KitHandler) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) UserDataManager(io.github.nucleuspowered.nucleus.dataservices.loaders.UserDataManager) InteractInventoryEvent(org.spongepowered.api.event.item.inventory.InteractInventoryEvent) Entity(org.spongepowered.api.entity.Entity) Collectors(java.util.stream.Collectors) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) Root(org.spongepowered.api.event.filter.cause.Root) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) List(java.util.List) Container(org.spongepowered.api.item.inventory.Container) NucleusFirstJoinEvent(io.github.nucleuspowered.nucleus.api.events.NucleusFirstJoinEvent) World(org.spongepowered.api.world.World) KitService(io.github.nucleuspowered.nucleus.dataservices.KitService) Player(org.spongepowered.api.entity.living.player.Player) Listener(org.spongepowered.api.event.Listener) KitConfigAdapter(io.github.nucleuspowered.nucleus.modules.kit.config.KitConfigAdapter) KitRedeemException(io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException) Listener(org.spongepowered.api.event.Listener)

Example 3 with KitRedeemException

use of io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException in project Nucleus by NucleusPowered.

the class KitGiveCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Kit kit = args.<Kit>getOne(KIT_PARAMETER).get();
    Player player = args.<Player>getOne(playerKey).get();
    boolean skip = args.hasAny("i");
    if (src instanceof Player && player.getUniqueId().equals(((Player) src).getUniqueId())) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.kit.give.self"));
    }
    Text playerName = Nucleus.getNucleus().getNameUtil().getName(player);
    Text kitName = Text.of(kit.getName());
    try {
        NucleusKitService.RedeemResult redeemResult = KIT_HANDLER.redeemKit(kit, player, !skip, this.mustGetAll);
        if (!redeemResult.rejected().isEmpty()) {
            // If we drop them, tell the user
            if (this.isDrop) {
                player.sendMessage(this.plugin.getMessageProvider().getTextMessageWithTextFormat("command.kit.give.itemsdropped", playerName));
                redeemResult.rejected().forEach(x -> Util.dropItemOnFloorAtLocation(x, player.getLocation()));
            } else {
                player.sendMessage(this.plugin.getMessageProvider().getTextMessageWithTextFormat("command.kit.give.fullinventory", playerName));
            }
        }
        src.sendMessage(this.plugin.getMessageProvider().getTextMessageWithTextFormat("command.kit.give.spawned", playerName, kitName));
        if (kit.isDisplayMessageOnRedeem()) {
            player.sendMessage(this.plugin.getMessageProvider().getTextMessageWithFormat("command.kit.spawned", kit.getName()));
        }
        return CommandResult.success();
    } catch (KitRedeemException ex) {
        switch(ex.getReason()) {
            case ALREADY_REDEEMED:
                throw ReturnMessageException.fromKeyText("command.kit.give.onetime.alreadyredeemed", kitName, playerName);
            case COOLDOWN_NOT_EXPIRED:
                KitRedeemException.Cooldown kre = (KitRedeemException.Cooldown) ex;
                throw ReturnMessageException.fromKeyText("command.kit.give.cooldown", playerName, Text.of(Util.getTimeStringFromSeconds(kre.getTimeLeft().getSeconds())), kitName);
            case PRE_EVENT_CANCELLED:
                KitRedeemException.PreCancelled krepe = (KitRedeemException.PreCancelled) ex;
                throw new ReturnMessageException(krepe.getCancelMessage().orElseGet(() -> (Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.kit.cancelledpre", kit.getName()))));
            case NO_SPACE:
                throw ReturnMessageException.fromKeyText("command.kit.give.fullinventorynosave", playerName);
            case UNKNOWN:
            default:
                throw ReturnMessageException.fromKeyText("command.kit.give.fail", playerName, kitName);
        }
    }
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) NucleusKitService(io.github.nucleuspowered.nucleus.api.service.NucleusKitService) Kit(io.github.nucleuspowered.nucleus.api.nucleusdata.Kit) Text(org.spongepowered.api.text.Text) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) KitRedeemException(io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException)

Example 4 with KitRedeemException

use of io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException in project Nucleus by NucleusPowered.

the class KitCommand method executeCommand.

@Override
public CommandResult executeCommand(Player player, CommandContext args) throws ReturnMessageException {
    Kit kit = args.<Kit>getOne(KIT_PARAMETER).get();
    EconHelper econHelper = Nucleus.getNucleus().getEconHelper();
    double cost = econHelper.economyServiceExists() ? kit.getCost() : 0;
    if (permissions.testCostExempt(player)) {
        // If exempt - no cost.
        cost = 0;
    }
    // If we have a cost for the kit, check we have funds.
    if (cost > 0 && !econHelper.hasBalance(player, cost)) {
        throw ReturnMessageException.fromKey("command.kit.notenough", kit.getName(), econHelper.getCurrencySymbol(cost));
    }
    try {
        NucleusKitService.RedeemResult redeemResult = KIT_HANDLER.redeemKit(kit, player, true, this.mustGetAll);
        if (!redeemResult.rejected().isEmpty()) {
            // If we drop them, tell the user
            if (this.isDrop) {
                player.sendMessage(this.plugin.getMessageProvider().getTextMessageWithFormat("command.kit.itemsdropped"));
                redeemResult.rejected().forEach(x -> Util.dropItemOnFloorAtLocation(x, player.getLocation()));
            } else {
                player.sendMessage(this.plugin.getMessageProvider().getTextMessageWithFormat("command.kit.fullinventory"));
            }
        }
        if (kit.isDisplayMessageOnRedeem()) {
            player.sendMessage(this.plugin.getMessageProvider().getTextMessageWithFormat("command.kit.spawned", kit.getName()));
        }
        // Charge, if necessary
        if (cost > 0 && econHelper.economyServiceExists()) {
            econHelper.withdrawFromPlayer(player, cost);
        }
        return CommandResult.success();
    } catch (KitRedeemException ex) {
        switch(ex.getReason()) {
            case ALREADY_REDEEMED:
                throw ReturnMessageException.fromKey("command.kit.onetime.alreadyredeemed", kit.getName());
            case COOLDOWN_NOT_EXPIRED:
                KitRedeemException.Cooldown kre = (KitRedeemException.Cooldown) ex;
                throw ReturnMessageException.fromKey("command.kit.cooldown", Util.getTimeStringFromSeconds(kre.getTimeLeft().getSeconds()), kit.getName());
            case PRE_EVENT_CANCELLED:
                KitRedeemException.PreCancelled krepe = (KitRedeemException.PreCancelled) ex;
                throw new ReturnMessageException(krepe.getCancelMessage().orElseGet(() -> (Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.kit.cancelledpre", kit.getName()))));
            case NO_SPACE:
                throw ReturnMessageException.fromKey("command.kit.fullinventorynosave", kit.getName());
            case UNKNOWN:
            default:
                throw ReturnMessageException.fromKey("command.kit.fail", kit.getName());
        }
    }
}
Also used : NucleusKitService(io.github.nucleuspowered.nucleus.api.service.NucleusKitService) NoCooldown(io.github.nucleuspowered.nucleus.internal.annotations.command.NoCooldown) Kit(io.github.nucleuspowered.nucleus.api.nucleusdata.Kit) EconHelper(io.github.nucleuspowered.nucleus.internal.EconHelper) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) KitRedeemException(io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException)

Aggregations

KitRedeemException (io.github.nucleuspowered.nucleus.api.exceptions.KitRedeemException)4 Kit (io.github.nucleuspowered.nucleus.api.nucleusdata.Kit)3 NucleusKitService (io.github.nucleuspowered.nucleus.api.service.NucleusKitService)2 ReturnMessageException (io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException)2 KitUserDataModule (io.github.nucleuspowered.nucleus.modules.kit.datamodules.KitUserDataModule)2 Player (org.spongepowered.api.entity.living.player.Player)2 Text (org.spongepowered.api.text.Text)2 Lists (com.google.common.collect.Lists)1 Nucleus (io.github.nucleuspowered.nucleus.Nucleus)1 NucleusFirstJoinEvent (io.github.nucleuspowered.nucleus.api.events.NucleusFirstJoinEvent)1 NucleusKitEvent (io.github.nucleuspowered.nucleus.api.events.NucleusKitEvent)1 KitService (io.github.nucleuspowered.nucleus.dataservices.KitService)1 UserDataManager (io.github.nucleuspowered.nucleus.dataservices.loaders.UserDataManager)1 EconHelper (io.github.nucleuspowered.nucleus.internal.EconHelper)1 ListenerBase (io.github.nucleuspowered.nucleus.internal.ListenerBase)1 PermissionRegistry (io.github.nucleuspowered.nucleus.internal.PermissionRegistry)1 NoCooldown (io.github.nucleuspowered.nucleus.internal.annotations.command.NoCooldown)1 Reloadable (io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable)1 KitConfigAdapter (io.github.nucleuspowered.nucleus.modules.kit.config.KitConfigAdapter)1 KitEvent (io.github.nucleuspowered.nucleus.modules.kit.events.KitEvent)1