Search in sources :

Example 96 with MapleCharacter

use of client.MapleCharacter in project HeavenMS by ronancpl.

the class Commands method executeHeavenMsCommandLv2.

public static boolean executeHeavenMsCommandLv2(Channel cserv, Server srv, MapleClient c, String[] sub) {
    // JrGM
    MapleCharacter player = c.getPlayer();
    MapleCharacter victim;
    Skill skill;
    switch(sub[0]) {
        case "hide":
            SkillFactory.getSkill(9101004).getEffect(SkillFactory.getSkill(9101004).getMaxLevel()).applyTo(player);
            break;
        case "unhide":
            SkillFactory.getSkill(9101004).getEffect(SkillFactory.getSkill(9101004).getMaxLevel()).applyTo(player);
            break;
        case "sp":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !sp [<playername>] <newsp>");
                break;
            }
            if (sub.length == 2) {
                int newSp = Integer.parseInt(sub[1]);
                if (newSp < 0)
                    newSp = 0;
                else if (newSp > ServerConstants.MAX_AP)
                    newSp = ServerConstants.MAX_AP;
                player.setRemainingSp(newSp);
                player.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
            } else {
                victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
                if (victim != null) {
                    int newSp = Integer.parseInt(sub[2]);
                    if (newSp < 0)
                        newSp = 0;
                    else if (newSp > ServerConstants.MAX_AP)
                        newSp = ServerConstants.MAX_AP;
                    victim.setRemainingSp(newSp);
                    victim.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
                    player.dropMessage(5, "SP given.");
                } else {
                    player.message("Player '" + sub[1] + "' could not be found on this channel.");
                }
            }
            break;
        case "ap":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !ap [<playername>] <newap>");
                break;
            }
            if (sub.length < 3) {
                int newAp = Integer.parseInt(sub[1]);
                if (newAp < 0)
                    newAp = 0;
                else if (newAp > ServerConstants.MAX_AP)
                    newAp = ServerConstants.MAX_AP;
                player.setRemainingAp(newAp);
                player.updateSingleStat(MapleStat.AVAILABLEAP, player.getRemainingAp());
            } else {
                victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
                if (victim != null) {
                    int newAp = Integer.parseInt(sub[2]);
                    if (newAp < 0)
                        newAp = 0;
                    else if (newAp > ServerConstants.MAX_AP)
                        newAp = ServerConstants.MAX_AP;
                    victim.setRemainingAp(newAp);
                    victim.updateSingleStat(MapleStat.AVAILABLEAP, victim.getRemainingAp());
                } else {
                    player.message("Player '" + sub[1] + "' could not be found on this channel.");
                }
            }
            break;
        case "empowerme":
            final int[] array = { 2311003, 2301004, 1301007, 4101004, 2001002, 1101007, 1005, 2301003, 5121009, 1111002, 4111001, 4111002, 4211003, 4211005, 1321000, 2321004, 3121002 };
            for (int i : array) {
                SkillFactory.getSkill(i).getEffect(SkillFactory.getSkill(i).getMaxLevel()).applyTo(player);
            }
            break;
        case "buffmap":
            SkillFactory.getSkill(9101001).getEffect(SkillFactory.getSkill(9101001).getMaxLevel()).applyTo(player, true);
            SkillFactory.getSkill(9101002).getEffect(SkillFactory.getSkill(9101002).getMaxLevel()).applyTo(player, true);
            SkillFactory.getSkill(9101003).getEffect(SkillFactory.getSkill(9101003).getMaxLevel()).applyTo(player, true);
            SkillFactory.getSkill(9101008).getEffect(SkillFactory.getSkill(9101008).getMaxLevel()).applyTo(player, true);
            SkillFactory.getSkill(1005).getEffect(SkillFactory.getSkill(1005).getMaxLevel()).applyTo(player, true);
            break;
        case "buff":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !buff <buffid>");
                break;
            }
            int skillid = Integer.parseInt(sub[1]);
            skill = SkillFactory.getSkill(skillid);
            if (skill != null)
                skill.getEffect(skill.getMaxLevel()).applyTo(player);
            break;
        case "bomb":
            if (sub.length > 1) {
                victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
                if (victim != null) {
                    victim.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9300166), victim.getPosition());
                    Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.serverNotice(5, player.getName() + " used !bomb on " + victim.getName()));
                } else {
                    player.message("Player '" + sub[1] + "' could not be found on this world.");
                }
            } else {
                player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9300166), player.getPosition());
            }
            break;
        case "dc":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !dc <playername>");
                break;
            }
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim == null) {
                victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
                if (victim == null) {
                    victim = player.getMap().getCharacterByName(sub[1]);
                    if (victim != null) {
                        try {
                            // sometimes bugged because the map = null
                            victim.getClient().disconnect(true, false);
                            player.getMap().removePlayer(victim);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        break;
                    }
                }
            }
            if (player.gmLevel() < victim.gmLevel()) {
                victim = player;
            }
            victim.getClient().disconnect(false, false);
            break;
        case "cleardrops":
            player.getMap().clearDrops(player);
            player.dropMessage(5, "Cleared dropped items");
            break;
        case "clearslot":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !clearslot <all, equip, use, setup, etc or cash.>");
                break;
            }
            String type = sub[1];
            if (type.equals("all")) {
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.EQUIP, (byte) i, tempItem.getQuantity(), false, true);
                }
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.USE).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.USE, (byte) i, tempItem.getQuantity(), false, true);
                }
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.ETC).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.ETC, (byte) i, tempItem.getQuantity(), false, true);
                }
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.SETUP).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.SETUP, (byte) i, tempItem.getQuantity(), false, true);
                }
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.CASH).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.CASH, (byte) i, tempItem.getQuantity(), false, true);
                }
                player.yellowMessage("All Slots Cleared.");
            } else if (type.equals("equip")) {
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.EQUIP, (byte) i, tempItem.getQuantity(), false, true);
                }
                player.yellowMessage("Equipment Slot Cleared.");
            } else if (type.equals("use")) {
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.USE).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.USE, (byte) i, tempItem.getQuantity(), false, true);
                }
                player.yellowMessage("Use Slot Cleared.");
            } else if (type.equals("setup")) {
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.SETUP).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.SETUP, (byte) i, tempItem.getQuantity(), false, true);
                }
                player.yellowMessage("Set-Up Slot Cleared.");
            } else if (type.equals("etc")) {
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.ETC).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.ETC, (byte) i, tempItem.getQuantity(), false, true);
                }
                player.yellowMessage("ETC Slot Cleared.");
            } else if (type.equals("cash")) {
                for (int i = 0; i < 101; i++) {
                    Item tempItem = c.getPlayer().getInventory(MapleInventoryType.CASH).getItem((byte) i);
                    if (tempItem == null)
                        continue;
                    MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.CASH, (byte) i, tempItem.getQuantity(), false, true);
                }
                player.yellowMessage("Cash Slot Cleared.");
            } else
                player.yellowMessage("Slot" + type + " does not exist!");
            break;
        case "warp":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !warp <mapid>");
                break;
            }
            try {
                MapleMap target = c.getChannelServer().getMapFactory().getMap(Integer.parseInt(sub[1]));
                if (target == null) {
                    player.yellowMessage("Map ID " + sub[1] + " is invalid.");
                    break;
                }
                if (player.getEventInstance() != null) {
                    player.getEventInstance().leftParty(player);
                }
                player.changeMap(target, target.getRandomPlayerSpawnpoint());
            } catch (Exception ex) {
                player.yellowMessage("Map ID " + sub[1] + " is invalid.");
                break;
            }
            break;
        case "warpto":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !warpto <playername> <mapid>");
                break;
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim == null) {
                // If victim isn't on current channel or isnt a character try and find him by loop all channels on current world.
                for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
                    victim = ch.getPlayerStorage().getCharacterByName(sub[1]);
                    if (victim != null) {
                        // We found the person, no need to continue the loop.
                        break;
                    }
                }
            }
            if (victim != null) {
                // Remove warper from current event instance.
                if (player.getEventInstance() != null) {
                    player.getEventInstance().unregisterPlayer(player);
                }
                // Attempt to join the victims warp instance.
                if (victim.getEventInstance() != null) {
                    if (victim.getClient().getChannel() == player.getClient().getChannel()) {
                        // just in case.. you never know...
                        // victim.getEventInstance().registerPlayer(player);
                        player.changeMap(victim.getEventInstance().getMapInstance(victim.getMapId()), victim.getMap().findClosestPortal(victim.getPosition()));
                    } else {
                        player.dropMessage(6, "Please change to channel " + victim.getClient().getChannel());
                    }
                } else {
                    // If victim isn't in an event instance, just warp them.
                    player.changeMap(victim.getMapId(), victim.getMap().findClosestPortal(victim.getPosition()));
                }
                if (player.getClient().getChannel() != victim.getClient().getChannel()) {
                    // And then change channel if needed.
                    player.dropMessage("Changing channel, please wait a moment.");
                    player.getClient().changeChannel(victim.getClient().getChannel());
                }
            } else {
                player.dropMessage(6, "Unknown player.");
            }
            break;
        case "warphere":
        case "summon":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !warphere <playername>");
                break;
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim == null) {
                // If victim isn't on current channel, loop all channels on current world.
                for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
                    victim = ch.getPlayerStorage().getCharacterByName(sub[1]);
                    if (victim != null) {
                        // We found the person, no need to continue the loop.
                        break;
                    }
                }
            }
            if (victim != null) {
                boolean changingEvent = true;
                if (victim.getEventInstance() != null) {
                    if (player.getEventInstance() != null && victim.getEventInstance().getLeaderId() == player.getEventInstance().getLeaderId()) {
                        changingEvent = false;
                    } else {
                        victim.getEventInstance().unregisterPlayer(victim);
                    }
                }
                // Attempt to join the warpers instance.
                if (player.getEventInstance() != null && changingEvent) {
                    if (player.getClient().getChannel() == victim.getClient().getChannel()) {
                        // just in case.. you never know...
                        player.getEventInstance().registerPlayer(victim);
                        victim.changeMap(player.getEventInstance().getMapInstance(player.getMapId()), player.getMap().findClosestPortal(player.getPosition()));
                    } else {
                        player.dropMessage("Target isn't on your channel, not able to warp into event instance.");
                    }
                } else {
                    // If victim isn't in an event instance or is in the same event instance as the one the caller is, just warp them.
                    victim.changeMap(player.getMapId(), player.getMap().findClosestPortal(player.getPosition()));
                }
                if (player.getClient().getChannel() != victim.getClient().getChannel()) {
                    // And then change channel if needed.
                    victim.dropMessage("Changing channel, please wait a moment.");
                    victim.getClient().changeChannel(player.getClient().getChannel());
                }
            } else {
                player.dropMessage(6, "Unknown player.");
            }
            break;
        case "reach":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !reach <playername>");
                break;
            }
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null && victim.isLoggedin()) {
                if (player.getClient().getChannel() != victim.getClient().getChannel()) {
                    player.dropMessage(5, "Player '" + victim.getName() + "' is at channel " + victim.getClient().getChannel() + ".");
                } else {
                    MapleMap map = victim.getMap();
                    player.changeMap(map, map.findClosestPortal(victim.getPosition()));
                }
            } else {
                player.dropMessage(6, "Unknown player.");
            }
            break;
        case "gmshop":
            MapleShopFactory.getInstance().getShop(1337).sendShop(c);
            break;
        case "heal":
            player.setHpMp(30000);
            break;
        case "item":
        case "drop":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !item <itemid> <quantity>");
                break;
            }
            int itemId = Integer.parseInt(sub[1]);
            MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
            if (ii.getName(itemId) == null) {
                player.yellowMessage("Item id '" + sub[1] + "' does not exist.");
                break;
            }
            short quantity = 1;
            if (sub.length >= 3)
                quantity = Short.parseShort(sub[2]);
            if (ServerConstants.BLOCK_GENERATE_CASH_ITEM && ii.isCash(itemId)) {
                player.yellowMessage("You cannot create a cash item with this command.");
                break;
            }
            if (ItemConstants.isPet(itemId)) {
                if (sub.length >= 3) {
                    // thanks to istreety & TacoBell
                    quantity = 1;
                    long days = Math.max(1, Integer.parseInt(sub[2]));
                    long expiration = System.currentTimeMillis() + (days * 24 * 60 * 60 * 1000);
                    int petid = MaplePet.createPet(itemId);
                    if (sub[0].equals("item")) {
                        MapleInventoryManipulator.addById(c, itemId, quantity, player.getName(), petid, expiration);
                    } else {
                        Item toDrop = new Item(itemId, (short) 0, quantity, petid);
                        toDrop.setExpiration(expiration);
                        toDrop.setOwner("");
                        if (player.gmLevel() < 3) {
                            byte b = toDrop.getFlag();
                            b |= ItemConstants.ACCOUNT_SHARING;
                            b |= ItemConstants.UNTRADEABLE;
                            toDrop.setFlag(b);
                        }
                        c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
                    }
                    break;
                } else {
                    player.yellowMessage("Pet Syntax: !item <itemid> <expiration>");
                    break;
                }
            }
            if (sub[0].equals("item")) {
                byte flag = 0;
                if (player.gmLevel() < 3) {
                    flag |= ItemConstants.ACCOUNT_SHARING;
                    flag |= ItemConstants.UNTRADEABLE;
                }
                MapleInventoryManipulator.addById(c, itemId, quantity, player.getName(), -1, flag, -1);
            } else {
                Item toDrop;
                if (ItemConstants.getInventoryType(itemId) == MapleInventoryType.EQUIP) {
                    toDrop = ii.getEquipById(itemId);
                } else {
                    toDrop = new Item(itemId, (short) 0, quantity);
                }
                toDrop.setOwner(player.getName());
                if (player.gmLevel() < 3) {
                    byte b = toDrop.getFlag();
                    b |= ItemConstants.ACCOUNT_SHARING;
                    b |= ItemConstants.UNTRADEABLE;
                    toDrop.setFlag(b);
                }
                c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
            }
            break;
        case "level":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !level <newlevel>");
                break;
            }
            player.loseExp(player.getExp(), false, false);
            player.setLevel(Math.min(Integer.parseInt(sub[1]), player.getMaxClassLevel()) - 1);
            player.resetPlayerRates();
            if (ServerConstants.USE_ADD_RATES_BY_LEVEL == true)
                player.setPlayerRates();
            player.setWorldRates();
            player.levelUp(false);
            break;
        case "levelpro":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !levelpro <newlevel>");
                break;
            }
            while (player.getLevel() < Math.min(player.getMaxClassLevel(), Integer.parseInt(sub[1]))) {
                player.levelUp(false);
            }
            break;
        case "setstat":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !setstat <newstat>");
                break;
            }
            int x;
            try {
                x = Integer.parseInt(sub[1]);
                if (x > Short.MAX_VALUE)
                    x = Short.MAX_VALUE;
                else if (x < 0)
                    x = 0;
                player.setStr(x);
                player.setDex(x);
                player.setInt(x);
                player.setLuk(x);
                player.updateSingleStat(MapleStat.STR, x);
                player.updateSingleStat(MapleStat.DEX, x);
                player.updateSingleStat(MapleStat.INT, x);
                player.updateSingleStat(MapleStat.LUK, x);
            } catch (NumberFormatException nfe) {
            }
            break;
        case "maxstat":
            final String[] s = { "setstat", String.valueOf(Short.MAX_VALUE) };
            executeHeavenMsCommandLv2(cserv, srv, c, s);
            player.loseExp(player.getExp(), false, false);
            player.setLevel(255);
            player.resetPlayerRates();
            if (ServerConstants.USE_ADD_RATES_BY_LEVEL == true)
                player.setPlayerRates();
            player.setWorldRates();
            player.setFame(13337);
            player.setMaxHp(30000);
            player.setMaxMp(30000);
            player.updateSingleStat(MapleStat.LEVEL, 255);
            player.updateSingleStat(MapleStat.FAME, 13337);
            player.updateSingleStat(MapleStat.MAXHP, 30000);
            player.updateSingleStat(MapleStat.MAXMP, 30000);
            player.yellowMessage("Stats maxed out.");
            break;
        case "maxskill":
            for (MapleData skill_ : MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/" + "String.wz")).getData("Skill.img").getChildren()) {
                try {
                    skill = SkillFactory.getSkill(Integer.parseInt(skill_.getName()));
                    player.changeSkillLevel(skill, (byte) skill.getMaxLevel(), skill.getMaxLevel(), -1);
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                    break;
                } catch (NullPointerException npe) {
                    continue;
                }
            }
            if (player.getJob().isA(MapleJob.ARAN1) || player.getJob().isA(MapleJob.LEGEND)) {
                skill = SkillFactory.getSkill(5001005);
                player.changeSkillLevel(skill, (byte) -1, -1, -1);
            } else {
                skill = SkillFactory.getSkill(21001001);
                player.changeSkillLevel(skill, (byte) -1, -1, -1);
            }
            player.yellowMessage("Skills maxed out.");
            break;
        case "mesos":
            if (sub.length >= 2) {
                player.gainMeso(Integer.parseInt(sub[1]), true);
            }
            break;
        case "search":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !search <type> <name>");
                break;
            }
            StringBuilder sb = new StringBuilder();
            String search = joinStringFrom(sub, 2);
            // for the lulz
            long start = System.currentTimeMillis();
            MapleData data = null;
            MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File("wz/String.wz"));
            if (!sub[1].equalsIgnoreCase("ITEM")) {
                if (sub[1].equalsIgnoreCase("NPC")) {
                    data = dataProvider.getData("Npc.img");
                } else if (sub[1].equalsIgnoreCase("MOB") || sub[1].equalsIgnoreCase("MONSTER")) {
                    data = dataProvider.getData("Mob.img");
                } else if (sub[1].equalsIgnoreCase("SKILL")) {
                    data = dataProvider.getData("Skill.img");
                /*} else if (sub[1].equalsIgnoreCase("MAP")) {
                                        TODO
                                */
                } else {
                    sb.append("#bInvalid search.\r\nSyntax: '!search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
                }
                if (data != null) {
                    String name;
                    for (MapleData searchData : data.getChildren()) {
                        name = MapleDataTool.getString(searchData.getChildByPath("name"), "NO-NAME");
                        if (name.toLowerCase().contains(search.toLowerCase())) {
                            sb.append("#b").append(Integer.parseInt(searchData.getName())).append("#k - #r").append(name).append("\r\n");
                        }
                    }
                }
            } else {
                for (Pair<Integer, String> itemPair : MapleItemInformationProvider.getInstance().getAllItems()) {
                    if (sb.length() < 32654) {
                        // ohlol
                        if (itemPair.getRight().toLowerCase().contains(search.toLowerCase())) {
                            // #v").append(id).append("# #k-
                            sb.append("#b").append(itemPair.getLeft()).append("#k - #r").append(itemPair.getRight()).append("\r\n");
                        }
                    } else {
                        sb.append("#bCouldn't load all items, there are too many results.\r\n");
                        break;
                    }
                }
            }
            if (sb.length() == 0) {
                sb.append("#bNo ").append(sub[1].toLowerCase()).append("s found.\r\n");
            }
            // because I can, and it's free
            sb.append("\r\n#kLoaded within ").append((double) (System.currentTimeMillis() - start) / 1000).append(" seconds.");
            c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, sb.toString(), "00 00", (byte) 0));
            break;
        case "jail":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !jail <playername> [<minutes>]");
                break;
            }
            int minutesJailed = 5;
            if (sub.length >= 3) {
                minutesJailed = Integer.valueOf(sub[2]);
                if (minutesJailed <= 0) {
                    player.yellowMessage("Syntax: !jail <playername> [<minutes>]");
                    break;
                }
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                victim.addJailExpirationTime(minutesJailed * 60 * 1000);
                int mapid = 300000012;
                if (victim.getMapId() != mapid) {
                    // those gone to jail won't be changing map anyway
                    MapleMap target = cserv.getMapFactory().getMap(mapid);
                    MaplePortal targetPortal = target.getPortal(0);
                    victim.changeMap(target, targetPortal);
                    player.message(victim.getName() + " was jailed for " + minutesJailed + " minutes.");
                } else {
                    player.message(victim.getName() + "'s time in jail has been extended for " + minutesJailed + " minutes.");
                }
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "unjail":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !unjail <playername>");
                break;
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                if (victim.getJailExpirationTimeLeft() <= 0) {
                    player.message("This player is already free.");
                    break;
                }
                victim.removeJailExpirationTime();
                victim.message("By lack of concrete proof you are now unjailed. Enjoy freedom!");
                player.message(victim.getName() + " was unjailed.");
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "job":
            if (sub.length == 2) {
                int jobid = Integer.parseInt(sub[1]);
                if (jobid < 0 || jobid >= 2200) {
                    player.message("Jobid " + jobid + " is not available.");
                    break;
                }
                player.changeJob(MapleJob.getById(jobid));
                player.equipChanged();
            } else if (sub.length == 3) {
                victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
                if (victim != null) {
                    int jobid = Integer.parseInt(sub[2]);
                    if (jobid < 0 || jobid >= 2200) {
                        player.message("Jobid " + jobid + " is not available.");
                        break;
                    }
                    victim.changeJob(MapleJob.getById(jobid));
                    player.equipChanged();
                } else {
                    player.message("Player '" + sub[1] + "' could not be found on this channel.");
                }
            } else {
                player.message("Syntax: !job <job id> <opt: IGN of another person>");
            }
            break;
        case "unbug":
            c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.enableActions());
            break;
        default:
            return false;
    }
    return true;
}
Also used : MapleCharacter(client.MapleCharacter) MapleData(provider.MapleData) Channel(net.server.channel.Channel) Point(java.awt.Point) SpawnPoint(server.life.SpawnPoint) SQLException(java.sql.SQLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) MapleMapItem(server.maps.MapleMapItem) Item(client.inventory.Item) MapleMap(server.maps.MapleMap) Skill(client.Skill) MaplePortal(server.MaplePortal) MapleItemInformationProvider(server.MapleItemInformationProvider) MapleDataProvider(provider.MapleDataProvider) File(java.io.File)

Example 97 with MapleCharacter

use of client.MapleCharacter in project HeavenMS by ronancpl.

the class Commands method executeHeavenMsCommandLv6.

public static boolean executeHeavenMsCommandLv6(Channel cserv, Server srv, MapleClient c, String[] sub) {
    // Admin
    MapleCharacter player = c.getPlayer();
    MapleCharacter victim;
    switch(sub[0]) {
        case "setgmlevel":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !setgmlevel <playername> <newlevel>");
                break;
            }
            int newLevel = Integer.parseInt(sub[2]);
            MapleCharacter target = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (target != null) {
                target.setGMLevel(newLevel);
                target.getClient().setGMLevel(newLevel);
                target.dropMessage("You are now a level " + newLevel + " GM. See @commands for a list of available commands.");
                player.dropMessage(target + " is now a level " + newLevel + " GM.");
            } else {
                player.dropMessage("Player '" + sub[1] + "' was not found on this channel.");
            }
            break;
        case "warpworld":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !warpworld <worldid>");
                break;
            }
            Server server = Server.getInstance();
            byte worldb = Byte.parseByte(sub[1]);
            if (worldb <= (server.getWorlds().size() - 1)) {
                try {
                    String[] socket = server.getIP(worldb, c.getChannel()).split(":");
                    c.getWorldServer().removePlayer(player);
                    // LOL FORGOT THIS ><
                    player.getMap().removePlayer(player);
                    c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);
                    player.setWorld(worldb);
                    // To set the new world :O (true because else 2 player instances are created, one in both worlds)
                    player.saveToDB();
                    c.announce(MaplePacketCreator.getChannelChange(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1])));
                } catch (UnknownHostException | NumberFormatException ex) {
                    ex.printStackTrace();
                    player.message("Error when trying to change worlds, are you sure the world you are trying to warp to has the same amount of channels?");
                }
            } else {
                player.message("Invalid world; highest number available: " + (server.getWorlds().size() - 1));
            }
            break;
        case "saveall":
            for (World world : Server.getInstance().getWorlds()) {
                for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
                    chr.saveToDB();
                }
            }
            String message = player.getName() + " used !saveall.";
            Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.serverNotice(5, message));
            player.message("All players saved successfully.");
            break;
        case "dcall":
            for (World world : Server.getInstance().getWorlds()) {
                for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
                    if (!chr.isGM()) {
                        chr.getClient().disconnect(false, false);
                    }
                }
            }
            player.message("All players successfully disconnected.");
            break;
        case "mapplayers":
            String names = "";
            int map = player.getMapId();
            for (World world : Server.getInstance().getWorlds()) {
                for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
                    int curMap = chr.getMapId();
                    String hp = Integer.toString(chr.getHp());
                    String maxhp = Integer.toString(chr.getMaxHp());
                    String name = chr.getName() + ": " + hp + "/" + maxhp;
                    if (map == curMap) {
                        names = names.equals("") ? name : (names + ", " + name);
                    }
                }
            }
            player.message("These b lurkin: " + names);
            break;
        case "getacc":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !getacc <playername>");
                break;
            }
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                player.message(victim.getName() + "'s account name is " + victim.getClient().getAccountName() + ".");
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this world.");
            }
            break;
        case "shutdown":
        case "shutdownnow":
            int time = 60000;
            if (sub[0].equals("shutdownnow")) {
                time = 1;
            } else if (sub.length > 1) {
                time *= Integer.parseInt(sub[1]);
            }
            if (time > 1) {
                int seconds = (int) (time / 1000) % 60;
                int minutes = (int) ((time / (1000 * 60)) % 60);
                int hours = (int) ((time / (1000 * 60 * 60)) % 24);
                int days = (int) ((time / (1000 * 60 * 60 * 24)));
                String strTime = "";
                if (days > 0)
                    strTime += days + " days, ";
                if (hours > 0)
                    strTime += hours + " hours, ";
                strTime += minutes + " minutes, ";
                strTime += seconds + " seconds";
                for (World w : Server.getInstance().getWorlds()) {
                    for (MapleCharacter chr : w.getPlayerStorage().getAllCharacters()) {
                        chr.dropMessage("Server is undergoing maintenance process, and will be shutdown in " + strTime + ". Prepare yourself to quit safely in the mean time.");
                    }
                }
            }
            TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
            break;
        case "clearquestcache":
            MapleQuest.clearCache();
            player.dropMessage(5, "Quest Cache Cleared.");
            break;
        case "clearquest":
            if (sub.length < 1) {
                player.dropMessage(5, "Please include a quest ID.");
                break;
            }
            MapleQuest.clearCache(Integer.parseInt(sub[1]));
            player.dropMessage(5, "Quest Cache for quest " + sub[1] + " cleared.");
            break;
        case "fred":
            c.announce(MaplePacketCreator.fredrickMessage(Byte.valueOf(sub[1])));
            break;
        default:
            return false;
    }
    return true;
}
Also used : MapleCharacter(client.MapleCharacter) Server(net.server.Server) UnknownHostException(java.net.UnknownHostException) World(net.server.world.World) Point(java.awt.Point) SpawnPoint(server.life.SpawnPoint)

Example 98 with MapleCharacter

use of client.MapleCharacter in project HeavenMS by ronancpl.

the class Commands method executeHeavenMsCommandLv3.

public static boolean executeHeavenMsCommandLv3(Channel cserv, Server srv, MapleClient c, String[] sub) {
    // GM
    MapleCharacter player = c.getPlayer();
    MapleCharacter victim;
    switch(sub[0]) {
        case "fly":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !fly <on/off>");
                break;
            }
            Integer accid = c.getAccID();
            String sendStr = "";
            if (sub[1].equalsIgnoreCase("on")) {
                sendStr += "Enabled Fly feature (F1). With fly active, you cannot attack.";
                if (!srv.canFly(accid))
                    sendStr += " Re-login to take effect.";
                srv.changeFly(c.getAccID(), true);
            } else {
                sendStr += "Disabled Fly feature. You can now attack.";
                if (srv.canFly(accid))
                    sendStr += " Re-login to take effect.";
                srv.changeFly(c.getAccID(), false);
            }
            player.dropMessage(6, sendStr);
            break;
        case "spawn":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !spawn <mobid>");
                break;
            }
            MapleMonster monster = MapleLifeFactory.getMonster(Integer.parseInt(sub[1]));
            if (monster == null) {
                break;
            }
            if (sub.length > 2) {
                for (int i = 0; i < Integer.parseInt(sub[2]); i++) {
                    player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(Integer.parseInt(sub[1])), player.getPosition());
                }
            } else {
                player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(Integer.parseInt(sub[1])), player.getPosition());
            }
            break;
        case "mutemap":
            if (player.getMap().isMuted()) {
                player.getMap().setMuted(false);
                player.dropMessage(5, "The map you are in has been un-muted.");
            } else {
                player.getMap().setMuted(true);
                player.dropMessage(5, "The map you are in has been muted.");
            }
            break;
        case "checkdmg":
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                int maxBase = victim.calculateMaxBaseDamage(victim.getTotalWatk());
                Integer watkBuff = victim.getBuffedValue(MapleBuffStat.WATK);
                Integer matkBuff = victim.getBuffedValue(MapleBuffStat.MATK);
                Integer blessing = victim.getSkillLevel(10000000 * player.getJobType() + 12);
                if (watkBuff == null)
                    watkBuff = 0;
                if (matkBuff == null)
                    matkBuff = 0;
                player.dropMessage(5, "Cur Str: " + victim.getTotalStr() + " Cur Dex: " + victim.getTotalDex() + " Cur Int: " + victim.getTotalInt() + " Cur Luk: " + victim.getTotalLuk());
                player.dropMessage(5, "Cur WATK: " + victim.getTotalWatk() + " Cur MATK: " + victim.getTotalMagic());
                player.dropMessage(5, "Cur WATK Buff: " + watkBuff + " Cur MATK Buff: " + matkBuff + " Cur Blessing Level: " + blessing);
                player.dropMessage(5, victim.getName() + "'s maximum base damage (before skills) is " + maxBase);
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this world.");
            }
            break;
        case "inmap":
            String st = "";
            for (MapleCharacter chr : player.getMap().getCharacters()) {
                st += chr.getName() + " ";
            }
            player.message(st);
            break;
        case "reloadevents":
            for (Channel ch : Server.getInstance().getAllChannels()) {
                ch.reloadEventScriptManager();
            }
            player.dropMessage(5, "Reloaded Events");
            break;
        case "reloaddrops":
            MapleMonsterInformationProvider.getInstance().clearDrops();
            player.dropMessage(5, "Reloaded Drops");
            break;
        case "reloadportals":
            PortalScriptManager.getInstance().reloadPortalScripts();
            player.dropMessage(5, "Reloaded Portals");
            break;
        case "reloadmap":
            MapleMap oldMap = c.getPlayer().getMap();
            MapleMap newMap = c.getChannelServer().getMapFactory().resetMap(player.getMapId());
            int callerid = c.getPlayer().getId();
            for (MapleCharacter chr : oldMap.getCharacters()) {
                chr.changeMap(newMap);
                if (chr.getId() != callerid)
                    chr.dropMessage("You have been relocated due to map reloading. Sorry for the inconvenience.");
            }
            newMap.respawn();
            break;
        case "hpmp":
            victim = player;
            int statUpdate = 1;
            if (sub.length >= 3) {
                victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
                statUpdate = Integer.valueOf(sub[2]);
            } else if (sub.length == 2) {
                statUpdate = Integer.valueOf(sub[1]);
            } else {
                player.yellowMessage("Syntax: !sethpmp [<playername>] <value>");
            }
            if (victim != null) {
                victim.setHp(statUpdate);
                victim.setMp(statUpdate);
                victim.updateSingleStat(MapleStat.HP, statUpdate);
                victim.updateSingleStat(MapleStat.MP, statUpdate);
                victim.checkBerserk(victim.isHidden());
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this world.");
            }
            break;
        case "music":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !music <song>");
                for (String s : songs) {
                    player.yellowMessage(s);
                }
                break;
            }
            String song = joinStringFrom(sub, 1);
            for (String s : songs) {
                if (s.equals(song)) {
                    player.getMap().broadcastMessage(MaplePacketCreator.musicChange(s));
                    player.yellowMessage("Now playing song " + song + ".");
                    break;
                }
            }
            player.yellowMessage("Song not found, please enter a song below.");
            for (String s : songs) {
                player.yellowMessage(s);
            }
            break;
        case "monitor":
            if (sub.length < 1) {
                player.yellowMessage("Syntax: !monitor <ign>");
                break;
            }
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim == null) {
                player.message("Player '" + sub[1] + "' could not be found on this world.");
                break;
            }
            boolean monitored = MapleLogger.monitored.contains(victim.getName());
            if (monitored) {
                MapleLogger.monitored.remove(victim.getName());
            } else {
                MapleLogger.monitored.add(victim.getName());
            }
            player.yellowMessage(victim.getName() + " is " + (!monitored ? "now being monitored." : "no longer being monitored."));
            String message = player.getName() + (!monitored ? " has started monitoring " : " has stopped monitoring ") + victim.getName() + ".";
            Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.serverNotice(5, message));
            break;
        case "monitors":
            for (String ign : MapleLogger.monitored) {
                player.yellowMessage(ign + " is being monitored.");
            }
            break;
        case "ignore":
            if (sub.length < 1) {
                player.yellowMessage("Syntax: !ignore <ign>");
                break;
            }
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim == null) {
                player.message("Player '" + sub[1] + "' could not be found on this world.");
                break;
            }
            boolean monitored_ = MapleLogger.ignored.contains(victim.getName());
            if (monitored_) {
                MapleLogger.ignored.remove(victim.getName());
            } else {
                MapleLogger.ignored.add(victim.getName());
            }
            player.yellowMessage(victim.getName() + " is " + (!monitored_ ? "now being ignored." : "no longer being ignored."));
            String message_ = player.getName() + (!monitored_ ? " has started ignoring " : " has stopped ignoring ") + victim.getName() + ".";
            Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.serverNotice(5, message_));
            break;
        case "ignored":
            for (String ign : MapleLogger.ignored) {
                player.yellowMessage(ign + " is being ignored.");
            }
            break;
        case "pos":
            float xpos = player.getPosition().x;
            float ypos = player.getPosition().y;
            float fh = player.getMap().getFootholds().findBelow(player.getPosition()).getId();
            player.dropMessage(6, "Position: (" + xpos + ", " + ypos + ")");
            player.dropMessage(6, "Foothold ID: " + fh);
            break;
        case "togglecoupon":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !togglecoupon <itemid>");
                break;
            }
            Server.getInstance().toggleCoupon(Integer.parseInt(sub[1]));
            break;
        case "chat":
            player.toggleWhiteChat();
            player.message("Your chat is now " + (player.getWhiteChat() ? " white" : "normal") + ".");
            break;
        case "fame":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !fame <playername> <gainfame>");
                break;
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                victim.setFame(Integer.parseInt(sub[2]));
                victim.updateSingleStat(MapleStat.FAME, victim.getFame());
                player.message("FAME given.");
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "givenx":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !givenx [<playername>] <gainnx>");
                break;
            }
            String recv;
            int value;
            if (sub.length > 2) {
                recv = sub[1];
                value = Integer.parseInt(sub[2]);
            } else {
                recv = c.getPlayer().getName();
                value = Integer.parseInt(sub[1]);
            }
            victim = cserv.getPlayerStorage().getCharacterByName(recv);
            if (victim != null) {
                victim.getCashShop().gainCash(1, value);
                player.message("NX given.");
            } else {
                player.message("Player '" + recv + "' could not be found on this channel.");
            }
            break;
        case "givevp":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !givevp <playername> <gainvotepoint>");
                break;
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                victim.getClient().addVotePoints(Integer.parseInt(sub[2]));
                player.message("VP given.");
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "givems":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !givems [<playername>] <gainmeso>");
                break;
            }
            String recv_;
            int value_;
            if (sub.length > 2) {
                recv_ = sub[1];
                value_ = Integer.parseInt(sub[2]);
            } else {
                recv_ = c.getPlayer().getName();
                value_ = Integer.parseInt(sub[1]);
            }
            victim = cserv.getPlayerStorage().getCharacterByName(recv_);
            if (victim != null) {
                victim.gainMeso(value_, true);
                player.message("MESO given.");
            } else {
                player.message("Player '" + recv_ + "' could not be found on this channel.");
            }
            break;
        case "id":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !id <id>");
                break;
            }
            try {
                try (BufferedReader dis = new BufferedReader(new InputStreamReader(new URL("http://www.mapletip.com/search_java.php?search_value=" + sub[1] + "&check=true").openConnection().getInputStream()))) {
                    String s;
                    while ((s = dis.readLine()) != null) {
                        player.dropMessage(s);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        case "expeds":
            for (Channel ch : Server.getInstance().getChannelsFromWorld(c.getWorld())) {
                if (ch.getExpeditions().size() == 0) {
                    player.yellowMessage("No Expeditions in Channel " + ch.getId());
                    continue;
                }
                player.yellowMessage("Expeditions in Channel " + ch.getId());
                int id = 0;
                for (MapleExpedition exped : ch.getExpeditions()) {
                    id++;
                    player.yellowMessage("> Expedition " + id);
                    player.yellowMessage(">> Type: " + exped.getType().toString());
                    player.yellowMessage(">> Status: " + (exped.isRegistering() ? "REGISTERING" : "UNDERWAY"));
                    player.yellowMessage(">> Size: " + exped.getMembers().size());
                    player.yellowMessage(">> Leader: " + exped.getLeader().getName());
                    int memId = 2;
                    for (MapleCharacter member : exped.getMembers()) {
                        if (exped.isLeader(member)) {
                            continue;
                        }
                        player.yellowMessage(">>> Member " + memId + ": " + member.getName());
                        memId++;
                    }
                }
            }
            break;
        case "kill":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !kill <playername>");
                break;
            }
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                victim.setHpMp(0);
                Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.serverNotice(5, player.getName() + " used !kill on " + victim.getName()));
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "seed":
            if (player.getMapId() != 910010000) {
                player.yellowMessage("This command can only be used in HPQ.");
                break;
            }
            Point[] pos = { new Point(7, -207), new Point(179, -447), new Point(-3, -687), new Point(-357, -687), new Point(-538, -447), new Point(-359, -207) };
            int[] seed = { 4001097, 4001096, 4001095, 4001100, 4001099, 4001098 };
            for (int i = 0; i < pos.length; i++) {
                Item item = new Item(seed[i], (byte) 0, (short) 1);
                player.getMap().spawnItemDrop(player, player, item, pos[i], false, true);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            break;
        case "energy":
            System.out.println(c.getPlayer().getDojoEnergy());
            break;
        case "maxenergy":
            c.getPlayer().setDojoEnergy(10000);
            c.announce(MaplePacketCreator.getEnergy("energy", 10000));
            break;
        case "killall":
            MapleMap map = player.getMap();
            List<MapleMapObject> monsters = map.getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.MONSTER));
            int count = 0;
            for (MapleMapObject monstermo : monsters) {
                monster = (MapleMonster) monstermo;
                if (!monster.getStats().isFriendly() && !(monster.getId() >= 8810010 && monster.getId() <= 8810018)) {
                    map.damageMonster(player, monster, Integer.MAX_VALUE);
                    count++;
                }
            }
            player.dropMessage(5, "Killed " + count + " monsters.");
            break;
        case "notice":
            Server.getInstance().broadcastMessage(c.getWorld(), MaplePacketCreator.serverNotice(6, "[Notice] " + joinStringFrom(sub, 1)));
            break;
        case "rip":
            Server.getInstance().broadcastMessage(c.getWorld(), MaplePacketCreator.serverNotice(6, "[RIP]: " + joinStringFrom(sub, 1)));
            break;
        case "openportal":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !openportal <portalid>");
                break;
            }
            player.getMap().getPortal(sub[1]).setPortalState(true);
            break;
        case "closeportal":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !closeportal <portalid>");
                break;
            }
            player.getMap().getPortal(sub[1]).setPortalState(false);
            break;
        case "pe":
            String packet = "";
            try {
                InputStreamReader is = new FileReader("pe.txt");
                Properties packetProps = new Properties();
                packetProps.load(is);
                is.close();
                packet = packetProps.getProperty("pe");
            } catch (IOException ex) {
                ex.printStackTrace();
                player.yellowMessage("Failed to load pe.txt");
                break;
            }
            MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter();
            mplew.write(HexTool.getByteArrayFromHexString(packet));
            SeekableLittleEndianAccessor slea = new GenericSeekableLittleEndianAccessor(new ByteArrayByteStream(mplew.getPacket()));
            short packetId = slea.readShort();
            final MaplePacketHandler packetHandler = PacketProcessor.getProcessor(0, c.getChannel()).getHandler(packetId);
            if (packetHandler != null && packetHandler.validateState(c)) {
                try {
                    player.yellowMessage("Receiving: " + packet);
                    packetHandler.handlePacket(slea, c);
                } catch (final Throwable t) {
                    FilePrinter.printError(FilePrinter.PACKET_HANDLER + packetHandler.getClass().getName() + ".txt", t, "Error for " + (c.getPlayer() == null ? "" : "player ; " + c.getPlayer() + " on map ; " + c.getPlayer().getMapId() + " - ") + "account ; " + c.getAccountName() + "\r\n" + slea.toString());
                    break;
                }
            }
            break;
        case "startevent":
            int players = 50;
            if (sub.length > 1)
                players = Integer.parseInt(sub[1]);
            c.getChannelServer().setEvent(new MapleEvent(player.getMapId(), players));
            player.dropMessage(5, "The event has been set on " + player.getMap().getMapName() + " and will allow " + players + " players to join.");
            break;
        case "endevent":
            c.getChannelServer().setEvent(null);
            player.dropMessage(5, "You have ended the event. No more players may join.");
            break;
        case "online2":
            int total = 0;
            for (Channel ch : srv.getChannelsFromWorld(player.getWorld())) {
                int size = ch.getPlayerStorage().getAllCharacters().size();
                total += size;
                String s = "(Channel " + ch.getId() + " Online: " + size + ") : ";
                if (ch.getPlayerStorage().getAllCharacters().size() < 50) {
                    for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
                        s += MapleCharacter.makeMapleReadable(chr.getName()) + ", ";
                    }
                    player.dropMessage(6, s.substring(0, s.length() - 2));
                }
            }
            // player.dropMessage(6, "There are a total of " + total + " players online.");
            player.showHint("Players online: #e#r" + total + "#k#n.", 300);
            break;
        case "warpsnowball":
            List<MapleCharacter> chars = new ArrayList<>(player.getMap().getCharacters());
            for (MapleCharacter chr : chars) {
                chr.changeMap(109060000, chr.getTeam());
            }
            break;
        case "ban":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !ban <IGN> <Reason> (Please be descriptive)");
                break;
            }
            String ign = sub[1];
            String reason = joinStringFrom(sub, 2);
            MapleCharacter target = c.getChannelServer().getPlayerStorage().getCharacterByName(ign);
            if (target != null) {
                String readableTargetName = MapleCharacter.makeMapleReadable(target.getName());
                String ip = target.getClient().getSession().getRemoteAddress().toString().split(":")[0];
                // Ban ip
                PreparedStatement ps = null;
                try {
                    Connection con = DatabaseConnection.getConnection();
                    if (ip.matches("/[0-9]{1,3}\\..*")) {
                        ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?, ?)");
                        ps.setString(1, ip);
                        ps.setString(2, String.valueOf(target.getClient().getAccID()));
                        ps.executeUpdate();
                        ps.close();
                    }
                    con.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    c.getPlayer().message("Error occured while banning IP address");
                    c.getPlayer().message(target.getName() + "'s IP was not banned: " + ip);
                }
                target.getClient().banMacs();
                reason = c.getPlayer().getName() + " banned " + readableTargetName + " for " + reason + " (IP: " + ip + ") " + "(MAC: " + c.getMacs() + ")";
                target.ban(reason);
                target.yellowMessage("You have been banned by #b" + c.getPlayer().getName() + " #k.");
                target.yellowMessage("Reason: " + reason);
                c.announce(MaplePacketCreator.getGMEffect(4, (byte) 0));
                final MapleCharacter rip = target;
                TimerManager.getInstance().schedule(new Runnable() {

                    @Override
                    public void run() {
                        rip.getClient().disconnect(false, false);
                    }
                }, // 5 Seconds
                5000);
                Server.getInstance().broadcastMessage(c.getWorld(), MaplePacketCreator.serverNotice(6, "[RIP]: " + ign + " has been banned."));
            } else if (MapleCharacter.ban(ign, reason, false)) {
                c.announce(MaplePacketCreator.getGMEffect(4, (byte) 0));
                Server.getInstance().broadcastMessage(c.getWorld(), MaplePacketCreator.serverNotice(6, "[RIP]: " + ign + " has been banned."));
            } else {
                c.announce(MaplePacketCreator.getGMEffect(6, (byte) 1));
            }
            break;
        case "unban":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !unban <playername>");
                break;
            }
            try {
                Connection con = DatabaseConnection.getConnection();
                int aid = MapleCharacter.getAccountIdByName(sub[1]);
                PreparedStatement p = con.prepareStatement("UPDATE accounts SET banned = -1 WHERE id = " + aid);
                p.executeUpdate();
                p = con.prepareStatement("DELETE FROM ipbans WHERE aid = " + aid);
                p.executeUpdate();
                p = con.prepareStatement("DELETE FROM macbans WHERE aid = " + aid);
                p.executeUpdate();
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
                player.message("Failed to unban " + sub[1]);
                return true;
            }
            player.message("Unbanned " + sub[1]);
            break;
        case "healmap":
            for (MapleCharacter mch : player.getMap().getCharacters()) {
                if (mch != null) {
                    mch.setHp(mch.getMaxHp());
                    mch.updateSingleStat(MapleStat.HP, mch.getMaxHp());
                    mch.setMp(mch.getMaxMp());
                    mch.updateSingleStat(MapleStat.MP, mch.getMaxMp());
                }
            }
            break;
        case "healperson":
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                victim.setHp(victim.getMaxHp());
                victim.updateSingleStat(MapleStat.HP, victim.getMaxHp());
                victim.setMp(victim.getMaxMp());
                victim.updateSingleStat(MapleStat.MP, victim.getMaxMp());
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "hurt":
            victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                victim.setHp(1);
                victim.updateSingleStat(MapleStat.HP, 1);
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this channel.");
            }
            break;
        case "killmap":
            for (MapleCharacter mch : player.getMap().getCharacters()) {
                mch.setHp(0);
                mch.updateSingleStat(MapleStat.HP, 0);
            }
            break;
        case "night":
            player.getMap().broadcastNightEffect();
            player.yellowMessage("Done.");
            break;
        case "npc":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !npc <npcid>");
                break;
            }
            MapleNPC npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
            if (npc != null) {
                npc.setPosition(player.getPosition());
                npc.setCy(player.getPosition().y);
                npc.setRx0(player.getPosition().x + 50);
                npc.setRx1(player.getPosition().x - 50);
                npc.setFh(player.getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId());
                player.getMap().addMapObject(npc);
                player.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
            }
            break;
        case "face":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !face [<playername>] <faceid>");
                break;
            }
            try {
                if (sub.length == 2) {
                    int itemId = Integer.parseInt(sub[1]);
                    if (!(itemId >= 20000 && itemId < 22000) || MapleItemInformationProvider.getInstance().getName(itemId) == null) {
                        player.yellowMessage("Face id '" + sub[1] + "' does not exist.");
                        break;
                    }
                    player.setFace(itemId);
                    player.updateSingleStat(MapleStat.FACE, itemId);
                    player.equipChanged();
                } else {
                    int itemId = Integer.parseInt(sub[2]);
                    if (!(itemId >= 20000 && itemId < 22000) || MapleItemInformationProvider.getInstance().getName(itemId) == null) {
                        player.yellowMessage("Face id '" + sub[2] + "' does not exist.");
                        break;
                    }
                    victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
                    if (victim == null) {
                        victim.setFace(itemId);
                        victim.updateSingleStat(MapleStat.FACE, itemId);
                        victim.equipChanged();
                    } else {
                        player.yellowMessage("Player '" + sub[1] + "' has not been found on this channel.");
                    }
                }
            } catch (Exception e) {
            }
            break;
        case "hair":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !hair [<playername>] <hairid>");
                break;
            }
            try {
                if (sub.length == 2) {
                    int itemId = Integer.parseInt(sub[1]);
                    if (!(itemId >= 30000 && itemId < 35000) || MapleItemInformationProvider.getInstance().getName(itemId) == null) {
                        player.yellowMessage("Hair id '" + sub[1] + "' does not exist.");
                        break;
                    }
                    player.setHair(itemId);
                    player.updateSingleStat(MapleStat.HAIR, itemId);
                    player.equipChanged();
                } else {
                    int itemId = Integer.parseInt(sub[2]);
                    if (!(itemId >= 30000 && itemId < 35000) || MapleItemInformationProvider.getInstance().getName(itemId) == null) {
                        player.yellowMessage("Hair id '" + sub[2] + "' does not exist.");
                        break;
                    }
                    victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
                    if (victim != null) {
                        victim.setHair(itemId);
                        victim.updateSingleStat(MapleStat.HAIR, itemId);
                        victim.equipChanged();
                    } else {
                        player.yellowMessage("Player '" + sub[1] + "' has not been found on this channel.");
                    }
                }
            } catch (Exception e) {
            }
            break;
        default:
            return false;
    }
    return true;
}
Also used : MapleCharacter(client.MapleCharacter) MaplePacketLittleEndianWriter(tools.data.output.MaplePacketLittleEndianWriter) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) MapleMapObject(server.maps.MapleMapObject) Properties(java.util.Properties) URL(java.net.URL) MapleMap(server.maps.MapleMap) MapleMapItem(server.maps.MapleMapItem) Item(client.inventory.Item) ByteArrayByteStream(tools.data.input.ByteArrayByteStream) FileReader(java.io.FileReader) MapleNPC(server.life.MapleNPC) MapleEvent(server.events.gm.MapleEvent) InputStreamReader(java.io.InputStreamReader) Channel(net.server.channel.Channel) SeekableLittleEndianAccessor(tools.data.input.SeekableLittleEndianAccessor) GenericSeekableLittleEndianAccessor(tools.data.input.GenericSeekableLittleEndianAccessor) Connection(java.sql.Connection) DatabaseConnection(tools.DatabaseConnection) PreparedStatement(java.sql.PreparedStatement) Point(java.awt.Point) SpawnPoint(server.life.SpawnPoint) IOException(java.io.IOException) Point(java.awt.Point) SpawnPoint(server.life.SpawnPoint) SQLException(java.sql.SQLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) GenericSeekableLittleEndianAccessor(tools.data.input.GenericSeekableLittleEndianAccessor) MapleExpedition(server.expeditions.MapleExpedition) BufferedReader(java.io.BufferedReader) MaplePacketHandler(net.MaplePacketHandler) MapleMonster(server.life.MapleMonster)

Example 99 with MapleCharacter

use of client.MapleCharacter in project HeavenMS by ronancpl.

the class NewYearCardRecord method removeAllNewYearCard.

public static void removeAllNewYearCard(boolean send, MapleCharacter chr) {
    int cid = chr.getId();
    /* not truly needed since it's going to be hard removed from the DB
        String actor = (send ? "sender" : "receiver");
        
        try (Connection con = DatabaseConnection.getConnection()) {
            try (PreparedStatement ps = con.prepareStatement("UPDATE newyear SET " + actor + "id = 1, received = 0 WHERE " + actor + "id = ?")) {
                ps.setInt(1, cid);
                ps.executeUpdate();
            }
        } catch(SQLException sqle) {
            sqle.printStackTrace();
        }
        */
    Set<NewYearCardRecord> set = new HashSet<>(chr.getNewYearRecords());
    for (NewYearCardRecord nyc : set) {
        if (send) {
            if (nyc.senderId == cid) {
                nyc.senderDiscardCard = true;
                nyc.receiverReceivedCard = false;
                chr.removeNewYearRecord(nyc);
                deleteNewYearCard(nyc.id);
                chr.getMap().broadcastMessage(MaplePacketCreator.onNewYearCardRes(chr, nyc, 0xE, 0));
                MapleCharacter other = chr.getClient().getWorldServer().getPlayerStorage().getCharacterById(nyc.getReceiverId());
                if (other != null && other.isLoggedin() && !other.isAwayFromWorld()) {
                    other.removeNewYearRecord(nyc);
                    other.getMap().broadcastMessage(MaplePacketCreator.onNewYearCardRes(other, nyc, 0xE, 0));
                    other.dropMessage(6, "[NEW YEAR] " + chr.getName() + " threw away the New Year card.");
                }
            }
        } else {
            if (nyc.receiverId == cid) {
                nyc.receiverDiscardCard = true;
                nyc.receiverReceivedCard = false;
                chr.removeNewYearRecord(nyc);
                deleteNewYearCard(nyc.id);
                chr.getMap().broadcastMessage(MaplePacketCreator.onNewYearCardRes(chr, nyc, 0xE, 0));
                MapleCharacter other = chr.getClient().getWorldServer().getPlayerStorage().getCharacterById(nyc.getSenderId());
                if (other != null && other.isLoggedin() && !other.isAwayFromWorld()) {
                    other.removeNewYearRecord(nyc);
                    other.getMap().broadcastMessage(MaplePacketCreator.onNewYearCardRes(other, nyc, 0xE, 0));
                    other.dropMessage(6, "[NEW YEAR] " + chr.getName() + " threw away the New Year card.");
                }
            }
        }
    }
}
Also used : MapleCharacter(client.MapleCharacter) HashSet(java.util.HashSet)

Example 100 with MapleCharacter

use of client.MapleCharacter in project HeavenMS by ronancpl.

the class MTSHandler method handlePacket.

@Override
public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
    if (!c.getPlayer().getCashShop().isOpened()) {
        return;
    }
    if (slea.available() > 0) {
        byte op = slea.readByte();
        if (op == 2) {
            // put item up for sale
            byte itemtype = slea.readByte();
            int itemid = slea.readInt();
            slea.readShort();
            slea.skip(7);
            short stars = 1;
            if (itemtype == 1) {
                slea.skip(32);
            } else {
                stars = slea.readShort();
            }
            // another useless thing (owner)
            slea.readMapleAsciiString();
            if (itemtype == 1) {
                slea.skip(32);
            } else {
                slea.readShort();
            }
            short slot;
            short quantity;
            if (itemtype != 1) {
                if (itemid / 10000 == 207 || itemid / 10000 == 233) {
                    slea.skip(8);
                }
                slot = (short) slea.readInt();
            } else {
                slot = (short) slea.readInt();
            }
            if (itemtype != 1) {
                if (itemid / 10000 == 207 || itemid / 10000 == 233) {
                    quantity = stars;
                    slea.skip(4);
                } else {
                    quantity = (short) slea.readInt();
                }
            } else {
                quantity = (byte) slea.readInt();
            }
            int price = slea.readInt();
            if (itemtype == 1) {
                quantity = 1;
            }
            if (quantity < 0 || price < 110 || c.getPlayer().getItemQuantity(itemid, false) < quantity) {
                return;
            }
            MapleInventoryType invType = ItemConstants.getInventoryType(itemid);
            Item i = c.getPlayer().getInventory(invType).getItem(slot).copy();
            if (i != null && c.getPlayer().getMeso() >= 5000) {
                Connection con = null;
                try {
                    con = DatabaseConnection.getConnection();
                    PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM mts_items WHERE seller = ?");
                    ps.setInt(1, c.getPlayer().getId());
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        if (rs.getInt(1) > 10) {
                            // They have more than 10 items up for sale already!
                            c.getPlayer().dropMessage(1, "You already have 10 items up for auction!");
                            c.announce(getMTS(1, 0, 0));
                            c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
                            c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
                            rs.close();
                            ps.close();
                            return;
                        }
                    }
                    rs.close();
                    ps.close();
                    Calendar calendar = Calendar.getInstance();
                    int year;
                    int month;
                    int day;
                    int oldmax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    int oldday = calendar.get(Calendar.DAY_OF_MONTH) + 7;
                    if (oldmax < oldday) {
                        if (calendar.get(Calendar.MONTH) + 2 > 12) {
                            year = calendar.get(Calendar.YEAR) + 1;
                            month = 1;
                            calendar.set(year, month, 1);
                            day = oldday - oldmax;
                        } else {
                            month = calendar.get(Calendar.MONTH) + 2;
                            year = calendar.get(Calendar.YEAR);
                            calendar.set(year, month, 1);
                            day = oldday - oldmax;
                        }
                    } else {
                        day = calendar.get(Calendar.DAY_OF_MONTH) + 7;
                        month = calendar.get(Calendar.MONTH);
                        year = calendar.get(Calendar.YEAR);
                    }
                    String date = year + "-";
                    if (month < 10) {
                        date += "0" + month + "-";
                    } else {
                        date += month + "-";
                    }
                    if (day < 10) {
                        date += "0" + day;
                    } else {
                        date += day + "";
                    }
                    if (!i.getInventoryType().equals(MapleInventoryType.EQUIP)) {
                        Item item = (Item) i;
                        ps = con.prepareStatement("INSERT INTO mts_items (tab, type, itemid, quantity, seller, price, owner, sellername, sell_ends) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        ps.setInt(1, 1);
                        ps.setInt(2, (int) invType.getType());
                        ps.setInt(3, item.getItemId());
                        ps.setInt(4, quantity);
                        ps.setInt(5, c.getPlayer().getId());
                        ps.setInt(6, price);
                        ps.setString(7, item.getOwner());
                        ps.setString(8, c.getPlayer().getName());
                        ps.setString(9, date);
                    } else {
                        Equip equip = (Equip) i;
                        ps = con.prepareStatement("INSERT INTO mts_items (tab, type, itemid, quantity, seller, price, upgradeslots, level, str, dex, `int`, luk, hp, mp, watk, matk, wdef, mdef, acc, avoid, hands, speed, jump, locked, owner, sellername, sell_ends, vicious, flag) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        ps.setInt(1, 1);
                        ps.setInt(2, (int) invType.getType());
                        ps.setInt(3, equip.getItemId());
                        ps.setInt(4, quantity);
                        ps.setInt(5, c.getPlayer().getId());
                        ps.setInt(6, price);
                        ps.setInt(7, equip.getUpgradeSlots());
                        ps.setInt(8, equip.getLevel());
                        ps.setInt(9, equip.getStr());
                        ps.setInt(10, equip.getDex());
                        ps.setInt(11, equip.getInt());
                        ps.setInt(12, equip.getLuk());
                        ps.setInt(13, equip.getHp());
                        ps.setInt(14, equip.getMp());
                        ps.setInt(15, equip.getWatk());
                        ps.setInt(16, equip.getMatk());
                        ps.setInt(17, equip.getWdef());
                        ps.setInt(18, equip.getMdef());
                        ps.setInt(19, equip.getAcc());
                        ps.setInt(20, equip.getAvoid());
                        ps.setInt(21, equip.getHands());
                        ps.setInt(22, equip.getSpeed());
                        ps.setInt(23, equip.getJump());
                        ps.setInt(24, 0);
                        ps.setString(25, equip.getOwner());
                        ps.setString(26, c.getPlayer().getName());
                        ps.setString(27, date);
                        ps.setInt(28, equip.getVicious());
                        ps.setInt(29, equip.getFlag());
                    }
                    ps.executeUpdate();
                    ps.close();
                    MapleInventoryManipulator.removeFromSlot(c, invType, slot, quantity, false);
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                c.getPlayer().gainMeso(-5000, false);
                c.announce(MaplePacketCreator.MTSConfirmSell());
                c.announce(getMTS(1, 0, 0));
                c.announce(MaplePacketCreator.enableCSUse());
                c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
                c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
            }
        } else if (op == 3) {
        // send offer for wanted item
        } else if (op == 4) {
            // list wanted item
            slea.readInt();
            slea.readInt();
            slea.readInt();
            slea.readShort();
            slea.readMapleAsciiString();
        } else if (op == 5) {
            // change page
            int tab = slea.readInt();
            int type = slea.readInt();
            int page = slea.readInt();
            c.getPlayer().changePage(page);
            if (tab == 4 && type == 0) {
                c.announce(getCart(c.getPlayer().getId()));
            } else if (tab == c.getPlayer().getCurrentTab() && type == c.getPlayer().getCurrentType() && c.getPlayer().getSearch() != null) {
                c.announce(getMTSSearch(tab, type, c.getPlayer().getCurrentCI(), c.getPlayer().getSearch(), page));
            } else {
                c.getPlayer().setSearch(null);
                c.announce(getMTS(tab, type, page));
            }
            c.getPlayer().changeTab(tab);
            c.getPlayer().changeType(type);
            c.announce(MaplePacketCreator.enableCSUse());
            c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
            c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
        } else if (op == 6) {
            // search
            int tab = slea.readInt();
            int type = slea.readInt();
            slea.readInt();
            int ci = slea.readInt();
            String search = slea.readMapleAsciiString();
            c.getPlayer().setSearch(search);
            c.getPlayer().changeTab(tab);
            c.getPlayer().changeType(type);
            c.getPlayer().changeCI(ci);
            c.announce(MaplePacketCreator.enableCSUse());
            c.announce(MaplePacketCreator.enableActions());
            c.announce(getMTSSearch(tab, type, ci, search, c.getPlayer().getCurrentPage()));
            c.announce(MaplePacketCreator.showMTSCash(c.getPlayer()));
            c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
            c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
        } else if (op == 7) {
            // cancel sale
            // id of the item
            int id = slea.readInt();
            Connection con = null;
            try {
                con = DatabaseConnection.getConnection();
                PreparedStatement ps = con.prepareStatement("UPDATE mts_items SET transfer = 1 WHERE id = ? AND seller = ?");
                ps.setInt(1, id);
                ps.setInt(2, c.getPlayer().getId());
                ps.executeUpdate();
                ps.close();
                ps = con.prepareStatement("DELETE FROM mts_cart WHERE itemid = ?");
                ps.setInt(1, id);
                ps.executeUpdate();
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            c.announce(MaplePacketCreator.enableCSUse());
            c.announce(getMTS(c.getPlayer().getCurrentTab(), c.getPlayer().getCurrentType(), c.getPlayer().getCurrentPage()));
            c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
            c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
        } else if (op == 8) {
            // transfer item from transfer inv.
            // id of the item
            int id = slea.readInt();
            Connection con = null;
            PreparedStatement ps;
            ResultSet rs;
            try {
                con = DatabaseConnection.getConnection();
                ps = con.prepareStatement("SELECT * FROM mts_items WHERE seller = ? AND transfer = 1  AND id= ? ORDER BY id DESC");
                ps.setInt(1, c.getPlayer().getId());
                ps.setInt(2, id);
                rs = ps.executeQuery();
                if (rs.next()) {
                    Item i;
                    if (rs.getInt("type") != 1) {
                        Item ii = new Item(rs.getInt("itemid"), (short) 0, (short) rs.getInt("quantity"));
                        ii.setOwner(rs.getString("owner"));
                        ii.setPosition(c.getPlayer().getInventory(ItemConstants.getInventoryType(rs.getInt("itemid"))).getNextFreeSlot());
                        i = ii.copy();
                    } else {
                        Equip equip = new Equip(rs.getInt("itemid"), (byte) rs.getInt("position"), -1);
                        equip.setOwner(rs.getString("owner"));
                        equip.setQuantity((short) 1);
                        equip.setAcc((short) rs.getInt("acc"));
                        equip.setAvoid((short) rs.getInt("avoid"));
                        equip.setDex((short) rs.getInt("dex"));
                        equip.setHands((short) rs.getInt("hands"));
                        equip.setHp((short) rs.getInt("hp"));
                        equip.setInt((short) rs.getInt("int"));
                        equip.setJump((short) rs.getInt("jump"));
                        equip.setLuk((short) rs.getInt("luk"));
                        equip.setMatk((short) rs.getInt("matk"));
                        equip.setMdef((short) rs.getInt("mdef"));
                        equip.setMp((short) rs.getInt("mp"));
                        equip.setSpeed((short) rs.getInt("speed"));
                        equip.setStr((short) rs.getInt("str"));
                        equip.setWatk((short) rs.getInt("watk"));
                        equip.setWdef((short) rs.getInt("wdef"));
                        equip.setUpgradeSlots((byte) rs.getInt("upgradeslots"));
                        equip.setLevel((byte) rs.getInt("level"));
                        equip.setVicious((byte) rs.getInt("vicious"));
                        equip.setFlag((byte) rs.getInt("flag"));
                        equip.setPosition(c.getPlayer().getInventory(ItemConstants.getInventoryType(rs.getInt("itemid"))).getNextFreeSlot());
                        i = equip.copy();
                    }
                    try (PreparedStatement pse = con.prepareStatement("DELETE FROM mts_items WHERE id = ? AND seller = ? AND transfer = 1")) {
                        pse.setInt(1, id);
                        pse.setInt(2, c.getPlayer().getId());
                        pse.executeUpdate();
                    }
                    MapleInventoryManipulator.addFromDrop(c, i, false);
                    c.announce(MaplePacketCreator.enableCSUse());
                    c.announce(getCart(c.getPlayer().getId()));
                    c.announce(getMTS(c.getPlayer().getCurrentTab(), c.getPlayer().getCurrentType(), c.getPlayer().getCurrentPage()));
                    c.announce(MaplePacketCreator.MTSConfirmTransfer(i.getQuantity(), i.getPosition()));
                    c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
                }
                rs.close();
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("MTS Transfer error: " + e);
            }
        } else if (op == 9) {
            // add to cart
            // id of the item
            int id = slea.readInt();
            Connection con;
            try {
                con = DatabaseConnection.getConnection();
                try (PreparedStatement ps1 = con.prepareStatement("SELECT id FROM mts_items WHERE id = ? AND seller <> ?")) {
                    // Dummy query, prevents adding to cart self owned items
                    ps1.setInt(1, id);
                    ps1.setInt(2, c.getPlayer().getId());
                    try (ResultSet rs1 = ps1.executeQuery()) {
                        if (rs1.next()) {
                            PreparedStatement ps = con.prepareStatement("SELECT cid FROM mts_cart WHERE cid = ? AND itemid = ?");
                            ps.setInt(1, c.getPlayer().getId());
                            ps.setInt(2, id);
                            try (ResultSet rs = ps.executeQuery()) {
                                if (!rs.next()) {
                                    try (PreparedStatement pse = con.prepareStatement("INSERT INTO mts_cart (cid, itemid) VALUES (?, ?)")) {
                                        pse.setInt(1, c.getPlayer().getId());
                                        pse.setInt(2, id);
                                        pse.executeUpdate();
                                    }
                                }
                            }
                        }
                    }
                }
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            c.announce(getMTS(c.getPlayer().getCurrentTab(), c.getPlayer().getCurrentType(), c.getPlayer().getCurrentPage()));
            c.announce(MaplePacketCreator.enableCSUse());
            c.announce(MaplePacketCreator.enableActions());
            c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
            c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
        } else if (op == 10) {
            // delete from cart
            // id of the item
            int id = slea.readInt();
            Connection con = null;
            try {
                con = DatabaseConnection.getConnection();
                try (PreparedStatement ps = con.prepareStatement("DELETE FROM mts_cart WHERE itemid = ? AND cid = ?")) {
                    ps.setInt(1, id);
                    ps.setInt(2, c.getPlayer().getId());
                    ps.executeUpdate();
                }
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            c.announce(getCart(c.getPlayer().getId()));
            c.announce(MaplePacketCreator.enableCSUse());
            c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
            c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
        } else if (op == 12) {
        // put item up for auction
        } else if (op == 13) {
        // cancel wanted cart thing
        } else if (op == 14) {
        // buy auction item now
        } else if (op == 16) {
            // buy
            // id of the item
            int id = slea.readInt();
            Connection con = null;
            PreparedStatement ps;
            ResultSet rs;
            try {
                con = DatabaseConnection.getConnection();
                ps = con.prepareStatement("SELECT * FROM mts_items WHERE id = ? ORDER BY id DESC");
                ps.setInt(1, id);
                rs = ps.executeQuery();
                if (rs.next()) {
                    // taxes
                    int price = rs.getInt("price") + 100 + (int) (rs.getInt("price") * 0.1);
                    if (c.getPlayer().getCashShop().getCash(4) >= price) {
                        // FIX
                        boolean alwaysnull = true;
                        for (Channel cserv : Server.getInstance().getAllChannels()) {
                            MapleCharacter victim = cserv.getPlayerStorage().getCharacterById(rs.getInt("seller"));
                            if (victim != null) {
                                victim.getCashShop().gainCash(4, rs.getInt("price"));
                                alwaysnull = false;
                            }
                        }
                        if (alwaysnull) {
                            ResultSet rse;
                            try (PreparedStatement pse = con.prepareStatement("SELECT accountid FROM characters WHERE id = ?")) {
                                pse.setInt(1, rs.getInt("seller"));
                                rse = pse.executeQuery();
                                if (rse.next()) {
                                    try (PreparedStatement psee = con.prepareStatement("UPDATE accounts SET nxPrepaid = nxPrepaid + ? WHERE id = ?")) {
                                        psee.setInt(1, rs.getInt("price"));
                                        psee.setInt(2, rse.getInt("accountid"));
                                        psee.executeUpdate();
                                    }
                                }
                            }
                            rse.close();
                        }
                        PreparedStatement pse = con.prepareStatement("UPDATE mts_items SET seller = ?, transfer = 1 WHERE id = ?");
                        pse.setInt(1, c.getPlayer().getId());
                        pse.setInt(2, id);
                        pse.executeUpdate();
                        pse.close();
                        pse = con.prepareStatement("DELETE FROM mts_cart WHERE itemid = ?");
                        pse.setInt(1, id);
                        pse.executeUpdate();
                        pse.close();
                        c.getPlayer().getCashShop().gainCash(4, -price);
                        c.announce(MaplePacketCreator.enableCSUse());
                        c.announce(getMTS(c.getPlayer().getCurrentTab(), c.getPlayer().getCurrentType(), c.getPlayer().getCurrentPage()));
                        c.announce(MaplePacketCreator.MTSConfirmBuy());
                        c.announce(MaplePacketCreator.showMTSCash(c.getPlayer()));
                        c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
                        c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
                        c.announce(MaplePacketCreator.enableActions());
                    } else {
                        c.announce(MaplePacketCreator.MTSFailBuy());
                    }
                }
                rs.close();
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                c.announce(MaplePacketCreator.MTSFailBuy());
            }
        } else if (op == 17) {
            // buy from cart
            // id of the item
            int id = slea.readInt();
            Connection con = null;
            PreparedStatement ps;
            ResultSet rs;
            try {
                con = DatabaseConnection.getConnection();
                ps = con.prepareStatement("SELECT * FROM mts_items WHERE id = ? ORDER BY id DESC");
                ps.setInt(1, id);
                rs = ps.executeQuery();
                if (rs.next()) {
                    int price = rs.getInt("price") + 100 + (int) (rs.getInt("price") * 0.1);
                    if (c.getPlayer().getCashShop().getCash(4) >= price) {
                        for (Channel cserv : Server.getInstance().getAllChannels()) {
                            MapleCharacter victim = cserv.getPlayerStorage().getCharacterById(rs.getInt("seller"));
                            if (victim != null) {
                                victim.getCashShop().gainCash(4, rs.getInt("price"));
                            } else {
                                ResultSet rse;
                                try (PreparedStatement pse = con.prepareStatement("SELECT accountid FROM characters WHERE id = ?")) {
                                    pse.setInt(1, rs.getInt("seller"));
                                    rse = pse.executeQuery();
                                    if (rse.next()) {
                                        try (PreparedStatement psee = con.prepareStatement("UPDATE accounts SET nxPrepaid = nxPrepaid + ? WHERE id = ?")) {
                                            psee.setInt(1, rs.getInt("price"));
                                            psee.setInt(2, rse.getInt("accountid"));
                                            psee.executeUpdate();
                                        }
                                    }
                                }
                                rse.close();
                            }
                        }
                        PreparedStatement pse = con.prepareStatement("UPDATE mts_items SET seller = ?, transfer = 1 WHERE id = ?");
                        pse.setInt(1, c.getPlayer().getId());
                        pse.setInt(2, id);
                        pse.executeUpdate();
                        pse.close();
                        pse = con.prepareStatement("DELETE FROM mts_cart WHERE itemid = ?");
                        pse.setInt(1, id);
                        pse.executeUpdate();
                        pse.close();
                        c.getPlayer().getCashShop().gainCash(4, -price);
                        c.announce(getCart(c.getPlayer().getId()));
                        c.announce(MaplePacketCreator.enableCSUse());
                        c.announce(MaplePacketCreator.MTSConfirmBuy());
                        c.announce(MaplePacketCreator.showMTSCash(c.getPlayer()));
                        c.announce(MaplePacketCreator.transferInventory(getTransfer(c.getPlayer().getId())));
                        c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(c.getPlayer().getId())));
                    } else {
                        c.announce(MaplePacketCreator.MTSFailBuy());
                    }
                }
                rs.close();
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                c.announce(MaplePacketCreator.MTSFailBuy());
            }
        } else {
            System.out.println("Unhandled OP(MTS): " + op + " Packet: " + slea.toString());
        }
    } else {
        c.announce(MaplePacketCreator.showMTSCash(c.getPlayer()));
    }
}
Also used : MapleCharacter(client.MapleCharacter) SQLException(java.sql.SQLException) Calendar(java.util.Calendar) Channel(net.server.channel.Channel) DatabaseConnection(tools.DatabaseConnection) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Item(client.inventory.Item) Equip(client.inventory.Equip) MapleInventoryType(client.inventory.MapleInventoryType) ResultSet(java.sql.ResultSet)

Aggregations

MapleCharacter (client.MapleCharacter)163 Point (java.awt.Point)32 SQLException (java.sql.SQLException)22 Item (client.inventory.Item)21 Connection (java.sql.Connection)15 PreparedStatement (java.sql.PreparedStatement)15 MapleMonster (server.life.MapleMonster)15 MapleMapObject (server.maps.MapleMapObject)15 DatabaseConnection (tools.DatabaseConnection)15 MapleMap (server.maps.MapleMap)14 ArrayList (java.util.ArrayList)13 Skill (client.Skill)12 SpawnPoint (server.life.SpawnPoint)12 LinkedList (java.util.LinkedList)11 MapleInventory (client.inventory.MapleInventory)10 World (net.server.world.World)10 MapleStatEffect (server.MapleStatEffect)10 MapleInventoryType (client.inventory.MapleInventoryType)9 ResultSet (java.sql.ResultSet)9 MapleItemInformationProvider (server.MapleItemInformationProvider)9